code
stringlengths 6
1.04M
| language
stringclasses 1
value | AST_depth
int64 -1
40
| alphanumeric_fraction
float64 0
0.97
| max_line_length
int64 0
1k
| avg_line_length
float64 0
171
| num_lines
int64 0
4.25k
| source
stringclasses 1
value |
---|---|---|---|---|---|---|---|
<filename>app/src/main/java/com/example/trackingmypantry/db/entities/PlaceSuggestion.kt
package com.example.trackingmypantry.db.entities
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity
data class PlaceSuggestion(
val latitude: Double,
val longitude: Double,
val title: String,
val username: String,
@PrimaryKey(autoGenerate = true) val id: Long = 0
)
| kotlin | 11 | 0.768448 | 87 | 27.071429 | 14 | starcoderdata |
package com.example.androiddevchallenge.domain
import com.example.androiddevchallenge.commons.K
import com.example.androiddevchallenge.commons.epochMs
import com.example.androiddevchallenge.domain.entities.Forecast
import com.example.androiddevchallenge.domain.entities.HourlyForecast
import com.example.androiddevchallenge.domain.entities.WeatherBit
import com.example.androiddevchallenge.data.api.entities.Forecast as ApiForecast
import com.example.androiddevchallenge.data.api.entities.HourlyForecast as ApiHourlyForecast
import com.example.androiddevchallenge.data.api.entities.WeatherBit as ApiWeatherBit
fun ApiWeatherBit.toDomainEntity() =
WeatherBit(
id,
main,
description,
icon,
)
fun ApiForecast.toDomainEntity(timezoneOffsetMillis: Int) =
Forecast(
(dt * 1000).epochMs(timezoneOffsetMillis),
sunrise,
sunset,
temp.K,
feelsLike,
pressure,
humidity,
dewPoint.K,
uvIndex,
clouds,
visibility,
windSpeed,
windDeg,
windGust,
weather.map(ApiWeatherBit::toDomainEntity),
)
fun ApiHourlyForecast.toDomainEntity() =
HourlyForecast(
lat,
lon,
timezone,
current.toDomainEntity(timezoneOffset * 100),
hourly.map { it.toDomainEntity(timezoneOffset * 100) },
) | kotlin | 17 | 0.707122 | 92 | 28.934783 | 46 | starcoderdata |
/**
* GitHub v3 REST API
*
* GitHub's v3 REST API.
*
* The version of the OpenAPI document: 1.1.4
*
*
* Please note:
* This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* Do not edit this file manually.
*/
@file:Suppress(
"ArrayInDataClass",
"EnumEntryName",
"RemoveRedundantQualifierName",
"UnusedImport"
)
package io.github.gmvalentino8.github.sample.remote.models
import io.github.gmvalentino8.github.sample.remote.models.RunnerMinusLabelApiModel
import kotlinx.serialization.*
/**
* A self hosted runner
* @param id The id of the runner.
* @param name The name of the runner.
* @param os The Operating System of the runner.
* @param status The status of the runner.
* @param busy
* @param labels
*/
@Serializable
data class RunnerApiModel(
/* The id of the runner. */
@SerialName(value = "id")
val id: kotlin.Int,
/* The name of the runner. */
@SerialName(value = "name")
val name: kotlin.String,
/* The Operating System of the runner. */
@SerialName(value = "os")
val os: kotlin.String,
/* The status of the runner. */
@SerialName(value = "status")
val status: kotlin.String,
@SerialName(value = "busy")
val busy: kotlin.Boolean,
@SerialName(value = "labels")
val labels: kotlin.collections.List<RunnerMinusLabelApiModel>
) {
}
| kotlin | 10 | 0.675145 | 86 | 23.140351 | 57 | starcoderdata |
<reponame>JiangKlijna/android-myutils<filename>app/src/main/java/com/jiangKlijna/activity/ActKotlin.kt
package com.jiangKlijna.activity
import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.*
import com.jiangKlijna.R
import com.jiangKlijna.kotlin.XAdapter
/**
* Created by jiangKlijna on 16-4-11.
*/
class ActKotlin : Activity(), AdapterView.OnItemClickListener {
companion object {
private val arr: Array<String> = arrayOf("XAdapter", "ObjectKey", "CrashHandler", "dlksajlkjdl", "android-myutil")
}
private var lv: ListView? = null
private var adapter: XAdapter<String>? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.act_main)
init()
}
private fun init() {
(findViewById(R.id.main_btn) as Button).let {
it.text = "kotlin to java"
it.setOnClickListener {
finish()
startActivity(Intent(this@ActKotlin, ActJava::class.java))
}
}
adapter = object : XAdapter<String>(this@ActKotlin) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val holder = XAdapter.getHolder(context, convertView, TextView::class.java)
// XAdapter.ViewHolder holder = XAdapter.getHolder(getContext(), convertView, parent, R.layout.text_item, position);
val tv = holder.getConvertView<TextView>()
tv.text = getItem(position)
tv.setPadding(20, 20, 20, 20)
tv.setTextColor(Color.rgb(0xab, 0xcd, 0xef))
tv.textSize = 20f
return tv
}
}
(findViewById(R.id.main_lv) as ListView).let {
lv = it
it.adapter = adapter
adapter!!.setData(arr)
it.onItemClickListener = this@ActKotlin
}
}
override fun onItemClick(adapterView: AdapterView<*>, view: View, i: Int, l: Long) {
Toast.makeText(this, adapter!!.getItem(i), Toast.LENGTH_SHORT).show()
}
}
| kotlin | 26 | 0.625386 | 147 | 33.907692 | 65 | starcoderdata |
fun main() {
var b = "BB";
print(B);
} | kotlin | 8 | 0.475 | 14 | 9.25 | 4 | starcoderdata |
package pers.acp.admin.workflow.controller.api
import io.github.zhangbinhub.acp.boot.exceptions.ServerException
import io.github.zhangbinhub.acp.boot.interfaces.LogAdapter
import io.github.zhangbinhub.acp.boot.vo.ErrorVo
import io.github.zhangbinhub.acp.cloud.annotation.AcpCloudDuplicateSubmission
import io.github.zhangbinhub.acp.core.CommonTools
import io.swagger.annotations.*
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.security.oauth2.provider.OAuth2Authentication
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*
import pers.acp.admin.api.WorkFlowApi
import pers.acp.admin.common.base.BaseController
import pers.acp.admin.common.feign.CommonOauthServer
import pers.acp.admin.common.po.ProcessHandlingPo
import pers.acp.admin.common.po.ProcessQueryPo
import pers.acp.admin.common.po.ProcessStartPo
import pers.acp.admin.common.po.ProcessTerminationPo
import pers.acp.admin.common.vo.*
import pers.acp.admin.constant.ModuleFuncCode
import pers.acp.admin.constant.TokenConstant
import pers.acp.admin.workflow.constant.WorkFlowExpression
import pers.acp.admin.workflow.domain.WorkFlowDomain
import springfox.documentation.annotations.ApiIgnore
import java.io.OutputStream
import javax.servlet.http.HttpServletResponse
import javax.validation.Valid
/**
* @author zhang by 10/06/2019
* @since JDK 11
*/
@Validated
@RestController
@RequestMapping(WorkFlowApi.basePath)
@Api(tags = ["工作流引擎"])
class WorkFlowController @Autowired
constructor(
logAdapter: LogAdapter,
private val commonOauthServer: CommonOauthServer,
private val workFlowDomain: WorkFlowDomain
) : BaseController(logAdapter) {
@ApiOperation(value = "启动流程", notes = "启动指定的流程,并关联唯一业务主键")
@ApiResponses(
ApiResponse(code = 201, message = "流程启动成功", response = InfoVo::class),
ApiResponse(code = 400, message = "参数校验不通过;系统异常", response = ErrorVo::class)
)
@PutMapping(value = [WorkFlowApi.start], produces = [MediaType.APPLICATION_JSON_VALUE])
@AcpCloudDuplicateSubmission
@Throws(ServerException::class)
fun start(@RequestBody @Valid processStartPo: ProcessStartPo): ResponseEntity<InfoVo> =
commonOauthServer.userInfo()?.let { user ->
workFlowDomain.startFlow(processStartPo, user.id).let {
ResponseEntity.status(HttpStatus.CREATED).body(InfoVo(message = it))
}
} ?: throw ServerException("获取当前登录用户信息失败!")
@ApiOperation(value = "查询流程任务列表")
@ApiResponses(ApiResponse(code = 400, message = "参数校验不通过;系统异常", response = ErrorVo::class))
@PreAuthorize(WorkFlowExpression.flowAdmin)
@GetMapping(value = [WorkFlowApi.taskList + "/{processInstanceId}"], produces = [MediaType.APPLICATION_JSON_VALUE])
@Throws(ServerException::class)
fun taskList(@PathVariable processInstanceId: String): ResponseEntity<List<ProcessTaskVo>> =
workFlowDomain.findTaskList(processInstanceId).let {
ResponseEntity.ok(it)
}
@ApiOperation(value = "查询待办任务", notes = "获取当前用户的待办任务列表")
@ApiResponses(ApiResponse(code = 400, message = "参数校验不通过;系统异常", response = ErrorVo::class))
@PreAuthorize(WorkFlowExpression.flowPending)
@PostMapping(value = [WorkFlowApi.pending], produces = [MediaType.APPLICATION_JSON_VALUE])
@Throws(ServerException::class)
fun pending(@RequestBody @Valid processQueryPo: ProcessQueryPo): ResponseEntity<CustomerQueryPageVo<ProcessTaskVo>> =
workFlowDomain.findTaskList(processQueryPo).let {
ResponseEntity.ok(it)
}
@ApiOperation(value = "分配任务", notes = "将任务指定给用户签收")
@ApiResponses(ApiResponse(code = 400, message = "参数校验不通过;系统异常", response = ErrorVo::class))
@PreAuthorize(WorkFlowExpression.flowAdmin)
@PatchMapping(
value = [WorkFlowApi.distribute + "/{taskId}/{userId}"],
produces = [MediaType.APPLICATION_JSON_VALUE]
)
@AcpCloudDuplicateSubmission
@Throws(ServerException::class)
fun distribute(
@ApiParam(value = "任务ID", required = true) @PathVariable taskId: String,
@ApiParam(value = "用户ID", required = true) @PathVariable userId: String
): ResponseEntity<InfoVo> =
workFlowDomain.claimTask(taskId, userId).let {
ResponseEntity.ok(InfoVo(message = "任务已分配"))
}
@ApiOperation(value = "领取任务", notes = "签收指定的任务")
@ApiResponses(ApiResponse(code = 400, message = "参数校验不通过;系统异常", response = ErrorVo::class))
@PreAuthorize(WorkFlowExpression.flowProcess)
@PatchMapping(value = [WorkFlowApi.claim + "/{taskId}"], produces = [MediaType.APPLICATION_JSON_VALUE])
@AcpCloudDuplicateSubmission
@Throws(ServerException::class)
fun claim(@ApiParam(value = "任务ID", required = true) @PathVariable taskId: String): ResponseEntity<InfoVo> =
workFlowDomain.claimTask(taskId).let {
ResponseEntity.ok(InfoVo(message = "任务已签收"))
}
@ApiOperation(value = "转办任务", notes = "转办指定的任务")
@ApiResponses(ApiResponse(code = 400, message = "参数校验不通过;系统异常", response = ErrorVo::class))
@PreAuthorize(WorkFlowExpression.flowProcess)
@PatchMapping(value = [WorkFlowApi.transfer + "/{taskId}/{userId}"], produces = [MediaType.APPLICATION_JSON_VALUE])
@AcpCloudDuplicateSubmission
@Throws(ServerException::class)
fun transfer(
@ApiParam(value = "任务ID", required = true) @PathVariable taskId: String,
@ApiParam(value = "目标userId", required = true) @PathVariable userId: String
): ResponseEntity<InfoVo> =
workFlowDomain.turnTask(taskId, userId).let {
ResponseEntity.ok(InfoVo(message = "任务已转办"))
}
@ApiOperation(value = "委托办理任务", notes = "委托办理指定的任务")
@ApiResponses(ApiResponse(code = 400, message = "参数校验不通过;系统异常", response = ErrorVo::class))
@PreAuthorize(WorkFlowExpression.flowProcess)
@PatchMapping(
value = [WorkFlowApi.delegate + "/{taskId}/{acceptUserId}"],
produces = [MediaType.APPLICATION_JSON_VALUE]
)
@AcpCloudDuplicateSubmission
@Throws(ServerException::class)
fun delegate(
@ApiParam(value = "任务ID", required = true) @PathVariable taskId: String,
@ApiParam(value = "接收userId", required = true) @PathVariable acceptUserId: String
): ResponseEntity<InfoVo> =
workFlowDomain.delegateTask(taskId, acceptUserId).let {
ResponseEntity.ok(InfoVo(message = "任务已委托办理"))
}
@ApiOperation(value = "流程处理", notes = "可选通过或不通过")
@ApiResponses(ApiResponse(code = 400, message = "参数校验不通过;系统异常", response = ErrorVo::class))
@PreAuthorize(WorkFlowExpression.flowProcess)
@PostMapping(value = [WorkFlowApi.process], produces = [MediaType.APPLICATION_JSON_VALUE])
@AcpCloudDuplicateSubmission
@Throws(ServerException::class)
fun process(@RequestBody @Valid processHandlingPo: ProcessHandlingPo): ResponseEntity<InfoVo> =
commonOauthServer.userInfo()?.let { userInfo ->
workFlowDomain.processTask(processHandlingPo, userInfo.id!!).let {
ResponseEntity.ok(InfoVo(message = "流程处理完成"))
}
} ?: throw ServerException("获取当前登录用户信息失败!")
@ApiOperation(value = "流程强制结束")
@ApiResponses(ApiResponse(code = 400, message = "参数校验不通过;系统异常", response = ErrorVo::class))
@PreAuthorize(WorkFlowExpression.flowProcess)
@DeleteMapping(value = [WorkFlowApi.termination], produces = [MediaType.APPLICATION_JSON_VALUE])
@AcpCloudDuplicateSubmission
@Throws(ServerException::class)
fun termination(
@ApiIgnore user: OAuth2Authentication,
@RequestBody @Valid processTerminationPo: ProcessTerminationPo
): ResponseEntity<InfoVo> =
workFlowDomain.findProcessInstance(processTerminationPo.processInstanceId!!).let { instance ->
if (instance.finished) {
false
} else {
when {
hasAuthentication(user, mutableListOf(ModuleFuncCode.flowAdmin)) -> {
true
}
else -> {
commonOauthServer.userInfo()?.let { userInfo ->
instance.startUser != null
&& !CommonTools.isNullStr(instance.startUser!!.id)
&& instance.startUser!!.id == userInfo.id
} ?: throw ServerException("获取当前登录人信息失败")
}
}
}
}.let {
if (it) {
workFlowDomain.deleteProcessInstance(
processTerminationPo,
commonOauthServer.tokenInfo()?.additionalInformation?.get(TokenConstant.USER_INFO_ID)?.toString()
).let {
ResponseEntity.ok(InfoVo(message = "强制结束流程实例成功"))
}
} else {
throw ServerException("流程已结束或当前登录人不是流程发起人,无法终止该流程!")
}
}
@ApiOperation(value = "获取流程实例", notes = "获取指定流程实例")
@ApiResponses(ApiResponse(code = 400, message = "参数校验不通过;系统异常", response = ErrorVo::class))
@GetMapping(value = [WorkFlowApi.instance + "/{processInstanceId}"], produces = [MediaType.APPLICATION_JSON_VALUE])
@Throws(ServerException::class)
fun queryInstance(
@ApiParam(value = "流程实例id", required = true)
@PathVariable
processInstanceId: String
): ResponseEntity<ProcessInstanceVo> =
workFlowDomain.findProcessInstance(processInstanceId).let {
ResponseEntity.ok(it)
}
@ApiOperation(value = "获取流程实例", notes = "获取流程实例")
@ApiResponses(ApiResponse(code = 400, message = "参数校验不通过;系统异常", response = ErrorVo::class))
@PostMapping(value = [WorkFlowApi.instance], produces = [MediaType.APPLICATION_JSON_VALUE])
@Throws(ServerException::class)
fun queryInstance(@RequestBody @Valid processQueryPo: ProcessQueryPo): ResponseEntity<CustomerQueryPageVo<ProcessInstanceVo>> =
workFlowDomain.findProcessInstance(processQueryPo).let {
ResponseEntity.ok(it)
}
@ApiOperation(value = "获取我处理过的流程实例", notes = "获取我处理过的流程实例")
@ApiResponses(ApiResponse(code = 400, message = "参数校验不通过;系统异常", response = ErrorVo::class))
@PostMapping(value = [WorkFlowApi.myProcess], produces = [MediaType.APPLICATION_JSON_VALUE])
@Throws(ServerException::class)
fun queryInstanceForMyProcess(@RequestBody @Valid processQueryPo: ProcessQueryPo): ResponseEntity<CustomerQueryPageVo<ProcessInstanceVo>> =
workFlowDomain.findProcessInstanceForMyProcess(processQueryPo).let {
ResponseEntity.ok(it)
}
@ApiOperation(value = "获取流程实例", notes = "获取流程实例")
@ApiResponses(ApiResponse(code = 400, message = "参数校验不通过;系统异常", response = ErrorVo::class))
@PostMapping(value = [WorkFlowApi.history], produces = [MediaType.APPLICATION_JSON_VALUE])
@Throws(ServerException::class)
fun queryHistoryInstance(@RequestBody @Valid processQueryPo: ProcessQueryPo): ResponseEntity<CustomerQueryPageVo<ProcessInstanceVo>> =
workFlowDomain.findHistoryProcessInstance(processQueryPo).let {
ResponseEntity.ok(it)
}
@ApiOperation(value = "获取流程历史记录", notes = "获取指定流程实例的历史处理记录")
@ApiResponses(ApiResponse(code = 400, message = "参数校验不通过;系统异常", response = ErrorVo::class))
@GetMapping(value = [WorkFlowApi.history + "/{processInstanceId}"], produces = [MediaType.APPLICATION_JSON_VALUE])
@Throws(ServerException::class)
fun queryHistoryActivity(
@ApiParam(value = "流程实例id", required = true)
@PathVariable
processInstanceId: String
): ResponseEntity<List<ProcessHistoryActivityVo>> =
workFlowDomain.findHistoryActivity(processInstanceId).let {
ResponseEntity.ok(it)
}
@ApiOperation(value = "获取流程任务信息", notes = "获取指定流程任务")
@ApiResponses(ApiResponse(code = 400, message = "参数校验不通过;系统异常", response = ErrorVo::class))
@PreAuthorize(WorkFlowExpression.flowProcess)
@GetMapping(value = [WorkFlowApi.task + "/{taskId}"], produces = [MediaType.APPLICATION_JSON_VALUE])
@Throws(ServerException::class)
fun queryTaskInfo(
@ApiParam(value = "流程任务ID", required = true)
@PathVariable
taskId: String
): ResponseEntity<ProcessTaskVo> =
workFlowDomain.findTaskById(taskId).let {
ResponseEntity.ok(it)
}
@ApiOperation(value = "获取流程图", notes = "获取指定实例id的流程图,返回图片二进制流数据")
@ApiResponses(
ApiResponse(code = 200, message = "请求成功,进行文件下载;", response = OutputStream::class),
ApiResponse(code = 400, message = "参数校验不通过;系统异常", response = ErrorVo::class)
)
@GetMapping(value = [WorkFlowApi.diagram + "/{processInstanceId}/{imgType}"], produces = [MediaType.ALL_VALUE])
@Throws(ServerException::class)
fun diagram(
response: HttpServletResponse,
@ApiParam(value = "流程实例id", required = true)
@PathVariable
processInstanceId: String,
@ApiParam(value = "图片格式", example = "png;bmp;jpg;gif", required = true)
@PathVariable
imgType: String
) {
response.contentType = "image/$imgType"
workFlowDomain.generateDiagram(processInstanceId, imgType)
.transferTo(response.outputStream)
}
}
| kotlin | 36 | 0.688899 | 143 | 46.851064 | 282 | starcoderdata |
<filename>MyPayTemplate/app/src/main/java/br/uea/transirie/mypay/mypaytemplate2/ui/home/Ajustes/AlterarPinActivity.kt
package br.uea.transirie.mypay.mypaytemplate2.ui.home.Ajustes
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import br.uea.transirie.mypay.mypaytemplate2.R
import br.uea.transirie.mypay.mypaytemplate2.databinding.ActivityAlterarPinBinding
import br.uea.transirie.mypay.mypaytemplate2.repository.room.AppDatabase
import br.uea.transirie.mypay.mypaytemplate2.ui.cadastro.GerarPinActivity
import br.uea.transirie.mypay.mypaytemplate2.utils.MyValidations
import org.jetbrains.anko.doAsync
class AlterarPinActivity : AppCompatActivity() {
private val context = this@AlterarPinActivity
private lateinit var viewModel: EstabelecimentoUsuarioViewModel
private val binding by lazy { ActivityAlterarPinBinding.inflate(layoutInflater) }
private lateinit var userPrefs: SharedPreferences
private var pinUsuario: Int? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
title = getString(R.string.title_alterar_pin)
userPrefs = getSharedPreferences(getString(R.string.PREF_USER_DATA), Context.MODE_PRIVATE)
pinUsuario = userPrefs.getInt(getString(R.string.PREF_PIN), 0)
binding.alterarPinBtAvancar.setOnClickListener {
checkAndAdvance()
}
}
private fun checkAndAdvance(){
val myValidations = MyValidations(context)
val isPinAtualCorrect = !myValidations.pinHasErrors(binding.alterarPinTiPin)
val isPinAtualConfCorrect = !myValidations.confPinHasErrors(
binding.alterarPinTiConfirmePin, binding.alterarPinTiPin
)
if (isPinAtualConfCorrect && isPinAtualCorrect ){
if (binding.alterarPinEtPin.text.toString().toInt()*100 == pinUsuario){
doAsync {
viewModel = EstabelecimentoUsuarioViewModel(AppDatabase.getDatabase(context))
val usuario = viewModel.usuarioByPin(pinUsuario!!)
val intent = Intent(context, GerarPinActivity::class.java)
.putExtra(getString(R.string.EXTRA_USUARIO), usuario)
.putExtra(getString(R.string.EXTRA_TOPBAR_TITLE), getString(R.string.title_alterar_pin))
startActivity(intent)
}
}else{
binding.alterarPinTiPin.error = "PIN incorreto"
binding.alterarPinTiConfirmePin.error = "PIN incorreto"
}
}
}
override fun onSupportNavigateUp(): Boolean {
onBackPressed()
return true
}
} | kotlin | 31 | 0.712747 | 117 | 44 | 64 | starcoderdata |
package com.giphy.codechallenge.data.source.remote
import androidx.annotation.VisibleForTesting
import com.giphy.codechallenge.data.SearchResult
import com.giphy.codechallenge.data.source.GifsDataSource
import com.giphy.codechallenge.util.AppExecutors
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class GifsRemoteDataSource private constructor (
private val appExecutors: AppExecutors,
private val giphyApiService: GiphyApiService
) : GifsDataSource {
/**
* Note: [GifsDataSource.LoadGifsCallback] would be fired if the server can't be contacted or the server
* returns an error.
*/
override fun searchGifs(query: String, callback: GifsDataSource.LoadGifsCallback) {
try {
appExecutors.networkIO.execute {
val call =
giphyApiService.search(
query,
GiphyApiService.API_KEY,
GiphyApiService.DEFAULT_LIMIT
)
call.enqueue(object : Callback<SearchResult> {
override fun onFailure(call: Call<SearchResult>, t: Throwable) {
// We can improve it by detecting the issue and displaying
// the appropriate message to the user
callback.onDataNotAvailable()
}
override fun onResponse(call: Call<SearchResult>, response: Response<SearchResult>) {
response.body()?.let {
when {
it.data.count() > 0 -> callback.onGifsLoaded(it.data)
else -> callback.onDataNotAvailable()
}
}
}
})
}
}
catch (e: Exception)
{
// We can improve it by detecting the issue and displaying
// the appropriate message to the user
callback.onDataNotAvailable()
}
}
companion object {
private var INSTANCE: GifsRemoteDataSource? = null
@JvmStatic
fun getInstance(appExecutors: AppExecutors, giphyApiService: GiphyApiService): GifsRemoteDataSource {
if (INSTANCE == null) {
synchronized(GifsRemoteDataSource::javaClass) {
INSTANCE = GifsRemoteDataSource(appExecutors, giphyApiService)
}
}
return INSTANCE!!
}
@VisibleForTesting
fun clearInstance() {
INSTANCE = null
}
}
} | kotlin | 37 | 0.560726 | 109 | 34.72973 | 74 | starcoderdata |
package io.github.droidkaigi.confsched2018.presentation
import android.app.Activity
import android.app.Application
import android.os.Bundle
import androidx.fragment.app.FragmentActivity
import com.tomoima.debot.Debot
class DebotObserver : Application.ActivityLifecycleCallbacks {
val debot: Debot by lazy {
Debot.getInstance()
}
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
if (activity !is Activity) return
debot.allowShake(activity.applicationContext)
}
override fun onActivityStarted(activity: Activity) {
// no-op
}
override fun onActivityResumed(activity: Activity) {
if (activity !is FragmentActivity) return
debot.startSensor(activity)
}
override fun onActivityPaused(activity: Activity) {
debot.stopSensor()
}
override fun onActivityStopped(activity: Activity) {
// no-op
}
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
// no-op
}
override fun onActivityDestroyed(activity: Activity) {
// no-op
}
}
| kotlin | 13 | 0.699029 | 85 | 24.75 | 44 | starcoderdata |
package com.arctouch.codechallenge.base
import android.support.v7.app.AppCompatActivity
import com.arctouch.codechallenge.api.TmdbApi
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.moshi.MoshiConverterFactory
abstract class BaseActivity : AppCompatActivity() {
protected val api: TmdbApi = Retrofit.Builder()
.baseUrl(TmdbApi.URL)
.client(OkHttpClient.Builder().build())
.addConverterFactory(MoshiConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
.create(TmdbApi::class.java)
}
| kotlin | 21 | 0.774963 | 66 | 34.315789 | 19 | starcoderdata |
<reponame>nanogiants/ba-playground-app-kmp<filename>android/app/src/main/kotlin/de/appcom/kmpplayground/fragments/base/BaseFragment.kt
package de.appcom.kmpplayground.fragments.base
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import dagger.android.support.DaggerFragment
import de.appcom.kmpplayground.activities.main.MainActivity
import kotlinx.android.synthetic.main.activity_main.main_toolbar
/**
* Created by <NAME> on 2019-10-23.
* Copyright (c) 2019 appcom interactive GmbH. All rights reserved.
*/
abstract class BaseFragment : DaggerFragment() {
@LayoutRes open val titleRes: Int = -1
open val adaptiveToolbarScrollContainer: View? = null
var toolbarElevationHelper: ToolbarElevationHelper? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return contentView(inflater, container, savedInstanceState)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
lifecycle.addObserver(providePresenterToParent())
configureParentToolbar()
}
private fun configureParentToolbar() {
adaptiveToolbarScrollContainer?.let { scrollableView ->
toolbarElevationHelper =
ToolbarElevationHelper(requireContext(), (activity as MainActivity).main_toolbar)
toolbarElevationHelper?.addAdaptiveElevation(scrollableView)
}
}
override fun onDestroyView() {
super.onDestroyView()
toolbarElevationHelper?.removeAdaptiveElevation()
}
// allows set presenter as lifecycle observer here in the BaseFragment
// instead of doing this in each specific fragment class
abstract fun providePresenterToParent(): BasePresenter
abstract fun contentView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View
} | kotlin | 20 | 0.776709 | 134 | 31.393443 | 61 | starcoderdata |
<reponame>saikocat/schema-registry-extension
/*
* 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.github.saikocat.schemaregistry.client.utils
import io.confluent.kafka.schemaregistry.ParsedSchema
import io.confluent.kafka.schemaregistry.SchemaProvider
import io.confluent.kafka.schemaregistry.client.rest.entities.Schema
import io.confluent.kafka.schemaregistry.client.rest.entities.SchemaString
import io.confluent.kafka.schemaregistry.utils.JacksonMapper
import java.util.Optional
/**
* RestSchemaHelper provides conversions for REST json string into Schema and SchemaString entities
*/
object RestSchemaHelper {
/**
* parseRestSchema converts REST json response into Schema entities Schema(subject, version, id,
* schemaType, references, schema).
*/
fun parseRestSchema(json: String): Schema {
return JacksonMapper.INSTANCE.readValue(json, Schema::class.java)
}
/**
* toSchemaString converts a Schema into a SchemaString as most provider works on SchemaString
* to parse into a ParseSchema.
*/
fun toSchemaString(restSchema: Schema): SchemaString {
return SchemaString().apply {
schemaType = restSchema.schemaType
schemaString = restSchema.schema
references = restSchema.references
maxId = restSchema.id
}
}
/** toParsedSchema converts a rest schema into an optional ParsedSchema. */
fun toParsedSchema(restSchema: Schema, provider: SchemaProvider): Optional<ParsedSchema> {
val schemaString = toSchemaString(restSchema)
return toParsedSchema(schemaString, provider)
}
fun toParsedSchema(schemaStringJson: String, provider: SchemaProvider): Optional<ParsedSchema> {
val schemaString = SchemaString.fromJson(schemaStringJson)
return toParsedSchema(schemaString, provider)
}
fun toParsedSchema(
schemaString: SchemaString, provider: SchemaProvider
): Optional<ParsedSchema> {
// TODO: can throw unknown schemaType with wrong provider
return provider.parseSchema(schemaString.getSchemaString(), schemaString.getReferences())
}
}
| kotlin | 15 | 0.73765 | 100 | 39.484848 | 66 | starcoderdata |
<filename>app/src/main/java/com/example/android/architecture/blueprints/todoapp/data/source/local/BancoDeDados.kt<gh_stars>0
package com.example.android.architecture.blueprints.todoapp.data.source.local
import androidx.room.DatabaseConfiguration
import androidx.room.InvalidationTracker
import androidx.room.Room
import androidx.sqlite.db.SupportSQLiteOpenHelper
class BancoDeDados : ToDoDatabase() {
override fun taskDao(): TasksDao {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun createOpenHelper(config: DatabaseConfiguration?): SupportSQLiteOpenHelper {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun createInvalidationTracker(): InvalidationTracker {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun clearAllTables() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
} | kotlin | 17 | 0.755677 | 124 | 39.814815 | 27 | starcoderdata |
package uk.gov.justice.digital.hmpps.sendlegalmailtoprisonsapi.barcode
import org.springframework.stereotype.Service
import kotlin.random.Random
@Service
class BarcodeGeneratorService {
private val maxBarcode = 999_999_999_999
fun generateBarcode(): String =
Random.nextLong(maxBarcode).toString()
.padStart(12, '0')
}
| kotlin | 13 | 0.779762 | 70 | 24.846154 | 13 | starcoderdata |
<reponame>ZBL-Kiven/iM-Core
package com.zj.im.chat.interfaces
/**
* Created by ZJJ
*/
interface HeartBeatsCallBack {
fun heartBeats(isOK: Boolean, throwable: Throwable?)
}
| kotlin | 8 | 0.723757 | 56 | 15.454545 | 11 | starcoderdata |
<filename>app/src/main/java/com/example/mypersonalassistant/model/QueryModel.kt
package com.example.mypersonalassistant.model
class QueryModel {
var id: Int
get() = field
set(value) {
field = value
}
var title: String
get() = field
set(value) {
field = value
}
var description: String
get() = field
set(value) {
field = value
}
var tag: String
get() = field
set(value) {
field = value
}
constructor(id: Int, title: String, description: String, tag: String ){
this.id = id
this.title = title
this.description = description
this.tag = tag
}
}
| kotlin | 10 | 0.525401 | 79 | 19.216216 | 37 | starcoderdata |
package com.angcyo.dsltablayout.demo
import android.os.Bundle
import android.widget.TextView
import com.angcyo.dsladapter.dpi
import com.angcyo.tablayout.DslTabLayout
/**
*
* Email:<EMAIL>
* @author angcyo
* @date 2021/05/19
* Copyright (c) 2020 ShenZhen Wayto Ltd. All rights reserved.
*/
class VerticalHintActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.vertical_hint_layout)
val tabLayout = find<DslTabLayout>(R.id.tab_layout)
/*tabLayout.tabHighlight?.apply {
highlightDrawable = _drawable(R.mipmap.ic_hint_b)
highlightHeightOffset = 20 * dpi
}*/
val textView = find<TextView>(R.id.text_view)
tabLayout.configTabLayoutConfig {
onSelectItemView = { itemView, index, select, fromUser ->
if (select && itemView is TextView) {
textView.text = itemView.text
}
false
}
}
}
} | kotlin | 20 | 0.629002 | 69 | 28.527778 | 36 | starcoderdata |
package network.o3.o3wallet.MarketPlace.NEP5Tokens
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.ViewModel
import com.google.gson.JsonObject
import network.o3.o3wallet.API.O3Platform.O3PlatformClient
import network.o3.o3wallet.API.O3Platform.TokenListing
import network.o3.o3wallet.API.O3Platform.TokenListings
import network.o3.o3wallet.API.Switcheo.SwitcheoAPI
class TokensViewModel: ViewModel() {
var listingData: MutableLiveData<Array<TokenListing>>? = null
var switcheoTokenData: MutableLiveData<JsonObject>? = null
fun getListingData(refresh: Boolean): LiveData<Array<TokenListing>> {
if (listingData == null || refresh) {
listingData = MutableLiveData()
loadListingData()
}
return listingData!!
}
fun loadListingData() {
O3PlatformClient().getMarketPlace {
if (it.second != null) return@getMarketPlace
listingData?.postValue(it.first?.assets!! + it.first?.nep5!!)
}
}
fun getSwitcheoTokenData(refresh: Boolean): LiveData<JsonObject> {
if (switcheoTokenData == null || refresh) {
switcheoTokenData = MutableLiveData()
loadSwitcheoTokenData()
}
return switcheoTokenData!!
}
fun loadSwitcheoTokenData() {
SwitcheoAPI().getTokens {
switcheoTokenData?.postValue(it.first)
}
}
fun filteredTokens(query: String): List<TokenListing> {
val tokens = getListingData(false).value ?: arrayOf()
val filteredTokens = tokens.filter { it.symbol.startsWith(query, true)
|| it.name.startsWith(query, true) }
return filteredTokens
}
} | kotlin | 20 | 0.681714 | 78 | 32.673077 | 52 | starcoderdata |
/*
* 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.idea.fir.low.level.api.util
import org.jetbrains.kotlin.fir.declarations.*
import org.jetbrains.kotlin.idea.fir.low.level.api.api.FirDeclarationUntypedDesignation
internal fun FirDeclarationUntypedDesignation.ensurePathPhase(firResolvePhase: FirResolvePhase) {
toSequence(includeTarget = false).forEach { firDeclaration ->
check(firDeclaration.resolvePhase >= firResolvePhase) {
"Designation element phase required to be $firResolvePhase but element resolved to ${firDeclaration.resolvePhase}"
}
}
}
internal fun FirDeclarationUntypedDesignation.ensureTargetPhase(firResolvePhase: FirResolvePhase) =
check(declaration.resolvePhase >= firResolvePhase) { "Expected $firResolvePhase but found ${declaration.resolvePhase}" }
internal fun FirDeclarationUntypedDesignation.ensureTargetPhaseIfClass(firResolvePhase: FirResolvePhase) = when (declaration) {
is FirProperty, is FirSimpleFunction -> Unit
is FirClass<*>, is FirTypeAlias -> ensureTargetPhase(firResolvePhase)
else -> error("Unexpected target")
}
internal fun FirDeclarationUntypedDesignation.targetContainingDeclaration(): FirDeclaration? = path.lastOrNull() | kotlin | 18 | 0.790632 | 127 | 49.357143 | 28 | starcoderdata |
<filename>src/main/kotlin/io/github/gciatto/kt/mpp/KtMppPlusPlusPlugin.kt
package io.github.gciatto.kt.mpp
import com.github.breadmoirai.githubreleaseplugin.GithubReleasePlugin
import com.jfrog.bintray.gradle.BintrayPlugin
import io.github.gciatto.kt.mpp.KtMppPlusPlusExtension.Companion.Defaults.AUTOMATICALLY_CONFIGURE_SUBPROJECTS
import io.github.gciatto.kt.mpp.KtMppPlusPlusExtension.Companion.Defaults.KT_FREE_COMPILER_ARGS_JVM
import io.github.gciatto.kt.mpp.KtMppPlusPlusExtension.Companion.Defaults.MAVEN_REPO
import io.github.gciatto.kt.mpp.KtMppPlusPlusExtension.Companion.Defaults.MOCHA_TIMEOUT
import io.github.gciatto.kt.mpp.ProjectConfiguration.configureDokka
import io.github.gciatto.kt.mpp.ProjectConfiguration.configureDokkaMultiModule
import io.github.gciatto.kt.mpp.ProjectConfiguration.configureGitHubReleaseForRootProject
import io.github.gciatto.kt.mpp.ProjectConfiguration.configureKtLint
import io.github.gciatto.kt.mpp.ProjectConfiguration.configureMavenPublications
import io.github.gciatto.kt.mpp.ProjectConfiguration.configureNpmPublishing
import io.github.gciatto.kt.mpp.ProjectConfiguration.configureSigning
import io.github.gciatto.kt.mpp.ProjectConfiguration.configureTestResultPrinting
import io.github.gciatto.kt.mpp.ProjectConfiguration.configureUploadToBintray
import io.github.gciatto.kt.mpp.ProjectConfiguration.configureUploadToGithub
import io.github.gciatto.kt.mpp.ProjectConfiguration.configureUploadToMavenCentral
import io.github.gciatto.kt.mpp.ProjectConfiguration.createMavenPublications
import io.github.gciatto.kt.mpp.ProjectExtensions.isRootProject
import io.github.gciatto.kt.mpp.ProjectExtensions.ktMpp
import io.github.gciatto.kt.mpp.ProjectUtils.getPropertyOrDefault
import io.github.gciatto.kt.mpp.ProjectUtils.getPropertyOrWarnForAbsence
import io.github.gciatto.kt.mpp.ProjectUtils.log
import org.gradle.api.DomainObjectSet
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.plugins.JavaLibraryPlugin
import org.gradle.api.plugins.JavaPluginExtension
import org.gradle.api.publish.maven.plugins.MavenPublishPlugin
import org.gradle.api.tasks.bundling.Jar
import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.dependencies
import org.gradle.kotlin.dsl.get
import org.gradle.kotlin.dsl.kotlin
import org.gradle.kotlin.dsl.the
import org.gradle.kotlin.dsl.withType
import org.gradle.plugins.signing.SigningPlugin
import org.jetbrains.dokka.gradle.DokkaPlugin
import org.jetbrains.kotlin.gradle.dsl.KotlinJsCompile
import org.jetbrains.kotlin.gradle.dsl.KotlinJsProjectExtension
import org.jetbrains.kotlin.gradle.dsl.KotlinJvmCompile
import org.jetbrains.kotlin.gradle.dsl.KotlinJvmProjectExtension
import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension
import org.jetbrains.kotlin.gradle.plugin.KotlinTarget
import org.jetbrains.kotlin.gradle.targets.js.dsl.KotlinJsTargetDsl
import org.jetbrains.kotlin.gradle.targets.js.nodejs.NodeJsRootExtension
import org.jetbrains.kotlin.gradle.targets.js.nodejs.NodeJsRootPlugin
import org.jetbrains.kotlin.gradle.targets.jvm.KotlinJvmTarget
class KtMppPlusPlusPlugin : Plugin<Project> {
private lateinit var extension: KtMppPlusPlusExtension
override fun apply(target: Project) {
extension = target.extensions.create(
KtMppPlusPlusExtension.NAME,
KtMppPlusPlusExtension::class.java,
target.objects
)
if (target.isRootProject) {
target.loadDefaultsFromProperties()
target.configureProject(ProjectType.KT)
target.configureSubprojects()
} else {
extension.copyPropertyValuesFromParentOf(target)
target.loadDefaultsFromProperties()
}
}
private fun Project.configureSubprojects() {
if (extension.automaticallyConfigureSubprojects.getOrElse(AUTOMATICALLY_CONFIGURE_SUBPROJECTS)) {
configureSubprojectsOfType(ProjectType.KT) { ktProjects }
configureSubprojectsOfType(ProjectType.JVM) { jvmProjects }
configureSubprojectsOfType(ProjectType.JS) { jsProjects }
configureSubprojectsOfType(ProjectType.OTHER) { otherProjects }
}
}
private fun Project.configureSubprojectsOfType(
projectType: ProjectType,
projectSet: KtMppPlusPlusExtension.() -> DomainObjectSet<String>
) {
extension.projectSet().configureEach { subprojectName ->
subprojects.find { it.name == subprojectName }?.let {
it.apply<KtMppPlusPlusPlugin>()
it.configureProject(projectType)
}
}
}
private fun Project.loadDefaultsFromProperties() {
with(extension) {
projectLongName.set(
provider {
name.split('-').joinToString(" ") { it.capitalize() }
}
)
getPropertyOrWarnForAbsence("projectDescription").let { desc ->
projectDescription.set(provider { description.takeIf { it.isNullOrBlank() } ?: desc })
}
githubToken.set(getPropertyOrWarnForAbsence("githubToken"))
githubOwner.set(getPropertyOrWarnForAbsence("githubOwner"))
githubRepo.set(getPropertyOrWarnForAbsence("githubRepo"))
bintrayUser.set(getPropertyOrWarnForAbsence("bintrayUser"))
bintrayKey.set(getPropertyOrWarnForAbsence("bintrayKey"))
bintrayRepo.set(getPropertyOrWarnForAbsence("bintrayRepo"))
bintrayUserOrg.set(getPropertyOrWarnForAbsence("bintrayUserOrg"))
projectHomepage.set(getPropertyOrWarnForAbsence("projectHomepage"))
projectLicense.set(getPropertyOrWarnForAbsence("projectLicense"))
projectLicenseUrl.set(getPropertyOrWarnForAbsence("projectLicenseUrl"))
mavenRepo.set(getPropertyOrWarnForAbsence("mavenRepo"))
mavenUsername.set(getPropertyOrWarnForAbsence("mavenUsername"))
mavenPassword.set(getPropertyOrWarnForAbsence("mavenPassword"))
scmUrl.set(getPropertyOrWarnForAbsence("scmUrl"))
scmConnection.set(getPropertyOrWarnForAbsence("scmConnection"))
signingKey.set(getPropertyOrWarnForAbsence("signingKey"))
signingPassword.set(getPropertyOrWarnForAbsence("signingPassword"))
npmToken.set(getPropertyOrWarnForAbsence("npmToken"))
findProperty("npmOrganization")?.let { npmOrganization.set(it.toString()) }
issuesUrl.set(getPropertyOrWarnForAbsence("issuesUrl"))
issuesEmail.set(getPropertyOrWarnForAbsence("issuesEmail"))
nodeJsVersion.set(getPropertyOrWarnForAbsence("nodeJsVersion"))
mochaTimeout.set(getPropertyOrDefault("mochaTimeout", MOCHA_TIMEOUT).toLong())
ktFreeCompilerArgsJvm.set(getPropertyOrDefault("ktFreeCompilerArgsJvm", KT_FREE_COMPILER_ARGS_JVM))
mavenRepo.set(getPropertyOrDefault("mavenRepo", MAVEN_REPO))
}
}
private fun Project.configureProject(projectType: ProjectType) {
when (this) {
rootProject -> {
require(projectType == ProjectType.KT) {
throw IllegalStateException("Root project must be configured as Kt project")
}
configureRootProject()
}
else -> when (projectType) {
ProjectType.JVM -> configureJvmProject()
ProjectType.JS -> configureJsProject()
ProjectType.OTHER -> configureOtherProject()
ProjectType.KT -> configureKtProject()
}
}
}
private fun Project.configureAllProjects() {
description = extension.projectDescription.get()
repositories.add(rootProject.repositories.gradlePluginPortal())
repositories.add(rootProject.repositories.mavenCentral())
configureTestResultPrinting()
}
private fun KotlinMultiplatformExtension.configureMppCommonSourceSets() {
sourceSets.getByName("commonMain") {
it.dependencies {
api(kotlin("stdlib-common"))
}
}
sourceSets.getByName("commonTest") {
it.dependencies {
implementation(kotlin("test-common"))
implementation(kotlin("test-annotations-common"))
}
}
}
private fun KotlinTarget.configureMppTarget() {
mavenPublication {
require(it.name in setOf("jvm", "js"))
it.artifactId = "${project.name}-${it.name}"
}
}
private fun KotlinJvmTarget.configureMppJvmSourceSets() {
configureMppTarget()
compilations["main"].defaultSourceSet {
dependencies {
api(kotlin("stdlib-jdk8"))
}
}
compilations["test"].defaultSourceSet {
dependencies {
implementation(kotlin("test-junit"))
}
}
}
private fun Project.configureKtJvmCompilation() {
tasks.withType<KotlinJvmCompile> {
kotlinOptions {
jvmTarget = extension.javaVersion.get().toString()
freeCompilerArgs = extension.ktFreeCompilerArgsJvm.get().split(';').toList()
}
}
}
private fun KotlinJvmTarget.configureJava() {
withJava()
}
private fun KotlinJsTargetDsl.configureNodeJs() {
nodejs {
testTask {
useMocha {
timeout = extension.mochaTimeout.get().toString()
}
}
}
}
private fun KotlinJsTargetDsl.configureJsSourceSets() {
compilations["main"].defaultSourceSet {
dependencies {
implementation(kotlin("stdlib-js"))
}
}
compilations["test"].defaultSourceSet {
dependencies {
implementation(kotlin("test-js"))
}
}
}
private fun Project.configureKtJsCompilation() {
tasks.withType<KotlinJsCompile> {
kotlinOptions {
moduleKind = "umd"
// noStdlib = true
metaInfo = true
sourceMap = true
sourceMapEmbedSources = "always"
}
}
}
private fun Project.configureMultiplatform() {
configure<KotlinMultiplatformExtension> {
configureMppCommonSourceSets()
jvm {
configureJava()
configureMppTarget()
configureKtJvmCompilation()
configureMppJvmSourceSets()
}
js {
configureNodeJs()
configureMppTarget()
configureKtJsCompilation()
configureJsSourceSets()
configureNodeJsVersion()
}
}
}
private fun Project.configureNodeJsVersion() {
plugins.withType(NodeJsRootPlugin::class.java) { _ ->
the<NodeJsRootExtension>().let { nodeJsExt ->
ktMpp.nodeJsVersion.takeIf { it.isPresent }?.let {
log("Use NodeJs v${it.get()} for project $name")
nodeJsExt.nodeVersion = it.get()
}
}
}
}
private fun Project.configureJvm() {
configure<JavaPluginExtension> {
sourceCompatibility = extension.javaVersion.get()
targetCompatibility = extension.javaVersion.get()
}
configure<KotlinJvmProjectExtension> {
dependencies {
add("api", kotlin("stdlib-jdk8"))
add("testImplementation", kotlin("test-junit"))
}
}
configureKtJvmCompilation()
tasks.create("jvmTest") { it.dependsOn("test") }
}
private fun Project.configureJvmProject() {
log("Auto-configure project `$name` as JVM project")
configureAllProjects()
apply(plugin = "org.jetbrains.kotlin.jvm")
apply<JavaLibraryPlugin>()
apply<MavenPublishPlugin>()
apply<SigningPlugin>()
apply<DokkaPlugin>()
apply<BintrayPlugin>()
configureJvm()
configureKtLint()
configureDokka()
createMavenPublications("jvm", "java", docArtifact = "packDokka")
configureUploadToMavenCentral()
configureUploadToBintray()
configureSigning()
configureUploadToGithub({ "shadow" in it })
}
private fun Project.configureKtProject() {
log("Auto-configure project `$name` as Kt project")
configureAllProjects()
apply(plugin = "org.jetbrains.kotlin.multiplatform")
apply<MavenPublishPlugin>()
apply<SigningPlugin>()
apply<DokkaPlugin>()
apply<BintrayPlugin>()
configureMultiplatform()
configureKtLint()
configureDokka("jvm", "js")
configureMavenPublications("packDokka")
configureUploadToMavenCentral()
// configureUploadToBintray("kotlinMultiplatform", "js", "jvm", "metadata")
configureUploadToBintray()
configureSigning()
configureNpmPublishing()
configureUploadToGithub({ "shadow" in it })
}
private fun Project.configureJsProject() {
log("Auto-configure project `$name` as JS project")
configureAllProjects()
apply(plugin = "org.jetbrains.kotlin.js")
apply<MavenPublishPlugin>()
apply<SigningPlugin>()
apply<DokkaPlugin>()
apply<BintrayPlugin>()
configureJs()
configureKtLint()
configureDokka()
createMavenPublications("js", "kotlin", docArtifact = "packDokka")
configureUploadToMavenCentral()
configureUploadToBintray()
configureSigning()
configureNpmPublishing()
}
private fun Project.configureJs() {
configure<KotlinJsProjectExtension> {
js {
configureNodeJs()
configureKtJsCompilation()
configureJsSourceSets()
configureNodeJsVersion()
}
tasks.maybeCreate("sourcesJar", Jar::class.java).run {
sourceSets.forEach { sourceSet ->
sourceSet.kotlin.srcDirs.forEach {
from(it)
}
}
}
}
tasks.create("jsTest") { it.dependsOn("test") }
}
private fun Project.configureOtherProject() {
log("Auto-configure project `$name` as other project")
configureAllProjects()
}
private fun Project.configureRootProject() {
apply<GithubReleasePlugin>()
configureKtProject()
configureGitHubReleaseForRootProject()
configureDokkaMultiModule()
}
}
| kotlin | 34 | 0.656638 | 111 | 38.636364 | 374 | starcoderdata |
<gh_stars>1-10
package parkandrest.parkingmanagement.core.monetary
enum class Currency {
PLN,
USD,
EU
}
| kotlin | 5 | 0.700855 | 51 | 13.625 | 8 | starcoderdata |
package com.murphy.appcompat.dialogfragment
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.util.DisplayMetrics
import android.view.*
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
abstract class AppCompatBottomSheetDialogFragment<DB : ViewDataBinding> : BottomSheetDialogFragment() {
private var dpiRatio : Float? = null
private var dataBinding : DB? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//去除白色背景圆角
setStyle(BottomSheetDialogFragment.STYLE_NORMAL, R.style.BottomSheetDialogTheme)
val displayMetrics = requireActivity().resources.displayMetrics
dpiRatio = displayMetrics.heightPixels.toFloat() / displayMetrics.widthPixels.toFloat()
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val window = dialog?.window
window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
dataBinding?.let { db: DB ->
db.root.parent?.let { p: ViewParent ->
(p as ViewGroup).removeView(db.root)
}
return db.root
}
dataBinding = DataBindingUtil.inflate(inflater, bindLayout(), container, false)
initView(dataBinding!!)
return dataBinding?.root
}
override fun onStart() {
super.onStart()
if (dpiRatio!! > 18/9) {
return
}
val db = dataBinding!!
val parent = db.root.parent as View
val behavior = BottomSheetBehavior.from(parent)
var peekHeight = behavior.peekHeight
db.root.measure(0, 0)
var measuredHeight = db.root.measuredHeight
val windowManager = requireContext().getSystemService(Context.WINDOW_SERVICE) as WindowManager
val displayMetrics = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(displayMetrics)
val screenHeight = displayMetrics.heightPixels
var peekHeightRatio = getPeekHeightRatio()
if (peekHeightRatio > 1) peekHeightRatio = 1f
peekHeight = peekHeight.coerceAtLeast(measuredHeight)//peekHeight <= measureHeight
peekHeight = peekHeight.coerceAtMost(screenHeight)//measuredHeight <= screenHeight
if (peekHeight < screenHeight) {
peekHeightRatio = 1f
}
behavior.peekHeight = (peekHeightRatio * peekHeight).toInt()
}
abstract fun initView(dataBinding: DB)
abstract fun bindLayout(): Int
open fun getPeekHeightRatio() : Float {
return 1f
}
} | kotlin | 22 | 0.694146 | 103 | 32.976471 | 85 | starcoderdata |
<gh_stars>1-10
package soup.movie.data.api.response
data class NaverInfoResponse(
val star: String,
val url: String?
)
| kotlin | 7 | 0.71875 | 36 | 17.285714 | 7 | starcoderdata |
<filename>buildSrc/src/main/kotlin/Versions.kt
object Versions {
/* build tools */
const val buildTools = "31.0.0"
/* kotlin */
const val kotlin = "1.5.30"
/* plugins */
const val androidPlugin = "7.0.2"
const val googleServices = "4.3.10"
const val crashlytics = "2.7.1"
const val benManes = "0.39.0"
const val detekt = "1.18.1"
const val doctor = "0.7.3"
const val protobufPlugin = "0.8.17"
const val playPublisher = "3.6.0"
/* libraries */
const val compose = "1.1.0-alpha04"
const val composeConstraint = "1.0.0-beta02"
const val composePaging = "1.0.0-alpha12"
const val composeWear = "1.0.0-alpha06"
const val navigation = "2.4.0-alpha09"
const val core = "1.7.0-alpha02"
const val activity = "1.4.0-alpha02"
const val appCompat = "1.4.0-alpha03"
const val lifecycle = "2.4.0-alpha03"
const val firebase = "28.4.1"
const val hilt = "2.38.1"
const val hiltCompose = "1.0.0-alpha03"
const val startUp = "1.1.0"
const val coroutines = "1.5.2"
const val dataStore = "1.0.0"
const val protobuf = "4.0.0-rc-2"
const val playCore = "1.10.1"
const val playCoreKtx = "1.8.1"
const val cameraX = "1.1.0-alpha08"
const val cameraView = "1.0.0-alpha28"
const val workManager = "2.7.0-beta01"
const val retrofit = "2.9.0"
const val okhttp = "4.9.1"
const val kotlinxSerializationConverter = "0.8.0"
const val kotlinxSerialization = "1.2.2"
const val accompanist = "0.18.0"
const val landscapist = "1.3.6"
const val orchestra = "1.1.0"
const val coil = "1.3.2"
const val glide = "4.12.0"
const val fresco = "2.5.0"
const val timber = "5.0.1"
const val lottie = "4.1.0"
const val ratingBar = "1.1.1"
const val revealSwipe = "1.0.0"
const val speedDial = "1.0.0-beta03"
const val fontAwesome = "1.0.0-beta02"
const val composeCharts = "0.3.2"
const val composeNeumorphism = "1.0.0-alpha02"
const val composeMarkdown = "0.2.6"
const val composeBarcodes = "1.0.1"
const val composeRichtext = "0.8.1"
const val zoomableImage = "0.1.0"
const val stageStepBar = "0.0.1"
const val plot = "0.1.1"
const val composeTimelineView = "1.0.2"
const val adMob = "20.3.0"
const val test = "1.4.1-alpha01"
} | kotlin | 6 | 0.617231 | 53 | 32.826087 | 69 | starcoderdata |
<filename>app/src/main/java/pifloor/webserver/ServerFragment.kt
package pifloor.webserver
import android.content.Context
import android.os.Bundle
import android.support.v4.app.Fragment
import android.util.Log
import android.view.*
import android.widget.TextView
import butterknife.BindView
import butterknife.ButterKnife
import butterknife.Unbinder
import pifloor.R
import pifloor.injection.PiFloorApplication
import java.io.IOException
import javax.inject.Inject
class ServerFragment : Fragment() {
private lateinit var unbinder: Unbinder
var hostNameTxt: String? = null
@Inject
lateinit var server: GameServer
@Inject
lateinit var connectionUtils: ConnectionUtils
private lateinit var fragmentView: View
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
fragmentView = inflater.inflate(R.layout.fragment_server, container, false)
unbinder = ButterKnife.bind(this, fragmentView)
return fragmentView
}
override fun onAttach(context: Context?) {
(this.activity!!.application as PiFloorApplication).component.inject(this)
super.onAttach(context)
}
fun startServer() {
// Run on localhost if no WiFi is present
if (!connectionUtils.isConnectedToWifi()) {
server.start(LOCAL_HOST, PORT_NUMBER, TOPIC_NAME)
} else {
server.start(connectionUtils.getIpAddress(), PORT_NUMBER, TOPIC_NAME)
}
displayAddresses()
}
private fun displayAddresses() {
val addresses = "${server.webAddress}\n${server.webSocketAddress}"
this.hostNameTxt = addresses
}
fun stopServer() {
try {
this.server.stop()
this.hostNameTxt = "Stopped"
} catch (e: IOException) {
// TODO: display a useful message
throw RuntimeException(e)
}
}
override fun onDestroy() {
super.onDestroy()
try {
this.server.stop()
} catch (e: UninitializedPropertyAccessException) {
Log.e(TAG, e::class.java.canonicalName, e)
}
}
override fun onDestroyView() {
super.onDestroyView()
unbinder.unbind()
}
companion object {
private const val PORT_NUMBER = 5444 // TODO make this configurable
// TODO make this configurable?, This is hardcoded in the client code [Change both]
private const val TOPIC_NAME = "game"
private const val LOCAL_HOST = "127.0.0.1"
private val TAG = this::class.java.canonicalName.toString()
}
}
| kotlin | 16 | 0.666033 | 115 | 28.573034 | 89 | starcoderdata |
<gh_stars>1-10
package id.ac.undip.ce.student.muhammadrizqi.footballapps.favorites
import android.content.Context
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.widget.SwipeRefreshLayout
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 org.jetbrains.anko.*
import org.jetbrains.anko.db.classParser
import org.jetbrains.anko.db.select
import org.jetbrains.anko.recyclerview.v7.recyclerView
import org.jetbrains.anko.support.v4.onRefresh
import org.jetbrains.anko.support.v4.swipeRefreshLayout
import id.ac.undip.ce.student.muhammadrizqi.footballapps.R.color.colorAccent
import id.ac.undip.ce.student.muhammadrizqi.footballapps.db.TeamDB
import id.ac.undip.ce.student.muhammadrizqi.footballapps.model.Team
import id.ac.undip.ce.student.muhammadrizqi.footballapps.db.database
import id.ac.undip.ce.student.muhammadrizqi.footballapps.teamsdetail.TeamDetailActivity
class FavoriteTeamsFragment: Fragment(), AnkoComponent<Context>{
private var teamDB: MutableList<TeamDB> = mutableListOf()
private lateinit var swipeRefresh: SwipeRefreshLayout
private lateinit var listTeams: RecyclerView
private lateinit var adapter: FavoriteTeamsAdapter
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
adapter = FavoriteTeamsAdapter(teamDB){
val team = Team(
it.teamId,
it.teamName,
it.teamBadge,
it.teamStadium,
it.teamFormedYear,
it.teamDescription
)
requireContext().startActivity<TeamDetailActivity>("teamObject" to team)
}
listTeams.adapter = adapter
showFavorite()
swipeRefresh.onRefresh {
showFavorite()
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return createView(AnkoContext.create(requireContext()))
}
override fun createView(ui: AnkoContext<Context>) = with(ui){
linearLayout {
lparams(width = matchParent, height = wrapContent)
topPadding = dip(16)
leftPadding = dip(16)
rightPadding = dip(16)
swipeRefresh = swipeRefreshLayout {
setColorSchemeResources(colorAccent,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light)
listTeams = recyclerView {
lparams(width = matchParent, height = wrapContent)
layoutManager = LinearLayoutManager(ctx)
}
}
}
}
private fun showFavorite(){
requireContext().database.use {
swipeRefresh.isRefreshing = true
val result = select(TeamDB.TABLE_TEAM)
val team = result.parseList(classParser<TeamDB>())
teamDB.clear()
teamDB.addAll(team)
adapter.notifyDataSetChanged()
swipeRefresh.isRefreshing = false
}
}
} | kotlin | 32 | 0.667566 | 116 | 36.077778 | 90 | starcoderdata |
package name.lmj0011.courierlocker.fragments
import android.annotation.SuppressLint
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.view.*
import androidx.appcompat.widget.SearchView
import androidx.core.content.pm.ShortcutInfoCompat
import androidx.core.content.pm.ShortcutManagerCompat
import androidx.core.graphics.drawable.IconCompat
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import androidx.navigation.fragment.findNavController
import androidx.paging.PagedList
import androidx.preference.PreferenceManager
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import kotlinx.coroutines.*
import name.lmj0011.courierlocker.CourierLockerApplication
import name.lmj0011.courierlocker.DeepLinkActivity
import name.lmj0011.courierlocker.MainActivity
import name.lmj0011.courierlocker.R
import name.lmj0011.courierlocker.adapters.MapListAdapter
import name.lmj0011.courierlocker.database.Apartment
import name.lmj0011.courierlocker.database.CourierLockerDatabase
import name.lmj0011.courierlocker.databinding.FragmentMapsBinding
import name.lmj0011.courierlocker.factories.ApartmentViewModelFactory
import name.lmj0011.courierlocker.helpers.*
import name.lmj0011.courierlocker.helpers.interfaces.SearchableRecyclerView
import name.lmj0011.courierlocker.viewmodels.ApartmentViewModel
import org.kodein.di.instance
import timber.log.Timber
/**
* A simple [Fragment] subclass.
*
*/
class MapsFragment : Fragment(), SearchableRecyclerView {
private lateinit var binding: FragmentMapsBinding
private lateinit var mainActivity: MainActivity
private lateinit var listAdapter: MapListAdapter
private lateinit var preferences: PreferenceHelper
private lateinit var viewModelFactory: ApartmentViewModelFactory
private lateinit var apartmentViewModel: ApartmentViewModel
private lateinit var locationHelper: LocationHelper
private var fragmentJob: Job = Job()
private val uiScope = CoroutineScope(Dispatchers.Main + fragmentJob)
private val scrollListener = object: RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
Timber.i("scrollListener called!")
// unlock list when scrolled all the way to the top
if (!recyclerView.canScrollVertically(-1)) {
ListLock.unlock()
} else {
ListLock.lock()
}
}
}
/**
* This Observer will cause the recyclerView to refresh itself periodically
*/
private val lastLocationListener = Observer<Double> {
if(!ListLock.isListLocked) {
this.refreshList()
}
}
@SuppressLint("NotifyDataSetChanged")
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = DataBindingUtil.inflate(
inflater, R.layout.fragment_maps, container, false)
mainActivity = activity as MainActivity
setHasOptionsMenu(true)
val application = requireActivity().application as CourierLockerApplication
preferences = application.kodein.instance()
val dataSource = CourierLockerDatabase.getInstance(application).apartmentDao
viewModelFactory = ApartmentViewModelFactory(dataSource, application)
apartmentViewModel = ViewModelProvider(this, viewModelFactory).get(ApartmentViewModel::class.java)
locationHelper = (requireContext().applicationContext as CourierLockerApplication).kodein.instance()
listAdapter = MapListAdapter( MapListAdapter.MapListener(
{apt ->
this.findNavController().navigate(MapsFragmentDirections.actionMapsFragmentToCreateOrEditApartmentMapFragment(apt.id))
},
{ apt ->
launchIO {
val gateCode = apartmentViewModel.getRelatedGateCode(apt.gateCodeId)
gateCode?.also {
withUIContext {
MaterialAlertDialogBuilder(binding.root.context)
.setTitle("Gate Codes")
.setMessage("${apt.name}\n\n${gateCode.codes.joinToString(", ")}")
.setPositiveButton("Ok") { _, _ ->}
.setNeutralButton("Disassociate") { dialog0, _ ->
dialog0.dismiss()
MaterialAlertDialogBuilder(binding.root.context)
.setTitle("Disassociate Gate Codes?")
.setMessage("${apt.name}\n\n${gateCode.codes.joinToString(", ")}")
.setPositiveButton("Yes") { dialog1, _ ->
dialog1.dismiss()
apt.gateCodeId = 0
apartmentViewModel.updateApartment(apt)
findNavController().navigate(R.id.mapsFragment)
}
.setNeutralButton("Cancel") {dialog, _ ->
dialog.dismiss()
}
.show()
}
.show()
}
}
}
},
{apt ->
uiScope.launch{
withContext(Dispatchers.IO) {
apartmentViewModel.database.deleteByApartmentId(apt.id)
}
listAdapter.notifyDataSetChanged()
}
}
), this,
MapListAdapter.VIEW_MODE_NORMAL
)
binding.mapList.addItemDecoration(DividerItemDecoration(mainActivity, DividerItemDecoration.VERTICAL))
binding.mapList.adapter = listAdapter
binding.lifecycleOwner = this
apartmentViewModel.apartmentsPaged.observe(viewLifecycleOwner, {
listAdapter.submitData(viewLifecycleOwner.lifecycle, it)
listAdapter.notifyItemRangeChanged(0, Const.DEFAULT_PAGE_COUNT)
binding.mapList.scrollToPosition(0)
})
locationHelper.lastLatitude.observe(viewLifecycleOwner, lastLocationListener)
binding.liveLocationUpdatingSwitch.setOnCheckedChangeListener { _, isChecked ->
ListLock.unlock()
apartmentViewModel.isOrderedByNearest.postValue(isChecked)
preferences.mapsIsOrderedByNearest = isChecked
}
if(!preferences.devControlsEnabled) {
binding.generateMapBtn.visibility = View.GONE
}
binding.mapsSearchView.setOnQueryTextListener(object: SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String?): Boolean {
return false
}
override fun onQueryTextChange(newText: String?): Boolean {
apartmentViewModel.filterText.postValue(newText)
return false
}
})
binding.mapsSearchView.setOnCloseListener {
this@MapsFragment.toggleSearch(mainActivity, binding.mapsSearchView, false)
false
}
binding.mapsSearchView.setOnQueryTextFocusChangeListener { view, hasFocus ->
if (hasFocus) {
ListLock.lock()
binding.mapList.removeOnScrollListener(scrollListener)
} else{
binding.mapsSearchView.setQuery("", true)
this@MapsFragment.toggleSearch(mainActivity, binding.mapsSearchView, false)
ListLock.unlock()
binding.mapList.addOnScrollListener(scrollListener)
}
}
binding.swipeRefresh.setOnRefreshListener {
ListLock.unlock()
this.findNavController().navigate(R.id.mapsFragment)
}
return binding.root
}
override fun onStart() {
super.onStart()
if(!PermissionHelper.permissionAccessFineLocationApproved) {
PermissionHelper.requestFineLocationAccess(mainActivity)
}
}
override fun onResume() {
super.onResume()
mainActivity.showFabAndSetListener(this::fabOnClickListenerCallback, R.drawable.ic_fab_add)
mainActivity.supportActionBar?.subtitle = null
this.applyPreferences()
this.refreshList()
binding.mapList.addOnScrollListener(scrollListener)
}
override fun onPause() {
super.onPause()
binding.mapList.removeOnScrollListener(scrollListener)
ListLock.unlock()
}
override fun onDestroy() {
super.onDestroy()
fragmentJob?.cancel()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.maps, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return when (item.itemId) {
R.id.action_maps_search -> {
this@MapsFragment.toggleSearch(mainActivity, binding.mapsSearchView, true)
true
}
R.id.action_maps_add_to_home -> {
if (ShortcutManagerCompat.isRequestPinShortcutSupported(requireContext())) {
ShortcutInfoCompat.Builder(requireContext(), resources.getString(R.string.shortcut_maps))
.setIcon(IconCompat.createWithResource(requireContext(), R.mipmap.ic_maps_shortcut))
.setShortLabel("Maps")
.setIntent(
Intent(requireContext(), DeepLinkActivity::class.java).apply {
action = MainActivity.INTENT_SHOW_MAPS
}
)
.build().also { shortCutInfo ->
ShortcutManagerCompat.requestPinShortcut(requireContext(), shortCutInfo, null)
}
} else {
mainActivity.showToastMessage(getString(R.string.cant_pinned_shortcuts))
}
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun fabOnClickListenerCallback() {
this.findNavController().navigate(MapsFragmentDirections.actionMapsFragmentToCreateOrEditApartmentMapFragment(0L))
}
private fun applyPreferences() {
val isChecked = preferences.mapsIsOrderedByNearest
binding.liveLocationUpdatingSwitch.isChecked = isChecked
apartmentViewModel.isOrderedByNearest.postValue(isChecked)
}
private fun refreshList() {
binding.swipeRefresh.isRefreshing = false
}
}
| kotlin | 40 | 0.626759 | 134 | 39.10453 | 287 | starcoderdata |
<reponame>frwang96/verik-examples
/*
* SPDX-License-Identifier: Apache-2.0
*/
@file:Verik
@file:Suppress("ClassName", "ConvertSecondaryConstructorToPrimary", "unused")
import imported.uvm_pkg.uvm_component
import imported.uvm_pkg.uvm_phase
import io.verik.core.*
@Entry
open class full_test : tinyalu_base_test {
@Inj
private val header = "`uvm_component_utils(${t<full_test>()});"
lateinit var runall_seq: run_all_sequence
@Task
override fun run_phase(phase: uvm_phase?) {
runall_seq = run_all_sequence("runall_seq")
phase!!.raise_objection(this)
runall_seq.start(null)
phase.drop_objection(this)
}
constructor(name: String, parent: uvm_component?) : super(name, parent)
}
| kotlin | 15 | 0.683715 | 77 | 23.766667 | 30 | starcoderdata |
package com.github.xeonkryptos.integration.gitlab.ui.clone.repository.event
import java.util.*
interface ClonePathEventListener : EventListener {
fun onClonePathChanged(event: ClonePathEvent)
} | kotlin | 7 | 0.82 | 75 | 24.125 | 8 | starcoderdata |
<reponame>jiechic/RxService<gh_stars>1-10
package com.jiechic.android.rxservice.sample
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.jiechic.android.rxservice.IServiceHandler
import com.jiechic.android.rxservice.RxService
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
RxService(this, ServiceHandler::class.java)
.connectService()
.map { IServiceHandler.Stub.asInterface(it) }
.subscribe { Log.d(MainActivity::class.java.simpleName, it.sendAndGet("hello world")) }
}
}
| kotlin | 19 | 0.728986 | 103 | 35.315789 | 19 | starcoderdata |
package com.example.pets
import com.example.pets.fixtures.PetDomain
import com.example.pets.fixtures.dynamic
import io.kotest.matchers.collections.shouldContain
import io.kotest.matchers.collections.shouldHaveSize
import io.kotest.matchers.should
import io.kotest.matchers.shouldBe
import java.util.stream.*
import org.junit.jupiter.api.TestFactory
import org.junit.jupiter.api.extension.ExtendWith
@ExtendWith(PetDomain::class)
class Exercise4 {
@TestFactory
fun ageStatisticsOfPets(people: People) =
dynamic {
failAll("Refactor to kotlin stdlib. Do not forget to remove this line.")
val petAges =
people.stream()
.map { it.pets }
.flatMap { it.stream() }
.mapToInt { it.age }
.boxed()
.collect(Collectors.toList())
val uniqueAges = petAges.toSet()
test("ages are 1,2,3,4") { uniqueAges shouldBe setOf(1, 2, 3, 4) }
val statistics = petAges.stream().mapToInt { it }.summaryStatistics()
test("min") { statistics.min shouldBe petAges.stream().mapToInt { it }.min().orElse(0) }
test("max") { statistics.max shouldBe petAges.stream().mapToInt { it }.max().orElse(0) }
test("sum") { statistics.sum shouldBe petAges.stream().mapToInt { it }.sum() }
test("average") {
statistics.average should
petAges.stream().mapToInt { it }.average().orElse(0.0).withDelta(0.0)
}
test("all ages should be greater than 0") {
petAges.stream().allMatch { it > 0 } shouldBe true
}
test("no any ages do not equal to 0") {
petAges.stream().anyMatch { it == 0 } shouldBe false
}
test("no any ages do not less than 0") {
petAges.stream().noneMatch { it < 0 } shouldBe true
}
}
@TestFactory
fun streamsToKotlinStdLibRefactor1(people: People) =
dynamic {
failAll("Refactor the stream API code to kotlin stdlib. Do not forget to remove this line.")
val person: Person =
people.stream().filter { it.named("<NAME>") }.findFirst().orElseThrow()
val names: String = person.pets.stream().map { it.name }.collect(Collectors.joining(" & "))
test("names should be Dolly & Spot") { names shouldBe "Dolly & Spot" }
}
@TestFactory
fun streamToKotlinStdLibRefactor2(people: People) =
dynamic {
failAll("Refactor the stream API code to kotlin stdlib. Do not forget to remove this line.")
val countByPetType: Map<PetType, Long> =
people.stream()
.flatMap { it.pets.stream() }
.collect(Collectors.groupingBy(Pet::type, Collectors.counting()))
test("cat -> 2") { countByPetType.getValue(PetType.CAT) shouldBe 2 }
test("dog -> 2") { countByPetType.getValue(PetType.DOG) shouldBe 2 }
test("hamster -> 2") { countByPetType.getValue(PetType.HAMSTER) shouldBe 2 }
test("snake -> 1") { countByPetType.getValue(PetType.SNAKE) shouldBe 1 }
test("turtle -> 1") { countByPetType.getValue(PetType.TURTLE) shouldBe 1 }
test("bird -> 1") { countByPetType.getValue(PetType.BIRD) shouldBe 1 }
}
@TestFactory
fun streamToKotlinStdLibRefactor3(people: People) =
dynamic {
failAll("Refactor the stream API code to kotlin stdlib. Do not forget to remove this line.")
val top3Favorites =
people.stream()
.flatMap { it.pets.stream() }
.collect(Collectors.groupingBy(Pet::type, Collectors.counting()))
.entries
.stream()
.sorted(Comparator.comparingLong { -it.value })
.limit(3)
.map { it.toPair() }
.collect(Collectors.toUnmodifiableList())
test("it has size 3") { top3Favorites shouldHaveSize 3 }
test("people with cat is 2") { top3Favorites shouldContain (PetType.CAT to 2L) }
test("people with dog is 2") { top3Favorites shouldContain (PetType.DOG to 2L) }
test("people with hamster is 2") { top3Favorites shouldContain (PetType.HAMSTER to 2L) }
}
}
| kotlin | 33 | 0.618626 | 100 | 40.356436 | 101 | starcoderdata |
package com.wenhaiz.himusic.module.collectlist
import com.wenhaiz.himusic.data.LoadCollectCallback
import com.wenhaiz.himusic.data.MusicRepository
import com.wenhaiz.himusic.data.bean.Collect
internal class CollectListPresenter(val view: CollectListContract.View) : CollectListContract.Presenter {
private val musicRepository: MusicRepository = MusicRepository.getInstance(view.getViewContext())
init {
view.setPresenter(this)
}
companion object {
const val TAG = "CollectListPresenter"
}
override fun loadCollects(page: Int) {
musicRepository.loadHotCollect(page, object : LoadCollectCallback {
override fun onStart() {
view.onLoading()
}
override fun onFailure(msg: String) {
view.onFailure(msg)
}
override fun onSuccess(collectList: List<Collect>) {
view.setCollects(collectList)
}
})
}
} | kotlin | 19 | 0.658487 | 105 | 28.666667 | 33 | starcoderdata |
<filename>app/src/main/java/com/dinaraparanid/prima/utils/web/genius/search_response/Stats.kt
package com.dinaraparanid.prima.utils.web.genius.search_response
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
import java.io.Serializable
/**
* Statistics for a searched track
*/
data class Stats(
@Expose
@JvmField
@SerializedName("unreviewed_annotations")
val unreviewedAnnotations: Int,
@Expose
@JvmField
val concurrents: Int? = null,
@Expose
@JvmField
@SerializedName("hot")
val isHot: Boolean,
@Expose
@JvmField
@SerializedName("pageviews")
val pageViews: Long? = null
) : Serializable | kotlin | 13 | 0.723496 | 93 | 21.548387 | 31 | starcoderdata |
package com.kuky.comvvmhelper.ui.fragment
import android.os.Bundle
import android.view.View
import com.kk.android.comvvmhelper.ui.BaseFragment
import com.kuky.comvvmhelper.R
import com.kuky.comvvmhelper.databinding.FragmentTestNewKoinBinding
import com.kuky.comvvmhelper.entity.EntityForKoinScopeTest
import org.koin.android.ext.android.inject
import org.koin.android.scope.AndroidScopeComponent
import org.koin.androidx.scope.fragmentScope
import org.koin.core.scope.Scope
/**
* @author kuky.
* @description
*/
class TestNewKoinFragment : BaseFragment<FragmentTestNewKoinBinding>(), AndroidScopeComponent {
override val scope: Scope by fragmentScope()
private val aInstance by inject<EntityForKoinScopeTest>()
override fun layoutId() = R.layout.fragment_test_new_koin
override fun initFragment(view: View, savedInstanceState: Bundle?) {
aInstance.print()
mBinding.resultDisplay.text = aInstance.result()
}
override fun onDestroy() {
super.onDestroy()
scope.close()
}
} | kotlin | 10 | 0.768046 | 95 | 28.714286 | 35 | starcoderdata |
package org.learning.by.example.reactive.kotlin.microservices.KotlinReactiveMS.handlers
import org.amshove.kluent.shouldEqual
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.learning.by.example.reactive.kotlin.microservices.KotlinReactiveMS.exceptions.*
import org.learning.by.example.reactive.kotlin.microservices.KotlinReactiveMS.handlers.ThrowableTranslator.Translate
import org.learning.by.example.reactive.kotlin.microservices.KotlinReactiveMS.test.BasicIntegrationTest
import org.learning.by.example.reactive.kotlin.microservices.KotlinReactiveMS.test.tags.UnitTest
import org.springframework.http.HttpStatus
import reactor.core.publisher.Mono
import kotlin.reflect.KClass
import kotlin.reflect.full.primaryConstructor
@UnitTest
@DisplayName("ThrowableTranslator Unit Tests")
private class ThrowableTranslatorTest : BasicIntegrationTest() {
private inline fun <reified T : Throwable> createException(cause: Throwable? = null) =
T::class.primaryConstructor?.call("", cause)!!
private inline fun <reified T : Throwable, reified K : Throwable> createExceptionWithCause() =
createException<T>(createException<K>())
private var <T : Throwable> T.httpStatus: HttpStatus
get() = Mono.just(this).transform(Translate::throwable).map { it.httpStatus }.block()
set(value) {
this.httpStatus = value
}
private infix fun Throwable.`should translate to`(theStatus: HttpStatus) {
this.httpStatus shouldEqual theStatus
}
@Suppress("unused")
private inline infix fun <reified T : Throwable> KClass<T>.`translates to`(theStatus: HttpStatus) {
createException<T>() `should translate to` theStatus
}
@Suppress("unused", "UNUSED_PARAMETER")
private inline infix fun <reified T : Throwable, reified K : Throwable> KClass<T>.withCause(otherClass: KClass<K>) =
createExceptionWithCause<T, K>()
@Test
fun translateGeoLocationNotFoundExceptionTest() {
GeoLocationNotFoundException::class `translates to` HttpStatus.NOT_FOUND
}
@Test
fun translateGetGeoLocationExceptionTest() {
GetGeoLocationException::class `translates to` HttpStatus.INTERNAL_SERVER_ERROR
}
@Test
fun translateGetSunriseSunsetExceptionTest() {
GetSunriseSunsetException::class `translates to` HttpStatus.INTERNAL_SERVER_ERROR
}
@Test
fun translateInvalidParametersExceptionTest() {
InvalidParametersException::class `translates to` HttpStatus.BAD_REQUEST
}
@Test
fun translatePathNotFoundExceptionTest() {
PathNotFoundException::class `translates to` HttpStatus.NOT_FOUND
}
@Test
fun translateWithCauseTest() {
GetGeoLocationException::class withCause InvalidParametersException::class `should translate to`
HttpStatus.BAD_REQUEST
}
}
| kotlin | 16 | 0.742847 | 120 | 37.171053 | 76 | starcoderdata |
<reponame>kioko/paybill-manager
package com.thomaskioko.paybillmanager.mobile.injection.module
import com.nhaarman.mockitokotlin2.mock
import com.thomaskioko.paybillmanager.data.executor.JobExecutor
import com.thomaskioko.paybillmanager.domain.executor.ThreadExecutor
import com.thomaskioko.paybillmanager.domain.repository.*
import dagger.Binds
import dagger.Module
import dagger.Provides
@Module
abstract class TestDataModule {
@Binds
abstract fun bindThreadExecutor(jobExecutor: JobExecutor): ThreadExecutor
@Module
companion object {
@Provides
@JvmStatic
fun providesTokenDataRepository(): JengaTokenRepository {
return mock()
}
@Provides
@JvmStatic
fun providesBillsDataRepository(): BillsRepository {
return mock()
}
@Provides
@JvmStatic
fun providesCategoryRepository(): CategoryRepository {
return mock()
}
@Provides
@JvmStatic
fun providesBillCategoryRepository(): BillCategoryRepository {
return mock()
}
@Provides
@JvmStatic
fun providesMpesaRequestRepository(): MpesaRequestRepository {
return mock()
}
}
} | kotlin | 12 | 0.672713 | 77 | 23.403846 | 52 | starcoderdata |
<reponame>MGaetan89/ShowsRage<gh_stars>10-100
package com.mgaetan89.showsrage.presenter
import android.support.annotation.ColorRes
import android.text.format.DateUtils
import com.mgaetan89.showsrage.extension.toRelativeDate
import com.mgaetan89.showsrage.model.Episode
class EpisodePresenter(val episode: Episode?) {
fun getAirDate(): CharSequence? {
val airDate = this._getEpisode()?.airDate ?: return null
if (airDate.isEmpty()) {
return null
}
return airDate.toRelativeDate("yyyy-MM-dd", DateUtils.DAY_IN_MILLIS)
}
fun getQuality(): String {
val quality = this._getEpisode()?.quality ?: return ""
return if ("N/A".equals(quality, true)) "" else quality
}
@ColorRes
fun getStatusColor() = this._getEpisode()?.getStatusBackgroundColor() ?: android.R.color.transparent
private fun _getEpisode() = if (this.episode?.isValid == true) this.episode else null
}
| kotlin | 13 | 0.747463 | 101 | 28.566667 | 30 | starcoderdata |
@file:JsModule("@material-ui/core/List")
@file:JsNonModule
package ui.external.materialui
import react.RClass
import react.RProps
@JsName("default")
external val list: RClass<RProps>
| kotlin | 7 | 0.784946 | 40 | 17.6 | 10 | starcoderdata |
<reponame>egaga/ahwen
package dev.komu.ahwen.file
import dev.komu.ahwen.types.FileName
import java.nio.ByteBuffer
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
/**
* A simple in-memory implementation of [FileManager] useful for unit tests.
*/
class MemoryFileManager : FileManager {
private val blocksByFiles = mutableMapOf<FileName, Int>()
private val dataByBlock = mutableMapOf<Block, ByteArray>()
private val lock = ReentrantLock()
override fun read(block: Block, bb: ByteBuffer) {
lock.withLock {
bb.position(0)
bb.put(getBlockData(block))
}
}
override fun write(block: Block, bb: ByteBuffer) {
lock.withLock {
bb.position(0)
bb.get(getBlockData(block))
}
}
override fun append(fileName: FileName, bb: ByteBuffer): Block {
lock.withLock {
val size = size(fileName)
blocksByFiles[fileName] = size + 1
val block = Block(fileName, size)
write(block, bb)
return block
}
}
override fun size(fileName: FileName): Int =
lock.withLock {
blocksByFiles.getOrPut(fileName) { 0 }
}
private fun getBlockData(block: Block): ByteArray =
dataByBlock.getOrPut(block) { ByteArray(Page.BLOCK_SIZE) }
}
| kotlin | 19 | 0.630387 | 76 | 26.938776 | 49 | starcoderdata |
<filename>android-startup/src/main/java/com/rousetime/android_startup/StartupListener.kt<gh_stars>1000+
package com.rousetime.android_startup
import com.rousetime.android_startup.model.CostTimesModel
/**
* Created by idisfkj on 2020/8/10.
* Email: <EMAIL>.
*/
interface StartupListener {
/**
* call when all startup completed.
* @param totalMainThreadCostTime cost times of main thread.
* @param costTimesModels list of cost times for every startup.
*/
fun onCompleted(totalMainThreadCostTime: Long, costTimesModels: List<CostTimesModel>)
} | kotlin | 12 | 0.749129 | 103 | 30.944444 | 18 | starcoderdata |
package com.apollographql.apollo.internal.response
import com.apollographql.apollo.api.CustomTypeAdapter
import com.apollographql.apollo.api.Operation
import com.apollographql.apollo.api.ResponseField
import com.apollographql.apollo.api.ScalarType
import com.apollographql.apollo.api.ScalarTypeAdapters
import com.apollographql.apollo.api.internal.ResolveDelegate
import com.apollographql.apollo.api.internal.ResponseFieldMarshaller
import com.apollographql.apollo.api.internal.ResponseWriter
import java.math.BigDecimal
import java.util.ArrayList
import java.util.LinkedHashMap
class RealResponseWriter(private val operationVariables: Operation.Variables, private val scalarTypeAdapters: ScalarTypeAdapters) : ResponseWriter {
val buffer: MutableMap<String, FieldDescriptor> = LinkedHashMap()
override fun writeString(field: ResponseField, value: String?) {
writeScalarFieldValue(field, value)
}
override fun writeInt(field: ResponseField, value: Int?) {
writeScalarFieldValue(field, if (value != null) BigDecimal.valueOf(value.toLong()) else null)
}
override fun writeLong(field: ResponseField, value: Long?) {
writeScalarFieldValue(field, if (value != null) BigDecimal.valueOf(value) else null)
}
override fun writeDouble(field: ResponseField, value: Double?) {
writeScalarFieldValue(field, if (value != null) BigDecimal.valueOf(value) else null)
}
override fun writeBoolean(field: ResponseField, value: Boolean?) {
writeScalarFieldValue(field, value)
}
override fun writeCustom(field: ResponseField.CustomTypeField, value: Any?) {
val typeAdapter = scalarTypeAdapters.adapterFor<Any>(field.scalarType)
writeScalarFieldValue(field, if (value != null) typeAdapter.encode(value).value else null)
}
override fun writeObject(field: ResponseField, marshaller: ResponseFieldMarshaller?) {
checkFieldValue(field, marshaller)
if (marshaller == null) {
buffer[field.responseName] = FieldDescriptor(field, null)
return
}
val nestedResponseWriter = RealResponseWriter(operationVariables, scalarTypeAdapters)
marshaller.marshal(nestedResponseWriter)
buffer[field.responseName] = FieldDescriptor(field, nestedResponseWriter.buffer)
}
override fun writeFragment(marshaller: ResponseFieldMarshaller?) {
marshaller?.marshal(this)
}
override fun <T> writeList(field: ResponseField, values: List<T>?, listWriter: ResponseWriter.ListWriter<T>) {
checkFieldValue(field, values)
if (values == null) {
buffer[field.responseName] = FieldDescriptor(field, null)
return
}
val accumulated = ArrayList<Any?>()
listWriter.write(values, ListItemWriter(operationVariables, scalarTypeAdapters, accumulated))
buffer[field.responseName] = FieldDescriptor(field, accumulated)
}
fun resolveFields(delegate: ResolveDelegate<Map<String, Any>?>) {
resolveFields(operationVariables, delegate, buffer)
}
private fun writeScalarFieldValue(field: ResponseField, value: Any?) {
checkFieldValue(field, value)
buffer[field.responseName] = FieldDescriptor(field, value)
}
private fun rawFieldValues(buffer: Map<String, FieldDescriptor>): Map<String, Any?> {
val fieldValues: MutableMap<String, Any?> = LinkedHashMap()
for ((fieldResponseName, value) in buffer) {
val fieldValue = value.value
if (fieldValue == null) {
fieldValues[fieldResponseName] = null
} else if (fieldValue is Map<*, *>) {
val nestedMap = rawFieldValues(fieldValue as Map<String, FieldDescriptor>)
fieldValues[fieldResponseName] = nestedMap
} else if (fieldValue is List<*>) {
fieldValues[fieldResponseName] = rawListFieldValues(fieldValue)
} else {
fieldValues[fieldResponseName] = fieldValue
}
}
return fieldValues
}
private fun rawListFieldValues(values: List<*>): List<*> {
val listValues = ArrayList<Any?>()
for (value in values) {
if (value is Map<*, *>) {
listValues.add(rawFieldValues(value as Map<String, FieldDescriptor>))
} else if (value is List<*>) {
listValues.add(rawListFieldValues(value))
} else {
listValues.add(value)
}
}
return listValues
}
private fun resolveFields(operationVariables: Operation.Variables,
delegate: ResolveDelegate<Map<String, Any>?>, buffer: Map<String, FieldDescriptor>) {
val rawFieldValues = rawFieldValues(buffer)
for (fieldResponseName in buffer.keys) {
val fieldDescriptor = buffer[fieldResponseName]
val rawFieldValue = rawFieldValues[fieldResponseName]
delegate.willResolve(fieldDescriptor!!.field, operationVariables, fieldDescriptor.value)
when (fieldDescriptor.field.type) {
ResponseField.Type.OBJECT -> {
resolveObjectFields(fieldDescriptor, rawFieldValue as Map<String, Any>?, delegate)
}
ResponseField.Type.LIST -> {
resolveListField(fieldDescriptor.field, fieldDescriptor.value as List<*>?, rawFieldValue as List<*>?, delegate)
}
else -> {
if (rawFieldValue == null) {
delegate.didResolveNull()
} else {
delegate.didResolveScalar(rawFieldValue)
}
}
}
delegate.didResolve(fieldDescriptor.field, operationVariables)
}
}
private fun resolveObjectFields(fieldDescriptor: FieldDescriptor,
rawFieldValues: Map<String, Any>?, delegate: ResolveDelegate<Map<String, Any>?>) {
delegate.willResolveObject(fieldDescriptor.field, rawFieldValues)
val value = fieldDescriptor.value
if (value == null) {
delegate.didResolveNull()
} else {
resolveFields(operationVariables, delegate, value as Map<String, FieldDescriptor>)
}
delegate.didResolveObject(fieldDescriptor.field, rawFieldValues)
}
private fun resolveListField(listResponseField: ResponseField, fieldValues: List<*>?,
rawFieldValues: List<*>?, delegate: ResolveDelegate<Map<String, Any>?>) {
if (fieldValues == null) {
delegate.didResolveNull()
return
}
fieldValues.forEachIndexed { i, fieldValue ->
delegate.willResolveElement(i)
when (fieldValue) {
is Map<*, *> -> {
delegate.willResolveObject(listResponseField, rawFieldValues!![i] as Map<String, Any>?)
resolveFields(operationVariables, delegate, fieldValue as Map<String, FieldDescriptor>)
delegate.didResolveObject(listResponseField, rawFieldValues[i] as Map<String, Any>?)
}
is List<*> -> {
resolveListField(listResponseField, fieldValue, rawFieldValues!![i] as List<*>?, delegate)
}
else -> {
delegate.didResolveScalar(rawFieldValues!![i])
}
}
delegate.didResolveElement(i)
}
delegate.didResolveList(rawFieldValues!!)
}
private class ListItemWriter internal constructor(val operationVariables: Operation.Variables, val scalarTypeAdapters: ScalarTypeAdapters, val accumulator: MutableList<Any?>) : ResponseWriter.ListItemWriter {
override fun writeString(value: String?) {
accumulator.add(value)
}
override fun writeInt(value: Int?) {
accumulator.add(if (value != null) BigDecimal.valueOf(value.toLong()) else null)
}
override fun writeLong(value: Long?) {
accumulator.add(if (value != null) BigDecimal.valueOf(value) else null)
}
override fun writeDouble(value: Double?) {
accumulator.add(if (value != null) BigDecimal.valueOf(value) else null)
}
override fun writeBoolean(value: Boolean?) {
accumulator.add(value)
}
override fun writeCustom(scalarType: ScalarType, value: Any?) {
val typeAdapter = scalarTypeAdapters.adapterFor<Any>(scalarType)
accumulator.add(if (value != null) typeAdapter.encode(value).value else null)
}
override fun writeObject(marshaller: ResponseFieldMarshaller?) {
val nestedResponseWriter = RealResponseWriter(operationVariables, scalarTypeAdapters)
marshaller!!.marshal(nestedResponseWriter)
accumulator.add(nestedResponseWriter.buffer)
}
override fun <T> writeList(items: List<T>?, listWriter: ResponseWriter.ListWriter<T>) {
if (items == null) {
accumulator.add(null)
} else {
val nestedAccumulated = ArrayList<Any?>()
listWriter.write(items, ListItemWriter(operationVariables, scalarTypeAdapters, nestedAccumulated))
accumulator.add(nestedAccumulated)
}
}
}
class FieldDescriptor internal constructor(val field: ResponseField, val value: Any?)
companion object {
private fun checkFieldValue(field: ResponseField, value: Any?) {
if (!field.optional && value == null) {
throw NullPointerException(String.format("Mandatory response field `%s` resolved with null value",
field.responseName))
}
}
}
} | kotlin | 25 | 0.703071 | 210 | 38.10917 | 229 | starcoderdata |
package com.withgoogle.experiments.unplugged.data.integrations.tasks
import com.withgoogle.experiments.unplugged.model.TaskItem
object TasksDataSource {
val tasks = mutableMapOf<String, List<TaskItem>>()
val ordered: List<TaskItem>
get() = tasks.values.flatten()
} | kotlin | 12 | 0.759717 | 68 | 27.4 | 10 | starcoderdata |
<filename>samples/redux/rxredux/src/main/java/com/lyft/domic/samples/redux/rxredux/signin/SignInView.kt
package com.lyft.domic.samples.redux.rxredux.signin
import com.lyft.domic.samples.redux.rxredux.signin.SignInStateMachine.Action
import com.lyft.domic.samples.redux.rxredux.signin.SignInStateMachine.State
import io.reactivex.Observable
import io.reactivex.disposables.Disposable
interface SignInView {
val actions: Observable<Action>
fun render(signInState: Observable<State>): Disposable
}
| kotlin | 15 | 0.829703 | 103 | 41.083333 | 12 | starcoderdata |
<filename>android_mobile/src/main/java/com/alexstyl/specialdates/events/namedays/activity/AndroidNamedaysOnADayView.kt<gh_stars>100-1000
package com.alexstyl.specialdates.events.namedays.activity
class AndroidNamedaysOnADayView(private val screenAdapter: NamedaysScreenAdapter) : NamedaysOnADayView {
override fun displayNamedays(viewModels: List<NamedayScreenViewModel>) {
screenAdapter.display(viewModels)
}
}
| kotlin | 14 | 0.825175 | 136 | 52.625 | 8 | starcoderdata |
/*
* 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.resolve.checkers
import org.jetbrains.kotlin.descriptors.annotations.KotlinTarget
import org.jetbrains.kotlin.name.FqName
data class Experimentality(val annotationFqName: FqName, val severity: Severity, val message: String?) {
enum class Severity { WARNING, ERROR, FUTURE_ERROR }
companion object {
val DEFAULT_SEVERITY = Severity.ERROR
val WRONG_TARGETS_FOR_MARKER = setOf(
KotlinTarget.EXPRESSION,
KotlinTarget.FILE,
KotlinTarget.TYPE,
KotlinTarget.TYPE_PARAMETER
)
}
}
| kotlin | 12 | 0.710889 | 115 | 32.291667 | 24 | starcoderdata |
package com.oxyggen.c4k.old.engine
import com.oxyggen.c4k.target.HttpTarget
import kotlinx.coroutines.*
import org.junit.jupiter.api.Test
internal class CrawlerEngineTest {
@Test
fun execute() = runBlocking {
println("Test coroutine scope ${this}")
val ce = CrawlerEngine(
CrawlerEngine.Config(
politenessDelay = 2000,
maxDepth = 2
)
)
//ce.addTarget(HttpTarget("https://www.wikipedia.org/"))
ce.addTarget(HttpTarget("https://google.com/"))
ce.execute(this)
println("out!")
}
} | kotlin | 19 | 0.597039 | 64 | 21.555556 | 27 | starcoderdata |
<gh_stars>0
package yet.ui.widget
import android.content.Context
import android.graphics.drawable.Drawable
import android.text.Editable
import android.text.TextWatcher
import android.view.MotionEvent
import android.view.View
import android.widget.EditText
import yet.ui.ext.dp
import yet.ui.ext.genId
import yet.ui.ext.hideInputMethod
import yet.ui.ext.padding
import yet.ui.res.D
import yet.util.fore
class EditTextX(context: Context) : EditText(context) {
private var x: Drawable = D.EditClear
init {
genId()
padding(5, 2, 5, 2)
this.setOnTouchListener(View.OnTouchListener { v, event ->
if (this@EditTextX.compoundDrawables[2] == null) {
return@OnTouchListener false
}
if (event.action != MotionEvent.ACTION_UP) {
return@OnTouchListener false
}
if (event.x > this@EditTextX.width - this@EditTextX.paddingRight
- IMAGE_WIDTH - dp(15)) {
this@EditTextX.setText("")
this@EditTextX.setCompoundDrawables(null, null, null, null)
fore {
this@EditTextX.hideInputMethod()
}
}
false
})
this.addTextChangedListener(object : TextWatcher {
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
this@EditTextX.setCompoundDrawables(null, null, if (this@EditTextX.text.toString() == "")
null
else
x, null)
}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
}
override fun afterTextChanged(s: Editable) {
}
})
}
override fun performClick(): Boolean {
return super.performClick()
}
companion object {
val IMAGE_WIDTH = 25
}
}
| kotlin | 25 | 0.710181 | 93 | 22.895522 | 67 | starcoderdata |
package com.ruskaof.weatherapp.presentation.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import com.ruskaof.weatherapp.presentation.theme.AppTheme.LocalAppColors
import com.ruskaof.weatherapp.presentation.theme.AppTheme.LocalAppShapes
import com.ruskaof.weatherapp.presentation.theme.AppTheme.LocalAppTypography
@Composable
fun MainTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
content: @Composable () -> Unit
) {
val colors = when (darkTheme) {
true -> darkColorPallet
false -> lightColorPallet
}
val typography = when (darkTheme) {
true -> darkTextTypography
false -> lightTextTypography
}
val shapes = defaultShapes
CompositionLocalProvider(
LocalAppColors provides colors,
LocalAppTypography provides typography,
LocalAppShapes provides shapes,
content = content
)
} | kotlin | 9 | 0.75 | 76 | 29.212121 | 33 | starcoderdata |
<reponame>shilpasayura/kotlin<gh_stars>0
// referential equation
class Point {
var pointX : Int = 0
var pointY : Int = 0
}
fun main(a : Array <String>) {
val p1 = Point()
p1.pointX = 10
p1.pointY = 20
val p2 = Point()
p2.pointX = 30
p2.pointY = 40
println(p1 === p2) // false
println(p1 !== p2) // true
var p3 = p1
println(p1 === p3) // true
}
| kotlin | 9 | 0.562341 | 40 | 19.684211 | 19 | starcoderdata |
<gh_stars>0
package co.railgun.common.activity
import android.util.Log
import android.widget.Toast
import co.railgun.common.BuildConfig
import com.trello.rxlifecycle2.android.ActivityEvent
import io.reactivex.Observable
import io.reactivex.Scheduler
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
import retrofit2.HttpException
import java.util.*
/**
* Created by roya on 2017/5/21.
*/
open class BaseActivity : co.railgun.common.activity.RxLifecycleActivity() {
private val runningMap by lazy { IdentityHashMap<String, Disposable>() }
fun showToast(s: String, t: Int = Toast.LENGTH_LONG) {
Toast.makeText(this, s, t).show()
}
protected fun <T> Observable<T>.withLifecycle(
subscribeOn: Scheduler = Schedulers.io(),
observeOn: Scheduler = AndroidSchedulers.mainThread(),
untilEvent: ActivityEvent = ActivityEvent.DESTROY
): Observable<T> = subscribeOn(subscribeOn)
.observeOn(observeOn)
.compose(bindUntilEvent(untilEvent))
protected fun <T> Observable<T>.onlyRunOneInstance(
taskId: String,
displace: Boolean = true
): Observable<T> {
if (runningMap.containsKey(taskId)) {
if (!displace) {
return Observable.create { wrapper -> wrapper.onComplete() }
} else {
runningMap[taskId]?.dispose()
runningMap.remove(taskId)
}
}
return Observable.create { wrapper ->
val obs = subscribe(
{ wrapper.onNext(it!!) },
{
runningMap.remove(taskId)
wrapper.onError(it)
},
{
runningMap.remove(taskId)
wrapper.onComplete()
}
)
if (!obs.isDisposed) {
runningMap[taskId] = obs
}
}
}
protected fun ignoreErrors(): Consumer<in Throwable> {
return Consumer {
if (BuildConfig.DEBUG) Log.w("toastErrors", it)
}
}
protected fun toastErrors(): Consumer<in Throwable> {
return Consumer {
if (BuildConfig.DEBUG) Log.w("toastErrors", it)
var errorMessage = getString(co.railgun.common.R.string.unknown_error)
if (it is HttpException) {
val body = it.response()?.errorBody()
val message = body?.let { it1 ->
co.railgun.common.api.ApiClient.converterErrorBody(it1)
}
if (message?.message() != null) {
errorMessage = message.message().toString()
}
}
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show()
}
}
protected fun toastErrors(e: Throwable) {
if (BuildConfig.DEBUG) Log.w("toastErrors", e)
var errorMessage = getString(co.railgun.common.R.string.unknown_error)
if (e is HttpException) {
val body = e.response()?.errorBody()
val message = body?.let { it1 ->
co.railgun.common.api.ApiClient.converterErrorBody(it1)
}
if (message?.message() != null) {
errorMessage = message.message().toString()
}
}
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show()
}
}
| kotlin | 33 | 0.580866 | 82 | 30.927273 | 110 | starcoderdata |
#!/usr/bin/env kotlin
@file:Import("strings.main.kts")
println(2.toBigInteger().pow(1000).toString().sumOfDigits())
| kotlin | 14 | 0.720339 | 60 | 22.6 | 5 | starcoderdata |
<reponame>linked-planet/ui-kit<filename>ui-kit-lib/src/main/kotlin/com/linkedplanet/uikit/wrapper/atlaskit/toggle/Imports.kt
/**
* Copyright 2022 linked-planet GmbH.
*
* 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.
*/
@file:JsModule("@atlaskit/toggle")
package com.linkedplanet.uikit.wrapper.atlaskit.toggle
import org.w3c.dom.events.Event
import react.ComponentClass
import react.Props
@JsName("default")
external val Toggle: ComponentClass<ToggleProps>
external interface ToggleProps : Props {
/**
* Use a pairing label with your toggle using id and htmlFor props to set the relationship. For more information see
* labels on MDN web docs.
*/
var id: String
/**
* Toggle size. One of:
* - "regular",
* - "large"
*/
var size: String
/**
* Handler to be called when native 'change' event happens internally.
*/
var onChange: (Event) -> Unit
/**
* If the toggle is disabled or not. This prevents any interaction.
*/
var isDisabled: Boolean
/**
* Whether the toggle is initially checked or not After initial mount whether the component is checked or not is
* controlled by the component.
*/
var defaultChecked: Boolean
/**
* If defined it takes precedence over defaultChecked and Toggle acts.
*/
var isChecked: Boolean
/**
* Descriptive name for value property to be submitted in a form.
*/
var name: String
/**
* Text to be used as aria-label of toggle component. Use when there is not visible label that you can pair toggle
* with.
*/
var label: String
} | kotlin | 13 | 0.686074 | 124 | 27.64 | 75 | starcoderdata |
package be.hogent.faith.database.event
import be.hogent.faith.database.common.EncryptedDetailEntity
import be.hogent.faith.service.encryption.EncryptedString
import java.util.UUID
data class EncryptedEventEntity(
val dateTime: String = "",
val title: String = "",
var emotionAvatar: String? = null,
var emotionAvatarThumbnail: String? = null,
val notes: String? = null,
val uuid: String = UUID.randomUUID().toString(),
val details: List<EncryptedDetailEntity> = emptyList(),
val encryptedDEK: EncryptedString = "",
val encryptedStreamingDEK: EncryptedString = ""
)
| kotlin | 9 | 0.73466 | 60 | 34.470588 | 17 | starcoderdata |
<gh_stars>0
package com.casualapps.mynotes.viewmodels
import androidx.hilt.lifecycle.ViewModelInject
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.casualapps.mynotes.data.entities.User
import com.casualapps.mynotes.data.repo.auth.AuthStateRepository
import com.casualapps.mynotes.data.repo.user.UserRepository
import kotlinx.coroutines.launch
class LoginViewModel @ViewModelInject constructor(private val userRepo: UserRepository, private val authStateRepository: AuthStateRepository) : ViewModel() {
private val _loginResultLiveData = MutableLiveData<Long>()
private val _userNameErrorLiveData = MutableLiveData<String?>()
private val _passwordErrorLiveData = MutableLiveData<String?>()
val userNameErrorLiveData: LiveData<String?>
get() = _userNameErrorLiveData
val passwordErrorLiveData: LiveData<String?>
get() = _passwordErrorLiveData
val loginResultLiveData: LiveData<Long>
get() = _loginResultLiveData
fun login(username: String, password: String) = viewModelScope.launch {
_userNameErrorLiveData.postValue(null)
_passwordErrorLiveData.postValue(null)
if (username.isEmpty()) {
_userNameErrorLiveData.postValue("Username cannot be empty!")
return@launch
}
if (password.isEmpty()) {
_passwordErrorLiveData.postValue("Password cannot be empty!")
return@launch
}
val user = User(username, password)
val loggedInUserId = userRepo.isValidUser(user = user)
if (loggedInUserId != -1L) {
authStateRepository.login(loggedInUserId)
}
_loginResultLiveData.postValue(loggedInUserId)
}
}
| kotlin | 17 | 0.730281 | 157 | 36.770833 | 48 | starcoderdata |
package halter.interview.herdservice.domain.cows
import java.util.*
data class Cow(val command: CreateCowCommand) {
var id: String = UUID.randomUUID().toString();
var collarId = command.collarId
var cowNumber = command.cowNumber
var createdAtUtc = Date()
var updatedAtUtc: Date? = null
}
| kotlin | 9 | 0.722581 | 50 | 27.181818 | 11 | starcoderdata |
package space.mephi.services.auth.presentation
import io.ktor.application.*
import io.ktor.routing.*
import space.mephi.services.auth.presentation.routes.*
fun Application.configureRouting() {
routing {
signIn()
signUp()
}
} | kotlin | 12 | 0.712 | 54 | 19.916667 | 12 | starcoderdata |
import kotlinx.browser.document
import org.w3c.dom.events.KeyboardEvent
import org.w3c.dom.svg.SVGElement
class TrellisOutput(svgElementId: String = "trellis") {
private val svgElement: SVGElement
init {
val element = document.getElementById(svgElementId)
svgElement = if("svg" == element?.tagName) {
element as SVGElement
}
else {
val createdElement = document.createElementNS(SVG_NAMESPACE_URI, "svg")
createdElement.id = svgElementId
createdElement.setAttribute("width", "600")
createdElement.setAttribute("height", "800")
document.body?.appendChild(createdElement)
createdElement as SVGElement
}
}
fun setup() {
// val snap = Snap(600, 800)
val snap = Snap(svgElement)
val line = snap.line(10, 10, 100, 10)
line.attr("stroke", "red")
line.attr("stroke-dasharray", "3")
val topRect = snap.rect(0, 0, 40, 40)
val text = snap.text(20, 20, "Test")
document.addEventListener("keyDown", {event ->
val keyboardEvent = event as KeyboardEvent
when(keyboardEvent.code) {
"ArrowDown" -> {
val bottomLine = snap.line(10, 100, 100, 100)
}
}
})
}
companion object {
const val SVG_NAMESPACE_URI = "http://www.w3.org/2000/svg"
}
} | kotlin | 21 | 0.560432 | 83 | 16.642857 | 84 | starcoderdata |
package com.gssirohi.materialforms
import android.content.Context
import android.util.Log
import android.view.View
import android.widget.FrameLayout
import android.widget.LinearLayout
import kotlinx.android.synthetic.main.field_view_frame.view.*
abstract class FieldView(val item:FormItem, ctx: Context): LinearLayout(ctx) {
init {
Log.d("FieldView","init");
}
fun initView(){
var view = View.inflate(context,R.layout.field_view_frame,null)
if(item.field.isMandatory)
view.field_label.text = item.field.label
item.iconRes?.let{
view.image_field.visibility = View.VISIBLE
view.image_field.setImageResource(item.iconRes)
}
var fieldView = provideFieldView()
view.findViewById<FrameLayout>(R.id.frame_field).addView(fieldView)
addView(view)
}
abstract fun provideFieldView(): View
} | kotlin | 17 | 0.694444 | 78 | 29.033333 | 30 | starcoderdata |
package io.sabag.androidConferences.storage
import androidx.lifecycle.LiveData
import androidx.room.*
import java.util.*
@Entity(tableName = "conferences")
data class RoomConference(@PrimaryKey val id: String)
@Dao
interface ConferencesDao{
@Insert(onConflict = OnConflictStrategy.IGNORE)
fun addConferences(conferencesList: List<RoomConference>)
@Delete
fun removeConferences(conferencesList: List<RoomConference>)
@Query("SELECT * FROM conferences")
fun getConferences(): List<RoomConference>
}
@Entity(tableName = "conference_details")
data class RoomConferenceDetails(
@PrimaryKey val id: String,
@ColumnInfo(name = "name") val name: String,
@ColumnInfo(name = "location") val location: String,
@ColumnInfo(name = "start_date")val startDate: Date,
@ColumnInfo(name = "end_date") val endDate: Date?,
@ColumnInfo(name = "cfp_start") val cfpStart: Date?,
@ColumnInfo(name = "cfp_end") val cfpEnd: Date?
)
@Dao
interface ConferenceDetailsDao{
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun addConferenceDetails(conferenceDetails: RoomConferenceDetails)
@Query("SELECT * FROM conference_details")
fun getConferenceDetails(): List<RoomConferenceDetails>
}
object TimeConverters {
@TypeConverter
@JvmStatic
fun fromTimestamp(value: Long?) = value?.let{ Date(value) }
@TypeConverter
@JvmStatic
fun dateToTimestamp(date: Date?) = date?.let{date.time}
}
@Database(entities = [RoomConference::class, RoomConferenceDetails::class],
version = 1, exportSchema = false)
@TypeConverters(TimeConverters::class)
abstract class ConferencesDatabase : RoomDatabase() {
abstract fun conferencesDao(): ConferencesDao
abstract fun conferenceDetailsDao(): ConferenceDetailsDao
} | kotlin | 15 | 0.728729 | 75 | 30.224138 | 58 | starcoderdata |
<gh_stars>0
package com.microsoft.fluentui.button
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.interaction.InteractionSource
import androidx.compose.foundation.interaction.collectIsFocusedAsState
import androidx.compose.foundation.interaction.collectIsHoveredAsState
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.graphics.Color
import com.microsoft.fluentui.theme.token.ControlInfo
import com.microsoft.fluentui.theme.token.ControlToken
import com.microsoft.fluentui.theme.token.StateBorderStroke
import com.microsoft.fluentui.theme.token.StateColor
import com.microsoft.fluentui.theme.token.controlTokens.ButtonInfo
import com.microsoft.fluentui.theme.token.controlTokens.ButtonTokens
import com.microsoft.fluentui.theme.token.controlTokens.FABInfo
import com.microsoft.fluentui.theme.token.controlTokens.FABTokens
import java.security.InvalidParameterException
@Composable
fun getColorByState(
stateData: StateColor,
enabled: Boolean,
interactionSource: InteractionSource
): Color {
if (enabled) {
val isPressed by interactionSource.collectIsPressedAsState()
if (isPressed)
return stateData.pressed
val isFocused by interactionSource.collectIsFocusedAsState()
if (isFocused)
return stateData.focused
val isHovered by interactionSource.collectIsHoveredAsState()
if (isHovered)
return stateData.focused
return stateData.rest
} else
return stateData.disabled
}
@Composable
fun backgroundColor(
tokens: ControlToken,
info: ControlInfo,
enabled: Boolean,
interactionSource: InteractionSource
): Color {
val backgroundColors: StateColor =
when (tokens) {
is ButtonTokens -> tokens.backgroundColor(info as ButtonInfo)
is FABTokens -> tokens.backgroundColor(info as FABInfo)
else -> throw InvalidParameterException()
}
return getColorByState(backgroundColors, enabled, interactionSource)
}
@Composable
fun iconColor(
tokens: ControlToken,
info: ControlInfo,
enabled: Boolean,
interactionSource: InteractionSource
): Color {
val iconColors: StateColor =
when (tokens) {
is ButtonTokens -> tokens.iconColor(info as ButtonInfo)
is FABTokens -> tokens.iconColor(info as FABInfo)
else -> throw InvalidParameterException()
}
return getColorByState(iconColors, enabled, interactionSource)
}
@Composable
fun textColor(
tokens: ControlToken,
info: ControlInfo,
enabled: Boolean,
interactionSource: InteractionSource
): Color {
val textColors: StateColor =
when (tokens) {
is ButtonTokens -> tokens.textColor(info as ButtonInfo)
is FABTokens -> tokens.textColor(info as FABInfo)
else -> throw InvalidParameterException()
}
return getColorByState(textColors, enabled, interactionSource)
}
@Composable
fun borderStroke(
tokens: ControlToken,
info: ControlInfo,
enabled: Boolean,
interactionSource: InteractionSource
): List<BorderStroke> {
val fetchBorderStroke: StateBorderStroke =
when (tokens) {
is ButtonTokens -> tokens.borderStroke(info as ButtonInfo)
is FABTokens -> tokens.borderStroke(info as FABInfo)
else -> throw InvalidParameterException()
}
if (enabled) {
val isPressed by interactionSource.collectIsPressedAsState()
if (isPressed)
return fetchBorderStroke.pressed
val isFocused by interactionSource.collectIsFocusedAsState()
if (isFocused)
return fetchBorderStroke.focused
val isHovered by interactionSource.collectIsHoveredAsState()
if (isHovered)
return fetchBorderStroke.focused
return fetchBorderStroke.rest
} else
return fetchBorderStroke.disabled
}
| kotlin | 14 | 0.699479 | 77 | 32.275591 | 127 | starcoderdata |