path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/core/java/billing/Market.kt
|
alwaysmda
| 362,380,486
| false
|
{"Kotlin": 210512}
|
package billing
import android.content.Intent
import android.net.Uri
import com.xodus.templatethree.BuildConfig
import com.xodus.templatethree.R
import org.json.JSONArray
import org.json.JSONObject
import java.util.*
data class Market(
var type: MarketType = MarketType.BAZAAR,
var name: String = "",
var nameFa: String = "",
var packageName: String = "",
var intentBilling: Intent = Intent(),
var intentDetail: Intent = Intent(),
var intentComment: Intent = Intent(),
var prefixLinkDetail: String = "",
var prefixLinkComment: String = "",
var storeLink: String = ""
) {
enum class MarketType {
BAZAAR,
MYKET,
IRANAPPS,
GOOGLEPLAY;
}
constructor(item: Market) : this(
item.type,
item.name,
item.nameFa,
item.packageName,
item.intentBilling,
item.intentDetail,
item.intentComment,
item.prefixLinkDetail,
item.prefixLinkComment,
item.storeLink
)
fun toJson(): JSONObject {
val jsonObject = JSONObject()
try {
jsonObject.put("type", this.type.toString())
jsonObject.put("name", this.name)
jsonObject.put("nameFa", this.nameFa)
jsonObject.put("packageName", this.packageName)
jsonObject.put("intentBilling", this.intentBilling.toString())
jsonObject.put("intentDetail", this.intentDetail.toString())
jsonObject.put("intentComment", this.intentComment.toString())
jsonObject.put("prefixLinkDetail", this.prefixLinkDetail)
jsonObject.put("prefixLinkComment", this.prefixLinkComment)
jsonObject.put("storeLink", this.storeLink)
} catch (e: Exception) {
e.printStackTrace()
}
return jsonObject
}
companion object {
const val PACKAGE_BAZAAR = "com.farsitel.bazaar"
const val PACKAGE_MYKET = "ir.mservices.market"
const val PACKAGE_IRANAPPS = "ir.tgbs.android.iranapp"
const val PACKAGE_GOOGLEPLAY = "com.android.vending"
fun init(marketType: MarketType): Market {
return when (marketType) {
MarketType.BAZAAR -> {
Market(
marketType,
"bazaar",
"بازار",
PACKAGE_BAZAAR,
Intent("ir.cafebazaar.pardakht.InAppBillingService.BIND").setPackage(PACKAGE_BAZAAR),
Intent(Intent.ACTION_VIEW, Uri.parse("bazaar://details?id=${BuildConfig.APPLICATION_ID}")).setPackage(PACKAGE_BAZAAR),
Intent(Intent.ACTION_VIEW, Uri.parse("bazaar://details?id=${BuildConfig.APPLICATION_ID}")).setPackage(PACKAGE_BAZAAR),
"bazaar://details?id=",
"bazaar://details?id=",
"https://cafebazaar.ir/app/${BuildConfig.APPLICATION_ID}/?l=fa"
)
}
MarketType.MYKET -> {
Market(
marketType,
"myket",
"مایکت",
PACKAGE_MYKET,
Intent("ir.mservices.market.InAppBillingService.BIND").setPackage(PACKAGE_MYKET),
Intent(Intent.ACTION_VIEW, Uri.parse("myket://details?id=${BuildConfig.APPLICATION_ID}")).setPackage(PACKAGE_MYKET),
Intent(Intent.ACTION_VIEW, Uri.parse("myket://comment?id=${BuildConfig.APPLICATION_ID}")).setPackage(PACKAGE_MYKET),
"myket://details?id=",
"myket://comment?id=",
"http://myket.ir/app/${BuildConfig.APPLICATION_ID}"
)
}
MarketType.IRANAPPS -> {
Market(
marketType,
"iranapps",
"ایراناپس",
PACKAGE_IRANAPPS,
Intent("ir.tgbs.iranapps.billing.InAppBillingService.BIND").setPackage(PACKAGE_IRANAPPS),
Intent(Intent.ACTION_VIEW, Uri.parse("iranapps://app/${BuildConfig.APPLICATION_ID}")).setPackage(PACKAGE_IRANAPPS),
Intent(Intent.ACTION_VIEW, Uri.parse("iranapps://app/${BuildConfig.APPLICATION_ID}")).setPackage(PACKAGE_IRANAPPS),
"iranapps://app/",
"iranapps://app/",
"http://iranapps.com/app/${BuildConfig.APPLICATION_ID}"
)
}
MarketType.GOOGLEPLAY -> {
Market(
marketType,
"googleplay",
"گوگلپلی",
PACKAGE_GOOGLEPLAY,
Intent("com.android.vending.billing.InAppBillingService.BIND").setPackage(PACKAGE_GOOGLEPLAY),
Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=${BuildConfig.APPLICATION_ID}")).setPackage(PACKAGE_GOOGLEPLAY),
Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=${BuildConfig.APPLICATION_ID}")).setPackage(PACKAGE_GOOGLEPLAY),
"market://details?id=",
"market://details?id=",
"http://play.google.com/store/apps/details?id=${BuildConfig.APPLICATION_ID}"
)
}
}
}
fun toJson(userList: List<Market>): JSONArray {
val jsonArray = JSONArray()
try {
for (i in userList.indices) {
jsonArray.put(userList[i].toJson())
}
} catch (e: Exception) {
e.printStackTrace()
}
return jsonArray
}
fun toModel(jsonArray: JSONArray): List<Market> {
val list = ArrayList<Market>()
try {
for (i in 0 until jsonArray.length()) {
list.add(toModel(jsonArray.getJSONObject(i)))
}
} catch (e: Exception) {
e.printStackTrace()
}
return list
}
fun toModel(jsonObject: JSONObject): Market {
val item = Market()
try {
item.type = MarketType.valueOf(jsonObject.getString("type"))
item.name = jsonObject.getString("name")
item.nameFa = jsonObject.getString("nameFa")
item.packageName = jsonObject.getString("packageName")
item.intentBilling = Intent(jsonObject.getString("intentBilling")).setPackage(item.packageName)
item.intentDetail = Intent(Intent.ACTION_VIEW, Uri.parse(jsonObject.getString("intentDetail"))).setPackage(item.packageName)
item.intentComment = Intent(Intent.ACTION_VIEW, Uri.parse(jsonObject.getString("intentComment"))).setPackage(item.packageName)
item.prefixLinkDetail = jsonObject.getString("prefixLinkDetail")
item.prefixLinkComment = jsonObject.getString("prefixLinkComment")
item.storeLink = jsonObject.getString("storeLink")
} catch (e: Exception) {
e.printStackTrace()
}
return item
}
fun cloneList(requestList: List<Market>): List<Market> {
val clonedList = ArrayList<Market>(requestList.size)
for (item in requestList) {
clonedList.add(Market(item))
}
return clonedList
}
}
}
| 0
|
Kotlin
|
0
| 1
|
fe26ede160d1af5b6df0f94d4ecc5f574e5b9146
| 7,702
|
TemplateThree
|
MIT License
|
plugins/maven/src/main/java/org/jetbrains/idea/maven/statistics/MavenIndexUsageCollector.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 org.jetbrains.idea.maven.statistics
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector
object MavenIndexUsageCollector : CounterUsagesCollector() {
val GROUP = EventLogGroup("maven.indexing", 3)
@JvmField
val IS_LOCAL = EventFields.Boolean("is_local", "True if index for local repository")
@JvmField
val IS_CENTRAL = EventFields.Boolean("is_central", "True if index for central repository")
@JvmField
val IS_PRIVATE_REMOTE = EventFields.Boolean("is_private", "True if index for remote repository and it is not maven cenral")
@JvmField
val IS_SUCCESS = EventFields.Boolean("is_success", "True is index for central repository")
@JvmField
val MANUAL = EventFields.Boolean("manual", "True if action triggered explicitly by user")
@JvmField
val GROUPS_COUNT = EventFields.RoundedInt("groups_count", "Number of distinct groupIds")
@JvmField
val ARTIFACTS_COUNT = EventFields.RoundedInt("artifacts_count", "Number of scanned artifacts")
@JvmField
val INDEX_UPDATE = GROUP.registerIdeActivity("index.update",
finishEventAdditionalFields = arrayOf(IS_LOCAL,
IS_CENTRAL,
IS_PRIVATE_REMOTE,
IS_SUCCESS,
MANUAL))
@JvmField
val GAV_INDEX_UPDATE = GROUP.registerIdeActivity("gav.index.update",
finishEventAdditionalFields = arrayOf(MANUAL,
IS_SUCCESS,
GROUPS_COUNT,
ARTIFACTS_COUNT))
@JvmField
val INDEX_BROKEN = GROUP.registerEvent("index.broken", "Sent when broken index detected")
@JvmField
val INDEX_OPENED = GROUP.registerEvent("index.open", IS_LOCAL, IS_CENTRAL,
IS_PRIVATE_REMOTE, "Sent when index opened")
@JvmField
val ADD_ARTIFACT_FROM_POM = GROUP.registerEvent("artifact.from.pom.added", "triggered if index did't contain the artifact, while it is present on disk and was added to index by highlight process")
override fun getGroup(): EventLogGroup = GROUP
}
| 284
| null |
5162
| 16,707
|
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
| 2,863
|
intellij-community
|
Apache License 2.0
|
app/src/main/java/com/huotu/android/mifang/fragment/QuanTabFragment.kt
|
hottech-jxd
| 163,493,643
| false
|
{"Gradle": 5, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Proguard": 3, "Java": 25, "XML": 188, "Kotlin": 269, "JSON": 1}
|
package com.huotu.android.mifang.fragment
import android.app.Activity.RESULT_OK
import android.content.*
import android.net.Uri
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.chad.library.adapter.base.BaseQuickAdapter
import android.provider.MediaStore.Images
import android.os.Environment
import android.support.v4.content.ContextCompat
import android.support.v4.widget.SwipeRefreshLayout
import com.huotu.android.mifang.AppInit
import com.huotu.android.mifang.R
import com.huotu.android.mifang.adapter.QuanAdapter
import com.huotu.android.mifang.base.BaseFragment
import com.huotu.android.mifang.bean.*
import com.huotu.android.mifang.mvp.IPresenter
import com.huotu.android.mifang.mvp.contract.QuanContract
import com.huotu.android.mifang.mvp.presenter.QuanPresenter
import com.huotu.android.mifang.util.ImageUtils
import com.huotu.android.mifang.utils.AppUtil
import com.huotu.android.mifang.widget.RecyclerViewDivider
import com.liulishuo.filedownloader.BaseDownloadTask
import com.liulishuo.filedownloader.FileDownloadListener
import com.liulishuo.filedownloader.FileDownloadQueueSet
import com.liulishuo.filedownloader.FileDownloader
import com.liulishuo.filedownloader.util.FileDownloadHelper
import com.shuyu.gsyvideoplayer.GSYVideoManager
import kotlinx.android.synthetic.main.fragment_quan_tab.*
import java.io.File
import java.io.FileOutputStream
import java.util.*
import kotlin.collections.ArrayList
private const val ARG_CATEGORY = "category"
/**
* A simple [Fragment] subclass.
* Use the [QuanTabFragment.newInstance] factory method to
* create an instance of this fragment.
*
*/
class QuanTabFragment : BaseFragment<QuanContract.Presenter>()
, QuanContract.View
, SwipeRefreshLayout.OnRefreshListener
, BaseQuickAdapter.RequestLoadMoreListener
, BaseQuickAdapter.OnItemChildClickListener {
private var category: Int? = null
private var quanAdapter: QuanAdapter? = null
private var data = ArrayList<Quan>()
private var iPresenter=QuanPresenter(this)
private var pageIndex = 0
private var isShowProgress=true
private var REQUEST_CODE_SHARE=3001
private var currentShareDataId = 0L
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
category = it.getInt(ARG_CATEGORY, 0)
}
}
override fun initView() {
quan_tab_refreshview.setOnRefreshListener(this)
quanAdapter = QuanAdapter(data)
var emptyView = LayoutInflater.from(context).inflate(R.layout.layout_empty, null)
quanAdapter!!.emptyView = emptyView
quanAdapter!!.isUseEmpty(false)
quan_tab_recyclerview.layoutManager = LinearLayoutManager(context)
quan_tab_recyclerview.addItemDecoration(RecyclerViewDivider(context!!, ContextCompat.getColor(context!!, R.color.line_color), 10f))
quan_tab_recyclerview.adapter = quanAdapter
quanAdapter!!.onItemChildClickListener = this
quanAdapter!!.setOnLoadMoreListener( this , quan_tab_recyclerview)
}
override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
when (view!!.id) {
R.id.quan_item_one_share -> {
share( adapter!!.data[position] as Quan)
}
R.id.quan_item_one_save_image -> {
save(adapter!!.data[position] as Quan)
}
}
}
private fun save( quan:Quan){
if(quan.Type==0){
val cm = context!!.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
// 将文本内容放到系统剪贴板里。
val clipData = ClipData.newPlainText( quan.ShareTitle , quan.ShareDescription )
cm.primaryClip = clipData
toast("复制成功~~")
}else if(quan.Type == 1){
savaImage( quan )
}else if(quan.Type==2){
saveVideo( quan )
}
}
private fun saveVideo(quan: Quan , needShare:Boolean=false){
if(quan.VideoUrls ==null || quan.VideoUrls!!.size<1){
toast("没有视频需要下载!")
return
}
var dir = Constants.VideoDirPath + quan.dataId+"/"
isShowProgress=true
var downLoadQueueSet = FileDownloadQueueSet(object : FileDownloadListener() {
override fun warn(task: BaseDownloadTask?) {
hideProgress()
toast("warn")
}
override fun completed(task: BaseDownloadTask?) {
hideProgress()
if ((task!!.tag as IdId).id == (task!!.tag as IdId).total) {
toast("视频已经保存在"+ dir)
if(needShare){
share(quan)
}
}
}
override fun pending(task: BaseDownloadTask?, soFarBytes: Int, totalBytes: Int) {
hideProgress()
}
override fun error(task: BaseDownloadTask?, e: Throwable?) {
hideProgress()
toast("error")
e!!.printStackTrace()
}
override fun progress(task: BaseDownloadTask?, soFarBytes: Int, totalBytes: Int) {
showProgress("")
}
override fun paused(task: BaseDownloadTask?, soFarBytes: Int, totalBytes: Int) {
hideProgress()
}
})
var tasks = ArrayList<BaseDownloadTask>()
var f = File(dir)
f.delete()
if (!f.exists()) {
f.parentFile.mkdir()
}
for (i in 0 until quan.VideoUrls!!.size) {
var name = AppUtil.getFileName( quan.VideoUrls!![i] )
var path = dir + name
var idId = IdId(i, quan.VideoUrls!!.size - 1)
tasks.add(FileDownloader.getImpl().create(quan.VideoUrls!![i]).setTag(i + 1).setPath(path).setTag(idId))
}
downLoadQueueSet.disableCallbackProgressTimes()
downLoadQueueSet.setAutoRetryTimes(1)
downLoadQueueSet.downloadSequentially(tasks)//串行下载
downLoadQueueSet.start()
showProgress("")
}
/**
* 将图片存到本地
*/
private fun savaImage(quan: Quan , needShare:Boolean=false) {
if(quan.SmallImageUrls ==null || quan.SmallImageUrls!!.size<1){
toast("没有图像需要下载!")
return
}
var dir = Constants.ImageDirPath + quan.dataId+"/"
isShowProgress=true
var downLoadQueueSet = FileDownloadQueueSet(object : FileDownloadListener() {
override fun warn(task: BaseDownloadTask?) {
hideProgress()
toast("warn")
}
override fun completed(task: BaseDownloadTask?) {
hideProgress()
if ((task!!.tag as IdId).id == (task!!.tag as IdId).total) {
toast("图片已经保存在"+dir)
if(needShare){
share(quan)
}
}
}
override fun pending(task: BaseDownloadTask?, soFarBytes: Int, totalBytes: Int) {
hideProgress()
}
override fun error(task: BaseDownloadTask?, e: Throwable?) {
hideProgress()
toast("error")
e!!.printStackTrace()
}
override fun progress(task: BaseDownloadTask?, soFarBytes: Int, totalBytes: Int) {
showProgress("")
}
override fun paused(task: BaseDownloadTask?, soFarBytes: Int, totalBytes: Int) {
hideProgress()
}
})
var tasks = ArrayList<BaseDownloadTask>()
//Environment.getExternalStorageDirectory().toString() + "/coupons/images/"+dataId+"/"
var f = File(dir)
f.delete()
if (!f.exists()) {
f.parentFile.mkdir()
}
for (i in 0 until quan.SmallImageUrls!!.size) {
var name = AppUtil.getFileName( quan.SmallImageUrls!![i] ) //(i + 1).toString() + ".jpg"
var path = dir + name
var idId = IdId(i, quan.SmallImageUrls!!.size - 1)
tasks.add(FileDownloader.getImpl().create(quan.SmallImageUrls!![i]).setTag(i + 1).setPath(path).setTag(idId))
}
downLoadQueueSet.disableCallbackProgressTimes()
downLoadQueueSet.setAutoRetryTimes(1)
downLoadQueueSet.downloadSequentially(tasks)//串行下载
downLoadQueueSet.start()
showProgress("")
}
private fun shareText(quan: Quan){
var intent = Intent(Intent.ACTION_SEND)
intent.type = "text/plan"
//intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, getLocalImages( quan.dataId ))
intent.putExtra(Intent.EXTRA_SUBJECT, quan.ShareTitle )
intent.putExtra(Intent.EXTRA_TEXT, quan.ShareDescription )
intent.putExtra(Intent.EXTRA_TITLE, quan.ShareTitle)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
currentShareDataId= quan.dataId
startActivityForResult(Intent.createChooser(intent, "分享") , REQUEST_CODE_SHARE)
}
private fun shareImages(quan: Quan) {
var dirPath = Constants.ImageDirPath + quan.dataId+"/"
if(isDownPicture(dirPath)) savaImage(quan ,true)
val cm = context!!.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
// 将文本内容放到系统剪贴板里。
val clipData = ClipData.newPlainText( quan.ShareTitle , quan.ShareDescription )
cm.primaryClip = clipData
toast("文本已复制~~")
var intent = Intent(Intent.ACTION_SEND_MULTIPLE)
intent.type = "image/*"
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, getLocalImages( Constants.ImageDirPath + quan.dataId+"/" ))
intent.putExtra(Intent.EXTRA_SUBJECT, quan.ShareTitle )
intent.putExtra(Intent.EXTRA_TEXT, quan.ShareDescription )
intent.putExtra(Intent.EXTRA_TITLE, quan.ShareTitle)
//intent.putExtra(Intent., quan.ShareTitle)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
var shareIntent = Intent.createChooser(intent, "分享")
//shareIntent.putExtra(Constants.INTENT_GOODSID , quan.dataId )
currentShareDataId=quan.dataId
startActivityForResult( shareIntent , REQUEST_CODE_SHARE )
}
private fun shareVideo(quan: Quan){
var fileName = File( quan.VideoUrls!![0]).name
var filePath = Constants.VideoDirPath + quan.dataId+"/"+fileName
var file = File(filePath)
if(!file.exists()) saveVideo( quan ,true)
//val cm = context!!.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
// 将文本内容放到系统剪贴板里。
//val clipData = ClipData.newPlainText( quan.ShareTitle , quan.ShareDescription )
//cm.primaryClip = clipData
var intent = Intent(Intent.ACTION_SEND)
intent.type = "video/*"
//intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, getLocalvideo( quan.dataId ))
intent.putExtra(Intent.EXTRA_STREAM , ImageUtils.getUriByVideoFile( context , filePath) )
intent.putExtra(Intent.EXTRA_SUBJECT, quan.ShareTitle )
intent.putExtra(Intent.EXTRA_TEXT, quan.ShareDescription )
intent.putExtra(Intent.EXTRA_TITLE, quan.ShareTitle)
//intent.putExtra(Intent., quan.ShareTitle)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
var shareIntent = Intent.createChooser(intent, "分享")
//shareIntent.putExtra(Constants.INTENT_GOODSID , quan.dataId )
currentShareDataId=quan.dataId
startActivityForResult( shareIntent , REQUEST_CODE_SHARE )
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if( requestCode==REQUEST_CODE_SHARE ){
//因为无法判断是否分享成功了,所以就都认为成功
//toast("分享回调了.....")
//var dataId = data!!.getLongExtra(Constants.INTENT_GOODSID,0L)
if(currentShareDataId>0) {
iPresenter.shareSuccess(currentShareDataId)
}
}
}
private fun share(quan: Quan) {
if(quan.Type==0){
shareText(quan)
}else if(quan.Type==1) {
shareImages(quan)
}else if(quan.Type==2){
shareVideo(quan)
}
}
private fun isDownPicture( dirPath : String ):Boolean{
//val imageDirectoryPath = Constants.ImageDirPath + quan.dataId+"/"
val dir = File(dirPath)
if (!dir.exists()) {
dir.mkdirs()
}
val imageDirectory = File(dirPath)
val fileList = imageDirectory.list()
return fileList.isEmpty()
}
/**
* 设置需要分享的照片放入Uri类型的集合里
*/
private fun getLocalImages( dirPath:String ): ArrayList<Uri> {
val myList = ArrayList<Uri>()
val imageDirectoryPath = dirPath //Constants.ImageDirPath + dataId+"/"
val dir = File(imageDirectoryPath)
if (!dir.exists()) {
dir.mkdirs()
}
val imageDirectory = File(imageDirectoryPath)
val fileList = imageDirectory.list()
if (fileList.isNotEmpty()) {
var count = if (fileList.size > 9) 9 else fileList.size
for (i in 0 until count) {
try {
val values = ContentValues(7)
values.put(Images.Media.TITLE, fileList[i])
values.put(Images.Media.DISPLAY_NAME, fileList[i])
values.put(Images.Media.DATE_TAKEN, Date().time)
values.put(Images.Media.MIME_TYPE, "image/jpeg")
values.put(Images.ImageColumns.BUCKET_ID, imageDirectoryPath.hashCode())
values.put(Images.ImageColumns.BUCKET_DISPLAY_NAME, fileList[i])
values.put("_data", imageDirectoryPath + fileList[i])
//val contentResolver = context!!.contentResolver
val uri = ImageUtils.getUriByFile(context, imageDirectoryPath+ fileList[i]) // Uri.fromFile( File(imageDirectoryPath + fileList[i])) //contentResolver.insert(Images.Media.EXTERNAL_CONTENT_URI, values)
myList.add(uri)
} catch (e: Exception) {
e.printStackTrace()
}
}
}
return myList
}
override fun fetchData() {
quanAdapter!!.isUseEmpty(false)
iPresenter.materialList(category!! , pageIndex+1)
}
override fun getLayoutResourceId(): Int {
return R.layout.fragment_quan_tab
}
override fun showProgress(msg: String) {
super.showProgress(msg)
if(isShowProgress){
quan_tab_progress.visibility=View.VISIBLE
}else{
quan_tab_progress.visibility=View.GONE
}
}
override fun hideProgress() {
super.hideProgress()
quan_tab_progress.visibility=View.GONE
isShowProgress=false
quan_tab_refreshview.isRefreshing= false
quanAdapter!!.isUseEmpty(true)
}
override fun onRefresh() {
pageIndex=0
isShowProgress=false
fetchData()
}
override fun onLoadMoreRequested() {
//iPresenter.materialList(category , pageIndex+1 )
fetchData()
}
override fun materialCategprysCallback(apiResult: ApiResult<List<MaterialCategory>>) {
}
override fun materialListCallback(apiResult: ApiResult<List<Quan>>) {
isShowProgress = false
quanAdapter!!.isUseEmpty(true)
//borrow_refreshview.setRefreshing(false)
if (processCommonErrorCode(apiResult )) return
if (apiResult.code != ApiResultCodeEnum.SUCCESS.code ) {
toast(apiResult.msg )
return
}
if (apiResult.data == null) return
if ( apiResult!!.data!!.size < Constants.PAGE_SIZE) {
//没有数据了
if (pageIndex == 0) {
quanAdapter!!.loadMoreEnd(true)
} else {
quanAdapter!!.loadMoreEnd()
}
pageIndex++
} else {
quanAdapter!!.loadMoreComplete()
pageIndex++
}
if (pageIndex == 1) {
data.clear()
data.addAll(apiResult.data!!)
quanAdapter!!.setNewData(apiResult.data)
quanAdapter!!.disableLoadMoreIfNotFullPage(quan_tab_recyclerview)
} else {
data.addAll(apiResult.data!!)
quanAdapter!!.addData(apiResult.data!!)
}
}
override fun shareSuccessCallback(apiResult: ApiResult<Any>) {
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment QuanTabFragment.
*/
@JvmStatic
fun newInstance(category: Int) =
QuanTabFragment().apply {
arguments = Bundle().apply {
putInt(ARG_CATEGORY, category)
}
}
}
}
| 1
| null |
1
| 1
|
d409993f3900a1ebef52bfd8ea2bbbd7799bce79
| 17,410
|
mifang-shopman-android
|
Apache License 2.0
|
superframe-kotlin/src/main/java/com/hz/zxk/superframe_kotlin/base/adapter/BaseRecyclerViewAdapter.kt
|
crazyxiaoke
| 223,301,380
| false
|
{"Gradle": 7, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 6, "Batchfile": 1, "INI": 4, "Proguard": 5, "Kotlin": 82, "XML": 36, "JSON": 1, "Java": 1}
|
package com.hz.zxk.superframe_kotlin.base.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Adapter
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView
/**
@author zhengxiaoke
@date 2020/4/22 9:56 AM
*/
class BaseRecyclerViewAdapter<T, B : ViewDataBinding>(
context: Context,
private val layoutId: Int,
private val variableId: Int = 0,
private var data: MutableList<T>? = null
) : RecyclerView.Adapter<BaseViewHolder>() {
private var mInflater: LayoutInflater
private var mItemClickListener: OnItemClickListener<T>? = null
private var mItemChildClickListener: OnItemChildClickListener<T, B>? = null
init {
if (data == null) {
data = arrayListOf()
}
mInflater = LayoutInflater.from(context)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder {
val binding: B = DataBindingUtil.inflate(mInflater, layoutId, parent, false)
return BaseViewHolder(binding.root, binding, viewType)
}
override fun getItemCount(): Int {
return data?.size ?: 0
}
override fun onBindViewHolder(holder: BaseViewHolder, position: Int) {
val binding: B = holder.binding as B
if (variableId > 0) {
binding.setVariable(variableId, data?.get(position))
}
holder.itemView.setOnClickListener {
mItemClickListener?.onClick(this as Adapter, position, data?.get(position))
}
if (mItemChildClickListener != null) {
mItemChildClickListener?.onClick(
this as Adapter,
binding,
position,
data?.get(position)
)
}
}
fun getItem(position: Int): T? {
return data?.get(position)
}
fun setOnItemClickListener(listener: OnItemClickListener<T>) {
this.mItemClickListener = listener
}
fun setOnItemChildClickListener(listener: OnItemChildClickListener<T, B>) {
this.mItemChildClickListener = listener
}
interface OnItemClickListener<T> {
fun onClick(adapter: Adapter, position: Int, data: T?)
}
interface OnItemChildClickListener<T, B : ViewDataBinding> {
fun onClick(adapter: Adapter, binding: B, position: Int, data: T?)
}
}
| 0
|
Kotlin
|
0
| 0
|
e83ade5f8d0a859bbc0c8537f087e17fd2051bba
| 2,451
|
SuperFrame
|
Apache License 2.0
|
superframe-kotlin/src/main/java/com/hz/zxk/superframe_kotlin/base/adapter/BaseRecyclerViewAdapter.kt
|
crazyxiaoke
| 223,301,380
| false
|
{"Gradle": 7, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 6, "Batchfile": 1, "INI": 4, "Proguard": 5, "Kotlin": 82, "XML": 36, "JSON": 1, "Java": 1}
|
package com.hz.zxk.superframe_kotlin.base.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Adapter
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView
/**
@author zhengxiaoke
@date 2020/4/22 9:56 AM
*/
class BaseRecyclerViewAdapter<T, B : ViewDataBinding>(
context: Context,
private val layoutId: Int,
private val variableId: Int = 0,
private var data: MutableList<T>? = null
) : RecyclerView.Adapter<BaseViewHolder>() {
private var mInflater: LayoutInflater
private var mItemClickListener: OnItemClickListener<T>? = null
private var mItemChildClickListener: OnItemChildClickListener<T, B>? = null
init {
if (data == null) {
data = arrayListOf()
}
mInflater = LayoutInflater.from(context)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder {
val binding: B = DataBindingUtil.inflate(mInflater, layoutId, parent, false)
return BaseViewHolder(binding.root, binding, viewType)
}
override fun getItemCount(): Int {
return data?.size ?: 0
}
override fun onBindViewHolder(holder: BaseViewHolder, position: Int) {
val binding: B = holder.binding as B
if (variableId > 0) {
binding.setVariable(variableId, data?.get(position))
}
holder.itemView.setOnClickListener {
mItemClickListener?.onClick(this as Adapter, position, data?.get(position))
}
if (mItemChildClickListener != null) {
mItemChildClickListener?.onClick(
this as Adapter,
binding,
position,
data?.get(position)
)
}
}
fun getItem(position: Int): T? {
return data?.get(position)
}
fun setOnItemClickListener(listener: OnItemClickListener<T>) {
this.mItemClickListener = listener
}
fun setOnItemChildClickListener(listener: OnItemChildClickListener<T, B>) {
this.mItemChildClickListener = listener
}
interface OnItemClickListener<T> {
fun onClick(adapter: Adapter, position: Int, data: T?)
}
interface OnItemChildClickListener<T, B : ViewDataBinding> {
fun onClick(adapter: Adapter, binding: B, position: Int, data: T?)
}
}
| 0
|
Kotlin
|
0
| 0
|
e83ade5f8d0a859bbc0c8537f087e17fd2051bba
| 2,451
|
SuperFrame
|
Apache License 2.0
|
app/src/main/java/com/fourteenrows/p2pcs/activities/trip/add_trip/location_trip/LocationTripPresenter.kt
|
FourteenRows
| 185,977,617
| false
| null |
package com.fourteenrows.p2pcs.activities.trip.add_trip.location_trip
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.JsonObjectRequest
import com.fourteenrows.p2pcs.R
import com.fourteenrows.p2pcs.model.database.ModelDatabase
import com.fourteenrows.p2pcs.model.database.ModelFirebase
import com.fourteenrows.p2pcs.model.volley.VolleySingleton
import com.fourteenrows.p2pcs.objects.trips.TripLocation
import kotlinx.android.synthetic.main.activity_add_trip_location.*
class LocationTripPresenter(toView: LocationTripActivity, private val database: ModelDatabase = ModelFirebase()) :
ILocationTripPresenter, ILocationTripListener {
private var view = toView
var tripType: String
init {
tripType = view.intent.getStringExtra("type")
if (tripType == "start") {
view.tripPointLayout.hint = view.resources.getString(R.string.trip_start)
} else {
view.tripPointLayout.hint = view.resources.getString(R.string.trip_end)
}
}
override fun getPlaces(text: String) {
view.startProgressDialog()
val point = view.tripPoint.text.toString()
val location = "45.411154,11.887554"
val array = ArrayList<TripLocation>()
val url =
"https://maps.googleapis.com/maps/api/place/autocomplete/json?input=$point&location=$location&radius=1000&language=it&key=AIzaSyC9ljVW0hvLLCF5ToiGv47WaKAjGBzLXos"
val jsonObjectRequest = JsonObjectRequest(Request.Method.GET, url, null,
Response.Listener {
val status = it.getString("status")
if (status == "OK") {
view.noLocation.visibility = android.view.View.GONE
view.recycleView.visibility = android.view.View.VISIBLE
val predictions = it.getJSONArray("predictions")
for (i in 0 until predictions.length()) {
val structure = predictions.getJSONObject(i).getJSONObject("structured_formatting")
val main = structure.getString("main_text")
val second = structure.getString("secondary_text")
val newLocation = TripLocation(main, second, tripType)
array.add(newLocation)
}
view.setRecyclerAdapter(LocationTripRecyclerAdapter(array, this))
view.stopProgressDialog()
} else {
view.noLocation.visibility = android.view.View.VISIBLE
view.recycleView.visibility = android.view.View.GONE
view.stopProgressDialog()
}
},
Response.ErrorListener {
view.stopProgressDialog()
view.makeAlertDialog(R.string.location_error, R.string.error)
})
val queue = VolleySingleton.getInstance(view).requestQueue
VolleySingleton.getInstance(view).addToRequestQueue(jsonObjectRequest)
queue.stop()
queue.start()
}
}
| 0
|
Kotlin
|
0
| 0
|
b88364cb6775aa24ef005845943d1086a7f76bbe
| 3,102
|
P2PCS
|
MIT License
|
app/src/main/java/vn/loitp/a/cv/layout/shadow/ShadowLayoutActivityFont.kt
|
tplloi
| 126,578,283
| false
| null |
package vn.loitp.a.cv.layout.shadow
import android.graphics.Color
import android.os.Bundle
import android.view.View
import androidx.core.view.isVisible
import com.loitp.annotation.IsFullScreen
import com.loitp.annotation.LogTag
import com.loitp.core.base.BaseActivityFont
import com.loitp.core.ext.openUrlInBrowser
import com.loitp.core.ext.setSafeOnClickListenerElastic
import com.loitp.core.utils.ConvertUtils
import kotlinx.android.synthetic.main.a_layout_shadow.*
import vn.loitp.R
@LogTag("ShadowLayoutActivity")
@IsFullScreen(false)
class ShadowLayoutActivityFont : BaseActivityFont(), View.OnClickListener {
override fun setLayoutResourceId(): Int {
return R.layout.a_layout_shadow
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setupViews()
}
private fun setupViews() {
lActionBar.apply {
this.ivIconLeft.setSafeOnClickListenerElastic(
runnable = {
onBaseBackPressed()
}
)
this.ivIconRight?.let {
it.setSafeOnClickListenerElastic(
runnable = {
context.openUrlInBrowser(
url = "https://github.com/lijiankun24/ShadowLayout"
)
}
)
it.isVisible = true
it.setImageResource(R.drawable.ic_baseline_code_48)
}
this.tvTitle?.text = ShadowLayoutActivityFont::class.java.simpleName
}
tvChangeOval.setOnClickListener(this)
tvChangeRadius.setOnClickListener(this)
tvChangeRectangle.setOnClickListener(this)
}
override fun onClick(v: View) {
when (v) {
tvChangeOval -> slOval.setShadowColor(getColor(R.color.black50))
tvChangeRadius -> slRectangle.setShadowColor(Color.parseColor("#EE00FF7F"))
tvChangeRectangle -> slRadius.setShadowRadius(ConvertUtils.dp2px(12f).toFloat())
}
}
}
| 0
|
Kotlin
|
0
| 10
|
333bebaf3287b1633f35d29b8adaf25b19c1859f
| 2,065
|
base
|
Apache License 2.0
|
base/src/main/java/jp/juggler/util/data/CollectionUtils.kt
|
tateisu
| 89,120,200
| false
|
{"Kotlin": 4343773, "Java": 324536, "Perl": 47551}
|
package jp.juggler.util.data
// same as x?.let{ dst.add(it) }
fun <T> T.addTo(dst: ArrayList<T>) = dst.add(this)
fun <E : List<*>> E?.notEmpty(): E? =
if (this?.isNotEmpty() == true) this else null
fun <E : Map<*, *>> E?.notEmpty(): E? =
if (this?.isNotEmpty() == true) this else null
fun ByteArray?.notEmpty(): ByteArray? =
if (this?.isNotEmpty() == true) this else null
fun <K, V : Any?> Iterable<Pair<K, V>>.toMutableMap() =
LinkedHashMap<K, V>().also { map -> forEach { map[it.first] = it.second } }
// 配列中の要素をラムダ式で変換して、戻り値が非nullならそこで処理を打ち切る
inline fun <T, V> Array<out T>.firstNonNull(predicate: (T) -> V?): V? {
for (element in this) return predicate(element) ?: continue
return null
}
fun <T : Any> MutableCollection<T>.removeFirst(check: (T) -> Boolean): T? {
val it = iterator()
while (it.hasNext()) {
val item = it.next()
if (check(item)) {
it.remove()
return item
}
}
return null
}
| 37
|
Kotlin
|
23
| 238
|
f20f9fee8ef29bfcbba0f4c610ca8c2fb1c29d4f
| 988
|
SubwayTooter
|
Apache License 2.0
|
platform/backend/repository/sqlite/src/main/kotlin/io/hamal/repository/sqlite/record/trigger/Repository.kt
|
hamal-io
| 622,870,037
| false
|
{"Kotlin": 2450833, "C": 1400046, "TypeScript": 323978, "Lua": 165691, "C++": 40651, "Makefile": 11728, "Java": 7564, "CMake": 2810, "JavaScript": 2640, "CSS": 1567, "Shell": 977, "HTML": 903}
|
package io.hamal.repository.sqlite.record.trigger
import io.hamal.lib.common.domain.Count
import io.hamal.lib.domain._enum.TriggerStatus
import io.hamal.lib.domain.vo.TriggerId
import io.hamal.repository.api.Trigger
import io.hamal.repository.api.TriggerCmdRepository.*
import io.hamal.repository.api.TriggerQueryRepository.TriggerQuery
import io.hamal.repository.api.TriggerRepository
import io.hamal.repository.record.CreateDomainObject
import io.hamal.repository.record.trigger.TriggerEntity
import io.hamal.repository.record.trigger.TriggerRecord
import io.hamal.repository.sqlite.record.RecordSqliteRepository
import java.nio.file.Path
internal object CreateTrigger : CreateDomainObject<TriggerId, TriggerRecord, Trigger> {
override fun invoke(recs: List<TriggerRecord>): Trigger {
check(recs.isNotEmpty()) { "At least one record is required" }
val firstRecord = recs.first()
check(
firstRecord is TriggerRecord.FixedRateCreated ||
firstRecord is TriggerRecord.EventCreated ||
firstRecord is TriggerRecord.HookCreated ||
firstRecord is TriggerRecord.CronCreated
)
var result = TriggerEntity(
id = firstRecord.entityId,
cmdId = firstRecord.cmdId,
sequence = firstRecord.sequence(),
recordedAt = firstRecord.recordedAt()
)
recs.forEach { record ->
result = result.apply(record)
}
return result.toDomainObject()
}
}
class TriggerSqliteRepository(
path: Path
) : RecordSqliteRepository<TriggerId, TriggerRecord, Trigger>(
path = path,
filename = "trigger.db",
createDomainObject = CreateTrigger,
recordClass = TriggerRecord::class,
projections = listOf(ProjectionCurrent, ProjectionUniqueName, ProjectionUniqueHook)
), TriggerRepository {
override fun create(cmd: CreateFixedRateCmd): Trigger.FixedRate {
val triggerId = cmd.triggerId
val cmdId = cmd.id
return tx {
if (commandAlreadyApplied(cmdId, triggerId)) {
versionOf(triggerId, cmdId) as Trigger.FixedRate
} else {
store(
TriggerRecord.FixedRateCreated(
cmdId = cmdId,
entityId = triggerId,
workspaceId = cmd.workspaceId,
funcId = cmd.funcId,
namespaceId = cmd.namespaceId,
name = cmd.name,
inputs = cmd.inputs,
duration = cmd.duration,
status = cmd.status,
correlationId = cmd.correlationId
)
)
(currentVersion(triggerId) as Trigger.FixedRate)
.also { ProjectionCurrent.upsert(this, it) }
.also { ProjectionUniqueName.upsert(this, it) }
}
}
}
override fun create(cmd: CreateEventCmd): Trigger.Event {
val triggerId = cmd.triggerId
val cmdId = cmd.id
return tx {
if (commandAlreadyApplied(cmdId, triggerId)) {
versionOf(triggerId, cmdId) as Trigger.Event
} else {
store(
TriggerRecord.EventCreated(
cmdId = cmdId,
entityId = triggerId,
workspaceId = cmd.workspaceId,
funcId = cmd.funcId,
namespaceId = cmd.namespaceId,
name = cmd.name,
inputs = cmd.inputs,
topicId = cmd.topicId,
status = cmd.status,
correlationId = cmd.correlationId
)
)
(currentVersion(triggerId) as Trigger.Event)
.also { ProjectionCurrent.upsert(this, it) }
.also { ProjectionUniqueName.upsert(this, it) }
}
}
}
override fun create(cmd: CreateHookCmd): Trigger.Hook {
val triggerId = cmd.triggerId
val cmdId = cmd.id
return tx {
if (commandAlreadyApplied(cmdId, triggerId)) {
versionOf(triggerId, cmdId) as Trigger.Hook
} else {
store(
TriggerRecord.HookCreated(
cmdId = cmdId,
entityId = triggerId,
workspaceId = cmd.workspaceId,
funcId = cmd.funcId,
namespaceId = cmd.namespaceId,
name = cmd.name,
inputs = cmd.inputs,
hookId = cmd.hookId,
hookMethod = cmd.hookMethod,
status = cmd.status,
correlationId = cmd.correlationId
)
)
(currentVersion(triggerId) as Trigger.Hook)
.also { ProjectionCurrent.upsert(this, it) }
.also { ProjectionUniqueName.upsert(this, it) }
.also { ProjectionUniqueHook.upsert(this, it) }
}
}
}
override fun create(cmd: CreateCronCmd): Trigger.Cron {
val triggerId = cmd.triggerId
val cmdId = cmd.id
return tx {
if (commandAlreadyApplied(cmdId, triggerId)) {
versionOf(triggerId, cmdId) as Trigger.Cron
} else {
store(
TriggerRecord.CronCreated(
cmdId = cmdId,
entityId = triggerId,
workspaceId = cmd.workspaceId,
funcId = cmd.funcId,
namespaceId = cmd.namespaceId,
name = cmd.name,
inputs = cmd.inputs,
cron = cmd.cron,
status = cmd.status,
correlationId = cmd.correlationId
)
)
(currentVersion(triggerId) as Trigger.Cron)
.also { ProjectionCurrent.upsert(this, it) }
.also { ProjectionUniqueName.upsert(this, it) }
}
}
}
override fun set(triggerId: TriggerId, cmd: SetTriggerStatusCmd): Trigger {
return tx {
if (commandAlreadyApplied(cmd.id, triggerId)) {
versionOf(triggerId, cmd.id)
} else {
if (cmd.status == TriggerStatus.Active) {
store(
TriggerRecord.SetActive(
cmdId = cmd.id,
entityId = triggerId
)
)
} else {
store(
TriggerRecord.SetInactive(
cmdId = cmd.id,
entityId = triggerId
)
)
}
(currentVersion(triggerId))
.also { ProjectionCurrent.upsert(this, it) }
.also { ProjectionUniqueName.upsert(this, it) }
}
}
}
override fun find(triggerId: TriggerId): Trigger? {
return ProjectionCurrent.find(connection, triggerId)
}
override fun list(query: TriggerQuery): List<Trigger> {
return ProjectionCurrent.list(connection, query)
}
override fun count(query: TriggerQuery): Count {
return ProjectionCurrent.count(connection, query)
}
}
| 38
|
Kotlin
|
0
| 0
|
7ead833ab99206c5a20bcb295103ee3642972423
| 7,751
|
hamal
|
Creative Commons Zero v1.0 Universal
|
FilmSearch/app/src/main/java/com/example/filmsearch/view/fragments/WatchLaterFragment.kt
|
skripkalisa
| 442,273,516
| false
| null |
package com.example.filmsearch.view.fragments
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.filmsearch.databinding.FragmentWatchLaterBinding
import com.example.filmsearch.utils.AnimationHelper
class WatchLaterFragment : Fragment() {
private lateinit var binding: FragmentWatchLaterBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentWatchLaterBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
AnimationHelper.performFragmentCircularRevealAnimation(
binding.watchLaterFragmentRoot,
requireActivity(),
3
)
}
}
| 0
|
Kotlin
|
0
| 0
|
1ce519b6d07a0c5ab37f10f5fe3b9cddf03ac964
| 974
|
SF_Android_proc
|
Apache License 2.0
|
app/src/main/java/com/eurobond/features/alarm/model/AttendanceReportDataModel.kt
|
DebashisINT
| 467,012,976
| false
|
{"Kotlin": 13903116, "Java": 999599}
|
package com.eurobond.features.alarm.model
import com.eurobond.base.BaseResponse
/**
* Created by Kinsuk on 20-02-2019.
*/
class AttendanceReportDataModel : BaseResponse() {
var attendance_report_list: ArrayList<AttendanceReport>? = null
}
| 0
|
Kotlin
|
0
| 0
|
199350926a457a54431252b1c680d5dcb609721c
| 246
|
Eurobond
|
Apache License 2.0
|
spotify-api/src/main/java/com/clipfinder/spotify/api/model/SearchResponseObject.kt
|
tosoba
| 133,674,301
| false
| null |
/**
* Spotify Web API No description provided (generated by Openapi Generator
* https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 0.0.1
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech Do not edit the class manually.
*/
package com.clipfinder.spotify.api.model
import com.squareup.moshi.Json
/**
*
* @param album
* @param artist
* @param playlist
* @param track
* @param show
* @param episode
*/
data class SearchResponseObject(
@Json(name = "album") val album: SimplifiedAlbumsPagingObject? = null,
@Json(name = "artist") val artist: SearchResponseObjectArtist? = null,
@Json(name = "playlist") val playlist: SimplifiedPlaylistsPagingObject? = null,
@Json(name = "track") val track: TracksPagingObject? = null,
@Json(name = "show") val show: SearchResponseObjectShow? = null,
@Json(name = "episode") val episode: SimplifiedEpisodesPagingObject? = null
)
| 1
|
Kotlin
|
1
| 1
|
84ae309c8c059308c16902ee43b0cdfd2740794c
| 1,017
|
ClipFinder
|
MIT License
|
app/src/main/java/com/carlos/pokemen/ui/theme/Type.kt
|
Carlosokumu
| 532,033,759
| false
| null |
package com.carlos.pokemen.ui.theme
import androidx.compose.material.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
import com.example.pokedex.R
val poppins = FontFamily(
Font(R.font.poppins_light, FontWeight.Light),
Font(R.font.poppins_regular, FontWeight.Normal),
Font(R.font.poppins_medium, FontWeight.Medium),
Font(R.font.poppins_semibold, FontWeight.SemiBold),
Font(R.font.poppin_bold, FontWeight.Bold)
)
// Set of Material typography styles to start with
val Typography = Typography(
body1 = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp
),
/* Other default text styles to override
button = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.W500,
fontSize = 14.sp
),
*/
caption = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 12.sp
),
h1 = TextStyle(
fontFamily = poppins,
fontWeight = FontWeight.Bold,
fontSize = 20.sp
),
h2 = TextStyle(
fontFamily = poppins,
fontWeight = FontWeight.Medium,
fontSize = 10.sp
),
h3 = TextStyle(
fontFamily = poppins,
fontWeight = FontWeight.Light,
fontSize = 15.sp
),
h4 = TextStyle(
fontFamily = poppins,
fontWeight = FontWeight.Medium,
fontSize = 20.sp
),
h5 = TextStyle(
fontFamily = poppins,
fontWeight = FontWeight.Light,
fontSize = 20.sp
),
h6 = TextStyle(
fontFamily = poppins,
fontWeight = FontWeight.ExtraLight,
fontSize = 10.sp
)
)
| 0
|
Kotlin
|
0
| 3
|
3643e30c42c9172301684ebed0394d5dc0be3db3
| 1,891
|
Pokemen
|
Apache License 2.0
|
dsl/src/commonTest/kotlin/it/unibo/collektive/aggregate/NeighboringTest.kt
|
Collektive
| 575,470,747
| false
|
{"Kotlin": 118369, "JavaScript": 548}
|
package it.unibo.collektive.aggregate
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.maps.shouldContainValue
import io.kotest.matchers.maps.shouldHaveSize
import it.unibo.collektive.Collektive.Companion.aggregate
import it.unibo.collektive.IntId
import it.unibo.collektive.aggregate.api.operators.neighboring
import it.unibo.collektive.network.NetworkImplTest
import it.unibo.collektive.network.NetworkManager
class NeighboringTest : StringSpec({
// device ids
val id0 = IntId(0)
val id1 = IntId(1)
val id2 = IntId(2)
val id3 = IntId(3)
// values
val initV1 = 1
val initV2 = 2
val initV3 = 3
val double: (Int) -> Int = { it * 2 }
val add: (Int) -> Int = { it + 1 }
"Neighboring without messages" {
aggregate(id0) {
val field = neighboring(initV1)
field.toMap() shouldContainValue initV1
}
}
"Neighboring with three aligned devices" {
val nm = NetworkManager()
// Device 1
val testNetwork1 = NetworkImplTest(nm, id1)
aggregate(id1, testNetwork1) {
val field = neighboring(double(initV1))
field.toMap() shouldContainValue 2
}
// Device 2
val testNetwork2 = NetworkImplTest(nm, id2)
aggregate(id2, testNetwork2) {
val field = neighboring(double(initV2))
field.toMap() shouldContainValue 2
field.toMap() shouldContainValue 4
}
// Device 3
val testNetwork3 = NetworkImplTest(nm, id3)
aggregate(id3, testNetwork3) {
val field = neighboring(double(initV3))
field.toMap() shouldContainValue 4
field.toMap() shouldContainValue 6
}
}
"Neighboring with two not aligned devices" {
val nm = NetworkManager()
// Device 1
val isDeviceOneKing = true
val testNetwork1 = NetworkImplTest(nm, id1)
aggregate(id1, testNetwork1) {
fun kingBehaviour() = neighboring(double(initV2))
fun queenBehaviour() = neighboring(add(initV1))
val f = if (isDeviceOneKing) kingBehaviour() else queenBehaviour()
f.toMap() shouldHaveSize 1
}
// Device 2
val isDeviceTwoKing = false
val testNetwork2 = NetworkImplTest(nm, id2)
aggregate(id2, testNetwork2) {
fun kingBehaviour() = neighboring(double(initV1))
fun queenBehaviour() = neighboring(add(initV2))
val field = if (isDeviceTwoKing) kingBehaviour() else queenBehaviour()
field.toMap() shouldHaveSize 1
}
}
})
| 6
|
Kotlin
|
2
| 7
|
824311a05f6d737fb45dbbb810b6201e50349975
| 2,653
|
collektive
|
Apache License 2.0
|
compiler/fir/tree/src/org/jetbrains/kotlin/fir/extensions/predicate/DeclarationPredicate.kt
|
JetBrains
| 3,432,266
| false
| null |
/*
* Copyright 2010-2021 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.fir.extensions.predicate
import org.jetbrains.kotlin.fir.extensions.AnnotationFqn
// -------------------------------------------- Predicates --------------------------------------------
// todo: Missing KDOC
sealed class DeclarationPredicate {
abstract val annotations: Set<AnnotationFqn>
abstract val metaAnnotations: Set<AnnotationFqn>
abstract fun <R, D> accept(visitor: DeclarationPredicateVisitor<R, D>, data: D): R
class Or(val a: DeclarationPredicate, val b: DeclarationPredicate) : DeclarationPredicate() {
override val annotations: Set<AnnotationFqn> = a.annotations + b.annotations
override val metaAnnotations: Set<AnnotationFqn> = a.metaAnnotations + b.metaAnnotations
override fun <R, D> accept(visitor: DeclarationPredicateVisitor<R, D>, data: D): R {
return visitor.visitOr(this, data)
}
}
class And(val a: DeclarationPredicate, val b: DeclarationPredicate) : DeclarationPredicate() {
override val annotations: Set<AnnotationFqn> = a.annotations + b.annotations
override val metaAnnotations: Set<AnnotationFqn> = a.metaAnnotations + b.metaAnnotations
override fun <R, D> accept(visitor: DeclarationPredicateVisitor<R, D>, data: D): R {
return visitor.visitAnd(this, data)
}
}
}
// ------------------------------------ Annotated ------------------------------------
/**
* Base class for all predicates with specific annotations
* Declaration will be matched if at least one of [annotations] is found
*/
sealed class Annotated(final override val annotations: Set<AnnotationFqn>) : DeclarationPredicate() {
init {
require(annotations.isNotEmpty()) {
"Annotations should be not empty"
}
}
final override val metaAnnotations: Set<AnnotationFqn>
get() = emptySet()
override fun <R, D> accept(visitor: DeclarationPredicateVisitor<R, D>, data: D): R {
return visitor.visitAnnotated(this, data)
}
}
/**
* Matches declarations, which are annotated with [annotations]
*
* @Ann
* fun foo() {}
*
* fun bar(@Ann param: Int) {}
*
* @Ann
* class A {
* fun baz() {}
*
* class Nested {
* fun foobar() {}
* }
* }
*
* Matched symbols: [fun foo, parameter `param` from fun bar, class A]
*/
class AnnotatedWith(annotations: Set<AnnotationFqn>) : Annotated(annotations) {
override fun <R, D> accept(visitor: DeclarationPredicateVisitor<R, D>, data: D): R {
return visitor.visitAnnotatedWith(this, data)
}
}
/**
* Matches declaration, if one of its containers annotated with [annotations]
*
* @Ann
* fun foo() {}
*
* fun bar(@Ann param: Int) {}
*
* @Ann
* class A {
* fun baz() {}
*
* class Nested {
* fun foobar() {}
* }
* }
*
* Matched symbols: [fun A.baz, class Nested, fun Nested.foobar]
*/
class AncestorAnnotatedWith(annotations: Set<AnnotationFqn>) : Annotated(annotations) {
override fun <R, D> accept(visitor: DeclarationPredicateVisitor<R, D>, data: D): R {
return visitor.visitAncestorAnnotatedWith(this, data)
}
}
/**
* Matches declaration, if its direct container annotated with [annotations]
*
* @Ann
* fun foo() {}
*
* fun bar(@Ann param: Int) {}
*
* @Ann
* class A {
* fun baz() {}
*
* class Nested {
* fun foobar() {}
* }
* }
*
* Matched symbols: [fun A.baz, class Nested]
*/
class ParentAnnotatedWith(annotations: Set<AnnotationFqn>) : Annotated(annotations) {
override fun <R, D> accept(visitor: DeclarationPredicateVisitor<R, D>, data: D): R {
return visitor.visitParentAnnotatedWith(this, data)
}
}
/**
* Matches declaration, if one of its direct child declarations annotated with [annotations]
*
* @Ann
* fun foo() {}
*
* fun bar(@Ann param: Int) {}
*
* class A {
* @Ann
* fun baz() {}
*
* class Nested {
* fun foobar() {}
* }
* }
*
* Matched symbols: [fun bar, class A]
*/
class HasAnnotatedWith(annotations: Set<AnnotationFqn>) : Annotated(annotations) {
override fun <R, D> accept(visitor: DeclarationPredicateVisitor<R, D>, data: D): R {
return visitor.visitHasAnnotatedWith(this, data)
}
}
// ------------------------------------ MetaAnnotated ------------------------------------
sealed class MetaAnnotated(final override val metaAnnotations: Set<AnnotationFqn>) : DeclarationPredicate() {
init {
require(metaAnnotations.isNotEmpty()) {
"Annotations should be not empty"
}
}
final override val annotations: Set<AnnotationFqn>
get() = emptySet()
override fun <R, D> accept(visitor: DeclarationPredicateVisitor<R, D>, data: D): R {
return visitor.visitMetaAnnotated(this, data)
}
}
class MetaAnnotatedWith(metaAnnotations: Set<AnnotationFqn>) : MetaAnnotated(metaAnnotations) {
override fun <R, D> accept(visitor: DeclarationPredicateVisitor<R, D>, data: D): R {
return visitor.visitMetaAnnotatedWith(this, data)
}
}
class AncestorMetaAnnotatedWith(metaAnnotations: Set<AnnotationFqn>) : MetaAnnotated(metaAnnotations) {
override fun <R, D> accept(visitor: DeclarationPredicateVisitor<R, D>, data: D): R {
return visitor.visitAncestorMetaAnnotatedWith(this, data)
}
}
class ParentMetaAnnotatedWith(metaAnnotations: Set<AnnotationFqn>) : MetaAnnotated(metaAnnotations) {
override fun <R, D> accept(visitor: DeclarationPredicateVisitor<R, D>, data: D): R {
return visitor.visitParentMetaAnnotatedWith(this, data)
}
}
class HasMetaAnnotatedWith(metaAnnotations: Set<AnnotationFqn>) : MetaAnnotated(metaAnnotations) {
override fun <R, D> accept(visitor: DeclarationPredicateVisitor<R, D>, data: D): R {
return visitor.visitHasMetaAnnotatedWith(this, data)
}
}
// -------------------------------------------- DSL --------------------------------------------
infix fun DeclarationPredicate.or(other: DeclarationPredicate): DeclarationPredicate = DeclarationPredicate.Or(this, other)
infix fun DeclarationPredicate.and(other: DeclarationPredicate): DeclarationPredicate = DeclarationPredicate.And(this, other)
// ------------------- varargs -------------------
fun annotated(vararg annotations: AnnotationFqn): DeclarationPredicate = AnnotatedWith(annotations.toSet())
fun ancestorAnnotated(vararg annotations: AnnotationFqn): DeclarationPredicate = AncestorAnnotatedWith(annotations.toSet())
fun parentAnnotated(vararg annotations: AnnotationFqn): DeclarationPredicate = ParentAnnotatedWith(annotations.toSet())
fun hasAnnotated(vararg annotations: AnnotationFqn): DeclarationPredicate = HasAnnotatedWith(annotations.toSet())
fun metaAnnotated(vararg metaAnnotations: AnnotationFqn): DeclarationPredicate = MetaAnnotatedWith(metaAnnotations.toSet())
fun metaAncestorAnnotated(vararg metaAnnotations: AnnotationFqn): DeclarationPredicate = AncestorMetaAnnotatedWith(metaAnnotations.toSet())
fun parentMetaAnnotated(vararg metaAnnotations: AnnotationFqn): DeclarationPredicate = ParentMetaAnnotatedWith(metaAnnotations.toSet())
fun hasMetaAnnotated(vararg metaAnnotations: AnnotationFqn): DeclarationPredicate = HasMetaAnnotatedWith(metaAnnotations.toSet())
fun annotatedOrUnder(vararg annotations: AnnotationFqn): DeclarationPredicate = annotated(*annotations) or ancestorAnnotated(*annotations)
fun metaAnnotatedOrUnder(vararg metaAnnotations: AnnotationFqn): DeclarationPredicate =
metaAnnotated(*metaAnnotations) or metaAncestorAnnotated(*metaAnnotations)
// ------------------- collections -------------------
fun annotated(annotations: Collection<AnnotationFqn>): DeclarationPredicate = AnnotatedWith(annotations.toSet())
fun ancestorAnnotated(annotations: Collection<AnnotationFqn>): DeclarationPredicate = AncestorAnnotatedWith(annotations.toSet())
fun parentAnnotated(annotations: Collection<AnnotationFqn>): DeclarationPredicate = ParentAnnotatedWith(annotations.toSet())
fun hasAnnotated(annotations: Collection<AnnotationFqn>): DeclarationPredicate = HasAnnotatedWith(annotations.toSet())
fun metaAnnotated(metaAnnotations: Collection<AnnotationFqn>): DeclarationPredicate = MetaAnnotatedWith(metaAnnotations.toSet())
fun metaAncestorAnnotated(metaAnnotations: Collection<AnnotationFqn>): DeclarationPredicate = AncestorMetaAnnotatedWith(metaAnnotations.toSet())
fun parentMetaAnnotated(metaAnnotations: Collection<AnnotationFqn>): DeclarationPredicate = ParentMetaAnnotatedWith(metaAnnotations.toSet())
fun hasMetaAnnotated(metaAnnotations: Collection<AnnotationFqn>): DeclarationPredicate = HasMetaAnnotatedWith(metaAnnotations.toSet())
fun annotatedOrUnder(annotations: Collection<AnnotationFqn>): DeclarationPredicate = annotated(annotations) or ancestorAnnotated(annotations)
fun metaAnnotatedOrUnder(metaAnnotations: Collection<AnnotationFqn>): DeclarationPredicate =
metaAnnotated(metaAnnotations) or metaAncestorAnnotated(metaAnnotations)
| 157
| null |
5209
| 42,102
|
65f712ab2d54e34c5b02ffa3ca8c659740277133
| 9,198
|
kotlin
|
Apache License 2.0
|
src/main/kotlin/net/fabricmc/example/server/damage/Damage.kt
|
DasPhiller
| 853,029,836
| false
|
{"Kotlin": 9671, "Java": 8520}
|
package net.fabricmc.example.server.damage
import net.minecraft.server.network.ServerPlayerEntity
import net.silkmc.silk.core.task.mcCoroutineTask
import java.util.UUID
import kotlin.time.Duration.Companion.seconds
object Damage {
private val isInCombat = mutableMapOf<UUID, Boolean>()
var ServerPlayerEntity.isInCombat: Boolean
get() = Damage.isInCombat[this.uuid] ?: false
set(value) {
Damage.isInCombat[this.uuid] = value
}
fun onDamage(player: ServerPlayerEntity) {
if (player.isInCombat) return
player.isInCombat = true
mcCoroutineTask(sync = true, delay = 15.seconds) {
player.isInCombat = false
}
}
}
| 0
|
Kotlin
|
0
| 1
|
99d2f0269852e6641b88d5c202059d22e7f1c4f9
| 707
|
Klassenpvp
|
Creative Commons Zero v1.0 Universal
|
sdk/onetap/onetap-common/src/main/kotlin/com/vk/id/onetap/common/auth/style/VKIDButtonRippleStyle.kt
|
VKCOM
| 696,297,549
| false
|
{"Kotlin": 468006, "Shell": 10543, "AIDL": 3429, "JavaScript": 1092}
|
package com.vk.id.onetap.common.auth.style
import com.vk.id.common.InternalVKIDApi
@InternalVKIDApi
public enum class VKIDButtonRippleStyle {
DARK,
LIGHT,
}
| 0
|
Kotlin
|
1
| 18
|
a0f4d0e936cef715d4a7e3384670e16e0949af4b
| 167
|
vkid-android-sdk
|
MIT License
|
app/src/main/java/dev/androidblog/mysamples/data/model/Photo.kt
|
YoonKyoungTae
| 441,923,584
| false
|
{"Kotlin": 8691}
|
package dev.androidblog.mysamples.data.model
data class Photo(
val id: String = "0",
val title: String = "",
val url: String = "",
var thumbnailUrl: String = ""
)
| 0
|
Kotlin
|
0
| 0
|
bcf74dde3cd77b212473ac69e0912949f895359b
| 179
|
ToolBox
|
MIT License
|
kotlin-client/src/main/kotlin/com/couchbase/client/kotlin/annotations/Api.kt
|
couchbase
| 151,122,650
| false
| null |
/*
* Copyright 2021 Couchbase, Inc.
*
* 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.couchbase.client.kotlin.annotations
import com.couchbase.client.core.annotation.Stability
/**
* APIs marked as volatile can change any time and for any reason.
*
* They may be volatile for reasons including:
*
* * Depends on specific implementation detail within the library which
* may change in the response.
*
* * Depends on specific implementation detail within the server which may
* change in the response.
*
* * Has been introduced as part of a trial phase for the specific feature.
*
* Note: This annotation corresponds to [Stability.Volatile] from the
* Couchbase Java SDK and core-io library. The Kotlin SDK uses a separate
* annotation in order to specify opt-in requirements.
*/
@MustBeDocumented
public annotation class VolatileCouchbaseApi
/**
* The API will probably remain stable, but no commitment has been made yet.
*
* It may be changed in incompatible ways or dropped from one release
* to another. The difference between uncommitted and volatile
* is that an uncommitted API is more mature and is less likely
* to be changed.
*
* Uncommitted APIs may mature into committed APIs.
*
* Note: This annotation corresponds to [Stability.Uncommitted] from the
* Couchbase Java SDK and core-io library. The Kotlin SDK uses a separate
* annotation in order to specify opt-in requirements.
*/
@MustBeDocumented
public annotation class UncommittedCouchbaseApi
| 1
| null |
40
| 47
|
ae4afe1760dc77b2f8541cd4339d3fd1ef529639
| 2,014
|
couchbase-jvm-clients
|
Apache License 2.0
|
app/src/main/java/com/example/flixster/DetailActivity.kt
|
nilmo-contreras
| 605,379,397
| false
| null |
package com.example.flixster
import android.os.Bundle
import android.util.Log
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.google.gson.Gson
private const val TAG = "DetailActivity"
class DetailActivity : AppCompatActivity() {
private lateinit var actorImageView: ImageView
private lateinit var actorNameView: TextView
private lateinit var knownForRecyclerView: RecyclerView
override fun onCreate(savedInstanceState: Bundle?) {
val gson = Gson()
val actor = gson.fromJson(intent.getStringExtra(ACTOR_EXTRA), Actor::class.java)
Log.d("actor", actor.knownFor[1].overview.toString())
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_detail)
actorImageView = findViewById(R.id.actor_portrait)
actorNameView = findViewById(R.id.actor_name)
knownForRecyclerView = findViewById(R.id.known_for)
val knownForAdapter = KnownForAdapter(actor.knownFor)
knownForRecyclerView.adapter = knownForAdapter
knownForRecyclerView.layoutManager = LinearLayoutManager(this)
actorNameView.text = actor.name
Glide.with(this)
.load("https://image.tmdb.org/t/p/w500/${actor.profilePath}")
.centerInside()
.placeholder(R.drawable.my_project__1_)
.error(R.drawable.my_project__1_)
.transform(RoundedCorners(20))
.into(actorImageView)
}
}
| 1
|
Kotlin
|
0
| 0
|
02905652d1909fbbde1e67dda29a26538aeb0a47
| 1,708
|
FlixsterPlusPart2_App
|
Apache License 2.0
|
comet-core/src/test/kotlin/ren/natsuyuk1/comet/test/network/thirdparty/projectsekai/TestProjectSekaiAPI.kt
|
StarWishsama
| 173,288,057
| false
| null |
/*
* Copyright (c) 2019-2022 StarWishsama.
*
* 此源代码的使用受 MIT 许可证约束, 欲阅读此许可证, 可在以下链接查看.
* Use of this source code is governed by the MIT License which can be found through the following link.
*
* https://github.com/StarWishsama/Comet-Bot/blob/dev/LICENSE
*/
package ren.natsuyuk1.comet.test.network.thirdparty.projectsekai
import io.ktor.client.plugins.*
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import org.jetbrains.exposed.sql.deleteAll
import org.jetbrains.exposed.sql.transactions.transaction
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.TestInstance
import ren.natsuyuk1.comet.api.database.DatabaseManager
import ren.natsuyuk1.comet.api.platform.LoginPlatform
import ren.natsuyuk1.comet.api.user.CometUser
import ren.natsuyuk1.comet.api.user.UserTable
import ren.natsuyuk1.comet.network.thirdparty.projectsekai.ProjectSekaiAPI.getEventList
import ren.natsuyuk1.comet.network.thirdparty.projectsekai.ProjectSekaiAPI.getRankPredictionInfo
import ren.natsuyuk1.comet.network.thirdparty.projectsekai.ProjectSekaiAPI.getSpecificRankInfo
import ren.natsuyuk1.comet.network.thirdparty.projectsekai.ProjectSekaiAPI.getUserEventInfo
import ren.natsuyuk1.comet.network.thirdparty.projectsekai.ProjectSekaiAPI.getUserInfo
import ren.natsuyuk1.comet.network.thirdparty.projectsekai.objects.kit33.toMessageWrapper
import ren.natsuyuk1.comet.network.thirdparty.projectsekai.objects.toMessageWrapper
import ren.natsuyuk1.comet.network.thirdparty.projectsekai.toMessageWrapper
import ren.natsuyuk1.comet.objects.pjsk.ProjectSekaiData
import ren.natsuyuk1.comet.objects.pjsk.ProjectSekaiDataTable
import ren.natsuyuk1.comet.objects.pjsk.ProjectSekaiUserData
import ren.natsuyuk1.comet.objects.pjsk.ProjectSekaiUserDataTable
import ren.natsuyuk1.comet.service.ProjectSekaiManager
import ren.natsuyuk1.comet.test.initTestDatabase
import ren.natsuyuk1.comet.test.isCI
import ren.natsuyuk1.comet.test.network.client
import ren.natsuyuk1.comet.test.print
import kotlin.coroutines.EmptyCoroutineContext
import kotlin.test.Test
import kotlin.test.assertTrue
private val logger = mu.KotlinLogging.logger {}
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class TestProjectSekaiAPI {
@BeforeAll
fun init() {
if (isCI()) {
return
}
initTestDatabase()
DatabaseManager.loadTables(ProjectSekaiDataTable, ProjectSekaiUserDataTable)
runBlocking {
ProjectSekaiManager.init(EmptyCoroutineContext)
ProjectSekaiData.updateEventInfo(true)
}
}
// Represent to event named `Find a way out`
private val eventID = 79
// Welcome to add me as friend :D
private val id = 210043933010767872L
@Test
fun testEventProfileFetch() {
if (isCI()) {
return
}
runBlocking {
val user = CometUser.create(id, LoginPlatform.TEST)
ProjectSekaiUserData.createData(user.id.value, this@TestProjectSekaiAPI.id)
val data = transaction {
ProjectSekaiData.all().forEach {
it.print()
}
ProjectSekaiUserData.getUserPJSKData(user.id.value)
} ?: return@runBlocking
client.getUserEventInfo(eventID, id)
.also { it.toMessageWrapper(data, eventID).print() }
transaction {
ProjectSekaiUserDataTable.deleteAll()
UserTable.deleteAll()
}
}
}
@Test
fun testEventRankingWithoutDatabaseFetch() {
if (isCI()) {
return
}
runBlocking {
client.getUserEventInfo(eventID, id).toMessageWrapper(null, eventID).print()
}
}
@Test
fun testEventRankingPositionFetch() {
if (isCI()) {
return
}
runBlocking {
client.getSpecificRankInfo(eventID, 100).toMessageWrapper(null, eventID).print()
}
}
@Test
fun testEventListFetch() {
if (isCI()) {
return
}
runBlocking { println(client.getEventList()) }
}
@Test
fun testRankPredictionFetch() {
if (isCI()) {
return
}
runBlocking {
try {
client.getRankPredictionInfo().toMessageWrapper().print()
} catch (_: ServerResponseException) {
}
}
}
@Test
fun testUserInfoFetch() {
if (isCI()) {
return
}
runBlocking {
client.getUserInfo(id).toMessageWrapper().print()
}
}
@Test
fun testB30() {
if (isCI()) return
runBlocking {
val b30 = client.getUserInfo(id).getBest30Songs()
Json.encodeToString(b30).print()
assertTrue { b30.size == 30 }
}
}
}
| 14
|
Kotlin
|
19
| 188
|
61d85469adca9e49a8d012d3916dafd92a303d91
| 4,925
|
Comet-Bot
|
MIT License
|
idea/testData/jetPsiMatcher/expressions/call/_call1.kt
|
chashnikov
| 14,658,474
| false
| null |
// NOT_EQUAL
f()
| 0
| null |
0
| 1
|
88a261234860ff0014e3c2dd8e64072c685d442d
| 16
|
kotlin
|
Apache License 2.0
|
build-logic/convention/src/main/kotlin/com/melih/apps/pokeapp/SdkVersions.kt
|
melomg
| 458,631,034
| false
|
{"Kotlin": 95088}
|
package com.melih.apps.pokeapp
object SdkVersions {
const val compileSdkVersion: Int = 34
const val minSdkVersion: Int = 27
const val targetSdkVersion: Int = 34
}
| 3
|
Kotlin
|
0
| 0
|
00fbfe60e75d26eeda2e9e1ce87250a6604d2fd1
| 176
|
pokeapp-android
|
Apache License 2.0
|
app/src/main/java/ca/grantelliott/audiogeneapp/ui/home/HomeFragment.kt
|
grelliott
| 291,516,382
| false
| null |
package ca.grantelliott.audiogeneapp.ui.home
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import ca.grantelliott.audiogeneapp.R
class HomeFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_home, container, false)
}
}
| 0
|
Kotlin
|
0
| 0
|
8300ca0a2981610dbbcefc3dd54b5adb9e86df6b
| 583
|
audiogene-app
|
MIT License
|
mobile/src/main/java/com/sebastiansokolowski/healthguard/dataModel/StatisticData.kt
|
sebastiansokolowski
| 125,769,078
| false
| null |
package com.sebastiansokolowski.healthguard.dataModel
/**
* Created by <NAME> on 16.09.19.
*/
data class StatisticData(var min: Float = Float.MAX_VALUE,
var max: Float = Float.MIN_VALUE,
var average: Float = 0f,
var sum: Float = 0f,
var count: Int = 0)
| 1
| null |
1
| 1
|
5c164405abb457b91f04b15ff04ef1702cee6a54
| 355
|
mHealth-Guard
|
Apache License 2.0
|
moove/domain/src/main/kotlin/io/charlescd/moove/domain/RegistryConfiguration.kt
|
xereda
| 275,209,237
| true
|
{"TypeScript": 1799453, "Kotlin": 1191679, "Groovy": 592744, "Java": 308094, "Go": 74665, "JavaScript": 53282, "Smarty": 45219, "C#": 9630, "TSQL": 8959, "Shell": 6465, "HTML": 6449, "Dockerfile": 2110, "Makefile": 920}
|
/*
* Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA
*
* 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 io.charlescd.moove.domain
abstract class RegistryConfiguration(
open val name: String,
open val address: String,
open val provider: RegistryConfigurationProviderEnum,
open val hostname: String,
open val author: User,
open val workspace: Workspace
)
data class AzureRegistryConfiguration(
override val name: String,
override val address: String,
override val author: User,
override val hostname: String,
override val workspace: Workspace,
val username: String,
val password: String
) : RegistryConfiguration(name, address, RegistryConfigurationProviderEnum.Azure, hostname, author, workspace)
data class AWSRegistryConfiguration(
override val name: String,
override val address: String,
override val author: User,
override val hostname: String,
override val workspace: Workspace,
val accessKey: String,
val secretKey: String,
val region: String
) : RegistryConfiguration(name, address, RegistryConfigurationProviderEnum.AWS, hostname, author, workspace)
enum class RegistryConfigurationProviderEnum {
AWS, Azure
}
| 0
| null |
0
| 1
|
d2597bf8a29920050ed0f566fa9846b9fc9eaaae
| 1,741
|
charlescd
|
Apache License 2.0
|
src/main/kotlin/com/github/erosb/jsonsKema/Const.kt
|
erosb
| 314,666,360
| false
|
{"Kotlin": 262694}
|
package com.github.erosb.jsonsKema
data class ConstSchema(val constant: IJsonValue, override val location: SourceLocation) : Schema(location) {
override fun <P> accept(visitor: SchemaVisitor<P>) = visitor.visitConstSchema(this)
}
internal val constLoader: KeywordLoader = { ctx -> ConstSchema(ctx.keywordValue, ctx.location)}
data class ConstValidationFailure(
override val schema: ConstSchema,
override val instance: IJsonValue
) : ValidationFailure(
"actual instance is not the same as expected constant value",
schema,
instance,
Keyword.CONST
)
| 19
|
Kotlin
|
8
| 49
|
26060fbad7917fc05d58b21184cba45ef97b53ba
| 579
|
json-sKema
|
MIT License
|
app/src/main/java/com/capstone/urskripsi/ui/content/leaderboard/LeaderBoard.kt
|
Naufal0010
| 429,732,609
| false
| null |
package com.capstone.urskripsi.ui.content.leaderboard
data class LeaderBoard(
val image: String? = null,
val name: String? = null,
val progressBar: Int? = 0
)
| 0
|
Kotlin
|
1
| 0
|
46c57498547218b1fda601b5f811511d999bd859
| 172
|
UrSkripsi
|
MIT License
|
projects/core/src/main/kotlin/site/siredvin/peripheralworks/xplat/PeripheralWorksCommonHooks.kt
|
SirEdvin
| 489,471,520
| false
| null |
package site.siredvin.peripheralworks.xplat
import dan200.computercraft.api.upgrades.UpgradeData
import net.minecraft.resources.ResourceLocation
import net.minecraft.world.item.CreativeModeTab
import site.siredvin.peripheralium.xplat.PeripheraliumPlatform
import site.siredvin.peripheralium.xplat.XplatRegistries
import site.siredvin.peripheralworks.PeripheralWorksCore
import site.siredvin.peripheralworks.common.setup.*
object PeripheralWorksCommonHooks {
fun onRegister() {
BlockEntityTypes.doSomething()
Items.doSomething()
Blocks.doSomething()
RecipeSerializers.doSomething()
PocketUpgradeSerializers.doSomething()
TurtleUpgradeSerializers.doSomething()
PeripheralWorksPlatform.registerCreativeTab(
ResourceLocation(PeripheralWorksCore.MOD_ID, "tab"),
PeripheralWorksCore.configureCreativeTab(PeripheraliumPlatform.createTabBuilder()).build(),
)
}
fun registerUpgradesInCreativeTab(output: CreativeModeTab.Output) {
PeripheralWorksPlatform.holder.turtleSerializers.forEach {
val upgrade = PeripheraliumPlatform.getTurtleUpgrade(XplatRegistries.TURTLE_SERIALIZERS.getKey(it.get()).toString())
if (upgrade != null) {
PeripheraliumPlatform.createTurtlesWithUpgrade(UpgradeData.ofDefault(upgrade)).forEach(output::accept)
}
}
PeripheralWorksPlatform.holder.pocketSerializers.forEach {
val upgrade = PeripheraliumPlatform.getPocketUpgrade(XplatRegistries.POCKET_SERIALIZERS.getKey(it.get()).toString())
if (upgrade != null) {
PeripheraliumPlatform.createPocketsWithUpgrade(UpgradeData.ofDefault(upgrade)).forEach(output::accept)
}
}
}
}
| 3
|
Kotlin
|
2
| 6
|
4261ad04499375f16704c8df3f3faeb0e314ac54
| 1,781
|
UnlimitedPeripheralWorks
|
MIT License
|
mastodon/src/commonMain/kotlin/fediapi/mastodon/model/status/Status.kt
|
wingio
| 739,512,706
| false
|
{"Kotlin": 162782}
|
package fediapi.mastodon.model.status
import kotlinx.datetime.Instant
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import fediapi.HTML
import fediapi.Language
import fediapi.URL
import fediapi.mastodon.model.CustomEmoji
import fediapi.mastodon.model.Visibility
import fediapi.mastodon.model.account.Account
import fediapi.mastodon.model.filter.FilterResult
import fediapi.mastodon.model.media.MediaAttachment
/**
* Represents a status posted by an account.
*
* @param id ID of the status in the database.
* @param uri URI of the status used for federation.,
* @param createdAt The date when this status was created.
* @param account The account that authored this status.
* @param content HTML-encoded status content.
* @param visibility Visibility of this status.
* @param sensitive Is this status marked as sensitive content?
* @param spoilerText Subject or summary line, below which status content is collapsed until expanded.
* @param mediaAttachments Media that is attached to this status.
* @param application The application used to post this status.
* @param mentions Mentions of users within the status content.
* @param tags Hashtags used within the status content.
* @param emojis Custom emoji to be used when rendering status content.
* @param reblogCount How many boosts this status has received.
* @param favoriteCount How many favourites this status has received.
* @param replyCount How many replies this status has received.
* @param url A link to the status’s HTML representation.
* @param inReplyToId ID of the status being replied to.
* @param inReplyToAccountId ID of the account that authored the status being replied to.
* @param reblog The status being reblogged.
* @param poll The poll attached to the status.
* @param card Preview card for links included within status content.
* @param language Primary language of this status.
* @param text Plain-text source of a status. Returned instead of [content] when status is deleted, so the user may redraft from the source text without the client having to reverse-engineer the original text from the HTML content.
* @param editedAt Timestamp of when the status was last edited.
* @param favorited If the current token has an authorized user: Have you favourited this status?
* @param reblogged If the current token has an authorized user: Have you boosted this status?
* @param muted If the current token has an authorized user: Have you muted notifications for this status’s conversation?
* @param bookmarked If the current token has an authorized user: Have you bookmarked this status?
* @param pinned If the current token has an authorized user: Have you pinned this status? Only appears if the status is pinnable.
* @param filtered If the current token has an authorized user: The filter and keywords that matched this status.
*/
@Serializable
public data class Status(
val id: String,
val uri: String,
@SerialName("created_at") val createdAt: Instant,
val account: Account,
val content: HTML,
val visibility: Visibility,
val sensitive: Boolean,
@SerialName("spoiler_text") val spoilerText: String,
@SerialName("media_attachments") val mediaAttachments: List<MediaAttachment>,
val application: Application? = null,
val mentions: List<Mention>,
val tags: List<Tag>,
val emojis: List<CustomEmoji>,
@SerialName("reblogs_count") val reblogCount: Int,
@SerialName("favourites_count") val favoriteCount: Int,
@SerialName("replies_count") val replyCount: Int,
val url: URL?,
@SerialName("in_reply_to_id") val inReplyToId: String?,
@SerialName("in_reply_to_account_id") val inReplyToAccountId: String?,
val reblog: Status?,
val poll: Poll?,
val card: PreviewCard?,
val language: Language?,
val text: String?,
@SerialName("edited_at") val editedAt: Instant?,
@SerialName("favourited") val favorited: Boolean? = null,
val reblogged: Boolean? = null,
val muted: Boolean? = null,
val bookmarked: Boolean? = null,
val pinned: Boolean? = null,
val filtered: List<FilterResult>? = null
) {
/**
* he application used to post a status.
*
* @param name The name of the application that posted this status.
* @param website The website associated with the application that posted this status.
*/
@Serializable
public data class Application(
val name: String,
val website: URL?
)
/**
* Account mentioned in a [Status]
*
* @param id The account ID of the mentioned user.
* @param username The username of the mentioned user.
* @param url The location of the mentioned user’s profile.
* @param acct The webfinger acct: URI of the mentioned user. Equivalent to [username] for local users, or `username@domain` for remote users.
*/
@Serializable
public data class Mention(
val id: String,
val username: String,
val url: URL,
val acct: String
)
/**
* Hashtag used in a [Status]
*
* @param name The value of the hashtag after the # sign.
* @param url A link to the hashtag on the instance.
*/
@Serializable
public data class Tag(
val name: String,
val url: URL
)
}
| 0
|
Kotlin
|
0
| 1
|
60720c72c90cd503e9b4cff88bcef1ac71c578b6
| 5,312
|
fediapi
|
MIT License
|
app/src/main/java/com/hy/baseapp/base/BaseFragment.kt
|
qwer2y
| 484,959,139
| false
|
{"Kotlin": 349881, "Java": 73310}
|
package com.hy.baseapp.base
import android.os.Bundle
import android.view.View
import androidx.annotation.ColorRes
import androidx.databinding.ViewDataBinding
import com.gyf.immersionbar.ImmersionBar
import me.hy.base.base.fragment.BaseVmDbFragment
import me.hy.base.base.viewmodel.BaseViewModel
/**
* 描述 : 你项目中的Fragment基类,在这里实现显示弹窗,吐司,还有自己的需求操作 ,如果不想用Databind,请继承
* BaseVmFragment例如
* abstract class BaseFragment<VM : BaseViewModel> : BaseVmFragment<VM>() {
*/
abstract class BaseFragment<VM : BaseViewModel, DB : ViewDataBinding> : BaseVmDbFragment<VM, DB>() {
abstract override fun initView(savedInstanceState: Bundle?)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
}
/**
* 懒加载 只有当前fragment视图显示时才会触发该方法
*/
override fun lazyLoadData() {}
/**
* 创建LiveData观察者 Fragment执行onViewCreated后触发
*/
override fun initObserver() {}
/**
* Fragment执行onViewCreated后触发
*/
override fun initData() {}
override fun onPause() {
super.onPause()
// hideSoftKeyboard(activity)
}
/**
* @color 顶部状态栏颜色
*/
fun setStatusBarColor(@ColorRes statusBarColor: Int) {
ImmersionBar.with(this)
.statusBarDarkFont(true, 0.2f)
.fitsSystemWindows(true)
.statusBarColor(statusBarColor)
.statusBarDarkFont(true)
.init()
}
/**
* 沉浸状态栏
*/
fun immersionFullStatusBar() {
ImmersionBar.with(this).statusBarDarkFont(true).transparentStatusBar().init()
}
override fun onDestroy() {
// dismissLoading()
super.onDestroy()
}
/**
* 延迟加载 防止 切换动画还没执行完毕时数据就已经加载好了,这时页面会有渲染卡顿 bug
* 这里传入你想要延迟的时间,延迟时间可以设置比转场动画时间长一点 单位: 毫秒
* 不传默认 300毫秒
* @return Long
*/
override fun lazyLoadTime(): Long {
return 300
}
}
| 0
|
Kotlin
|
0
| 0
|
e96ec50468fcdda690527180b7aeefc455871b7a
| 1,925
|
BaseApp
|
Apache License 2.0
|
app/src/main/java/com/kasuminotes/ui/app/chara/CharaUserData.kt
|
chilbi
| 399,723,451
| false
|
{"Kotlin": 868235}
|
package com.kasuminotes.ui.app.chara
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import com.kasuminotes.R
import com.kasuminotes.data.EquipData
import com.kasuminotes.data.MaxUserData
import com.kasuminotes.data.UniqueData
import com.kasuminotes.data.ExEquipSlot
import com.kasuminotes.data.UnitPromotion
import com.kasuminotes.data.UserData
import com.kasuminotes.ui.components.BadgedDiffBox
import com.kasuminotes.ui.components.DraggableImageIcon
import com.kasuminotes.ui.components.ImageIcon
import com.kasuminotes.ui.theme.GrayFilter
import com.kasuminotes.utils.UrlUtil
@Composable
fun CharaUserData(
userData: UserData,
originUserData: UserData,
maxUserData: MaxUserData,
maxRarity: Int,
hasUnique1: Boolean,
unitPromotion: UnitPromotion?,
unique1Data: UniqueData?,
unique2Data: UniqueData?,
exEquipSlots: List<ExEquipSlot>,
onEquipClick: (equipData: EquipData, slot: Int) -> Unit,
onUniqueClick: (uniqueData: UniqueData, slot: Int) -> Unit,
onExEquipClick: (ExEquipSlot) -> Unit,
onEquipChange: (equip: Boolean, slot: Int) -> Unit,
onUniqueChange: (equip: Boolean, slot: Int) -> Unit,
onCharaLevelChange: (Int) -> Unit,
onRarityChange: (Int) -> Unit,
onUniqueLevelChange: (value: Int, slot: Int) -> Unit,
onLoveLevelChange: (Int) -> Unit,
onPromotionLevelChange: (Int) -> Unit,
onSkillLevelChange: (value: Int, labelText: String) -> Unit,
onLvLimitBreakChange: (maxCharaLevel: Int) -> Unit
) {
Column(Modifier.padding(8.dp)) {
CharaStatus(
userData,
originUserData,
maxUserData,
maxRarity,
hasUnique1,
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 8.dp),
onCharaLevelChange,
onRarityChange,
onUniqueLevelChange,
onLoveLevelChange,
onPromotionLevelChange,
onSkillLevelChange
)
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 4.dp),
horizontalArrangement = Arrangement.SpaceBetween
) {
Column(horizontalAlignment = Alignment.Start) {
Box(Modifier.padding(start = 24.dp)) {
Unique1Icon(
userData.unique1Level,
unique1Data,
onUniqueClick,
onUniqueChange
)
}
Box(Modifier.padding(vertical = 4.dp)) {
Unique2Icon(
userData.unique2Level,
originUserData.unique2Level,
unique2Data,
onUniqueClick,
onUniqueChange
)
}
Box(Modifier.padding(start = 24.dp)) {
ImageIcon(
url = UrlUtil.getItemIconUrl(41000),
onClick = { onLvLimitBreakChange(maxUserData.maxCharaLevel) },
colorFilter = if (userData.lvLimitBreak > 0) null else GrayFilter
)
}
}
CharaEquipSlots(
userData,
originUserData,
unitPromotion,
onEquipClick,
onEquipChange
)
CharaExEquipSlots(
userData,
originUserData,
exEquipSlots,
onExEquipClick
)
}
}
}
@Composable
private fun Unique1Icon(
unique1Level: Int,
unique1Data: UniqueData?,
onClick: (UniqueData, Int) -> Unit,
onChange: (Boolean, Int) -> Unit
) {
if (unique1Data == null) {
ImageIcon(
painter = painterResource(R.drawable.unique_0),
loading = false,
enabled = false,
)
} else {
val isEquipped = unique1Level > 0
DraggableImageIcon(
url = UrlUtil.getEquipIconUrl(unique1Data.equipmentId),
onClick = { if (isEquipped) onClick(unique1Data, 1) else onChange(true, 1) },
onDragged = { onChange(!isEquipped, 1) },
colorFilter = if (isEquipped) null else GrayFilter
)
}
}
@Composable
private fun Unique2Icon(
unique2Level: Int,
originUnique2Level: Int,
unique2Data: UniqueData?,
onClick: (UniqueData, Int) -> Unit,
onChange: (Boolean, Int) -> Unit
) {
if (unique2Data == null) {
ImageIcon(
painter = painterResource(R.drawable.unique_0),
loading = false,
enabled = false,
)
} else {
val isEquipped = unique2Level > -1
BadgedDiffBox(unique2Level, originUnique2Level) {
DraggableImageIcon(
url = UrlUtil.getEquipIconUrl(unique2Data.equipmentId),
onClick = { if (isEquipped) onClick(unique2Data, 2) else onChange(true, 2) },
onDragged = { onChange(!isEquipped, 2) },
colorFilter = if (isEquipped) null else GrayFilter
) {
if (isEquipped) {
Row(
Modifier
.align(Alignment.BottomStart)
.fillMaxWidth()
.padding(2.dp)
) {
repeat(5) { i ->
Image(
painter = painterResource(
if (i < unique2Level) R.drawable.star_small_1
else R.drawable.star_small_0
),
contentDescription = null,
modifier = Modifier.size((8.8f).dp)
)
}
}
}
}
}
}
}
| 0
|
Kotlin
|
0
| 1
|
330d32057c4a86ee091cd9327e44cdf61235c38f
| 6,564
|
KasumiNotes
|
Apache License 2.0
|
src/test/kotlin/net/purefunc/kotlin/ddd/Sample.kt
|
PureFuncInc
| 509,896,101
| false
| null |
package net.purefunc.kotlin.ddd
import net.purefunc.kotlin.ddd.domain.entity.DomainAggRoot
import net.purefunc.kotlin.ddd.domain.entity.DomainEntity
import net.purefunc.kotlin.ddd.domain.entity.DomainEntityId
import net.purefunc.kotlin.ddd.domain.entity.DomainEvent
import net.purefunc.kotlin.ddd.domain.entity.DomainModifyCmd
import net.purefunc.kotlin.ddd.domain.vo.DomainVO
import net.purefunc.kotlin.ddd.infrastructure.enu.Deleted
import net.purefunc.kotlin.ddd.infrastructure.po.BasePo
data class SampleAggRoot(
val key: Key,
val value: String,
override val entityId: SampleId,
) : DomainAggRoot<SampleId>()
data class SampleEntity(
val key: Key,
override val entityId: SampleId,
) : DomainEntity<SampleId>()
data class SampleEvent(
val key: Key,
val name: String,
override val entityId: SampleId,
) : DomainEvent<SampleId>()
data class SampleModifyCmd(
val key: Key,
val value: String,
override val entityId: SampleId,
) : DomainModifyCmd<SampleId>()
data class SampleId(
override val uuid: Long,
override val createUser: String,
override val lastModifiedUser: String,
override val memo: String,
) : DomainEntityId()
data class Key(
override val memo: String,
) : DomainVO()
data class SamplePO(
val id: Long?,
override val uuid: Long,
override var deleted: Deleted,
override val createDate: Long,
override var lastModifiedDate: Long,
override val createUser: String,
override var lastModifiedUser: String,
override var memo: String,
override val version: Long,
) : BasePo()
| 0
|
Kotlin
|
0
| 8
|
3ac62aec9dd74c46f316bae92014bd4ba15a6436
| 1,589
|
kotlin-extensions
|
MIT License
|
app/src/main/java/com/dev334/swipe/module/MyApplication.kt
|
iamanantshukla
| 657,931,492
| false
| null |
package com.dev334.idog.module
import android.app.Application
import org.koin.android.ext.koin.androidContext
import org.koin.android.ext.koin.androidLogger
import org.koin.core.context.GlobalContext.startKoin
import org.koin.core.logger.Level
class MyApplication: Application() {
override fun onCreate() {
super.onCreate()
startKoin {
androidLogger(Level.ERROR)
androidContext(this@MyApplication)
modules(listOf( appModule))
}
}
}
| 0
|
Kotlin
|
0
| 0
|
32cd55684f2b7895767c7ba2b68c84a16ec7a6e8
| 502
|
iDog
|
MIT License
|
src/main/kotlin/de/uniwuerzburg/omod/core/PopulationDef.kt
|
L-Strobel
| 592,367,144
| false
| null |
package de.uniwuerzburg.omod.core
import kotlinx.serialization.Serializable
/**
* Definition of the agent population in terms of sociodemographic features
*/
@Serializable
data class PopulationDef (
val homogenousGroup: Map<HomogeneousGrp, Double>,
val mobilityGroup: Map<MobilityGrp, Double>,
val age: Map<AgeGrp, Double>
)
| 0
|
Kotlin
|
0
| 1
|
7878381f833b6545ff682a12b6c6aa68a255207c
| 341
|
omod
|
MIT License
|
demos/comida-app/src/main/kotlin/dev/tonycode/composed/comida/ui/screens/main/RestaurantCard.kt
|
tonycode
| 734,835,138
| false
|
{"Kotlin": 13282}
|
package dev.tonycode.composed.comida.ui.screens.main
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.size
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import dev.tonycode.composed.comida.ui.theme.ComidaAppTheme
import dev.tonycode.composed.comida.ui.theme.ComidaPalette
@Composable
fun RestaurantCard(
title: String,
) {
Surface(
shape = MaterialTheme.shapes.medium,
color = ComidaPalette.MistyBlue,
modifier = Modifier.size(width = 264.dp, height = 176.dp),
) {
Box(
modifier = Modifier.fillMaxWidth(),
contentAlignment = Alignment.Center,
) {
Text(
title,
style = MaterialTheme.typography.headlineMedium,
color = ComidaPalette.White,
)
}
}
}
@Preview
@Composable
private fun PreviewRestaurantCard() {
ComidaAppTheme {
Surface(
color = MaterialTheme.colorScheme.background,
modifier = Modifier.fillMaxWidth(),
) {
RestaurantCard("Seafood maki sushi")
}
}
}
| 0
|
Kotlin
|
0
| 0
|
99e9580b8a1e21acc46be76247325afc289861da
| 1,473
|
composed
|
MIT License
|
ohlot-domain/src/main/kotlin/ohlot/account/model/exception/LoginIdExistsException.kt
|
PCloud63514
| 429,459,130
| false
| null |
package ohlot.account.model.exception
private const val MSG: String = "이미 존재하는 아이디 입니다."
class LoginIdExistsException: RuntimeException(MSG)
| 0
|
Kotlin
|
0
| 0
|
e37809decf150a1d7fad79be10bde8aad9594ce0
| 142
|
ohlot-architecture-hexagonal-template
|
Apache License 2.0
|
app/src/main/java/com/example/socialapp/PostAdapter.kt
|
BolisettySujith
| 675,320,382
| false
| null |
package com.example.socialapp
import android.view.LayoutInflater
import android.view.OnReceiveContentListener
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.socialapp.models.Post
import com.firebase.ui.firestore.FirestoreRecyclerAdapter
import com.firebase.ui.firestore.FirestoreRecyclerOptions
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
class PostAdapter(options: FirestoreRecyclerOptions<Post>, val listener: IPostAdapter) : FirestoreRecyclerAdapter<Post, PostViewHolder>(
options
) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PostViewHolder {
val viewHolder = PostViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_post, parent, false))
viewHolder.likeButton.setOnClickListener{
listener.onLikeClicked(snapshots.getSnapshot(viewHolder.absoluteAdapterPosition).id)
}
return viewHolder
}
override fun onBindViewHolder(holder: PostViewHolder, position: Int, model: Post) {
holder.postText.text = model.text
holder.userText.text = model.createdBy.displayName
Glide.with(holder.userImage.context).load(model.createdBy.imageUrl).circleCrop().into(holder.userImage)
Glide.with(holder.postImage.context).load(model.postImageUrl).into(holder.postImage)
holder.likeCount.text = model.likedBy.size.toString()
holder.createdAt.text = Utils.getTimeAgo(model.createdAt)
val auth = Firebase.auth
val currentUserId = auth.currentUser!!.uid
val isLiked = model.likedBy.contains(currentUserId)
if(isLiked) {
holder.likeButton.setImageDrawable(ContextCompat.getDrawable(holder.likeButton.context, R.drawable.baseline_favorite_filled))
} else {
holder.likeButton.setImageDrawable(ContextCompat.getDrawable(holder.likeButton.context, R.drawable.baseline_favorite_border))
}
}
}
class PostViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
val postText: TextView = itemView.findViewById(R.id.postTitle)
val userText: TextView = itemView.findViewById(R.id.userName)
val createdAt: TextView = itemView.findViewById(R.id.createdAt)
val likeCount: TextView = itemView.findViewById(R.id.likeCount)
val userImage: ImageView = itemView.findViewById(R.id.userImage)
val postImage: ImageView = itemView.findViewById(R.id.postImages)
val likeButton: ImageView = itemView.findViewById(R.id.likeButton)
}
interface IPostAdapter{
fun onLikeClicked(postId: String)
}
| 0
|
Kotlin
|
0
| 0
|
4aa62026094998f43105fb52f65f1c60e4eda050
| 2,763
|
Post-It
|
MIT License
|
src/main/kotlin/data/graph_save/GraphSaverUnified.kt
|
spbu-coding-2023
| 790,909,287
| false
|
{"Kotlin": 152697}
|
package data.graph_save
import model.graph_model.Graph
import java.nio.file.Path
fun graphSaveUnified(path: String, graph: Graph<*>) {
when {
path.endsWith(".graphml") -> saveGraphML(path, graph)
}
}
| 3
|
Kotlin
|
0
| 1
|
2484a51767bc30093a810fa3af8077a97f0e007a
| 217
|
graphs-team-11
|
MIT License
|
idea/tests/testData/quickfix/typeMismatch/wrapWithCollectionLiteral/toArray.kt
|
JetBrains
| 278,369,660
| false
| null |
// "Wrap element with 'arrayOf()' call" "true"
// WITH_RUNTIME
fun foo(a: String) {
bar(a<caret>)
}
fun bar(a: Array<String>) {}
| 0
| null |
30
| 82
|
cc81d7505bc3e9ad503d706998ae8026c067e838
| 135
|
intellij-kotlin
|
Apache License 2.0
|
app/src/main/kotlin/com/github/xero/istheapp/ui/adapters/notifyadapter/InterfaceNotifyMessageAdapter.kt
|
eurosabuj
| 243,512,293
| false
|
{"Kotlin": 475240, "Java": 997}
|
package com.github.xero.istheapp.ui.adapters.notifyadapter
import com.github.xero.istheapp.ui.adapters.basedapter.InterfaceAdapter
/**
* Created by luis rafael on 20/03/18.
*/
interface InterfaceNotifyMessageAdapter : InterfaceAdapter{
fun onItemClick(key: String?, child: String,position:Int)
fun onItemLongClick(key: String?, child: String,position:Int)
}
| 0
|
Kotlin
|
0
| 0
|
aac16d6f41eaa4b38ddaa6a3c79079ed77e3bc8f
| 370
|
spy-app
|
Apache License 2.0
|
secdra-admin/src/main/kotlin/com/junjie/secdraadmin/controller/UserController.kt
|
lipstick-49
| 208,569,806
| true
|
{"Kotlin": 244725, "HTML": 4151}
|
package com.junjie.secdraadmin.controller
import com.junjie.secdraaccount.service.AccountService
import com.junjie.secdradata.constant.Gender
import com.junjie.secdradata.database.primary.dao.UserDAO
import com.junjie.secdradata.database.primary.entity.User
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.io.File
import java.util.*
@RestController
@RequestMapping("user")
class UserController(private val userDAO: UserDAO, private val accountService: AccountService) {
@GetMapping("i")
fun i(): Int {
val list = userDAO.findAll()
var j = 0
for (item in list) {
j++
val account = accountService.signUp(j.toString(), "123456", Date())
item.accountId = account.id!!
userDAO.save(item)
}
return j
}
@PostMapping("init")
fun init(headPath: String, backPath: String, nameList: List<String>? = listOf("北梦木兮", "南国旧事", "醉酒盛唐", "浮生若茶", "潇湘书笛", "南笙一梦", "红颜知己", "犹寒眉心砂", "时光巷陌", "古道琴台", "乌衣巷口", "城春草木深", "几味老友", "乱世皆烽火", "乱世逐鹿", "难觅旧知音", "诗禅", "借月留云", "笑醉歌寒", "佳人远嫁", "浊酒贪杯", "执墨欲书", "江山美人策", "醉卧红尘", "醉卧青丝衫", "金戈伴铁马", "故人还说着旧梦", "素衫青布白少年", "枕上诗书闲", "酌酒弄弦", "世俗儒生", "时间煮雨", "江南过客", "一曲诀别诗", "浊酒几杯", "弹指红颜", "醉卧红尘外", "相顾无言", "茶饮三道", "半路酒家", "故人不归", "战场书生", "青衫烟雨", "一介書生", "疏影横窗君暗数", "温酒烫眉山", "青衣沽酒醉风尘", "咖啡不懂酒的醉", "清风烈酒", "粗茶布衣", "独赏雨雪纷飞?", "隔岸灯火欲将心事亲藏?", "情人醉倒在花海水乡?", "一缕冷香远", "一别几春", "青丝断情", "春雨浴指", "琴音调齐", "深秋愁凉", "绝望抹杀了期待", "继短半山居人", "如梦无痕", "浊发清眸", "今生他是谁", "挽留你的歌", "残缺韵律", "七分少女心.", "海以南不再蓝.", "一夕夙愿", "落满城月", "浮生若伤", "共茶谈笑", "来日岁月", "浮生尽歇", "及故人", "空城旧人", "红颜一笑醉倾城", "西北望长安", "墨袖留香", "轻纱青衣", "情之所钟", "右耳离心", "衣香鬓影")) {
}
}
| 0
| null |
0
| 0
|
b4317e70fad3256c82a9c418cb2aa25fe14ef62f
| 1,843
|
secdra
|
MIT License
|
tokisaki-function/src/main/kotlin/io/micro/function/infra/converter/ImageMapper.kt
|
spcookie
| 730,690,607
| false
|
{"Kotlin": 224366, "Java": 21819}
|
package io.micro.function.infra.converter
import io.micro.function.domain.image.model.Image
import io.micro.function.domain.image.model.entity.AnimeCartoon
import io.micro.function.domain.image.model.entity.Girl
import io.micro.function.infra.po.ImagePO
import io.micro.function.types.ImageCategory
import jakarta.inject.Singleton
import org.mapstruct.AfterMapping
import org.mapstruct.MappingTarget
/**
*@author Augenstern
*@since 2023/10/12
*/
@Singleton
class ImageMapper {
@AfterMapping
fun imageToImagePO(image: Image, @MappingTarget po: ImagePO) {
when (image) {
is Girl -> po.apply { category = ImageCategory.GIRL }
is AnimeCartoon -> po.apply { category = ImageCategory.ANIME }
else -> throw IllegalArgumentException("不能映射: $image -> ImagePO")
}
}
}
| 0
|
Kotlin
|
0
| 0
|
a0fb4013d85fc51e83754b2f0a21fe0920d71a8d
| 828
|
Tokisaki
|
Apache License 2.0
|
ThingsflowProject/app/src/main/java/com/dodopa/thingsflowproject/viewholder/EmptyViewHolder.kt
|
dodopa
| 304,207,044
| false
| null |
package com.dodopa.thingsflowproject.viewholder
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.dodopa.thingsflowproject.R
import com.dodopa.thingsflowproject.databinding.ListItemImageIssueBinding
class EmptyViewHolder(
parent: ViewGroup,
view: View = LayoutInflater.from(parent.context)
.inflate(R.layout.list_item_empty, parent, false)
) : SmartViewHolder(view)
| 10
|
Kotlin
|
0
| 0
|
65b1083e7e6cceb65e54f38220eb860c26893e90
| 541
|
thigsflow_project
|
Apache License 2.0
|
time/src/commonMain/kotlin/com/merseyside/merseyLib/time/FormattedDate.kt
|
Merseyside
| 396,607,192
| false
|
{"Kotlin": 107114, "Swift": 13697, "Ruby": 1888, "Shell": 119}
|
package com.merseyside.merseyLib.time
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
@Serializable(with = StringAsFormattedDateSerializer::class)
open class FormattedDate (val date: String) {
override fun toString(): String {
return date
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is FormattedDate) return false
if (date != other.date) return false
return true
}
override fun hashCode(): Int {
return date.hashCode()
}
companion object {
fun empty(): FormattedDate = FormattedDate("")
}
}
fun FormattedDate.isEmpty() = date.isEmpty()
class StringAsFormattedDateSerializer : KSerializer<FormattedDate> {
override val descriptor: SerialDescriptor =
PrimitiveSerialDescriptor(
"com.merseyside.merseyLib.time.StringAsFormattedDateSerializer",
PrimitiveKind.STRING
)
override fun deserialize(decoder: Decoder): FormattedDate {
return FormattedDate(decoder.decodeString())
}
override fun serialize(encoder: Encoder, value: FormattedDate) {
encoder.encodeString(value.date)
}
}
| 0
|
Kotlin
|
0
| 0
|
03ad897c5c471b4d2347ba3a5c5dcd05a444d2f3
| 1,501
|
mersey-kmp-time
|
Apache License 2.0
|
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsmanageprisonvisitsorchestration/dto/orchestration/PrisonDto.kt
|
ministryofjustice
| 575,484,836
| false
|
{"Kotlin": 770674, "Dockerfile": 1166}
|
package uk.gov.justice.digital.hmpps.hmppsmanageprisonvisitsorchestration.dto.orchestration
import io.swagger.v3.oas.annotations.media.Schema
import jakarta.validation.constraints.Min
import uk.gov.justice.digital.hmpps.hmppsmanageprisonvisitsorchestration.dto.prison.register.PrisonRegisterPrisonDto
import uk.gov.justice.digital.hmpps.hmppsmanageprisonvisitsorchestration.dto.visit.scheduler.PrisonUserClientDto
import uk.gov.justice.digital.hmpps.hmppsmanageprisonvisitsorchestration.dto.visit.scheduler.VisitSchedulerPrisonDto
import java.time.LocalDate
@Schema(description = "Prison dto")
data class PrisonDto(
@Schema(description = "prison code", example = "BHI", required = true)
val code: String,
@Schema(description = "prison name", example = "<NAME>", required = true)
val prisonName: String,
@Schema(description = "is prison active", example = "true", required = true)
val active: Boolean = false,
@Schema(description = "minimum number of days notice from the current date to booked a visit", example = "2", required = true)
val policyNoticeDaysMin: Int,
@Schema(description = "maximum number of days notice from the current date to booked a visit", example = "28", required = true)
val policyNoticeDaysMax: Int,
@Schema(description = "Max number of total visitors")
@field:Min(1)
val maxTotalVisitors: Int,
@Schema(description = "Max number of adults")
@field:Min(1)
val maxAdultVisitors: Int,
@Schema(description = "Max number of children")
@field:Min(0)
val maxChildVisitors: Int,
@Schema(description = "Age of adults in years")
val adultAgeYears: Int,
@Schema(description = "exclude dates", required = false)
val excludeDates: Set<LocalDate> = setOf(),
@Schema(description = "prison user client", required = false)
val clients: List<PrisonUserClientDto> = listOf(),
) {
constructor(visitSchedulerPrisonDto: VisitSchedulerPrisonDto, prisonRegisterPrisonDto: PrisonRegisterPrisonDto) : this(
code = visitSchedulerPrisonDto.code,
prisonName = prisonRegisterPrisonDto.prisonName,
active = visitSchedulerPrisonDto.active,
policyNoticeDaysMin = visitSchedulerPrisonDto.policyNoticeDaysMin,
policyNoticeDaysMax = visitSchedulerPrisonDto.policyNoticeDaysMax,
maxTotalVisitors = visitSchedulerPrisonDto.maxTotalVisitors,
maxAdultVisitors = visitSchedulerPrisonDto.maxAdultVisitors,
maxChildVisitors = visitSchedulerPrisonDto.maxChildVisitors,
adultAgeYears = visitSchedulerPrisonDto.adultAgeYears,
excludeDates = visitSchedulerPrisonDto.excludeDates,
clients = visitSchedulerPrisonDto.clients,
)
}
| 3
|
Kotlin
|
0
| 4
|
91e614a4f2ee1101c96221a69c6fdf68a5b7b720
| 2,615
|
hmpps-manage-prison-visits-orchestration
|
MIT License
|
mastodon4j/src/main/java/com/sys1yagi/mastodon4j/api/entity/History.kt
|
andehr
| 266,110,095
| true
|
{"Gradle": 6, "YAML": 1, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Java": 4, "Kotlin": 97, "JSON": 26}
|
package com.sys1yagi.mastodon4j.api.entity
import com.google.gson.annotations.SerializedName
/**
* Created by <NAME> on 22/05/2020.
*/
data class History (
@SerializedName("day") val day: Long = 0L,
@SerializedName("uses") val uses: Int = 0,
@SerializedName("accounts") val accounts: Int = 0){
}
| 1
|
Kotlin
|
0
| 0
|
fd22346ed920a8da21c38b0b2b9facb3f23baa1e
| 311
|
mastodon4j
|
MIT License
|
app/src/main/java/de/rauschdo/animals/fragments/web/WebFragment.kt
|
rauschdo
| 752,729,154
| false
|
{"Kotlin": 246779, "Java": 32524}
|
package de.rauschdo.animals.fragments.web
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.KeyEvent
import android.view.MenuItem
import android.view.View
import android.webkit.HttpAuthHandler
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import de.rauschdo.animals.Constants
import de.rauschdo.animals.R
import de.rauschdo.animals.architecture.BaseFragment
import de.rauschdo.animals.databinding.FragmentWebBinding
import de.rauschdo.animals.utility.detailBinding
class WebFragment : BaseFragment<FragmentWebBinding>(R.layout.fragment_web) {
private val args: WebFragmentArgs by navArgs()
private var useNavHost = false
companion object {
fun create(url: String, useNavHost: Boolean) = WebFragment().apply {
arguments = Bundle().apply {
putString(Constants.EXTRA_URL, url)
putBoolean(Constants.EXTRA_USES_NAV_HOST, useNavHost)
}
}
}
@SuppressLint("SetJavaScriptEnabled")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding {
useNavHost = arguments?.getBoolean(Constants.EXTRA_USES_NAV_HOST, false) ?: false
if (args.url != null || arguments?.containsKey(Constants.EXTRA_URL) == true) {
webview.apply {
webViewClient = object : WebViewClient() {
override fun onReceivedHttpAuthRequest(
v: WebView?,
h: HttpAuthHandler?,
host: String?,
r: String?
) {
}
override fun onPageFinished(view: WebView?, url: String?) {
webOverlayTitle.text = view?.title
}
}
settings.javaScriptEnabled = true
setOnKeyListener(object : View.OnKeyListener {
override fun onKey(v: View, keyCode: Int, event: KeyEvent): Boolean {
if (event.action == KeyEvent.ACTION_DOWN) {
(v as? WebView)?.let { webView ->
when (keyCode) {
KeyEvent.KEYCODE_BACK -> if (webView.canGoBack()) {
webView.goBack()
return true
}
}
}
}
return false
}
})
when {
args.url != null -> {
args.url?.let {
loadUrl(it)
}
}
arguments?.get(Constants.EXTRA_URL) != null -> {
arguments?.get(Constants.EXTRA_URL)?.let {
loadUrl(it as String)
}
}
else -> onBackPressed()
}
}
} else {
destroyFragment()
}
}
}
private fun destroyFragment() {
if (useNavHost) {
findNavController().popBackStack()
} else {
detailBinding {
containerFragment.visibility = View.GONE
}
parentFragmentManager.popBackStack()
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
destroyFragment()
return true
}
}
return super.onOptionsItemSelected(item)
}
}
| 0
|
Kotlin
|
0
| 0
|
d193a3850a84cdcc591d2c1940711a84539ca98d
| 4,097
|
animals
|
MIT License
|
domain/src/main/kotlin/no/nav/su/se/bakover/domain/beregning/fradrag/Fradragstype.kt
|
navikt
| 227,366,088
| false
| null |
package no.nav.su.se.bakover.domain.beregning.fradrag
import arrow.core.Either
import arrow.core.left
import arrow.core.right
enum class Fradragstype {
NAVytelserTilLivsopphold,
Arbeidsinntekt,
OffentligPensjon,
PrivatPensjon,
Sosialstønad,
Kontantstøtte,
Introduksjonsstønad,
Kvalifiseringsstønad,
BidragEtterEkteskapsloven,
Kapitalinntekt,
ForventetInntekt,
AvkortingUtenlandsopphold,
/**
* Resulting type of the operation that calculates EPS fradrag to be included in brukers beregning.
* Represents a "mixed bag" of fradrag that in total exceeds the respecive limits given by §5 and §6.
* Not to be used for input-operations (i.e. from frontend).
*/
BeregnetFradragEPS,
UnderMinstenivå;
companion object {
fun tryParse(value: String): Either<UgyldigFradragstype, Fradragstype> {
return values().firstOrNull { it.name == value }?.right() ?: UgyldigFradragstype.left()
}
}
object UgyldigFradragstype
}
| 6
|
Kotlin
|
0
| 0
|
b0864f973c8986f58af07c4bc7f601caa602dbfc
| 1,032
|
su-se-bakover
|
MIT License
|
rtron-transformer/src/main/kotlin/io/rtron/transformer/opendrive2roadspaces/analysis/FunctionBuilder.kt
|
tum-gis
| 258,142,903
| false
| null |
/*
* Copyright 2019-2022 Chair of Geoinformatics, Technical University of Munich
*
* 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 io.rtron.transformer.opendrive2roadspaces.analysis
import io.rtron.io.logging.Logger
import io.rtron.math.analysis.function.univariate.UnivariateFunction
import io.rtron.math.analysis.function.univariate.combination.ConcatenatedFunction
import io.rtron.math.analysis.function.univariate.combination.SectionedUnivariateFunction
import io.rtron.math.analysis.function.univariate.combination.StackedFunction
import io.rtron.math.analysis.function.univariate.pure.LinearFunction
import io.rtron.math.geometry.euclidean.threed.curve.Curve3D
import io.rtron.model.opendrive.road.lanes.RoadLanes
import io.rtron.model.opendrive.road.lanes.RoadLanesLaneSectionLRLaneWidth
import io.rtron.model.opendrive.road.lateralprofile.RoadLateralProfileShape
import io.rtron.model.opendrive.road.lateralprofile.RoadLateralProfileSuperelevation
import io.rtron.model.opendrive.road.objects.RoadObjectsObjectRepeat
import io.rtron.model.roadspaces.roadspace.RoadspaceIdentifier
import io.rtron.model.roadspaces.roadspace.road.LaneIdentifier
import io.rtron.std.filterToStrictSortingBy
import io.rtron.std.handleAndRemoveFailure
import io.rtron.transformer.opendrive2roadspaces.configuration.Opendrive2RoadspacesConfiguration
/**
* Builder for functions of the OpenDRIVE data model.
*/
class FunctionBuilder(
private val reportLogger: Logger,
private val configuration: Opendrive2RoadspacesConfiguration
) {
// Methods
/**
* Builds a function that describes the torsion of the road reference line.
*
* @param superelevation entries containing coefficients for polynomial functions
*/
fun buildCurveTorsion(id: RoadspaceIdentifier, superelevation: List<RoadLateralProfileSuperelevation>):
UnivariateFunction {
if (superelevation.isEmpty()) return LinearFunction.X_AXIS
val superelevationEntriesAdjusted = superelevation
.filterToStrictSortingBy { it.s }
if (superelevationEntriesAdjusted.size < superelevation.size)
this.reportLogger.info(
"Removing superelevation entries which are not placed in strict order" +
" according to s.",
id.toString()
)
return ConcatenatedFunction.ofPolynomialFunctions(
superelevationEntriesAdjusted.map { it.s },
superelevationEntriesAdjusted.map { it.coefficients },
prependConstant = true,
prependConstantValue = 0.0
)
}
/**
* Builds a function that describes one lateral entry of a road's shape.
*
* @param roadLateralProfileShape the cross-sectional profile of a road at a certain curve position
*/
fun buildLateralShape(id: RoadspaceIdentifier, roadLateralProfileShape: List<RoadLateralProfileShape>):
UnivariateFunction {
require(roadLateralProfileShape.isNotEmpty()) { "Lateral profile shape must contain elements in order to build a univariate function." }
require(roadLateralProfileShape.all { it.s == roadLateralProfileShape.first().s }) { "All lateral profile shape elements must have the same curve position." }
val lateralProfileEntriesAdjusted = roadLateralProfileShape
.filterToStrictSortingBy { it.t }
if (lateralProfileEntriesAdjusted.size < roadLateralProfileShape.size)
this.reportLogger.info(
"Removing lateral profile entries which are not placed in strict order " +
"according to t.",
id.toString()
)
return ConcatenatedFunction.ofPolynomialFunctions(
lateralProfileEntriesAdjusted.map { it.t },
lateralProfileEntriesAdjusted.map { it.coefficients },
prependConstant = true
)
}
/**
* Builds a function that described the lateral lane offset to the road reference line.
*/
fun buildLaneOffset(id: RoadspaceIdentifier, lanes: RoadLanes): UnivariateFunction {
if (lanes.laneOffset.isEmpty()) return LinearFunction.X_AXIS
val laneOffsetEntriesAdjusted = lanes.laneOffset.filterToStrictSortingBy { it.s }
if (laneOffsetEntriesAdjusted.size < lanes.laneOffset.size)
this.reportLogger.info(
"Removing lane offset entries which are not placed in strict order " +
"according to s.",
id.toString()
)
return ConcatenatedFunction.ofPolynomialFunctions(
laneOffsetEntriesAdjusted.map { it.s },
laneOffsetEntriesAdjusted.map { it.coefficients },
prependConstant = true,
prependConstantValue = 0.0
)
}
/**
* Builds a function that describes the lane width.
*
* @param laneWidthEntries entries containing coefficients for polynomial functions
* @param id identifier of the lane, required for logging output
* @return function describing the width of a lane
*/
fun buildLaneWidth(id: LaneIdentifier, laneWidthEntries: List<RoadLanesLaneSectionLRLaneWidth>):
UnivariateFunction {
val widthEntriesProcessable = laneWidthEntries.map { it.getAsResult() }.handleAndRemoveFailure { reportLogger.log(it, id.toString(), "Removing width entry.") }
if (widthEntriesProcessable.isEmpty()) {
this.reportLogger.info(
"The lane does not contain any valid width entries. " +
"Continuing with a zero width.",
id.toString()
)
return LinearFunction.X_AXIS
}
if (widthEntriesProcessable.first().sOffset > 0.0)
this.reportLogger.info(
"The width should be defined for the full length of the lane section and" +
" thus must also be defined for s=0.0. Not defined positions are interpreted with a width of 0.",
id.toString()
)
val widthEntriesAdjusted = widthEntriesProcessable
.filterToStrictSortingBy { it.sOffset }
if (widthEntriesAdjusted.size < widthEntriesProcessable.size)
this.reportLogger.info(
"Removing width entries which are not in strict order according to sOffset.",
id.toString()
)
return ConcatenatedFunction.ofPolynomialFunctions(
widthEntriesAdjusted.map { it.sOffset },
widthEntriesAdjusted.map { it.coefficients },
prependConstant = true,
prependConstantValue = 0.0
)
}
/**
* Returns the absolute height function of a [RoadObjectsObjectRepeat] object. Therefore a linear function is build
* for the zOffsets and is added to the height function of the [roadReferenceLine].
*
* @param repeat object for which the height function shall be constructed
* @param roadReferenceLine road's height
* @return function of the object's absolute height
*/
fun buildStackedHeightFunctionFromRepeat(repeat: RoadObjectsObjectRepeat, roadReferenceLine: Curve3D):
StackedFunction {
val heightFunctionSection = SectionedUnivariateFunction(
roadReferenceLine.heightFunction,
repeat.getRoadReferenceLineParameterSection()
)
return StackedFunction.ofSum(heightFunctionSection, repeat.getHeightOffsetFunction())
}
}
| 4
| null |
8
| 26
|
5d7013f8d0e0b65418c0256211d39dc28b71d019
| 8,003
|
rtron
|
Apache License 2.0
|
app/src/main/java/com/inc/sada_pay_test/util/Constants.kt
|
AtifAbbAsi19
| 504,501,910
| false
| null |
package com.inc.sada_pay_test.util
object Constants {
val ANDROID: String ="android"
val DEVICE_TYPE: String ="x-device"
const val BASE_URL ="https://api.github.com/"
const val PREFERENCES_STORE_NAME ="setting"
}
| 0
|
Kotlin
|
0
| 0
|
138d565cba2a2ed38ee01225751cb1521baa4aab
| 232
|
trending-repositories
|
Apache License 2.0
|
app/sepuling-kotlin/src/main/kotlin/smecalculus/bezmen/messaging/SepulkaClientImpl.kt
|
smecalculus
| 481,685,166
| false
|
{"Maven POM": 15, "Text": 4, "Ignore List": 3, "AsciiDoc": 10, "Java": 102, "INI": 9, "PlantUML": 1, "Dockerfile": 10, "Jinja": 7, "YAML": 46, "Kotlin": 20, "SQL": 7, "XML": 2}
|
package smecalculus.bezmen.messaging
import smecalculus.bezmen.core.SepulkaService
import smecalculus.bezmen.messaging.SepulkaMessageEm.RegistrationRequest
import smecalculus.bezmen.messaging.SepulkaMessageEm.RegistrationResponse
import smecalculus.bezmen.messaging.SepulkaMessageEm.ViewingRequest
import smecalculus.bezmen.messaging.SepulkaMessageEm.ViewingResponse
import smecalculus.bezmen.validation.EdgeValidator
class SepulkaClientImpl(
private val validator: EdgeValidator,
private val mapper: SepulkaMessageMapper,
private val service: SepulkaService,
) : SepulkaClient {
override fun register(requestEdge: RegistrationRequest): RegistrationResponse {
validator.validate(requestEdge)
val request = mapper.toDomain(requestEdge)
val response = service.register(request)
return mapper.toEdge(response)
}
override fun view(requestEdge: ViewingRequest): ViewingResponse {
validator.validate(requestEdge)
val request = mapper.toDomain(requestEdge)
val response = service.view(request)
return mapper.toEdge(response)
}
}
| 11
|
Java
|
0
| 0
|
c39dfa4126a55f2b01dbab7448d6e9c09f2f4fc5
| 1,117
|
bezmen
|
MIT License
|
v2.x/Showcase/app/src/main/kotlin/com/scichart/scishowcase/MainActivity.kt
|
tosky102
| 141,718,404
| true
|
{"Markdown": 1, "Java Properties": 28, "Shell": 14, "Batchfile": 14, "Proguard": 14, "Java": 187, "Kotlin": 61}
|
//******************************************************************************
// SCICHART® Copyright SciChart Ltd. 2011-2017. All rights reserved.
//
// Web: http://www.scichart.com
// Support: support@scichart.com
// Sales: sales@scichart.com
//
// MainActivity.kt is part of the SCICHART® Showcases. Permission is hereby granted
// to modify, create derivative works, distribute and publish any part of this source
// code whether for commercial, private or personal use.
//
// The SCICHART® examples are distributed in the hope that they will be useful, but
// without any warranty. It is provided "AS IS" without warranty of any kind, either
// expressed or implied.
//******************************************************************************
package com.scichart.scishowcase
import android.Manifest
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.View
import com.scichart.charting.themes.ThemeManager
import com.scichart.core.annotations.Visibility
import com.scichart.scishowcase.databinding.ActivityMainBinding
import com.scichart.scishowcase.utils.PermissionManager
import com.scichart.scishowcase.views.HomePageFragment
// The main activity for the application
class MainActivity : AppCompatActivity() {
private var activityBinding: ActivityMainBinding? = null
private val permissionManager = PermissionManager(this)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
activityBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
setUpSciChartLicense()
requestShowcasePermissions()
initAppBar()
setUpThemes()
supportFragmentManager.beginTransaction().replace(R.id.fragment_container, HomePageFragment()).commit()
supportFragmentManager.addOnBackStackChangedListener {
val isBackStackEmpty = supportFragmentManager.backStackEntryCount > 0
supportActionBar!!.setDisplayHomeAsUpEnabled(isBackStackEmpty)
activityBinding!!.logo.visibility = if (isBackStackEmpty) View.GONE else View.VISIBLE
}
}
private fun setUpThemes() {
ThemeManager.addTheme(this, R.style.SciChart_Bright_Spark)
}
private fun requestShowcasePermissions() {
// permissions for Audio Analyzer
permissionManager.requestPermission(Manifest.permission.RECORD_AUDIO)
permissionManager.requestPermission(Manifest.permission.MODIFY_AUDIO_SETTINGS)
// permissions for SciTrader
permissionManager.requestPermission(Manifest.permission.INTERNET)
permissionManager.requestPermission(Manifest.permission.ACCESS_NETWORK_STATE)
}
private fun initAppBar() {
setSupportActionBar(activityBinding!!.appToolbar)
activityBinding!!.appToolbar.setNavigationOnClickListener({ onBackPressed() })
}
private fun setUpSciChartLicense() {
// Set your license code here to license the SciChart Android Examples app
// You can get a trial license key from https://www.scichart.com/licensing-scichart-android/
// Purchased license keys can be viewed at https://www.scichart.com/profile
//
// e.g.
//
// com.scichart.charting.visuals.SciChartSurface.setRuntimeLicenseKey(
// "<LicenseContract>" +
// "<Customer>your-email@company.com</Customer>" +
// "<OrderId>Trial</OrderId>" +
// "<LicenseCount>1</LicenseCount>" +
// "<IsTrialLicense>true</IsTrialLicense>" +
// "<SupportExpires>12/21/2017 00:00:00</SupportExpires>" +
// "<ProductCode>SC-ANDROID-2D-ENTERPRISE-SRC</ProductCode>" +
// "<KeyCode>6ccc960b22b7b12360a141a7c2a89bce4e40.....09744b6c195022e9fa1ebcf9a0e78167cbaa8f9b8eee9221</KeyCode>" +
// "</LicenseContract>"
// );
try {
com.scichart.charting.visuals.SciChartSurface.setRuntimeLicenseKey("")
} catch (e: Exception) {
Log.e("SciChart", "Error when setting the license", e)
}
}
}
| 0
|
Java
|
0
| 1
|
ad34c990635e3a0779f7e9fce2585c643a63a5f9
| 4,259
|
SciChart.Android.Examples
|
MIT License
|
app/src/main/java/com/lifesolutions/bd/kotlinCode/utils/Notification.kt
|
alamin1x0
| 601,487,426
| false
|
{"Java": 2650731, "Kotlin": 822798, "Assembly": 59}
|
package com.lifesolutions.bd.kotlinCode.utils
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import com.lifesolutions.bd.Activities.CallScreenActivity
import com.lifesolutions.bd.R
import com.lifesolutions.bd.kotlinCode.constant.AppConstant
import com.lifesolutions.bd.kotlinCode.services.NotificationReceiver
class Notification(private val context: Context) {
fun ongoingCallNotification() {
val intent = Intent(context, CallScreenActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
intent.putExtra("message", "Hello")
val pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_ONE_SHOT)
// val intentAction = Intent(this, NotificationReceiver::class.java)
// intentAction.putExtra("CALL_ACTION", notificationActionData)
// val pendingIntentTest =
// PendingIntent.getBroadcast(this, 12345, intentAction, PendingIntent.FLAG_UPDATE_CURRENT)
//Yes intent
val yesReceive = Intent(context, NotificationReceiver::class.java)
yesReceive.action = AppConstant.YES_ACTION
val pendingIntentYes =
PendingIntent.getBroadcast(context, AppConstant.INCOMING_CALL_REQ_CODE, yesReceive, PendingIntent.FLAG_UPDATE_CURRENT)
//No intent
val noReceive = Intent(context, NotificationReceiver::class.java)
noReceive.action = AppConstant.STOP_ACTION
val pendingIntentNo =
PendingIntent.getBroadcast(context, AppConstant.INCOMING_CALL_REQ_CODE, noReceive, PendingIntent.FLAG_UPDATE_CURRENT)
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
// val notificationId = Random.nextInt()
val notificationId = AppConstant.INC_CALL_NOTIFY_ID
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createNotificationChannel(notificationManager)
}
val notification = NotificationCompat.Builder(context, AppConstant.INC_CALL_CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(context.resources, R.drawable.app_icon))
.setColor(ContextCompat.getColor(context, R.color.colorMain))
.setContentTitle(context.getString(R.string.hello))
.setContentText("This is Notification Description")
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setCategory(NotificationCompat.CATEGORY_CALL)
.setAutoCancel(true)
.setOngoing(true)
.addAction(R.drawable.ic_video_call_icon, "Home", pendingIntentYes)
.addAction(R.drawable.ic_video_call_icon, "End Call", pendingIntentNo)
.build()
notificationManager.notify(notificationId, notification)
}
@RequiresApi(Build.VERSION_CODES.O)
private fun createNotificationChannel(notificationManager: NotificationManager) {
val channel = NotificationChannel(AppConstant.INC_CALL_CHANNEL_ID, AppConstant.INC_CALL_CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH).apply {
description = "My channel description"
enableLights(true)
lightColor = Color.GREEN
}
notificationManager.createNotificationChannel(channel)
}
}
| 1
| null |
1
| 1
|
87b3217cedb0340417a8a0fae3b0ef2741ad9012
| 3,806
|
Lifesolutions
|
BSD Source Code Attribution
|
potassium-nitrite/src/main/kotlin/org/dizitart/kno2/Nitrite.kt
|
lamba92
| 701,275,830
| true
|
{"YAML": 7, "Gradle Kotlin DSL": 10, "Markdown": 11, "Shell": 1, "EditorConfig": 1, "Batchfile": 1, "Ignore List": 1, "Java": 1002, "XML": 7, "SVG": 1, "Kotlin": 20, "TOML": 1, "INI": 1}
|
/*
* Copyright (c) 2017-2020. Nitrite author or authors.
*
* 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 org.dizitart.kno2
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.builtins.serializer
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import org.dizitart.no2.Nitrite
import org.dizitart.no2.collection.NitriteCollection
import org.dizitart.no2.collection.NitriteId
import org.dizitart.no2.common.module.NitriteModule.module
import org.dizitart.no2.common.module.NitritePlugin
import org.dizitart.no2.common.tuples.Pair
import org.dizitart.no2.index.IndexOptions
import org.dizitart.no2.index.IndexType
import org.dizitart.no2.repository.EntityDecorator
import org.dizitart.no2.repository.ObjectRepository
/**
* @since 2.1.0
* @author <NAME>
*/
/**
* Opens a named collection from the store. If the collection does not exist it will be created
* automatically and returned. If a collection is already opened, it is returned as is.
*
* Returned collection is thread-safe for concurrent use.
*
* The name cannot contain below reserved strings:
*
* - {@link Constants#INTERNAL_NAME_SEPARATOR}
* - {@link Constants#USER_MAP}
* - {@link Constants#INDEX_META_PREFIX}
* - {@link Constants#INDEX_PREFIX}
* - {@link Constants#OBJECT_STORE_NAME_SEPARATOR}
*
* @param [name] name of the collection
* @param [op] collection builder block
* @return the collection with the given name
*/
fun Nitrite.getCollection(
name: String,
op: (NitriteCollection.() -> Unit)? = null
): NitriteCollection {
val collection = this.getCollection(name)
op?.invoke(collection)
return collection
}
/**
* Opens a type-safe object repository from the store. If the repository does not exist it will be
* created automatically and returned. If a repository is already opened, it is returned as is.
*
* The returned repository is thread-safe for concurrent use.
*
* @param [T] type parameter
* @param [op] repository builder block
* @return the repository of type [T]
*/
inline fun <reified T : Any> Nitrite.getRepository(
noinline op: (ObjectRepository<T>.() -> Unit)? = null
): ObjectRepository<T> {
val repository = this.getRepository(T::class.java)
op?.invoke(repository)
return repository
}
/**
* Opens a type-safe object repository with a key identifier from the store. If the repository does
* not exist it will be created automatically and returned. If a repository is already opened, it is
* returned as is.
*
* The returned repository is thread-safe for concurrent use.
*
* @param [T] type parameter
* @param key the key that will be appended to the repositories name
* @param [op] repository builder block
* @return the repository of type [T]
*/
inline fun <reified T : Any> Nitrite.getRepository(
key: String,
noinline op: (ObjectRepository<T>.() -> Unit)? = null
): ObjectRepository<T> {
val repository = this.getRepository(T::class.java, key)
op?.invoke(repository)
return repository
}
/**
* Opens a type-safe object repository using a {@link EntityDecorator}. If the
* repository does not exist it will be created automatically and returned.
* If a repository is already opened, it is returned as is.
* <p>
* The returned repository is thread-safe for concurrent use.
*
* @param [T] type parameter
* @param [entityDecorator] the entityDecorator
* @return the repository of type [T]
*/
inline fun <reified T : Any> Nitrite.getRepository(
entityDecorator: EntityDecorator<T>,
noinline op: (ObjectRepository<T>.() -> Unit)? = null
): ObjectRepository<T> {
val repository = this.getRepository(entityDecorator)
op?.invoke(repository)
return repository
}
/**
* Opens a type-safe object repository using a {@link EntityDecorator} and a key
* identifier from the store. If the repository does not exist it will be
* created
* automatically and returned. If a repository is already opened, it is returned
* as is.
* <p>
* The returned repository is thread-safe for concurrent use.
*
* @param [T] type parameter
* @param [entityDecorator] the entityDecorator
* @param [key] the key
* @return the repository of type [T]
*/
inline fun <reified T : Any> Nitrite.getRepository(
entityDecorator: EntityDecorator<T>,
key: String,
noinline op: (ObjectRepository<T>.() -> Unit)? = null
): ObjectRepository<T> {
val repository = this.getRepository(entityDecorator, key)
op?.invoke(repository)
return repository
}
/**
* Returns an [IndexOptions] object with the specified index type.
*
* @param indexType the type of index to use, defaults to [IndexType.UNIQUE].
* @return an [IndexOptions] object with the specified index type.
*/
fun option(indexType: String = IndexType.UNIQUE): IndexOptions =
IndexOptions.indexOptions(indexType)
inline fun <reified T : Any> ObjectRepository<T>.insert(items: Iterable<T>) =
insert(items.toList().toTypedArray())
fun Builder.loadModule(plugin: NitritePlugin) =
loadModule(module(plugin))
operator fun <A, B> Pair<A, B>.component1(): A = first
operator fun <A, B> Pair<A, B>.component2(): B = second
object NitriteIdSerializer : KSerializer<NitriteId> {
override val descriptor = String.serializer().descriptor
override fun deserialize(decoder: Decoder): NitriteId =
NitriteId.createId(decoder.decodeString())
override fun serialize(encoder: Encoder, value: NitriteId) {
encoder.encodeString(value.idValue)
}
}
typealias SerializableNitriteId = @Serializable(with = NitriteIdSerializer::class) NitriteId
| 0
|
Java
|
0
| 0
|
be77b16e57f1fbb87b29cff782c8968654b8797f
| 6,262
|
nitrite-java
|
Apache License 2.0
|
app/src/main/java/com/example/sfutransiter/views/search_by/SearchBy.kt
|
Parfaits
| 560,714,206
| false
|
{"Kotlin": 99931}
|
package com.example.sfutransiter.views.search_by
import android.R
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import com.example.sfutransiter.databinding.FragmentSearchByBinding
import com.example.sfutransiter.views.MainFragment
class SearchBy : Fragment() {
private var _binding: FragmentSearchByBinding? = null
private val binding get() = _binding!!
private lateinit var searchByFragmentInterface: SearchByFragmentInterface
override fun onAttach(context: Context) {
super.onAttach(context)
if (context is SearchByFragmentInterface)
searchByFragmentInterface = context
else Log.e(
MainFragment.TAG,
"onAttach: MainActivity must implement SearchByFragmentInterface"
)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentSearchByBinding.inflate(inflater, container, false)
setupButtons()
return binding.root
}
private fun setupButtons() {
// binding.btnBus.setOnClickListener {
// searchByFragmentInterface.swapToSelectBus()
//
//
// }
binding.btnBusStop.setOnClickListener {
searchByFragmentInterface.swapToSelectStation()
}
}
companion object {
@JvmStatic
fun newInstance() = SearchBy()
val TAG: String = SearchBy::class.java.simpleName
}
interface SearchByFragmentInterface {
fun swapToSelectBus()
fun swapToSelectStation()
}
}
| 0
|
Kotlin
|
1
| 0
|
a2258262f7d14d44c7ab4f249f1ce519b462e11c
| 1,849
|
SFU-Transiter
|
MIT License
|
cli/src/main/kotlin/io/github/legion2/tosca_orchestrator/cli/Main.kt
|
Legion2
| 350,881,803
| false
| null |
package io.github.legion2.tosca_orchestrator.cli
import com.github.ajalt.clikt.core.subcommands
import io.github.legion2.tosca_orchestrator.cli.commands.*
fun createCLI(): RitamCli {
return RitamCli().subcommands(
GetResources(),
CreateResources(),
UpdateResources(),
ApplyResources(),
DeleteResources()
)
}
fun main(args: Array<String>) = createCLI().main(args)
| 6
|
Kotlin
|
0
| 3
|
fb4ef1a7bf3d79d258da2b6779381a87e0c435e9
| 414
|
ritam
|
Apache License 2.0
|
app/src/main/java/com/example/demovideoplayer/video/VideoModule.kt
|
seksky333
| 799,025,497
| false
|
{"Kotlin": 28845}
|
package com.example.demovideoplayer.video
import com.example.demovideoplayer.network.datasource.remote.DemoDemoVideoApiImpl
import com.example.demovideoplayer.network.datasource.remote.DemoVideoRemoteDataSource
import com.example.demovideoplayer.video.repository.VideoRepository
import com.example.demovideoplayer.video.repository.VideoRepositoryImpl
import kotlinx.coroutines.GlobalScope
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.dsl.module
val videoModule = module {
single<VideoRepository> {
VideoRepositoryImpl(
scope = GlobalScope,
dataSource = DemoVideoRemoteDataSource(
demoVideoApi = DemoDemoVideoApiImpl()
)
)
}
viewModel { VideoViewModel(videoRepository = get()) }
}
| 0
|
Kotlin
|
0
| 0
|
78dc1df1021de3d028038ebbabf5f61484a2d8a3
| 782
|
demo-video-player
|
MIT License
|
app/src/main/java/com/yueban/yopic/data/model/Historical.kt
|
yueban
| 162,973,285
| false
|
{"Kotlin": 164160}
|
package com.yueban.yopic.data.model
import android.os.Parcelable
import androidx.room.ColumnInfo
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import kotlinx.android.parcel.Parcelize
@JsonClass(generateAdapter = true)
@Parcelize
data class Historical(
@Json(name = "quantity") @ColumnInfo(name = "quantity")
val quantity: Int = 0,
@Json(name = "change") @ColumnInfo(name = "change")
val change: Int = 0,
@Json(name = "values") @ColumnInfo(name = "values")
val values: List<HistoricalValueItem>?,
@Json(name = "resolution") @ColumnInfo(name = "resolution")
val resolution: String = ""
) : Parcelable
| 0
|
Kotlin
|
0
| 6
|
dd2e23efadc4bd7c36f67670772f7ba3c7a55828
| 653
|
YoPic
|
Apache License 2.0
|
app/src/main/java/info/hzvtc/hipixiv/inject/module/ActivityModule.kt
|
Tait4198
| 94,422,381
| false
| null |
package info.hzvtc.hipixiv.inject.module
import android.app.Activity
import android.content.Context
import dagger.Module
import dagger.Provides
import info.hzvtc.hipixiv.inject.annotation.ActivityContext
import info.hzvtc.hipixiv.net.ApiService
import info.hzvtc.hipixiv.net.OAuthService
import info.hzvtc.hipixiv.net.RetrofitManager
@Module
class ActivityModule(activity : Activity) {
private val mActivity : Activity = activity
@Provides
fun provideActivity() : Activity = mActivity
@Provides
@ActivityContext
fun provideContext(): Context = mActivity
@Provides
fun provideRetrofitManager(): RetrofitManager = RetrofitManager(mActivity)
@Provides
fun provideOAuthService(): OAuthService = provideRetrofitManager().newOAuthService()
@Provides
fun provideApiService() : ApiService = provideRetrofitManager().newApiService()
}
| 0
|
Kotlin
|
0
| 0
|
35def2de39973a82e0fcf03f63733bb34c32d98d
| 881
|
hi_pixiv
|
MIT License
|
app/src/main/java/com/github/teracy/roompagingsample/di/ViewModelMapKey.kt
|
teracy
| 138,241,414
| false
|
{"Kotlin": 46099}
|
package com.github.teracy.roompagingsample.di
import android.arch.lifecycle.ViewModel
import dagger.MapKey
import kotlin.reflect.KClass
@MapKey
annotation class ViewModelMapKey(val value: KClass<out ViewModel>)
| 0
|
Kotlin
|
0
| 0
|
9ab546c5b8994da9c0d6ead40b98e2cb4faea371
| 212
|
RoomPagingSample
|
Apache License 2.0
|
app/src/main/java/com/rahul/app/weatherapp/core/BaseViewModel.kt
|
yuganshu007
| 328,369,128
| false
| null |
package com.rahul.app.weatherapp.core
import androidx.lifecycle.ViewModel
open class BaseViewModel : ViewModel()
| 0
|
Kotlin
|
0
| 0
|
aa3b4625d316d350577cb293784221aade4f450b
| 117
|
Weather-App
|
The Unlicense
|
src/main/kotlin/com/mx/hush/core/drivers/HushVulnerabilityScanDriver.kt
|
mxenabled
| 504,646,339
| false
| null |
/**
* Copyright 2020 MX Technologies.
*
* 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.mx.hush.core.drivers
import com.mx.hush.core.models.HushSuppression
import com.mx.hush.core.models.HushVulnerability
import org.gradle.api.Project
/**
* Driver class for creating implementations with plugins
*/
abstract class HushVulnerabilityScanDriver(private val project: Project) {
/**
* All logic which should run within Hush's apply() method
*/
abstract fun setupProject()
/**
* Get a list of vulnerabilities for the project
*/
abstract fun getVulnerabilities(): HashMap<String, HushVulnerability>
/**
* Get a list of suppressions for the project
*/
abstract fun getSuppressions(): List<HushSuppression>
/**
* Get suggested suppression file text
*/
abstract fun getSuggestedSuppressionText(suppressions: List<HushSuppression>): String
/**
* Write suggested suppression file text to the suppression file
*/
abstract fun writeSuggestedSuppressions(suppressions: String)
/**
* Validates that suggested suppressions can be generated and written
*/
abstract fun canWriteSuggestedSuppressions(): Boolean
/**
* Returns the path to the report file
*/
abstract fun getReportFilePath(): String
/**
* Returns the path to the suppression file
*/
abstract fun getSuppressionFilePath(): String
/**
* Performs rudimentary validation on a note
*/
abstract fun isValidNote(note: String): Boolean
/**
* Returns a list of suppressions with invalid notes
*/
abstract fun getInvalidNotes(suppressions: List<HushSuppression>): List<HushSuppression>
/**
* Returns the name of the task that must run before Hush
*/
abstract fun getPrerequisiteTaskName(): String
}
| 0
|
Kotlin
|
0
| 3
|
e828053c327b25f7328f0dac34ef145d0b041b8c
| 2,366
|
hush
|
Apache License 2.0
|
app/src/main/java/com/auth0/sample/MainActivity.kt
|
kpritam
| 497,408,678
| false
|
{"Kotlin": 11404}
|
package com.auth0.sample
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isVisible
import com.auth0.android.Auth0
import com.auth0.android.authentication.AuthenticationAPIClient
import com.auth0.android.authentication.AuthenticationException
import com.auth0.android.callback.Callback
import com.auth0.android.lock.AuthenticationCallback
import com.auth0.android.lock.Lock
import com.auth0.android.lock.PasswordlessLock
import com.auth0.android.management.ManagementException
import com.auth0.android.management.UsersAPIClient
import com.auth0.android.provider.CustomTabsOptions
import com.auth0.android.provider.WebAuthProvider
import com.auth0.android.result.Credentials
import com.auth0.android.result.UserProfile
import com.auth0.sample.databinding.ActivityMainBinding
// browser based => authorization code grant flow (oauth2)
// => hosted page on auth0 server
// => app -> pull hosted page from auth0
// native/embedded
// => password grant flow (username + password)
// => UI/pages are embedded into your application
// => not open webview
// => passwordless (email or phone)
// => email or phone
// => otp/magic link (Swiggy, Paytm)
// native (Android lock)
// how do you setup MFA page at the time of sign up?
// irrespective of login mode
// how do you enable mobile as your 2FA?
enum class LoginMethod {
Native, Passwordless, BrowserBased
}
class MainActivity : AppCompatActivity() {
private lateinit var account: Auth0
private lateinit var lock: Lock
private lateinit var binding: ActivityMainBinding
private var cachedCredentials: Credentials? = null
private var cachedUserProfile: UserProfile? = null
private val loginMethod = LoginMethod.Native
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Bind the button click with the login action
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
when (loginMethod) {
LoginMethod.Passwordless -> {
account = Auth0(
getString(R.string.com_auth0_passwordless_client_id),
getString(R.string.com_auth0_passwordless_domain)
)
binding.buttonLogin.setOnClickListener { loginPasswordLessNative() }
}
LoginMethod.Native -> {
account = Auth0(
getString(R.string.com_auth0_client_id),
getString(R.string.com_auth0_domain)
)
binding.buttonLogin.setOnClickListener { loginNative() }
}
LoginMethod.BrowserBased -> {
account = Auth0(
getString(R.string.com_auth0_client_id),
getString(R.string.com_auth0_domain)
)
binding.buttonLogin.setOnClickListener { loginWithBrowser() }
}
}
binding.buttonLogout.setOnClickListener { logout() }
binding.buttonGetMetadata.setOnClickListener { getUserMetadata() }
binding.buttonPatchMetadata.setOnClickListener { patchUserMetadata() }
}
private fun updateUI() {
binding.buttonLogout.isEnabled = cachedCredentials != null
binding.metadataPanel.isVisible = cachedCredentials != null
binding.buttonLogin.isEnabled = cachedCredentials == null
binding.userProfile.isVisible = cachedCredentials != null
binding.userProfile.text =
"Name: ${cachedUserProfile?.name ?: ""}\n" +
"Email: ${cachedUserProfile?.email ?: ""}"
if (cachedUserProfile == null) {
binding.inputEditMetadata.setText("")
}
}
private fun loginWithBrowser() {
val ctOptions = CustomTabsOptions.newBuilder()
.withToolbarColor(R.color.com_auth0_lock_form_background)
.showTitle(true)
.build()
// Setup the WebAuthProvider, using the custom scheme and scope.
WebAuthProvider.login(account)
.withCustomTabsOptions(ctOptions)
.withScheme(getString(R.string.com_auth0_scheme))
.withScope("openid profile email read:current_user update:current_user_metadata")
.withAudience("https://${getString(R.string.com_auth0_domain)}/api/v2/")
// Launch the authentication passing the callback where the results will be received
.start(this, object : Callback<Credentials, AuthenticationException> {
override fun onFailure(error: AuthenticationException) {
SnackBar.show(applicationContext, binding.root, "Failure: ${error.getCode()}")
}
override fun onSuccess(result: Credentials) {
cachedCredentials = result
SnackBar.show(
applicationContext,
binding.root,
"Success: ${result.accessToken}"
)
updateUI()
showUserProfile()
}
})
}
private fun loginNative() {
lock = Lock.newBuilder(account, nativeCallback)
.withScheme(getString(R.string.com_auth0_scheme))
.withScope("openid profile email read:current_user update:current_user_metadata")
.withAudience("https://${getString(R.string.com_auth0_domain)}/api/v2/")
.closable(true)
.setShowTerms(true)
.setMustAcceptTerms(true)
.build(this)
startActivity(lock.newIntent(this))
}
private fun loginPasswordLessNative() {
val lock = PasswordlessLock.newBuilder(account, nativeCallback)
.withScheme(getString(R.string.com_auth0_scheme))
.withScope("openid profile email read:current_user update:current_user_metadata")
.withAudience("https://${getString(R.string.com_auth0_domain)}/api/v2/")
.useCode()
.build(this)
startActivity(lock.newIntent(this))
}
private val nativeCallback = object : AuthenticationCallback() {
override fun onAuthentication(credentials: Credentials) {
cachedCredentials = credentials
SnackBar.show(applicationContext, binding.root, "Success: ${credentials.accessToken}")
updateUI()
showUserProfile()
// Authenticated
}
override fun onError(error: AuthenticationException) {
println(error)
SnackBar.show(applicationContext, binding.root, "Failure: ${error.getCode()}")
}
}
private fun logout() {
WebAuthProvider.logout(account)
.withScheme(getString(R.string.com_auth0_scheme))
.start(this, object : Callback<Void?, AuthenticationException> {
override fun onSuccess(result: Void?) {
// The user has been logged out!
cachedCredentials = null
cachedUserProfile = null
updateUI()
}
override fun onFailure(error: AuthenticationException) {
updateUI()
SnackBar.show(applicationContext, binding.root, "Failure: ${error.getCode()}")
}
})
}
private fun showUserProfile() {
val client = AuthenticationAPIClient(account)
// Use the access token to call userInfo endpoint.
// In this sample, we can assume cachedCredentials has been initialized by this point.
client.userInfo(cachedCredentials!!.accessToken)
.start(object : Callback<UserProfile, AuthenticationException> {
override fun onFailure(error: AuthenticationException) {
SnackBar.show(applicationContext, binding.root, "Failure: ${error.getCode()}")
}
override fun onSuccess(result: UserProfile) {
cachedUserProfile = result
updateUI()
}
})
}
private fun getUserMetadata() {
// Create the user API client
val usersClient = UsersAPIClient(account, cachedCredentials!!.accessToken)
// Get the full user profile
usersClient.getProfile(cachedUserProfile!!.getId()!!)
.start(object : Callback<UserProfile, ManagementException> {
override fun onFailure(error: ManagementException) {
SnackBar.show(applicationContext, binding.root, "Failure: ${error.getCode()}")
}
override fun onSuccess(result: UserProfile) {
cachedUserProfile = result
updateUI()
val country = result.getUserMetadata()["country"] as String?
binding.inputEditMetadata.setText(country)
}
})
}
private fun patchUserMetadata() {
val usersClient = UsersAPIClient(account, cachedCredentials!!.accessToken)
val metadata = mapOf("country" to binding.inputEditMetadata.text.toString())
usersClient
.updateMetadata(cachedUserProfile!!.getId()!!, metadata)
.start(object : Callback<UserProfile, ManagementException> {
override fun onFailure(error: ManagementException) {
SnackBar.show(applicationContext, binding.root, "Failure: ${error.getCode()}")
}
override fun onSuccess(result: UserProfile) {
cachedUserProfile = result
updateUI()
SnackBar.show(applicationContext, binding.root, "Successful")
}
})
}
}
| 0
|
Kotlin
|
0
| 0
|
1449133da1ade3dcc26005e2408cc11f95899d2c
| 9,876
|
auth0-android-lock
|
MIT License
|
common/src/main/java/com/ekoapp/ekosdk/uikit/common/Extensions.kt
|
amadeus-n
| 467,842,651
| true
|
{"Kotlin": 1114879}
|
package com.ekoapp.ekosdk.uikit.common
import android.content.Context
import android.content.res.Resources
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.os.AsyncTask
import android.view.TouchDelegate
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.ColorRes
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.paging.PagedList
import com.bumptech.glide.Glide
import com.ekoapp.ekosdk.uikit.R
import com.ekoapp.ekosdk.uikit.common.views.ColorPaletteUtil
import com.ekoapp.ekosdk.uikit.common.views.ColorShade
import com.ekoapp.ekosdk.uikit.utils.EkoListDataSource
import com.ekoapp.ekosdk.uikit.utils.ScaleErrorImageViewTarget
import com.google.android.material.shape.CornerFamily
import com.google.android.material.shape.MaterialShapeDrawable
import com.google.android.material.shape.ShapeAppearanceModel
import java.math.RoundingMode
import java.text.DecimalFormat
import java.util.concurrent.TimeUnit
import kotlin.math.ln
import kotlin.math.pow
fun String.isNotEmptyOrBlank(): Boolean {
return this.isNotEmpty() && this.isNotBlank()
}
fun TextView.leftDrawable(drawable: Drawable) {
this.setCompoundDrawablesRelativeWithIntrinsicBounds(drawable, null, null, null)
}
fun String.changeValue(default: String, previous: String): String {
return if (this == default) {
previous
} else {
this
}
}
fun Boolean.changeValue(default: Boolean, previous: Boolean): Boolean {
return if (this == default) {
previous
} else {
this
}
}
fun ImageView.loadImage(url: String?, id: Int? = null) {
if (id != null) {
Glide.with(this)
.load(url)
.centerCrop()
.placeholder(id)
.into(ScaleErrorImageViewTarget(this).error())
} else {
Glide.with(this)
.load(url)
.centerCrop()
.placeholder(R.drawable.amity_ic_user)
.into(ScaleErrorImageViewTarget(this).error())
}
}
fun Long.readableFeedPostTime(context: Context): String {
val diff = System.currentTimeMillis() - this
val days = TimeUnit.MILLISECONDS.toDays(diff)
val hours = TimeUnit.MILLISECONDS.toHours(diff)
val minutes = TimeUnit.MILLISECONDS.toMinutes(diff)
return when {
days > 0 -> context.resources.getQuantityString(
R.plurals.amity_number_of_days,
days.toInt(),
days
)
hours > 0 -> context.resources.getQuantityString(
R.plurals.amity_number_of_hours,
hours.toInt(),
hours
)
minutes > 0 -> context.resources.getQuantityString(
R.plurals.amity_number_of_mins,
minutes.toInt(),
minutes
)
else -> context.getString(R.string.amity_just_now)
}
}
fun isPlurals(number: Long): Boolean {
return number > 1
}
fun Int.readableNumber(): String {
if (this < 1000) return "" + this
val exp = (ln(this.toDouble()) / ln(1000.0)).toInt()
val format = DecimalFormat("0.#")
val value: String = format.format(this / 1000.0.pow(exp.toDouble()))
return String.format("%s%c", value, "kMBTPE"[exp - 1])
}
fun <T : Any> List<T>.toPagedList(pageSize: Int): PagedList<T> {
val config = PagedList.Config.Builder()
.setEnablePlaceholders(false)
.setPageSize(pageSize)
.build()
return PagedList.Builder(EkoListDataSource(this), config)
.setNotifyExecutor(EkoListDataSource.EkoUiThreadExecutor())
.setFetchExecutor(AsyncTask.THREAD_POOL_EXECUTOR)
.build()
}
fun View.setShape(
topLeft: Float?, bottomLeft: Float?,
topRight: Float?, bottomRight: Float?, @ColorRes fillColor: Int?,
@ColorRes strokeColor: Int?, colorShade: ColorShade?
) {
val modal = ShapeAppearanceModel()
.toBuilder()
val cornerRadius = this.context.resources.getDimensionPixelSize(R.dimen.amity_eight).toFloat()
if (topLeft == null) {
modal.setTopLeftCorner(CornerFamily.ROUNDED, cornerRadius)
} else {
modal.setTopLeftCorner(CornerFamily.ROUNDED, topLeft)
}
if (bottomLeft == null) {
modal.setBottomLeftCorner(CornerFamily.ROUNDED, cornerRadius)
} else {
modal.setBottomLeftCorner(CornerFamily.ROUNDED, bottomLeft)
}
if (topRight == null) {
modal.setTopRightCorner(CornerFamily.ROUNDED, cornerRadius)
} else {
modal.setTopRightCorner(CornerFamily.ROUNDED, topRight)
}
if (bottomRight == null) {
modal.setBottomRightCorner(CornerFamily.ROUNDED, cornerRadius)
} else {
modal.setBottomRightCorner(CornerFamily.ROUNDED, bottomRight)
}
val shapeDrawable = MaterialShapeDrawable(modal.build())
if (fillColor == null) {
shapeDrawable.fillColor = ContextCompat.getColorStateList(this.context, R.color.amityColorWhite)
} else {
if (colorShade == null)
shapeDrawable.fillColor = ContextCompat.getColorStateList(this.context, fillColor)
else {
shapeDrawable.setTint(
ColorPaletteUtil.getColor(
ContextCompat.getColor(
this.context,
fillColor
), colorShade
)
)
}
if (strokeColor == null) {
if (colorShade == null) {
shapeDrawable.setStroke(2F, ContextCompat.getColor(this.context, fillColor))
} else {
shapeDrawable.setStroke(
2F, ColorPaletteUtil.getColor(
ContextCompat.getColor(
this.context,
fillColor
), colorShade
)
)
}
} else {
if (colorShade == null) {
shapeDrawable.setStroke(2F, ContextCompat.getColor(this.context, strokeColor))
} else {
shapeDrawable.setStroke(
2F, ColorPaletteUtil.getColor(
ContextCompat.getColor(
this.context,
strokeColor
), colorShade
)
)
}
}
ViewCompat.setBackground(this, shapeDrawable)
}
}
fun View.toCircularShape(fillColor: Int, strokeWidth: Float? = null) {
val modal = ShapeAppearanceModel()
.toBuilder()
.setAllCorners(
CornerFamily.ROUNDED,
this.context.resources.getDimensionPixelSize(R.dimen.amity_thirty_two).toFloat()
)
val shapeDrawable = MaterialShapeDrawable(modal.build())
shapeDrawable.setTint(fillColor)
if (strokeWidth != null) {
shapeDrawable.setStroke(strokeWidth, ContextCompat.getColor(this.context, R.color.amityColorWhite))
}
ViewCompat.setBackground(this, shapeDrawable)
}
fun View.setBackgroundColor(color: Int?, colorShade: ColorShade?) {
val shade = colorShade ?: ColorShade.DEFAULT
val backgroundColor = color ?: ContextCompat.getColor(this.context, R.color.amityColorBase)
this.setBackgroundColor(ColorPaletteUtil.getColor(backgroundColor, shade))
}
fun Double.formatCount(): String {
val suffixChars = "KMGTPE"
val formatter = DecimalFormat("###.#")
formatter.roundingMode = RoundingMode.DOWN
return if (this < 1000.0) {
formatter.format(this)
} else {
val exp = (ln(this) / ln(1000.0)).toInt()
formatter.format(this / 1000.0.pow(exp.toDouble())) + suffixChars[exp - 1]
}
}
fun View.expandViewHitArea(): View? {
val parent = (this.parent as? View)
parent?.post {
val parentRect = Rect()
val childRect = Rect()
parent.getHitRect(parentRect)
this.getHitRect(childRect)
childRect.left -= 4
childRect.top -= 4
childRect.right += 4
childRect.bottom += 4
parent.touchDelegate = TouchDelegate(childRect, this)
}
return parent
}
fun Int.toDp(): Int = (this / Resources.getSystem().displayMetrics.density).toInt()
| 0
| null |
0
| 0
|
d4fe097da96f71ab281c9b39fafdaa901aed377c
| 8,238
|
ASC-UIKit-Android
|
Microsoft Public License
|
src/main/kotlin/com/jerryjeon/logjerry/ui/ExceptionDetectionView.kt
|
jkj8790
| 521,791,909
| false
| null |
package com.jerryjeon.logjerry.ui
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.LocalTextStyle
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.jerryjeon.logjerry.detector.DetectionFocus
import com.jerryjeon.logjerry.detector.ExceptionDetection
@Composable
fun ExceptionDetectionView(
modifier: Modifier,
detectionFocus: DetectionFocus?,
moveToPreviousOccurrence: (DetectionFocus) -> Unit,
moveToNextOccurrence: (DetectionFocus) -> Unit,
) {
CompositionLocalProvider(
LocalTextStyle provides LocalTextStyle.current.copy(fontSize = 12.sp),
) {
Box(modifier = modifier) {
Column(Modifier.height(IntrinsicSize.Min).padding(8.dp)) {
Text(AnnotatedString("Exception", spanStyle = ExceptionDetection.detectedStyle))
if (detectionFocus == null) {
Spacer(Modifier.height(16.dp))
Text("No results", textAlign = TextAlign.Center)
} else {
ExceptionDetectionFocusExist(detectionFocus, moveToPreviousOccurrence, moveToNextOccurrence)
}
}
}
}
}
@Composable
fun ExceptionDetectionFocusExist(
focus: DetectionFocus,
moveToPreviousOccurrence: (DetectionFocus) -> Unit,
moveToNextOccurrence: (DetectionFocus) -> Unit
) {
Row {
/* TODO not sure it's helpful... remove it because it looks bad
Row(modifier = Modifier.weight(1f).fillMaxHeight()) {
// TODO cleanup ; don't cast
(it.focusing as? ExceptionDetectionResult)?.let {
Text(it.exception, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
*/
Row(modifier = Modifier.weight(1f).fillMaxHeight()) {
if (focus.focusing == null) {
Text(
"${focus.allDetections.size} results",
modifier = Modifier.align(Alignment.CenterVertically)
)
} else {
Text(
"${focus.currentIndexInView} / ${focus.totalCount}",
modifier = Modifier.align(Alignment.CenterVertically)
)
}
}
IconButton(onClick = { moveToPreviousOccurrence(focus) }) {
Icon(Icons.Default.KeyboardArrowUp, "Previous Occurrence")
}
IconButton(onClick = { moveToNextOccurrence(focus) }) {
Icon(Icons.Default.KeyboardArrowDown, "Next Occurrence")
}
}
}
| 4
|
Kotlin
|
3
| 36
|
096d09d3cdd19ab0d6f3290d51307d85ac4385c2
| 3,553
|
LogJerry
|
Apache License 2.0
|
fixture/src/main/kotlin/com/appmattus/kotlinfixture/resolver/KNamedPropertyResolver.kt
|
gavelez
| 310,143,296
| true
|
{"Kotlin": 536970, "Java": 2317}
|
/*
* Copyright 2020 Appmattus Limited
*
* 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.appmattus.kotlinfixture.resolver
import com.appmattus.kotlinfixture.Context
import com.appmattus.kotlinfixture.Unresolved
import com.appmattus.kotlinfixture.config.DefaultGenerator
internal class KNamedPropertyResolver : Resolver {
override fun resolve(context: Context, obj: Any): Any? {
if (obj is KNamedPropertyRequest) {
val overrides = context.configuration.properties.getOrElse(obj.containingClass) { emptyMap() }
return if (obj.name in overrides) {
overrides[obj.name]?.invoke(DefaultGenerator(context))
} else {
context.resolve(obj.type)
}
}
return Unresolved.Unhandled
}
}
| 0
| null |
0
| 0
|
f618632233736ab5e2d6e27ca3497837eb54a27f
| 1,308
|
kotlinfixture
|
Apache License 2.0
|
2020/day3/day3.kt
|
flwyd
| 426,866,266
| false
|
{"Julia": 207516, "Elixir": 120623, "Raku": 119287, "Kotlin": 89230, "Go": 37074, "Shell": 24820, "Makefile": 16393, "sed": 2310, "Jsonnet": 1104, "HTML": 398}
|
/*
* Copyright 2021 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
package day3
import kotlin.time.ExperimentalTime
import kotlin.time.TimeSource
import kotlin.time.measureTimedValue
/* Input is grid of . for open and # for blocked, conceptually extended infinitely to the right.
* Moving right 3, down 1 each time, count the number of # blocks.
*/
object Part1 {
fun solve(input: Sequence<String>): String {
return input.withIndex()
.filter { it.value[it.index * 3 % it.value.length] == '#' }
.count()
.toString()
}
}
/* Now try with several slopes and multiply counts together. */
object Part2 {
data class Slope(val right: Int, val down: Int, var obstacles: Long = 0)
fun solve(input: Sequence<String>): String {
val slopes = listOf(Slope(1, 1), Slope(3, 1), Slope(5, 1), Slope(7, 1), Slope(1, 2))
input.withIndex().forEach { line ->
slopes.forEach {
if (line.index % it.down == 0 &&
line.value[line.index / it.down * it.right % line.value.length] == '#'
) {
it.obstacles++
}
}
}
// println(slopes)
return slopes.map(Slope::obstacles).reduce(Long::times).toString()
}
}
@ExperimentalTime
@Suppress("UNUSED_PARAMETER")
fun main(args: Array<String>) {
val lines = generateSequence(::readLine).toList()
print("part1: ")
TimeSource.Monotonic.measureTimedValue { Part1.solve(lines.asSequence()) }.let {
println(it.value)
System.err.println("Completed in ${it.duration}")
}
print("part2: ")
TimeSource.Monotonic.measureTimedValue { Part2.solve(lines.asSequence()) }.let {
println(it.value)
System.err.println("Completed in ${it.duration}")
}
}
| 0
|
Julia
|
1
| 5
|
f2d6dbb67d41f8f2898dbbc6a98477d05473888f
| 1,810
|
adventofcode
|
MIT License
|
app/src/main/java/dog/snow/androidrecruittest/repository/AlbumRepository.kt
|
Lejdi
| 303,955,299
| false
|
{"Kotlin": 62566}
|
package dog.snow.androidrecruittest.repository
import dog.snow.androidrecruittest.repository.cache.dao.AlbumDao
import dog.snow.androidrecruittest.repository.cache.mapper.AlbumMapper
import dog.snow.androidrecruittest.repository.cache.model.Album
import dog.snow.androidrecruittest.repository.networking.service.AlbumRetrofit
import dog.snow.androidrecruittest.util.SplashState
import java.lang.Exception
class AlbumRepository
constructor(
private val albumDao: AlbumDao,
private val albumRetrofit: AlbumRetrofit,
private val albumCacheMapper: AlbumMapper,
private val albumNetworkMapper: dog.snow.androidrecruittest.repository.networking.mapper.AlbumMapper
) {
suspend fun getAllFromNetwork() : SplashState {
try{
val albums = albumRetrofit.getAlbums()
if(albums!=null){
val mappedAlbums = albumNetworkMapper.mapListFromEntity(albums)
albumDao.clearData()
mappedAlbums.forEach {
albumDao.insert(albumCacheMapper.mapToEntity(it))
}
}
else{
throw Exception("Failed to download albums")
}
}
catch(e : Exception){
e.printStackTrace()
return SplashState.ERROR
}
return SplashState.SUCCESS
}
suspend fun getFromNetworkById(id: Int) : SplashState {
try{
val album = albumRetrofit.getAlbumById(id)
if(album != null){
val mappedAlbum = albumNetworkMapper.mapFromEntity(album)
albumDao.insert(albumCacheMapper.mapToEntity(mappedAlbum))
}
else{
throw Exception("Failed to download an album")
}
}
catch(e : Exception){
e.printStackTrace()
return SplashState.ERROR
}
return SplashState.SUCCESS
}
suspend fun getAllFromCache() : List<Album> {
return albumDao.getAllAlbums()
}
suspend fun getFromCacheById(id: Int) : Album {
return albumDao.getAlbumById(id)
}
suspend fun clearCache(){
albumDao.clearData()
}
}
| 0
|
Kotlin
|
0
| 0
|
94bce0609da24f40fc77f9510be85cb48e5e814c
| 2,178
|
SnowDog_Recruit
|
Apache License 2.0
|
kotlin-typescript/src/jsMain/generated/typescript/couldStartTrivia.kt
|
JetBrains
| 93,250,841
| false
|
{"Kotlin": 12635434, "JavaScript": 423801}
|
// Automatically generated - do not modify!
@file:JsModule("typescript")
package typescript
external fun couldStartTrivia(text: String, pos: Double): Boolean
| 38
|
Kotlin
|
162
| 1,347
|
997ed3902482883db4a9657585426f6ca167d556
| 161
|
kotlin-wrappers
|
Apache License 2.0
|
app/src/test/java/com/dfavilav/marvelapplication/data/paging/SearchHeroesSourceTest.kt
|
davilav
| 751,080,023
| false
|
{"Kotlin": 110960}
|
package com.dfavilav.marvelapplication.data.paging
import androidx.paging.PagingSource
import com.dfavilav.marvelapplication.data.local.MarvelDatabase
import com.dfavilav.marvelapplication.data.paging.hero.SearchHeroesSource
import com.dfavilav.marvelapplication.data.remote.FakeMarvelApi
import com.dfavilav.marvelapplication.data.remote.MarvelApi
import com.dfavilav.marvelapplication.domain.model.Thumbnail
import com.dfavilav.marvelapplication.domain.model.hero.Hero
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.Mockito.mock
import kotlin.test.assertTrue
class SearchHeroesSourceTest {
private lateinit var marvelApi: MarvelApi
private lateinit var heroes: List<Hero>
@Mock
private lateinit var marvelDatabase: MarvelDatabase
@Before
fun setup() {
marvelDatabase = mock(MarvelDatabase::class.java)
marvelApi = FakeMarvelApi()
heroes = listOf(
Hero(
id = 1,
name = "Iron Man",
description = "",
thumbnail = Thumbnail("", "")
),
Hero(
id = 2,
name = "Iron Man",
description = "",
thumbnail = Thumbnail("", "")
),
Hero(
id = 3,
name = "Iron Man",
description = "",
thumbnail = Thumbnail("", "")
)
)
}
@Test
fun `Search api with empty hero name, assert empty heroes list and LoadResult_Page`() =
runTest {
val charactersSource = SearchHeroesSource(
marvelApi = marvelApi,
query = "Iron Man",
marvelDatabase
)
val loadResult = charactersSource.load(
PagingSource.LoadParams.Refresh(
key = null,
loadSize = 3,
placeholdersEnabled = false
)
)
val result = marvelApi.searchHeroes("").data.results
assertTrue { result.isEmpty() }
}
@Test
fun `Search api with non_existing hero name, assert empty heroes list and LoadResult_Page`() =
runTest {
val charactersSource = SearchHeroesSource(
marvelApi = marvelApi,
query = "Iron Man",
marvelDatabase
)
val loadResult = charactersSource.load(
PagingSource.LoadParams.Refresh(
key = null,
loadSize = 3,
placeholdersEnabled = false
)
)
val result = marvelApi.searchHeroes("Unknown").data.results
assertTrue { result.isEmpty() }
}
}
| 0
|
Kotlin
|
0
| 0
|
25beb759cd9e84ec7740e893fa17eed5b7f972b1
| 2,864
|
MarvelApp
|
Apache License 2.0
|
logindomain/src/main/java/com/nikitamaslov/logindomain/interactor/LogInUseCase.kt
|
nikitamasloff
| 182,624,620
| false
| null |
package com.nikitamaslov.logindomain.interactor
import com.nikitamaslov.logindomain.model.Credential
import com.nikitamaslov.logindomain.repository.LoginRepository
import io.reactivex.Completable
interface LogInUseCase {
operator fun invoke(credential: Credential): Completable
}
class LogInUseCaseImpl(private val loginRepository: LoginRepository) : LogInUseCase {
override fun invoke(credential: Credential): Completable =
loginRepository.logIn(credential)
}
| 0
| null |
0
| 0
|
cbdd62b9eab3ae3362c6fec4f8c0d498133174c0
| 482
|
in-touch
|
Apache License 2.0
|
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/lookoutmetrics/CfnAnomalyDetectorFileFormatDescriptorPropertyDsl.kt
|
cloudshiftinc
| 667,063,030
| false
| null |
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package cloudshift.awscdk.dsl.services.lookoutmetrics
import cloudshift.awscdk.common.CdkDslMarker
import software.amazon.awscdk.IResolvable
import software.amazon.awscdk.services.lookoutmetrics.CfnAnomalyDetector
/**
* Contains information about a source file's formatting.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.lookoutmetrics.*;
* FileFormatDescriptorProperty fileFormatDescriptorProperty =
* FileFormatDescriptorProperty.builder()
* .csvFormatDescriptor(CsvFormatDescriptorProperty.builder()
* .charset("charset")
* .containsHeader(false)
* .delimiter("delimiter")
* .fileCompression("fileCompression")
* .headerList(List.of("headerList"))
* .quoteSymbol("quoteSymbol")
* .build())
* .jsonFormatDescriptor(JsonFormatDescriptorProperty.builder()
* .charset("charset")
* .fileCompression("fileCompression")
* .build())
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lookoutmetrics-anomalydetector-fileformatdescriptor.html)
*/
@CdkDslMarker
public class CfnAnomalyDetectorFileFormatDescriptorPropertyDsl {
private val cdkBuilder: CfnAnomalyDetector.FileFormatDescriptorProperty.Builder =
CfnAnomalyDetector.FileFormatDescriptorProperty.builder()
/**
* @param csvFormatDescriptor Contains information about how a source CSV data file should be
* analyzed.
*/
public fun csvFormatDescriptor(csvFormatDescriptor: IResolvable) {
cdkBuilder.csvFormatDescriptor(csvFormatDescriptor)
}
/**
* @param csvFormatDescriptor Contains information about how a source CSV data file should be
* analyzed.
*/
public
fun csvFormatDescriptor(csvFormatDescriptor: CfnAnomalyDetector.CsvFormatDescriptorProperty) {
cdkBuilder.csvFormatDescriptor(csvFormatDescriptor)
}
/**
* @param jsonFormatDescriptor Contains information about how a source JSON data file should be
* analyzed.
*/
public fun jsonFormatDescriptor(jsonFormatDescriptor: IResolvable) {
cdkBuilder.jsonFormatDescriptor(jsonFormatDescriptor)
}
/**
* @param jsonFormatDescriptor Contains information about how a source JSON data file should be
* analyzed.
*/
public
fun jsonFormatDescriptor(jsonFormatDescriptor: CfnAnomalyDetector.JsonFormatDescriptorProperty) {
cdkBuilder.jsonFormatDescriptor(jsonFormatDescriptor)
}
public fun build(): CfnAnomalyDetector.FileFormatDescriptorProperty = cdkBuilder.build()
}
| 1
|
Kotlin
|
0
| 0
|
17c41bdaffb2e10d31b32eb2282b73dd18be09fa
| 2,776
|
awscdk-dsl-kotlin
|
Apache License 2.0
|
browser-kotlin/src/jsMain/kotlin/web/cache/CacheStorage.kt
|
karakum-team
| 393,199,102
| false
| null |
// Automatically generated - do not modify!
package web.cache
import js.core.ReadonlyArray
import web.http.Request
import web.http.Response
import web.url.URL
import kotlin.js.Promise
sealed external class CacheStorage {
fun delete(cacheName: String): Promise<Boolean>
fun has(cacheName: String): Promise<Boolean>
fun keys(): Promise<ReadonlyArray<String>>
fun match(
request: Request,
options: MultiCacheQueryOptions = definedExternally,
): Promise<Response?>
fun match(
request: String,
options: MultiCacheQueryOptions = definedExternally,
): Promise<Response?>
fun match(
request: URL,
options: MultiCacheQueryOptions = definedExternally,
): Promise<Response?>
fun open(cacheName: String): Promise<Cache>
}
| 0
|
Kotlin
|
6
| 22
|
340fa5d93f874ebf14810ab797a9808af574e058
| 804
|
types-kotlin
|
Apache License 2.0
|
app/src/androidMain/kotlin/kosh/app/di/AndroidAppComponent.kt
|
niallkh
| 855,100,709
| false
|
{"Kotlin": 1892361, "Swift": 21492}
|
package kosh.app.di
import kosh.app.BuildConfig
class AndroidAppComponent : AppComponent {
override val debug: Boolean
get() = BuildConfig.DEBUG
}
| 0
|
Kotlin
|
0
| 3
|
e0149252019f8b47ceede5c0c1eb78c0a1e1c203
| 161
|
kosh
|
MIT License
|
src/main/kotlin/com/baulsupp/okurl/services/jira/model/jira.kt
|
hhy5277
| 181,409,482
| true
|
{"Kotlin": 534300, "Shell": 10198}
|
package com.baulsupp.okurl.services.jira.model
data class ProjectCategory(val id: String, val name: String, val description: String, val self: String)
data class Project(
val id: String,
val key: String,
val name: String,
val avatarUrls: Map<String, String>,
val projectCategory: ProjectCategory?,
val projectTypeKey: String
)
| 0
|
Kotlin
|
0
| 0
|
a154485d96e91e75f0557bf7652aed434b9353d1
| 341
|
okurl
|
Apache License 2.0
|
domain-access/src/main/java/pl/kamilszustak/read/domain/access/usecase/device/GetPhoneNumberUseCase.kt
|
swistak7171
| 289,985,013
| false
| null |
package pl.kamilszustak.read.domain.access.usecase.device
import pl.kamilszustak.read.domain.access.usecase.UseCase
/**
* For devices running Android M or higher you have to explicitly
* ask user for permission (android.permission.READ_PHONE_STATE).
*/
interface GetPhoneNumberUseCase : UseCase<String?>
| 2
|
Kotlin
|
0
| 1
|
70d7be58042410bdb969035413b726126426e3d3
| 308
|
read
|
Apache License 2.0
|
src/main/kotlin/Supervisor.kt
|
CuteReimu
| 591,960,504
| false
| null |
package org.tfcc.bingo
import io.netty.channel.Channel
import io.netty.channel.ChannelId
// 用以记录channel和player的对应关系,非线程安全
object Supervisor {
private val channelIdToPlayer = HashMap<ChannelId, String>()
private val playerTokenToChannel = HashMap<String, Channel>()
fun add(channel: Channel, playerToken: String) {
channelIdToPlayer[channel.id()] = playerToken
playerTokenToChannel[playerToken] = channel
}
fun removeByChannelId(channelId: ChannelId): String? {
val token = channelIdToPlayer.remove(channelId)
playerTokenToChannel.remove(token)
return token
}
fun getPlayerToken(channelId: ChannelId): String? {
return channelIdToPlayer[channelId]
}
fun getChannel(playerToken: String): Channel? {
return playerTokenToChannel[playerToken]
}
}
| 4
| null |
0
| 4
|
bf1c38776ce9796f5d2bf56e3a13427f5cecec5b
| 843
|
th-bingo
|
MIT License
|
sample/src/main/java/ro/andob/outofroom/sample/view/EditTextX.kt
|
andob
| 363,221,615
| false
| null |
package ro.andob.outofroom.sample.view
import android.text.Editable
import android.text.TextWatcher
import android.widget.EditText
fun EditText.setOnTextChangedListener(listener : (String) -> (Unit))
{
addTextChangedListener(object : TextWatcher
{
override fun beforeTextChanged(s : CharSequence?, start : Int, count : Int, after : Int) {}
override fun onTextChanged(s : CharSequence?, start : Int, before : Int, count : Int) = listener(text.toString())
override fun afterTextChanged(s : Editable?) {}
})
}
| 0
|
Kotlin
|
0
| 4
|
418211123a4b782a9bf29d01692d006ada7cc0a7
| 545
|
OutOfROOM
|
Apache License 2.0
|
src/main/kotlin/com/mino/smartcheck/config/SmartCheckProperties.kt
|
carlosmontoyargz
| 216,790,827
| false
|
{"HTML": 671011, "TypeScript": 104755, "Kotlin": 18773, "JavaScript": 2481, "CSS": 1227, "Java": 972}
|
package com.mino.smartcheck.config
import org.springframework.boot.context.properties.ConfigurationProperties
@ConfigurationProperties(prefix = "jwt")
class SmartCheckProperties(var secretKey: String = "")
| 28
|
HTML
|
0
| 0
|
2e2f091a701e68381963d88994138b3f20601192
| 208
|
ortograma
|
MIT License
|
app/src/main/java/com/kusamaru/standroid/nicovideo/NicoVideoInfoFragment.kt
|
kusamaru
| 442,642,043
| false
| null |
package com.kusamaru.standroid.nicovideo
import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.Color
import android.os.Bundle
import android.text.Spannable
import android.text.Spanned
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.core.net.toUri
import androidx.core.text.HtmlCompat
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.preference.PreferenceManager
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.google.android.material.snackbar.Snackbar
import com.kusamaru.standroid.MainActivity
import com.kusamaru.standroid.nicoapi.nicovideo.dataclass.NicoVideoData
import com.kusamaru.standroid.nicovideo.bottomfragment.NicoVideoLikeBottomFragment
import com.kusamaru.standroid.nicovideo.bottomfragment.NicoVideoLikeThanksMessageBottomFragment
import com.kusamaru.standroid.nicovideo.fragment.NicoVideoMyListListFragment
import com.kusamaru.standroid.nicovideo.fragment.NicoVideoSearchFragment
import com.kusamaru.standroid.nicovideo.fragment.NicoVideoSeriesFragment
import com.kusamaru.standroid.nicovideo.viewmodel.NicoVideoViewModel
import com.kusamaru.standroid.R
import com.kusamaru.standroid.tool.*
import com.kusamaru.standroid.databinding.FragmentNicovideoInfoBinding
import java.text.SimpleDateFormat
import java.util.*
/**
* 動画情報Fragment
* */
class NicoVideoInfoFragment : Fragment() {
val prefSetting by lazy { PreferenceManager.getDefaultSharedPreferences(context) }
// NicoVideoFragmentのViewModelを取得する
val viewModel: NicoVideoViewModel by viewModels({ requireParentFragment() })
/** findViewById駆逐 */
private val viewBinding by lazy { FragmentNicovideoInfoBinding.inflate(layoutInflater) }
/** NicoVideoFragmentを取得する */
private fun requireDevNicoVideoFragment(): NicoVideoFragment {
return requireParentFragment() as NicoVideoFragment
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return viewBinding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewBinding.fragmentNicovideoInfoDescriptionTextview.movementMethod = LinkMovementMethod.getInstance()
// LiveData監視
setLiveData()
// いいね機能
setLike()
}
/**
* LiveDataで動画情報をもらう
* */
private fun setLiveData() {
// 動画情報
viewModel.nicoVideoData.observe(viewLifecycleOwner) { nicovideoData ->
viewBinding.fragmentNicovideoInfoTitleTextview.text = nicovideoData.title
// 投稿日時、再生数 等
viewBinding.fragmentNicovideoInfoUploadTextview.text = "${getString(R.string.post_date)}:${toFormatTime(nicovideoData.date)}"
viewBinding.fragmentNicovideoInfoPlayCountTextview.text = "${getString(R.string.play_count)}:${nicovideoData.viewCount}"
viewBinding.fragmentNicovideoInfoMylistCountTextview.text = "${getString(R.string.mylist)}:${nicovideoData.mylistCount}"
viewBinding.fragmentNicovideoInfoCommentCountTextview.text = "${getString(R.string.comment_count)}:${nicovideoData.commentCount}"
// 今日の日付から計算
viewBinding.fragmentNicovideoInfoUploadDayCountTextview.text = "今日の日付から ${getDayCount(toFormatTime(nicovideoData.date))} 日前に投稿"
// 一周年とか。
val anniversary = calcAnniversary(toUnixTime(toFormatTime(nicovideoData.date))) // AnniversaryDateクラス みて
when {
anniversary == 0 -> {
viewBinding.fragmentNicovideoInfoUploadTextview.setTextColor(Color.RED)
}
anniversary != -1 -> {
viewBinding.fragmentNicovideoInfoUploadAnniversaryTextview.apply {
isVisible = true
text = AnniversaryDate.makeAnniversaryMessage(anniversary) // お祝いメッセージ作成
}
}
}
}
// 動画説明文
viewModel.nicoVideoDescriptionLiveData.observe(viewLifecycleOwner) { description ->
setLinkText(HtmlCompat.fromHtml(description, HtmlCompat.FROM_HTML_MODE_COMPACT), viewBinding.fragmentNicovideoInfoDescriptionTextview)
}
// 投稿者情報
viewBinding.fragmentNicovideoInfoOwnerTextview.isVisible = false
viewModel.userDataLiveData.observe(viewLifecycleOwner) { userData ->
viewBinding.fragmentNicovideoInfoOwnerTextview.isVisible = true
viewBinding.fragmentNicovideoInfoOwnerTextview.text = userData.nickName
// 押したとき
viewBinding.fragmentNicovideoInfoOwnerCardview.setOnClickListener {
if (!userData.userId.contains("co") && !userData.userId.contains("ch")) {
// ユーザー情報Fragmentへ飛ばす
val accountFragment = NicoAccountFragment().apply {
arguments = Bundle().apply {
putString("userId", userData.userId)
}
}
(requireActivity() as MainActivity).setFragment(accountFragment, "account")
requireDevNicoVideoFragment().viewBinding.fragmentNicovideoMotionLayout.transitionToState(R.id.fragment_nicovideo_transition_end)
} else {
//チャンネルの時、ch以外にもそれぞれアニメの名前を入れても通る。例:te-kyu2 / gochiusa など
openBrowser("https://ch.nicovideo.jp/${userData.userId}")
}
}
// 投稿者アイコン。インターネット接続時
if (isConnectionInternet(context) && userData.largeIcon.isNotEmpty()) {
// ダークモード対策
viewBinding.fragmentNicovideoInfoOwnerImageview.imageTintList = null
Glide.with(viewBinding.fragmentNicovideoInfoOwnerImageview)
.load(userData.largeIcon)
.apply(RequestOptions.bitmapTransform(RoundedCorners(10)))
.into(viewBinding.fragmentNicovideoInfoOwnerImageview)
}
}
// シリーズ。あれば
viewModel.seriesHTMLDataLiveData.observe(viewLifecycleOwner) { seriesData ->
seriesData ?: return@observe
viewBinding.fragmentNicovideoInfoSeriesCardView.isVisible = true
viewBinding.fragmentNicovideoInfoSeriesNameTextView.text = seriesData.seriesData.title
Glide.with(viewBinding.fragmentNicovideoInfoSeriesThumbImageView)
.load(seriesData.seriesData.thumbUrl)
.apply(RequestOptions.bitmapTransform(RoundedCorners(10)))
.into(viewBinding.fragmentNicovideoInfoSeriesThumbImageView)
viewBinding.fragmentNicovideoInfoSeriesThumbImageView.imageTintList = null
// 連続再生開始ボタン
viewBinding.fragmentNicovideoInfoSeriesStartButton.setOnClickListener {
// シリーズ連続再生押した時
viewModel.addSeriesPlaylist(seriesId = seriesData.seriesData.seriesId)
}
// 最初、前後のボタン
if (seriesData.firstVideoData != null) {
viewBinding.fragmentNicovideoInfoSeriesFirstButton.text = """
${getString(R.string.nicovideo_series_first_video)}
${seriesData.firstVideoData.title}
""".trimIndent()
viewBinding.fragmentNicovideoInfoSeriesFirstButton.setOnClickListener {
viewModel.load(seriesData.firstVideoData.videoId, seriesData.firstVideoData.isCache, viewModel.isEco, viewModel.useInternet)
}
} else {
viewBinding.fragmentNicovideoInfoSeriesFirstButton.isVisible = false
}
if (seriesData.prevVideoData != null) {
viewBinding.fragmentNicovideoInfoSeriesPrevButton.text = """
${getString(R.string.nicovideo_series_prev_video)}
${seriesData.prevVideoData.title}
""".trimIndent()
viewBinding.fragmentNicovideoInfoSeriesPrevButton.setOnClickListener {
viewModel.load(seriesData.prevVideoData.videoId, seriesData.prevVideoData.isCache, viewModel.isEco, viewModel.useInternet)
}
} else {
viewBinding.fragmentNicovideoInfoSeriesPrevButton.isVisible = false
}
if (seriesData.nextVideoData != null) {
viewBinding.fragmentNicovideoInfoSeriesNextButton.text = """
${getString(R.string.nicovideo_series_next_video)}
${seriesData.nextVideoData.title}
""".trimIndent()
viewBinding.fragmentNicovideoInfoSeriesNextButton.setOnClickListener {
viewModel.load(seriesData.nextVideoData.videoId, seriesData.nextVideoData.isCache, viewModel.isEco, viewModel.useInternet)
}
} else {
viewBinding.fragmentNicovideoInfoSeriesNextButton.isVisible = false
}
}
// タグ
viewModel.tagListLiveData.observe(viewLifecycleOwner) { tagList ->
//たぐ
viewBinding.fragmentNicovideoInfoTitleLinearlayout.removeAllViews()
tagList.forEach { tagData ->
val name = tagData.tagName
val isDictionaryExists = tagData.hasNicoPedia //大百科があるかどうか
val linearLayout = LinearLayout(context)
linearLayout.orientation = LinearLayout.HORIZONTAL
//ボタン
val button = Button(context)
//大きさとか
val linearLayoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
linearLayoutParams.weight = 1F
button.layoutParams = linearLayoutParams
button.text = name
button.isAllCaps = false
linearLayout.addView(button)
if (isDictionaryExists) {
val dictionaryButton = Button(context)
dictionaryButton.text = getString(R.string.dictionary)
linearLayout.addView(dictionaryButton)
//大百科ひらく
dictionaryButton.setOnClickListener {
openBrowser("https://dic.nicovideo.jp/a/$name")
}
}
viewBinding.fragmentNicovideoInfoTitleLinearlayout.addView(linearLayout)
// タグ検索FragmentをViewPagerに追加する
button.setOnClickListener {
// オフライン時は動かさない
if (isConnectionInternet(context)) {
val searchFragment = NicoVideoSearchFragment().apply {
arguments = Bundle().apply {
putString("search", name)
putBoolean("search_hide", true)
putBoolean("sort_show", true)
}
}
// 追加位置
val addPos = requireDevNicoVideoFragment().viewPagerAdapter.fragmentList.size
// ViewPager追加
requireDevNicoVideoFragment().viewPagerAdapter.addFragment(searchFragment, "${getString(R.string.tag)}:$name")
// ViewPager移動
requireDevNicoVideoFragment().viewBinding.fragmentNicovideoViewpager.currentItem = addPos
}
// 動画IDのとき。例:「後編→sm」とか
val id = IDRegex(name)
if (id != null) {
Snackbar.make(button, "${getString(R.string.find_video_id)} : $id", Snackbar.LENGTH_SHORT).apply {
setAction(R.string.play) {
(requireActivity() as? MainActivity)?.setNicovideoFragment(videoId = id)
}
show()
}
}
}
}
}
}
/** いいね機能用意 */
private fun setLike() {
if (viewModel.isOfflinePlay.value == false && isLoginMode(context)) {
// キャッシュじゃない かつ ログイン必須モード
viewBinding.fragmentNicovideoInfoLikeChip.isVisible = true
// LiveData監視
viewModel.isLikedLiveData.observe(viewLifecycleOwner) { isLiked ->
viewModel.nicoVideoData.observe(viewLifecycleOwner) { data ->
// いいねボタン変更
setLikeChipStatus(isLiked, data)
}
}
// お礼メッセージ監視
viewModel.likeThanksMessageLiveData.observe(viewLifecycleOwner) {
if (!viewModel.isAlreadyShowThanksMessage) {
val thanksMessageBottomFragment = NicoVideoLikeThanksMessageBottomFragment()
thanksMessageBottomFragment.show(parentFragmentManager, "thanks")
}
}
// いいね押したとき
viewBinding.fragmentNicovideoInfoLikeChip.setOnClickListener {
if (viewModel.isLikedLiveData.value == true) {
requireDevNicoVideoFragment().showSnackbar(getString(R.string.unlike), getString(R.string.torikesu)) {
// いいね解除API叩く
viewModel.removeLike()
}
} else {
// いいね開く
val nicoVideoLikeBottomFragment = NicoVideoLikeBottomFragment()
nicoVideoLikeBottomFragment.show(parentFragmentManager, "like")
}
}
}
}
/** ハートのアイコン色とテキストを変更する関数 */
private fun setLikeChipStatus(liked: Boolean, data: NicoVideoData) {
val isShowLikeCount = prefSetting.getBoolean("setting_nicovideo_show_like_count", false)
requireActivity().runOnUiThread {
// いいね済み
if (liked) {
// いいね済み
viewBinding.fragmentNicovideoInfoLikeChip.apply {
chipIconTint = ColorStateList.valueOf(Color.parseColor("#ffc0cb")) // ピンク
text = if (isShowLikeCount) {
"${getString(R.string.liked)}:${data.likeCount}"
} else {
getString(R.string.liked)
}
}
} else {
viewBinding.fragmentNicovideoInfoLikeChip.apply {
chipIconTint = ColorStateList.valueOf(getThemeTextColor(context)) // テーマの色
text = if (isShowLikeCount) {
"${getString(R.string.like)}:${data.likeCount}"
} else {
getString(R.string.like)
}
}
}
}
}
/** 投稿日のフォーマットをUnixTimeへ変換する */
private fun toUnixTime(postedDateTime: String) = SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse(postedDateTime).time
/**
* 動画投稿日が何日前か数えるやつ。
* @param upDateTime yyyy/MM/dd HH:mm:ssの形式で。
*
* */
private fun getDayCount(upDateTime: String): String {
// UnixTime(ミリ秒)へ変換
val simpleDateFormat = SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
// 時、分とかは切り捨てる(多分いらない。)
val calendar = Calendar.getInstance().apply {
time = simpleDateFormat.parse(upDateTime)
set(Calendar.HOUR, 0)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
}
// 現在時刻から引く
val calc = System.currentTimeMillis() - calendar.time.time
// 計算で出す。多分もっといい方法ある。
val second = calc / 1000 // ミリ秒から秒へ
val minute = second / 60 // 秒から分へ
val hour = minute / 60 // 分から時間へ
val day = hour / 24 // 時間から日付へ
return day.toString()
}
fun openBrowser(url: String) {
val intent = Intent(Intent.ACTION_VIEW, url.toUri())
startActivity(intent)
}
fun showToast(message: String) {
activity?.runOnUiThread {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
}
}
/**
* TextViewのリンク(mylist/数字)とか(sm157)とかを押したときブラウザ開くのではなくこのアプリ内で表示できるようにする。
* */
fun setLinkText(text: Spanned, textView: TextView) {
// リンクを付ける。
val span = Spannable.Factory.getInstance().newSpannable(text.toString())
// 動画ID押せるように。ちなみに↓の変数はニコ動の動画ID正規表現
val mather = NICOVIDEO_ID_REGEX.toPattern().matcher(text)
while (mather.find()) {
// 動画ID取得
val id = mather.group()
span.setSpan(object : ClickableSpan() {
override fun onClick(widget: View) {
// 再生画面表示
(requireActivity() as? MainActivity)?.setNicovideoFragment(videoId = id, isCache = false)
}
}, mather.start(), mather.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
// マイリスト押せるように
val mylistMatcher = NICOVIDEO_MYLIST_ID_REGEX.toPattern().matcher(text)
while (mylistMatcher.find()) {
val mylist = mylistMatcher.group()
span.setSpan(object : ClickableSpan() {
override fun onClick(widget: View) {
// マイリスト表示FragmentをViewPagerに追加する
val mylistFragment = NicoVideoMyListListFragment().apply {
arguments = Bundle().apply {
putString("mylist_id", mylist.replace("mylist/", ""))// IDだけくれ
putBoolean("is_other", true)
}
}
requireDevNicoVideoFragment().apply {
// ViewPager追加
viewPagerAdapter.addFragment(mylistFragment, "${getString(R.string.mylist)}:$mylist")
// ViewPager移動
viewBinding.fragmentNicovideoViewpager.currentItem = viewPagerAdapter.fragmentTabName.size
}
}
}, mylistMatcher.start(), mylistMatcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
// シリーズ押せるように
val seriesMatcher = NICOVIDEO_SERIES_ID_REGEX.toPattern().matcher(text)
while (seriesMatcher.find()) {
val series = seriesMatcher.group()
span.setSpan(object : ClickableSpan() {
override fun onClick(widget: View) {
// マイリスト表示FragmentをViewPagerに追加する
val seriesFragment = NicoVideoSeriesFragment().apply {
arguments = Bundle().apply {
putString("series_id", series.replace("series/", "")) // IDだけくれ
putString("series_title", series) // シリーズのタイトル知らないのでIDでごめんね
}
}
requireDevNicoVideoFragment().apply {
// ViewPager追加
viewPagerAdapter.addFragment(seriesFragment, "${getString(R.string.series)}:$series")
// ViewPager移動
viewBinding.fragmentNicovideoViewpager.currentItem = viewPagerAdapter.fragmentTabName.size
}
}
}, seriesMatcher.start(), seriesMatcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
// URL押せるように
val URL_REGEX = "https?://[\\w!?/\\+\\-_~=;\\.,*&@#\$%\\(\\)\\'\\[\\]]+"
val urlMather = URL_REGEX.toPattern().matcher(text)
while (urlMather.find()) {
val url = urlMather.group()
span.setSpan(object : ClickableSpan() {
override fun onClick(widget: View) {
// ブラウザ
val intent = Intent(Intent.ACTION_VIEW, url.toUri())
startActivity(intent)
}
}, urlMather.start(), urlMather.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
// 再生時間へ移動。例:#25:25で25:25へ移動できる
val SEEK_TIME_REGEX = "(#)([0-9][0-9]):([0-9][0-9])"
val seekTimeMatcher = SEEK_TIME_REGEX.toPattern().matcher(text)
while (seekTimeMatcher.find()) {
val time = seekTimeMatcher.group().replace("#", "")
span.setSpan(object : ClickableSpan() {
override fun onClick(widget: View) {
// 再生時間操作
requireDevNicoVideoFragment().apply {
// 分:秒 を ミリ秒へ
val minute = time.split(":")[0].toLong() * 60
val second = time.split(":")[1].toLong()
exoPlayer.seekTo((minute + second) * 1000)
}
}
}, seekTimeMatcher.start(), seekTimeMatcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
textView.text = span
textView.movementMethod = LinkMovementMethod.getInstance();
}
}
| 0
| null |
0
| 3
|
5c58707eecc7a994fbd4bc900b22106697bf3806
| 21,275
|
StanDroid
|
Apache License 2.0
|
app/src/main/java/com/jumpingphantom/flow/core/ui/containers/Elements.kt
|
JumpingPhantom
| 811,400,534
| false
|
{"Kotlin": 109236}
|
package com.jumpingphantom.flow.core.ui.containers
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
private val defaultPadding = 4.dp
@Composable
fun BasicRow(modifier: Modifier = Modifier, content: @Composable RowScope.() -> Unit) {
Row(
modifier = Modifier
.padding(defaultPadding)
.then(modifier)
) {
content()
}
}
@Composable
fun CenteredRow(modifier: Modifier = Modifier, content: @Composable RowScope.() -> Unit) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center,
modifier = Modifier
.fillMaxWidth()
.padding(defaultPadding)
.then(modifier)
) {
content()
}
}
@Composable
fun SpacedBetweenRow(modifier: Modifier = Modifier, content: @Composable RowScope.() -> Unit) {
Row(
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.padding(defaultPadding)
.then(modifier)
) {
content()
}
}
@Composable
fun SpacedAroundRow(modifier: Modifier = Modifier, content: @Composable RowScope.() -> Unit) {
Row(
horizontalArrangement = Arrangement.SpaceAround,
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.padding(defaultPadding)
.then(modifier)
) {
content()
}
}
@Composable
fun BasicColumn(modifier: Modifier = Modifier, content: @Composable ColumnScope.() -> Unit) {
Column(
modifier = Modifier
.padding(defaultPadding)
.then(modifier)
) {
content()
}
}
@Composable
fun ScreenSizedColumn(modifier: Modifier = Modifier, content: @Composable ColumnScope.() -> Unit) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier
.padding(defaultPadding)
.fillMaxSize()
.then(modifier)
) {
content()
}
}
@Composable
fun CenteredColumn(modifier: Modifier = Modifier, content: @Composable ColumnScope.() -> Unit) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier
.padding(defaultPadding)
.then(modifier)
) {
content()
}
}
| 0
|
Kotlin
|
0
| 0
|
7c82814773d647043401c8e67781af0cae0947a9
| 3,029
|
Flow
|
MIT License
|
app/src/main/java/com/magonxesp/randomanimepicker/ui/anime/compose/AnimeList.kt
|
magonxesp
| 741,908,674
| false
|
{"Kotlin": 269209, "Makefile": 1027}
|
package com.magonxesp.randomanimepicker.ui.anime.compose
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.Icon
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
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.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.magonxesp.randomanimepicker.R
import com.magonxesp.randomanimepicker.domain.anime.Anime
import com.magonxesp.randomanimepicker.domain.anime.info.AnimeInfo
import com.magonxesp.randomanimepicker.domain.anime.pick.AnimePick
import com.magonxesp.randomanimepicker.ui.shared.compose.RemoteImage
import com.magonxesp.randomanimepicker.ui.shared.compose.itemsGroupedByRelativeTime
@Composable
fun AnimePickList(picks: List<Pair<AnimePick, AnimeInfo>>) {
LazyColumn(
modifier = Modifier.fillMaxSize()
) {
itemsGroupedByRelativeTime(
items = picks,
selector = { it.first.pickedOn.date }
) { item ->
val pick = item.first
val animeInfo = item.second
ListItem(
headlineContent = {
Text(
text = animeInfo.title.romaji,
style = MaterialTheme.typography.titleSmall,
maxLines = 2,
overflow = TextOverflow.Ellipsis
)
},
supportingContent = {
Text(
text = animeInfo.title.japanese,
style = MaterialTheme.typography.bodySmall,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(top = 2.dp)
)
},
leadingContent = {
RemoteImage(
modifier = Modifier
.width(64.dp)
.height(82.dp),
url = animeInfo.image.url,
contentDescription = stringResource(
id = R.string.anime_pick_list_item_cover,
animeInfo.title.romaji
)
)
},
trailingContent = {
if (pick.like.value) {
Icon(
painter = painterResource(id = R.drawable.outline_favorite_24),
contentDescription = stringResource(id = R.string.anime_pick_list_item_liked),
tint = Color.Green
)
} else {
Icon(
painter = painterResource(id = R.drawable.close_24px),
contentDescription = stringResource(id = R.string.anime_pick_list_item_not_liked),
tint = Color.Red
)
}
}
)
}
}
}
@Preview
@Composable
fun AnimePickListPreview() {
AnimePickList(picks = examplePickList)
}
| 0
|
Kotlin
|
0
| 1
|
1d6738bade13a9567417d2eaba2c76d156a90d69
| 2,832
|
RandomAnimePicker-android
|
MIT License
|
libnavui-dropin/src/main/java/com/mapbox/navigation/dropin/component/recenter/RecenterViewModel.kt
|
k4anubhav
| 439,334,238
| true
|
{"Kotlin": 4189704, "Java": 26254, "Python": 11580, "Makefile": 6163, "Shell": 5704}
|
package com.mapbox.navigation.dropin.component.recenter
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.scan
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
@OptIn(ExperimentalCoroutinesApi::class)
class RecenterViewModel : ViewModel() {
private val _recenterState: MutableStateFlow<RecenterState> = MutableStateFlow(
RecenterState.initial()
)
internal fun recenterState(): Flow<RecenterState> = _recenterState
internal fun consumeAction(action: Flow<RecenterButtonAction>) {
viewModelScope.launch {
action
.reduce()
.onEach { _recenterState.value = it }
.stateIn(viewModelScope)
}
}
private fun Flow<RecenterButtonAction>.reduce(): Flow<RecenterState> =
scan(_recenterState.value) { accumulator, value ->
when (value) {
is RecenterButtonAction.UpdateNavigationState -> {
val visibilityResult = RecenterButtonProcessor.ProcessVisibilityState(
value.navigationState,
accumulator.cameraState
).process()
val navigationStateResult = RecenterButtonProcessor.ProcessNavigationState(
value.navigationState
).process()
accumulator.copy(
isVisible = visibilityResult.isVisible,
navigationState = navigationStateResult.navigationState,
cameraState = accumulator.cameraState
)
}
is RecenterButtonAction.UpdateCameraState -> {
val visibilityResult = RecenterButtonProcessor.ProcessVisibilityState(
accumulator.navigationState,
value.cameraState
).process()
val cameraStateResult = RecenterButtonProcessor.ProcessCameraState(
value.cameraState
).process()
accumulator.copy(
isVisible = visibilityResult.isVisible,
navigationState = accumulator.navigationState,
cameraState = cameraStateResult.cameraState
)
}
}
}
}
| 0
| null |
1
| 1
|
3751b1323b3e585976a5476176810049061ca1ec
| 2,607
|
mapbox-navigation-android
|
Apache License 2.0
|
app/src/main/java/com/frafio/myfinance/data/enums/db/PurchaseCode.kt
|
francescofiorella
| 360,818,457
| false
|
{"Kotlin": 202595}
|
package com.frafio.myfinance.data.enums.db
import com.frafio.myfinance.utils.getCurrentLanguage
enum class PurchaseCode(val code: Int, val message: String) {
EMPTY_NAME(
1, when (getCurrentLanguage()) {
Languages.ENGLISH.value -> "Enter the purchase name."
Languages.ITALIANO.value -> "Inserisci il nome dell'acquisto."
else -> "Enter the purchase name." // english
}
),
EMPTY_PRICE(
2, when (getCurrentLanguage()) {
Languages.ENGLISH.value -> "Enter the purchase price."
Languages.ITALIANO.value -> "Inserisci il costo dell'acquisto."
else -> "Enter the purchase price." // english
}
),
WRONG_NAME_TOTAL(
3, when (getCurrentLanguage()) {
Languages.ENGLISH.value -> "The purchase name can't be 'Total'."
Languages.ITALIANO.value -> "L'acquisto non può chiamarsi 'Totale'."
else -> "The purchase name can't be 'Total'." // english
}
),
EMPTY_CATEGORY(
4, when (getCurrentLanguage()) {
Languages.ENGLISH.value -> "Enter the purchase category."
Languages.ITALIANO.value -> "Inserisci la categoria dell'acquisto."
else -> "Enter the purchase category." // english
}
),
PURCHASE_ADD_SUCCESS(
10, when (getCurrentLanguage()) {
Languages.ENGLISH.value -> "Purchase added!"
Languages.ITALIANO.value -> "Acquisto aggiunto!"
else -> "Purchase added!" // english
}
),
PURCHASE_ADD_FAILURE(
11, when (getCurrentLanguage()) {
Languages.ENGLISH.value -> "Purchase not added!"
Languages.ITALIANO.value -> "Acquisto non aggiunto!"
else -> "Purchase not added!" // english
}
),
PURCHASE_EDIT_SUCCESS(
20, when (getCurrentLanguage()) {
Languages.ENGLISH.value -> "Purchase edited!"
Languages.ITALIANO.value -> "Acquisto modificato!"
else -> "Purchase edited!" // english
}
),
PURCHASE_EDIT_FAILURE(
21, when (getCurrentLanguage()) {
Languages.ENGLISH.value -> "Purchase not edited!"
Languages.ITALIANO.value -> "Acquisto non modificato!"
else -> "Purchase not edited!" // english
}
),
PURCHASE_DELETE_SUCCESS(
30, when (getCurrentLanguage()) {
Languages.ENGLISH.value -> "Purchase deleted!"
Languages.ITALIANO.value -> "Acquisto eliminato!"
else -> "Purchase deleted!" // english
}
),
PURCHASE_DELETE_FAILURE(
31, when (getCurrentLanguage()) {
Languages.ENGLISH.value -> "Purchase not deleted correctly!"
Languages.ITALIANO.value -> "Acquisto non eliminato correttamente!"
else -> "Purchase not deleted correctly!" // english
}
),
PURCHASE_LIST_UPDATE_SUCCESS(
40, when (getCurrentLanguage()) {
Languages.ENGLISH.value -> "List updated!"
Languages.ITALIANO.value -> "Lista aggiornata!"
else -> "List Updated!" // english
}
),
PURCHASE_LIST_UPDATE_FAILURE(
41, when (getCurrentLanguage()) {
Languages.ENGLISH.value -> "List not updated!"
Languages.ITALIANO.value -> "Lista non aggiornata!"
else -> "List not updated!" // english
}
),
PURCHASE_AGGREGATE_SUCCESS(
50, when (getCurrentLanguage()) {
Languages.ENGLISH.value -> "Aggregation query successful!"
Languages.ITALIANO.value -> "Query di aggregazione riuscita!"
else -> "Aggregation query successful!" // english
}
),
PURCHASE_AGGREGATE_FAILURE(
51, when (getCurrentLanguage()) {
Languages.ENGLISH.value -> "Aggregation query failed!"
Languages.ITALIANO.value -> "Query di aggregazione non riuscita!"
else -> "Aggregation query failed!" // english
}
),
PURCHASE_COUNT_SUCCESS(
52, when (getCurrentLanguage()) {
Languages.ENGLISH.value -> "Count query successful!"
Languages.ITALIANO.value -> "Query di conteggio riuscita!"
else -> "Count query successful!" // english
}
),
PURCHASE_COUNT_FAILURE(
53, when (getCurrentLanguage()) {
Languages.ENGLISH.value -> "Count query failed!"
Languages.ITALIANO.value -> "Query di conteggio non riuscita!"
else -> "Count query failed!" // english
}
),
BUDGET_UPDATE_SUCCESS(
60, when (getCurrentLanguage()) {
Languages.ENGLISH.value -> "Budget updated!"
Languages.ITALIANO.value -> "Budget aggiornato"
else -> "Budget updated!" // english
}
),
BUDGET_UPDATE_FAILURE(
61, when (getCurrentLanguage()) {
Languages.ENGLISH.value -> "Budget not updated!"
Languages.ITALIANO.value -> "Budget non aggiornato"
else -> "Budget not updated!" // english
}
),
INCOME_LIST_UPDATE_SUCCESS(
70, when (getCurrentLanguage()) {
Languages.ENGLISH.value -> "Income list updated!"
Languages.ITALIANO.value -> "Lista delle entrate aggiornata!"
else -> "Income list updated!" // english
}
),
INCOME_LIST_UPDATE_FAILURE(
71, when (getCurrentLanguage()) {
Languages.ENGLISH.value -> "Income list not updated!"
Languages.ITALIANO.value -> "Lista delle entrate non aggiornata!"
else -> "Income list not updated!" // english
}
),
INCOME_ADD_SUCCESS(
72, when (getCurrentLanguage()) {
Languages.ENGLISH.value -> "Income added!"
Languages.ITALIANO.value -> "Entrata aggiunta!"
else -> "Income added!" // english
}
),
INCOME_ADD_FAILURE(
73, when (getCurrentLanguage()) {
Languages.ENGLISH.value -> "Income not added!"
Languages.ITALIANO.value -> "Entrata non aggiunta!"
else -> "Income not added!" // english
}
),
INCOME_DELETE_SUCCESS(
74, when (getCurrentLanguage()) {
Languages.ENGLISH.value -> "Income deleted!"
Languages.ITALIANO.value -> "Entrata eliminata!"
else -> "Income deleted!" // english
}
),
INCOME_DELETE_FAILURE(
75, when (getCurrentLanguage()) {
Languages.ENGLISH.value -> "Income not deleted correctly!"
Languages.ITALIANO.value -> "Entrata non eliminata correttamente!"
else -> "Income not deleted correctly!" // english
}
),
INCOME_EDIT_SUCCESS(
76, when (getCurrentLanguage()) {
Languages.ENGLISH.value -> "Income edited!"
Languages.ITALIANO.value -> "Entrata modificata!"
else -> "Income edited!" // english
}
),
INCOME_EDIT_FAILURE(
77, when (getCurrentLanguage()) {
Languages.ENGLISH.value -> "Income not edited!"
Languages.ITALIANO.value -> "Entrata non modificata!"
else -> "Income not edited!" // english
}
),
}
| 0
|
Kotlin
|
0
| 1
|
95982a5b5725046a0cc95ef78a98776da86721b4
| 7,269
|
MyFinance
|
MIT License
|
Chapter3/favedish-presentation/src/main/java/com/favedish/presentation/dishdetails/model/DishDetailsPresentationNotification.kt
|
bpbpublications
| 533,628,168
| false
| null |
package com.favedish.presentation.dishdetails.model
class DishDetailsPresentationNotification
| 0
|
Kotlin
|
5
| 7
|
cd85b9fb89e307ad4977bcdb63121aa906f19427
| 95
|
Clean-Architecture-for-Android
|
MIT License
|
io/http/src/test/kotlin/io/bluetape4k/http/hc5/fluent/FluentExecutorExamples.kt
|
debop
| 625,161,599
| false
|
{"Kotlin": 7504333, "HTML": 502995, "Java": 2273, "JavaScript": 1351, "Shell": 1301, "CSS": 444, "Dockerfile": 121, "Mustache": 82}
|
package io.bluetape4k.http.hc5.fluent
import io.bluetape4k.http.hc5.AbstractHc5Test
import io.bluetape4k.http.hc5.http.httpHostOf
import io.bluetape4k.junit5.folder.TempFolder
import io.bluetape4k.junit5.folder.TempFolderTest
import io.bluetape4k.logging.KLogging
import io.bluetape4k.logging.debug
import io.bluetape4k.support.toUtf8String
import org.apache.hc.client5.http.fluent.Executor
import org.apache.hc.client5.http.fluent.Form
import org.apache.hc.core5.http.ContentType
import org.apache.hc.core5.http.HttpVersion
import org.apache.hc.core5.util.Timeout
import org.junit.jupiter.api.Test
/**
* This example demonstrates how the he HttpClient fluent API can be used to execute multiple
* requests within the same security context. The Executor class maintains a common context shared
* by all requests executed with it. The Executor is thread-safe and can be used to execute
* requests concurrently from multiple threads of execution.
*/
@TempFolderTest
class FluentExecutorExamples: AbstractHc5Test() {
companion object: KLogging()
private val executor: Executor = Executor.newInstance()
.auth(httpHostOf(httpbinBaseUrl), "user", "passwd".toCharArray())
.auth(httpHostOf("http://nghttp2.org"), "user", "passwd".toCharArray())
.authPreemptive(httpHostOf(httpbinBaseUrl))
@Test
fun `get with timeout settings`() {
// Execute a GET with timeout settings and return response content as String.
val content = executor
.execute(
requestGet("$httpbinBaseUrl/basic-auth/user/passwd")
.connectTimeout(Timeout.ofSeconds(1))
)
.returnContent()
.asString(Charsets.UTF_8)
log.debug { "content=$content" }
}
@Test
fun `post with HTTP 1_1`() {
// Execute a POST with the 'expect-continue' handshake, using HTTP/1.1,
// containing a request body as String and return response content as byte array.
val contentBytes = executor
.execute(
requestPost("$httpbinBaseUrl/post")
.useExpectContinue()
.version(HttpVersion.HTTP_1_1)
.bodyString("Important stuff", ContentType.DEFAULT_TEXT)
)
.returnContent()
.asBytes()
log.debug { "contentBytes=${contentBytes.toUtf8String()}" }
}
@Test
fun `post multi-part form data`(tempFolder: TempFolder) {
// Execute a POST with a custom header through the proxy containing a request body
// as an HTML form and save the result to the file
// @see hc5/examples/ClientMultipartFormPost
val path = tempFolder.createFile()
executor
.execute(
requestPost("$httpbinBaseUrl/post")
.addHeader("X-Custom-Header", "stuff")
.bodyForm(
Form.form()
.add("username", "user")
.add("password", "<PASSWORD>")
.build()
)
)
.saveContent(path)
}
}
| 0
|
Kotlin
|
0
| 1
|
ce3da5b6bddadd29271303840d334b71db7766d2
| 3,162
|
bluetape4k
|
MIT License
|
src/main/kotlin/me/fzzyhmstrs/amethyst_imbuement/entity/hamster/HamsicleEntity.kt
|
fzzyhmstrs
| 461,338,617
| false
| null |
package me.fzzyhmstrs.amethyst_imbuement.entity.hamster
import me.fzzyhmstrs.amethyst_core.interfaces.SpellCastingEntity
import net.minecraft.entity.*
import net.minecraft.entity.damage.DamageSource
import net.minecraft.nbt.NbtCompound
import net.minecraft.registry.tag.DamageTypeTags
import net.minecraft.world.LocalDifficulty
import net.minecraft.world.ServerWorldAccess
import net.minecraft.world.World
open class HamsicleEntity: BaseHamsterEntity, SpellCastingEntity {
constructor(entityType: EntityType<HamsicleEntity>, world: World): super(entityType, world)
constructor(entityType: EntityType<HamsicleEntity>, world: World, ageLimit: Int, createdBy: LivingEntity? = null) : super(entityType, world, ageLimit, createdBy){
}
override fun initialize(
world: ServerWorldAccess,
difficulty: LocalDifficulty,
spawnReason: SpawnReason,
entityData: EntityData?,
entityNbt: NbtCompound?
): EntityData? {
val data = super.initialize(world, difficulty, spawnReason, entityData, entityNbt)
setVariant(HamsterVariant.FROST)
return data
}
override fun canFreeze(): Boolean {
return false
}
override fun attackEffects(target: Entity, damageSource: DamageSource, damage: Float) {
target.frozenTicks = 180
}
override fun damage(source: DamageSource, amount: Float): Boolean {
if (source.isIn(DamageTypeTags.IS_FREEZING))
return false
return super.damage(source, amount)
}
}
| 16
|
Kotlin
|
7
| 3
|
9971606dfafa9422e9558238c7783f8e27bd34a3
| 1,529
|
ai
|
MIT License
|
src/test/java/com/hi/dhl/ext/RemoteMachineInfo.kt
|
hi-dhl
| 547,103,098
| false
| null |
package com.hi.dhl.ext
import com.hi.dhl.common.Common
/**
* <pre>
* author: dhl
* date : 2022/9/10
* desc :
* </pre>
*/
data class RemoteMachineInfo(
val port: String,
val host: String,
val user: String,
val rootDir: String = Common.remoteRootDir
)
| 3
|
Kotlin
|
9
| 89
|
bccce0621b756f44c7d5eba026871fce5292c2be
| 287
|
SyncKit
|
Apache License 2.0
|
mapper/src/main/kotlin/com/kncept/mapper/java/time/JavaTimeModule.kt
|
kncept
| 761,612,876
| false
|
{"Kotlin": 45446}
|
package com.kncept.mapper.java.time
import com.kncept.mapper.TypeMapper
import com.kncept.mapper.TypeMapperModule
class JavaTimeModule : TypeMapperModule {
var truncateTypesToEpochSecond = true
override fun mappers(): List<TypeMapper<*>> {
return listOf(
LocalDateTimeMapper(),
LocalDateMapper(),
LocalTimeMapper(),
InstantMapper(truncateTypesToEpochSecond),
ZonedDateTimeMapper(),
DurationMapper(),
OffsetDateTimeMapper(),
OffsetTimeMapper(),
ZoneIdMapper(),
ZoneOffsetMapper(),
)
}
}
| 0
|
Kotlin
|
0
| 0
|
09132cf7f3af26d46ae770546090b7e03e8d3539
| 584
|
kotlin-dynamodb-mapper
|
MIT License
|
tvshow/presentation/detail/src/main/java/com/movietime/tvshow/detail/presentation/model/UiTvShowDetail.kt
|
milanga
| 471,352,982
| false
|
{"Kotlin": 191910}
|
package com.movietime.tvshow.detail.presentation.model
import com.movietime.domain.model.TvShowDetail
data class UiTvShowDetail(
val backdropPath: String,
val overview: String,
val tagline: String,
val title: String
)
fun TvShowDetail.toUiTvShowDetail(): UiTvShowDetail =
UiTvShowDetail(
backdropUrl,
overview,
tagline,
name
)
| 0
|
Kotlin
|
0
| 0
|
4a7a64d5beb57aea9a47377b8d03456bd8d2abcd
| 386
|
MovieTime
|
Apache License 2.0
|
src/main/kotlin/io/github/kr8gz/playerstatistics/commands/ServerTotalCommand.kt
|
kr8gz
| 780,166,652
| false
|
{"Kotlin": 42638, "Java": 2449}
|
package io.github.kr8gz.playerstatistics.commands
import io.github.kr8gz.playerstatistics.commands.ShareCommand.storeShareData
import io.github.kr8gz.playerstatistics.database.Leaderboard
import io.github.kr8gz.playerstatistics.database.Statistics
import io.github.kr8gz.playerstatistics.extensions.ServerCommandSource.sendFeedback
import io.github.kr8gz.playerstatistics.extensions.Text.build
import io.github.kr8gz.playerstatistics.extensions.Text.space
import io.github.kr8gz.playerstatistics.messages.*
import net.minecraft.server.command.ServerCommandSource
import net.minecraft.stat.Stat
import net.minecraft.text.Text
import net.silkmc.silk.commands.LiteralCommandBuilder
import net.silkmc.silk.core.text.literalText
object ServerTotalCommand : StatsCommand("total") {
override fun LiteralCommandBuilder<ServerCommandSource>.build() {
statArgument { maybeStat ->
optionalPlayerArgument { maybePlayer ->
executes {
val stat = maybeStat() ?: throw Exceptions.NO_DATA.create()
val player = maybePlayer() ?: source.player?.gameProfile?.name
usingDatabase { source.sendServerTotal(stat, player) }
}
}
}
}
private suspend fun ServerCommandSource.sendServerTotal(stat: Stat<*>, highlightName: String?) {
val statFormatter = StatFormatter(stat)
val label = run {
val statName = LeaderboardCommand.formatStatNameWithSuggestion(statFormatter).withColor(Colors.WHITE)
Text.translatable("playerstatistics.command.total", statName).withColor(Colors.GRAY)
}
val content = label.build {
val total = Statistics.serverTotal(stat)
text(": "); text(statFormatter.formatValue(total)) { color = Colors.VALUE_HIGHLIGHT }
highlightName?.let { Leaderboard.Entry(stat, it) }?.let { (_, name, value) ->
newLine()
val formattedName = literalText(name) { color = Colors.WHITE }
val contributed = statFormatter.formatValue(value).build { color = Colors.VALUE_HIGHLIGHT }
text(Text.translatable("playerstatistics.command.total.contributed", formattedName, contributed)) { color = Colors.GRAY }
text(" ") {
text("(")
val percentage = formatNumber(value.toFloat() / total * 100)
text("$percentage%") { color = Colors.VALUE }
text(")")
color = Colors.GRAY
}
}
}
sendFeedback {
val shareCode = storeShareData(label, content)
content space Components.shareButton(shareCode)
}
}
}
| 1
|
Kotlin
|
0
| 3
|
7ec35d74be4cdcd6d91b09193c2faf39e2cd96a2
| 2,756
|
PlayerStatistics
|
MIT License
|
modulecheck-api/src/main/kotlin/modulecheck/api/ProjectDependencies.kt
|
jeremiahvanofferen
| 397,332,342
| true
|
{"Kotlin": 440018, "JavaScript": 9458, "CSS": 3037}
|
/*
* Copyright (C) 2021 <NAME>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package modulecheck.api
class ProjectDependencies(
map: Map<ConfigurationName, List<ConfiguredProjectDependency>>
) : Map<ConfigurationName, List<ConfiguredProjectDependency>> by map {
fun main(): List<ConfiguredProjectDependency> = ConfigurationName.main()
.flatMap { configurationName ->
get(configurationName).orEmpty()
}
fun public(): List<ConfiguredProjectDependency> = ConfigurationName.public()
.flatMap { configurationName ->
get(configurationName).orEmpty()
}
fun private(): List<ConfiguredProjectDependency> = ConfigurationName.private()
.flatMap { configurationName ->
get(configurationName).orEmpty()
}
}
| 0
| null |
0
| 0
|
65455e246ffcfe398335af0ca87348d561348c54
| 1,263
|
ModuleCheck
|
Apache License 2.0
|
src/main/kotlin/com/exactpro/th2/act/ssh/cfg/SshServiceConfiguration.kt
|
th2-net
| 441,131,998
| false
|
{"Kotlin": 53956, "Java": 6977, "Dockerfile": 445}
|
/*
* Copyright 2020-2021 Exactpro (Exactpro Systems Limited)
*
* 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.exactpro.th2.act.ssh.cfg
import com.fasterxml.jackson.annotation.JsonSubTypes
import com.fasterxml.jackson.annotation.JsonTypeInfo
import java.nio.file.Path
class SshServiceConfiguration(
val connection: ConnectionParameters,
val executions: List<Execution>,
val reporting: ReportingConfiguration = ReportingConfiguration(),
val messagePublication: PublicationConfiguration = PublicationConfiguration(),
) {
init {
require(executions.isNotEmpty()) { "At least one alias must be set" }
checkCollisions("Execution", executions, Execution::alias)
}
}
class ReportingConfiguration(
val rootName: String = "ActSsh",
val addStackStraceForErrors: Boolean = true
)
class ConnectionParameters(
val endpoints: List<EndpointParameters>,
val stopWaitTimeout: Long = 10_000L
) {
init {
require(stopWaitTimeout > 0) { "Stop timeout must be greater that zero (0)" }
checkCollisions("Endpoints", endpoints, EndpointParameters::alias)
}
}
class EndpointParameters(
val alias: String,
val host: String,
val username: String,
val password: String? = null,
val privateKeyPath: Path? = null,
val port: Int = 22,
val connectionTimeout: Long = 1000L,
val authTimeout: Long = 1000L
) {
init {
require(alias.isNotBlank()) { "alias must not be blank" }
require(host.isNotBlank()) { "host must not be blank" }
require(username.isNotBlank()) { "username must not be blank" }
require(port > 0) { "port must be a positive integer but was $port" }
require(privateKeyPath != null && password == null || password != null && privateKeyPath == null) {
"Either privateKeyPath or password must be set"
}
}
}
class PublicationConfiguration(
val enabled: Boolean = false,
)
@JsonSubTypes(
JsonSubTypes.Type(CommandExecution::class, name = "command"),
JsonSubTypes.Type(ScriptExecution::class, name = "script")
)
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "type",
defaultImpl = CommandExecution::class
)
sealed class Execution(
val alias: String,
val execution: String,
val defaultParameters: Map<String, String>,
val addOutputToResponse: Boolean,
val timeout: Long,
val interruptOnTimeout: Boolean,
val messagePublication: PublicationConfiguration?,
)
class CommandExecution(
alias: String,
execution: String,
defaultParameters: Map<String, String> = emptyMap(),
addOutputToResponse: Boolean = true,
timeout: Long,
interruptOnTimeout: Boolean = false,
messagePublication: PublicationConfiguration? = null,
) : Execution(
alias,
execution,
defaultParameters,
addOutputToResponse,
timeout,
interruptOnTimeout,
messagePublication,
)
class ScriptExecution(
alias: String,
val scriptPath: String,
options: String = "",
val addScriptToReport: Boolean = true,
defaultParameters: Map<String, String> = emptyMap(),
addOutputToResponse: Boolean = true,
timeout: Long,
interruptOnTimeout: Boolean = false,
messagePublication: PublicationConfiguration? = null,
) : Execution(
alias,
if (options.isBlank()) scriptPath else "$scriptPath $options",
defaultParameters,
addOutputToResponse,
timeout,
interruptOnTimeout,
messagePublication,
)
private fun <T> checkCollisions(name: String, executions: List<T>, aliasExtractor: T.() -> String) {
val aliases = executions.map { it.aliasExtractor() }
val collisions = aliases.filter { alias -> aliases.asSequence().filter { alias.equals(it, ignoreCase = true) }.take(2).toList().size > 1 }
require(collisions.isEmpty()) {
"$name aliases are case insensitive. Collisions found: $collisions"
}
}
| 0
|
Kotlin
|
1
| 1
|
30643e1d58e370bc366e93ac6efd1c4a93fc0bf2
| 4,456
|
th2-act-ssh
|
Apache License 2.0
|
app/src/main/java/dev/mahdisml/webimmortalguards/ui/MainViewModel.kt
|
mahdisml
| 650,152,883
| false
| null |
package dev.mahdisml.webimmortalguards.ui
import android.app.Activity
import android.content.Context
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dev.mahdisml.webimmortalguards.data.SettingsRepository
import dev.mahdisml.webimmortalguards.net.VpnController
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
class MainViewModel : ViewModel() {
var pageState :Int? by mutableStateOf(null) //0=greeting,1=home,2=settings
private var checkPageStateJob: Job? = null
private var greetingsDoneJob: Job? = null
private var vpnController : VpnController? = null
var vpnState :Boolean by mutableStateOf(false)
private set
fun setVpnState(ctx:Context){
val prepared = android.net.VpnService.prepare(ctx)
if (prepared == null) {
if (vpnController == null) {
vpnController = VpnController(ctx)
}
vpnState = if (vpnState) {
vpnController?.endVpn()
false
} else {
vpnController?.startVpn()
true
}
}else{
(ctx as Activity).startActivityForResult(prepared,0x0F)
}
}
fun checkVpnState(ctx:Context){
viewModelScope.launch {
if(vpnController == null){
vpnController = VpnController(ctx)
}
vpnController?.let {
vpnState = it.isOn()
}
}
}
fun checkPageState(ctx:Context){
checkPageStateJob?.cancel()
checkPageStateJob = viewModelScope.launch{
pageState = if (SettingsRepository(ctx).getGreetingsState()){
1
}else{
0
}
}
}
fun greetingsDone(ctx:Context){
greetingsDoneJob?.cancel()
greetingsDoneJob = viewModelScope.launch{
SettingsRepository(ctx).setGreetingsState(true)
checkPageState(ctx)
}
}
}
| 0
|
Kotlin
|
1
| 29
|
f3870f22f9302efe80e83db88c5d3bcf4f312bb3
| 2,145
|
WebImmortalGuards
|
MIT License
|
src/test/resources/test-compile-data/jvm/kotlin-web-site/null-safety/caab662b5f82c6c847bb060aa8f9d04b.3.kt
|
AlexanderPrendota
| 219,478,945
| false
| null |
fun main() {
//sampleStart
val a = "Kotlin"
val b: String? = null
println(b?.length)
println(a?.length) // Unnecessary safe call
//sampleEnd
}
| 14
|
Kotlin
|
47
| 89
|
95326951087813b6dea8b5ef4234fc06f252bd80
| 158
|
kotlin-compiler-server
|
Apache License 2.0
|
lib/src/main/java/zone/bitverse/connect/BitverseConnectApi.kt
|
Bitverse-Pte
| 661,320,703
| false
| null |
package zone.bitverse.connect
import android.app.Application
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Handler
import android.util.Log
import com.squareup.moshi.Moshi
import com.walletconnect.android.Core
import com.walletconnect.android.CoreClient
import com.walletconnect.android.relay.ConnectionType
import com.walletconnect.sign.client.Sign
import com.walletconnect.sign.client.SignClient
import okhttp3.OkHttpClient
import zone.bitverse.connect.impls.BCClient
import zone.bitverse.connect.impls.MoshiPayloadAdapter
import zone.bitverse.connect.impls.OkHttpTransport
import java.net.URLEncoder
object BitverseConnectApi {
private var client: Client? = null
private var url: String? = null
private var appContext : Application? = null
private var delegate: BitverseConnectDelegate? = null
const val TAG = "BitverseConnectApi"
fun initilize(application: Application,
dappName: String,
dappDescription: String,
dappUrl: String,
icons: List<String>,
callbackUrl: String,
delegate: BitverseConnectDelegate?) {
appContext = application
this.delegate = delegate;
val serverUri = "wss://relay.walletconnect.com?projectId=1c8433f67cf7bfd3e7f9e169118802ce"
CoreClient.initialize(
relayServerUrl = serverUri, connectionType = ConnectionType.AUTOMATIC, application = application, metaData = Core.Model.AppMetaData(
name = dappName,
description = dappDescription,
url = dappUrl,
icons = icons,
redirect = callbackUrl
)
) {}
val init = Sign.Params.Init(core = CoreClient)
SignClient.initialize(init) { error ->
// Error will be thrown if there's an issue during initialization
}
val dappDelegate = object : SignClient.DappDelegate {
override fun onSessionApproved(approvedSession: Sign.Model.ApprovedSession) {
// Triggered when Dapp receives the session approval from wallet
val componets = approvedSession.accounts.first().split(':')
val size = componets.count()
if (size > 1) {
delegate?.didConnect(componets[size - 2].toInt(), listOf(componets[size - 1]))
} else {
delegate?.failedToConnect()
}
}
override fun onSessionRejected(rejectedSession: Sign.Model.RejectedSession) {
// Triggered when Dapp receives the session rejection from wallet
delegate?.didDisconnect()
}
override fun onSessionUpdate(updatedSession: Sign.Model.UpdatedSession) {
// Triggered when Dapp receives the session update from wallet
}
override fun onSessionExtend(session: Sign.Model.Session) {
// Triggered when Dapp receives the session extend from wallet
}
override fun onSessionEvent(sessionEvent: Sign.Model.SessionEvent) {
// Triggered when the peer emits events that match the list of events agreed upon session settlement
}
override fun onSessionDelete(deletedSession: Sign.Model.DeletedSession) {
// Triggered when Dapp receives the session delete from wallet
}
override fun onSessionRequestResponse(response: Sign.Model.SessionRequestResponse) {
// Triggered when Dapp receives the session request response from wallet
}
override fun onConnectionStateChange(state: Sign.Model.ConnectionState) {
//Triggered whenever the connection state is changed
when(state.isAvailable) {
false -> delegate?.didDisconnect()
else -> print("connected")
}
}
override fun onError(error: Sign.Model.Error) {
// Triggered whenever there is an issue inside the SDK
}
}
SignClient.setDappDelegate(dappDelegate)
}
/**
* dappName:dapp的名称
* dappDescription:dapp的描述
* dappUrl:dapp对应的链接
* bitverseDapp:当前app的deeplink或者Universal Links,以便Bitverse产生相关结果后可以回调回到当前app
*/
fun connect(
context: Context,
dappName: String,
dappDescription: String,
dappUrl: String,
icons: List<String>,
callbackUrl: String
) {
val pairing: Core.Model.Pairing =
CoreClient.Pairing.create() { error ->
delegate?.didDisconnect()
}!!
val namespace: String = "eip155"
val chains: List<String> = listOf("eip155:1")
val methods: List<String> = listOf("eth_sendTransaction", "personal_sign", "eth_sign", "eth_signTypedData")
val events: List<String> = listOf("chainChanged", "accountsChanged")
val requiredNamespaces: Map<String, Sign.Model.Namespace.Proposal> = mapOf(namespace to Sign.Model.Namespace.Proposal(chains, methods, events)) /*Required namespaces to setup a session*/
//val pairing: Core.Model.Pairing = /*Either an active or inactive pairing*/
val connectParams = Sign.Params.Connect(requiredNamespaces, null, null, pairing)
SignClient.connect(connectParams,
onSuccess = {
// Get a handler that can be used to post to the main thread
val mainHandler = Handler(context.mainLooper)
val myRunnable = object: Runnable {
override fun run() {
val wsURL = pairing.uri
Log.e(TAG, "wsURL:" + wsURL)
var url = "https://bitverseapp.page.link/?apn=com.bitverse.app&afl=https://bitverse.zone/download?deeplink%3Dbitverseapp://open/wallet&isi=1645515614&ibi=com.bitverse.app&link=https://bitverse.zone/download?deeplink%3Dbitverseapp://open/wallet?uri="+URLEncoder.encode(URLEncoder.encode(wsURL));
url += URLEncoder.encode(URLEncoder.encode("&callbackUrl=${URLEncoder.encode(callbackUrl)}"));
val intent = Intent(Intent.ACTION_VIEW).apply {
data = Uri.parse(url)
}
context.startActivity(intent)
} // This is your code
};
mainHandler.post(myRunnable);
},
onError = {
delegate?.failedToConnect()
}
)
}
fun ethSign(
context: Context,
message: String,
account: String,
callback: (Session.MethodCall.Response) -> Unit
) {
client?.ethSign(message, account, callback)
startBitverseApp(context)
}
fun personalSign(
context: Context,
message: String,
account: String,
callback: (Session.MethodCall.Response) -> Unit
) {
client?.personalSign(message, account, callback)
startBitverseApp(context)
}
fun ethSignTypedData(
context: Context,
message: String,
account: String,
callback: (Session.MethodCall.Response) -> Unit
) {
client?.ethSignTypedData(message, account, callback)
startBitverseApp(context)
}
fun ethSendTransaction(
context: Context,
transaction: Transaction,
callback: (Session.MethodCall.Response) -> Unit
) {
client?.ethSendTransaction(transaction, callback)
startBitverseApp(context)
}
fun disconnect() {
client?.disconnect()
}
fun reconnectIfNeeded() {
client?.reconnectIfNeeded()
}
private fun startBitverseApp(context: Context) {
val intent = Intent(Intent.ACTION_VIEW).apply {
data = Uri.parse("bitverseapp://open/wallet")
}
context.startActivity(intent)
}
}
| 0
|
Kotlin
|
0
| 0
|
b8e37ccac7bf5824e94130ca624c1446b012bdc2
| 7,500
|
BitverseConnectKotlin
|
MIT License
|
currencies/src/main/kotlin/by/jprof/telegram/bot/currencies/parser/CAD.kt
|
JavaBy
| 367,980,780
| false
| null |
package by.jprof.telegram.bot.currencies.parser
class CAD : MonetaryAmountParserBase() {
override val currency: String = "CAD"
override val currencyRegex: String = "(CAD|CA$|Can$|C$)"
}
| 21
|
Kotlin
|
2
| 2
|
7e0f2c68e3acc9ff239effa34f5823e4ef8212c9
| 197
|
jprof_by_bot
|
MIT License
|
foosball/app/src/tablet/java/com/instructure/androidfoosball/activities/MainActivity.kt
|
instructure
| 179,290,947
| false
| null |
/*
* Copyright (C) 2017 - present Instructure, Inc.
*
* 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.instructure.androidfoosball.activities
import android.app.AlertDialog
import android.content.Intent
import android.media.AudioManager
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.text.Html
import android.view.View
import android.widget.Toast
import com.afollestad.materialdialogs.MaterialDialog
import com.instructure.androidfoosball.R
import com.instructure.androidfoosball.ktmodels.*
import com.instructure.androidfoosball.receivers.GoalReceiver
import com.instructure.androidfoosball.utils.*
import com.instructure.androidfoosball.views.ConfirmPinDialog
import kotlinx.android.synthetic.tablet.activity_main.*
import org.jetbrains.anko.sdk21.listeners.onClick
import org.jetbrains.anko.startActivity
import java.text.SimpleDateFormat
import java.util.*
class MainActivity : AppCompatActivity() {
private val dateFormat = SimpleDateFormat("MMM d 'at' h:mm aa", Locale.getDefault())
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Set volume stream to media to control commentator
volumeControlStream = AudioManager.STREAM_MUSIC
setupListeners()
// Set table name
tableNameView.text = Table.getSelectedTable().name
@Suppress("DEPRECATION", "UsePropertyAccessSyntax")
(motivosityWelcomeView.setText(Html.fromHtml(getString(R.string.motivosity_welcome))))
GoalReceiver.register(this, goalReceiver)
}
override fun onResume() {
super.onResume()
// Show 'resume game' button if there are any ongoing games
resumeGameButton.visibility = if (Table.hasOngoingGames()) View.VISIBLE else View.GONE
}
private val goalReceiver = GoalReceiver {
mCommentator.announceBadTouch()
Toast.makeText(this, "There is no game in progress", Toast.LENGTH_SHORT).show()
}
private fun setupListeners() {
// Create new game
newGameButton.onClick { startActivity<CreateGameActivity>() }
// Cut-throat game
cutthroatGameButton.onClick { startActivity<CreateCutThroatGameActivity>() }
// King of the Table game
tableKingGameButton.onClick { startActivity<CreateTableKingGameActivity>() }
// Team Twister game
teamTwisterGameButton.onClick { startActivity<CreateTeamTwisterGameActivity>() }
// Create new user
addUserButton.onClick { startActivity<CreatePlayerActivity>() }
// Show leaderboard
leaderboardButton.onClick { startActivity<LeaderboardActivity>() }
// Open settings
clockView.setOnClickListener { startActivity(Intent(android.provider.Settings.ACTION_SETTINGS)) }
// Switch tables
tableNameView.setOnClickListener {
AlertDialog.Builder(this)
.setMessage("Assign this tablet to a different foosball table?")
.setPositiveButton(android.R.string.yes) { _, _ ->
Prefs.tableId = ""
finish()
startActivity<SyncActivity>()
}.setNegativeButton(android.R.string.no, null)
.show()
}
// Edit Player
editPlayerButton.setOnClickListener {
showUserPicker(this) {
if (it.guest) {
shortToast(R.string.cannot_edit_guests)
} else {
ConfirmPinDialog(this@MainActivity, it) {
startActivity<EditUserActivity>(Const.USER_ID to it.id)
}.show()
}
}
}
// Resume game
resumeGameButton.onClick {
val games = Table.getOngoingGames()
MaterialDialog.Builder(this)
.items(games.map { game ->
when (game) {
is Game -> {
val dateString = dateFormat.format(Calendar.getInstance().apply { timeInMillis = game.startTime }.time)
"Game started $dateString with players ${(game.teamOne!!.users + game.teamTwo!!.users).joinToString { it.name }}"
}
is CutThroatGame -> {
val dateString = dateFormat.format(Calendar.getInstance().apply { timeInMillis = game.startTime }.time)
"Cut-Throat Game started $dateString with players ${game.players.joinToString { it.user?.name.orEmpty() }}"
}
is TableKingGame -> {
val dateString = dateFormat.format(Calendar.getInstance().apply { timeInMillis = game.startTime }.time)
"King of the Table started $dateString with players ${game.teams.flatMap { it.users }.distinct().joinToString { it?.name.orEmpty() }}"
}
is TeamTwisterGame -> {
val dateString = dateFormat.format(Calendar.getInstance().apply { timeInMillis = game.startTime }.time)
"Team Twister Game started $dateString with players ${game.teams.flatMap { it.users }.distinct().joinToString { it?.name.orEmpty() }}"
}
else -> "Unknown game"
}
})
.itemsCallback { _, _, i, _ ->
val game = games[i]
when (game) {
is Game -> startActivity<GameActivity>(GameActivity.EXTRA_GAME_ID to game.id)
is CutThroatGame -> startActivity<CutThroatGameActivity>(CutThroatGameActivity.EXTRA_GAME_ID to game.id)
is TableKingGame -> startActivity<TableKingGameActivity>(TableKingGameActivity.EXTRA_GAME_ID to game.id)
is TeamTwisterGame -> startActivity<TeamTwisterGameActivity>(TeamTwisterGameActivity.EXTRA_GAME_ID to game.id)
}
}
.show()
}
}
override fun onDestroy() {
super.onDestroy()
GoalReceiver.unregister(this, goalReceiver)
}
override fun onBackPressed() {
// Do nothing. This should act as the root activity.
}
}
| 2
|
Kotlin
|
85
| 99
|
1bac9958504306c03960bdce7fbb87cc63bc6845
| 7,116
|
canvas-android
|
Apache License 2.0
|
tools/conventions/src/main/kotlin/dev/elide/build/jvm/toolchain/GraalVMToolchainResolver.kt
|
elide-dev
| 506,113,888
| false
|
{"Kotlin": 4156801, "Rust": 130170, "Java": 51233, "Python": 7851, "JavaScript": 6037, "Ruby": 2474, "C": 1926, "RenderScript": 578, "Shell": 160, "Pkl": 102, "TypeScript": 78, "Swift": 23}
|
/*
* Copyright (c) 2024 Elide Technologies, Inc.
*
* Licensed under the MIT license (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://opensource.org/license/mit/
*
* 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.
*/
@file:Suppress("UnstableApiUsage")
package dev.elide.build.jvm.toolchain
import org.gradle.api.initialization.Settings
import org.gradle.api.model.ObjectFactory
import org.gradle.api.provider.Property
import org.gradle.jvm.toolchain.JavaToolchainDownload
import org.gradle.jvm.toolchain.JavaToolchainRequest
import org.gradle.jvm.toolchain.JavaToolchainResolver
import java.net.URI
import java.util.*
import javax.inject.Inject
/** Resolves/auto-provisions GraalVM toolchains. */
abstract class GraalVMToolchainResolver @Inject constructor (
private val settings: Settings
) : JavaToolchainResolver {
override fun resolve(request: JavaToolchainRequest): Optional<JavaToolchainDownload> {
val ext = settings.extensions.findByType(GraalVMToolchainExtension::class.java)
?: return Optional.empty()
return Optional.of(JavaToolchainDownload {
ext.renderDownloadUrl().toURI()
})
}
}
| 75
|
Kotlin
|
16
| 97
|
652036fb4e8394e8ad1aced2f4bbfaa9e00a5181
| 1,490
|
elide
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.