path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
component-acgcomic/src/main/java/com/rabtman/acgcomic/mvp/ui/activity/QiMiaoComicReadActivity.kt
|
Rabtman
| 129,618,096
| false
| null |
package com.rabtman.acgcomic.mvp.ui.activity
import android.view.View
import android.view.animation.Animation
import android.view.animation.TranslateAnimation
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.SeekBar
import android.widget.TextView
import androidx.appcompat.widget.AppCompatSeekBar
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import butterknife.BindView
import butterknife.OnClick
import com.alibaba.android.arouter.facade.annotation.Route
import com.rabtman.acgcomic.R
import com.rabtman.acgcomic.R2
import com.rabtman.acgcomic.base.constant.IntentConstant
import com.rabtman.acgcomic.di.DaggerQiMiaoComicEpisodeDetailComponent
import com.rabtman.acgcomic.di.QiMiaoComicEpisodeDetailModule
import com.rabtman.acgcomic.mvp.QiMIaoComicChapterDetailContract
import com.rabtman.acgcomic.mvp.model.entity.jsoup.QiMiaoComicChapterDetail
import com.rabtman.acgcomic.mvp.presenter.QiMiaoComicReadPresenter
import com.rabtman.acgcomic.mvp.ui.adapter.QiMiaoComicReadAdapter
import com.rabtman.common.base.BaseActivity
import com.rabtman.common.di.component.AppComponent
import com.rabtman.router.RouterConstants
/**
* @author Rabtman
*/
@Route(path = RouterConstants.PATH_COMIC_QIMIAO_READ)
class QiMiaoComicReadActivity : BaseActivity<QiMiaoComicReadPresenter>(), QiMIaoComicChapterDetailContract.View {
//漫画阅读控制栏
@BindView(R2.id.layout_comic_top)
lateinit var layoutComicTop: RelativeLayout
@BindView(R2.id.btn_comic_back)
lateinit var btnComicBack: ImageView
@BindView(R2.id.tv_comic_title)
lateinit var tvComicTitle: TextView
@BindView(R2.id.layout_comic_bottom)
lateinit var layoutComicBottom: RelativeLayout
@BindView(R2.id.btn_comic_before)
lateinit var btnComicBefore: ImageView
@BindView(R2.id.btn_comic_next)
lateinit var btnComicNext: ImageView
@BindView(R2.id.seekbar_comic_proc)
lateinit var seekComicProc: AppCompatSeekBar
@BindView(R2.id.tv_comic_count)
lateinit var tvComicCount: TextView
@BindView(R2.id.tv_comic_pos)
lateinit var tvComicPos: TextView
@BindView(R2.id.tv_comic_pos_tip)
lateinit var tvComicPosTip: TextView
/**
* 控制栏的显示状态
*/
private var mVisible: Boolean = false
/**
* 动画时间
*/
private val UI_ANIMATION_DELAY = 200
//漫画内容
@BindView(R2.id.rcv_qimiao_comic_content)
lateinit var rcvComicContent: RecyclerView
lateinit var layoutManager: LinearLayoutManager
private lateinit var qiMiaoComicReadAdapter: QiMiaoComicReadAdapter
//当前漫画名称
private var curComicTitle = ""
//当前漫画页面下标
private var curPagePos = 0
//当前漫画总页数
private var maxPage = 0
override fun setupActivityComponent(appComponent: AppComponent) {
DaggerQiMiaoComicEpisodeDetailComponent.builder()
.appComponent(appComponent)
.qiMiaoComicEpisodeDetailModule(QiMiaoComicEpisodeDetailModule(this))
.build()
.inject(this)
}
override fun getLayoutId(): Int {
return R.layout.acgcomic_activity_qimiao_comic_content
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (hasFocus) {
val decorView = window.decorView
//沉浸
decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_FULLSCREEN
or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY)
}
}
override fun setStatusBar() {}
override fun onPause() {
super.onPause()
rcvComicContent.stopScroll() //防止销毁时再回调滑动事件造成的异常
}
override fun initData() {
curComicTitle = intent.getStringExtra(IntentConstant.QIMIAO_COMIC_TITLE)
qiMiaoComicReadAdapter = QiMiaoComicReadAdapter()
qiMiaoComicReadAdapter.setOnItemClickListener { _, _, _ ->
toogleDisplayPanel()
}
layoutManager = LinearLayoutManager(this)
rcvComicContent.layoutManager = layoutManager
rcvComicContent.adapter = qiMiaoComicReadAdapter
rcvComicContent.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
val pos = layoutManager.findFirstVisibleItemPosition()
if (maxPage > 0 && maxPage == layoutManager.findLastCompletelyVisibleItemPosition() + 1) {
curPagePos = maxPage - 1
seekComicProc?.let { it ->
it.progress = maxPage - 1
}
tvComicPos?.let { it ->
it.text = maxPage.toString()
}
} else if (curPagePos != pos) {
curPagePos = pos
seekComicProc?.let { it ->
it.progress = pos
}
tvComicPos?.let { it ->
it.text = (pos + 1).toString()
}
}
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
mPresenter.updateScheduleReadRecord(curPagePos)
}
}
})
seekComicProc.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onStartTrackingTouch(p0: SeekBar?) {
//先停止滑动
rcvComicContent.stopScroll()
tvComicPosTip.visibility = View.VISIBLE
tvComicPosTip.text = (curPagePos + 1).toString()
}
override fun onStopTrackingTouch(p0: SeekBar?) {
rcvComicContent.scrollToPosition(curPagePos)
mPresenter.updateScheduleReadRecord(curPagePos)
tvComicPosTip.visibility = View.GONE
}
override fun onProgressChanged(seekbar: SeekBar?, progress: Int, fromUser: Boolean) {
if (fromUser) {
curPagePos = progress
val displayPos = (progress + 1).toString()
tvComicPosTip.text = displayPos
tvComicPos.text = displayPos
}
}
})
mPresenter.setIntentData(intent.getStringExtra(IntentConstant.QIMIAO_COMIC_ID),
intent.getStringExtra(IntentConstant.QIMIAO_COMIC_CHAPTER_ID))
mPresenter.getEpisodeDetailAndCache()
}
@OnClick(R2.id.btn_comic_back)
fun onBack() {
finish()
}
@OnClick(R2.id.btn_comic_before)
fun preComicEpisode() {
rcvComicContent.stopScroll()
mPresenter.getPreChapterDetail()
}
@OnClick(R2.id.btn_comic_next)
fun nextComicEpisode() {
rcvComicContent.stopScroll()
mPresenter.getNextChapterDetail()
}
override fun showChapterDetail(chapterDetail: QiMiaoComicChapterDetail, lastPagePos: Int) {
layoutComicBottom.visibility = View.VISIBLE
//是否存在上一话
if (chapterDetail.preChapterId != "-1") {
btnComicBefore.visibility = View.VISIBLE
} else {
btnComicBefore.visibility = View.INVISIBLE
}
//是否存在下一话
if (chapterDetail.nextChapterId != "-1") {
btnComicNext.visibility = View.VISIBLE
} else {
btnComicNext.visibility = View.INVISIBLE
}
tvComicTitle.text = chapterDetail.title
qiMiaoComicReadAdapter.setList(chapterDetail.listImg)
if (chapterDetail.listImg.isEmpty()) {
maxPage = 0
} else {
maxPage = chapterDetail.listImg.size
//每次刷新重置控件
rcvComicContent.scrollToPosition(lastPagePos)
seekComicProc.progress = lastPagePos
seekComicProc.max = maxPage - 1
tvComicPos.text = (lastPagePos + 1).toString()
}
tvComicCount.text = maxPage.toString()
}
/**
* 触发上下栏的显示与隐藏
*/
internal fun toogleDisplayPanel() {
if (mVisible) {
hidePanel()
mVisible = false
} else {
showPanel()
mVisible = true
}
}
/**
* 展示上下栏
*/
internal fun showPanel() {
val translateAnimation = TranslateAnimation(
Animation.RELATIVE_TO_SELF, 0.0f,
Animation.RELATIVE_TO_SELF, 0.0f,
Animation.RELATIVE_TO_SELF, 1.0f,
Animation.RELATIVE_TO_SELF, 0.0f)
val translateAnimation1 = TranslateAnimation(
Animation.RELATIVE_TO_SELF, 0.0f,
Animation.RELATIVE_TO_SELF, 0.0f,
Animation.RELATIVE_TO_SELF, -1.0f,
Animation.RELATIVE_TO_SELF, 0.0f)
translateAnimation.duration = UI_ANIMATION_DELAY.toLong()
translateAnimation1.duration = UI_ANIMATION_DELAY.toLong()
layoutComicTop.animation = translateAnimation1
layoutComicBottom.animation = translateAnimation
layoutComicTop.visibility = View.VISIBLE//这里通过改变可见性来播放动画
layoutComicBottom.visibility = View.VISIBLE//这里通过改变可见性来播放动画
}
/**
* 隐藏上下栏
*/
internal fun hidePanel() {
val translateAnimation = TranslateAnimation(
Animation.RELATIVE_TO_SELF, 0.0f,
Animation.RELATIVE_TO_SELF, 0.0f,
Animation.RELATIVE_TO_SELF, 0.0f,
Animation.RELATIVE_TO_SELF, -1.0f)
val translateAnimation1 = TranslateAnimation(
Animation.RELATIVE_TO_SELF, 0.0f,
Animation.RELATIVE_TO_SELF, 0.0f,
Animation.RELATIVE_TO_SELF, 0.0f,
Animation.RELATIVE_TO_SELF, 1.0f)
translateAnimation.duration = UI_ANIMATION_DELAY.toLong()
translateAnimation1.duration = UI_ANIMATION_DELAY.toLong()
layoutComicTop.animation = translateAnimation
layoutComicBottom.animation = translateAnimation1
layoutComicTop.visibility = View.INVISIBLE//这里通过改变可见性来播放动画
layoutComicBottom.visibility = View.INVISIBLE//这里通过改变可见性来播放动画
}
}
| 2
| null |
120
| 840
|
9150f3abe50e046afd83cc97cb4415a39b1f1bd1
| 10,412
|
AcgClub
|
Apache License 2.0
|
kotlin-mui-icons/src/main/generated/mui/icons/material/NightShelter.kt
|
JetBrains
| 93,250,841
| false
| null |
// Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/NightShelter")
package mui.icons.material
@JsName("default")
external val NightShelter: SvgIconComponent
| 12
| null |
5
| 983
|
a99345a0160a80a7a90bf1adfbfdc83a31a18dd6
| 188
|
kotlin-wrappers
|
Apache License 2.0
|
app/src/main/java/com/kasuminotes/ui/app/clanBattle/ClanBattle.kt
|
chilbi
| 399,723,451
| false
|
{"Kotlin": 827770}
|
package com.kasuminotes.ui.app.clanBattle
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Security
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.kasuminotes.R
import com.kasuminotes.data.ClanBattlePeriod
import com.kasuminotes.ui.components.BottomBar
import com.kasuminotes.ui.app.state.ClanBattleState
import com.kasuminotes.ui.components.TopBar
@Composable
fun ClanBattle(
clanBattleState: ClanBattleState,
onNavigateToMapList: (label: String, period: ClanBattlePeriod) -> Unit,
onNavigateTo: (Int) -> Unit,
onDrawerOpen: () -> Unit
) {
// val snackbarHostState = remember { SnackbarHostState() }
// val scope = rememberCoroutineScope()
// val message = stringResource(R.string.functionality_not_implemented)
// val onClick: () -> Unit = {
// scope.launch {
// snackbarHostState.showSnackbar(message)
// }
// }
Scaffold(
topBar = { ClanBattleTopBar() },
bottomBar = { BottomBar(2, onNavigateTo, onDrawerOpen) },
// snackbarHost = { SnackbarHost(snackbarHostState) },
// floatingActionButton = {
// FloatingActionButton(onClick) {
// Icon(Icons.Filled.Dashboard, null)
// }
// },
containerColor = MaterialTheme.colorScheme.surface,
content = { contentPadding ->
Box(Modifier.padding(contentPadding)) {
ClanBattlePeriodList(clanBattleState.clanBattlePeriodList, onNavigateToMapList)
}
}
)
}
@Composable
private fun ClanBattleTopBar() {
TopBar(
title = {
Text(stringResource(R.string.clan_battle))
},
navigationIcon = {
Box(
modifier = Modifier.size(48.dp),
contentAlignment = Alignment.Center
) {
Icon(Icons.Filled.Security, null)
}
}
)
}
| 0
|
Kotlin
|
0
| 0
|
7ce458181f7f8b71ce7836cbe9488c28d92e0e9e
| 2,397
|
KasumiNotes
|
Apache License 2.0
|
bot/storage-mongo/src/main/kotlin/StoryDefinitionConfigurationMongoDAO.kt
|
theopenconversationkit
| 84,538,053
| false
| null |
/*
* Copyright (C) 2017/2021 e-voyageurs technologies
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ai.tock.bot.mongo
import ai.tock.bot.admin.answer.AnswerConfigurationType
import ai.tock.bot.admin.answer.AnswerConfigurationType.builtin
import ai.tock.bot.admin.story.StoryDefinitionConfiguration
import ai.tock.bot.admin.story.StoryDefinitionConfigurationDAO
import ai.tock.bot.admin.story.StoryDefinitionConfigurationSummary
import ai.tock.bot.admin.story.StoryDefinitionConfigurationSummaryRequest
import ai.tock.bot.admin.story.StoryDefinitionConfiguration_.Companion.BotId
import ai.tock.bot.admin.story.StoryDefinitionConfiguration_.Companion.Category
import ai.tock.bot.admin.story.StoryDefinitionConfiguration_.Companion.CurrentType
import ai.tock.bot.admin.story.StoryDefinitionConfiguration_.Companion.Intent
import ai.tock.bot.admin.story.StoryDefinitionConfiguration_.Companion.Name
import ai.tock.bot.admin.story.StoryDefinitionConfiguration_.Companion.Namespace
import ai.tock.bot.admin.story.StoryDefinitionConfiguration_.Companion.StoryId
import ai.tock.bot.admin.story.StoryDefinitionConfiguration_.Companion.Tags
import ai.tock.bot.definition.StoryTag
import ai.tock.bot.mongo.MongoBotConfiguration.asyncDatabase
import ai.tock.bot.mongo.MongoBotConfiguration.database
import ai.tock.bot.mongo.StoryDefinitionConfigurationHistoryCol_.Companion.Date
import ai.tock.shared.defaultLocale
import ai.tock.shared.ensureIndex
import ai.tock.shared.ensureUniqueIndex
import ai.tock.shared.error
import ai.tock.shared.safeCollation
import ai.tock.shared.trace
import ai.tock.shared.warn
import ai.tock.shared.watch
import com.mongodb.client.model.Collation
import mu.KotlinLogging
import org.litote.jackson.data.JacksonData
import org.litote.kmongo.Data
import org.litote.kmongo.Id
import org.litote.kmongo.and
import org.litote.kmongo.ascending
import org.litote.kmongo.contains
import org.litote.kmongo.deleteOneById
import org.litote.kmongo.eq
import org.litote.kmongo.find
import org.litote.kmongo.findOne
import org.litote.kmongo.findOneById
import org.litote.kmongo.getCollection
import org.litote.kmongo.getCollectionOfName
import org.litote.kmongo.ne
import org.litote.kmongo.or
import org.litote.kmongo.projection
import org.litote.kmongo.reactivestreams.getCollectionOfName
import org.litote.kmongo.regex
import org.litote.kmongo.save
import org.litote.kmongo.withDocumentClass
import java.time.Instant
/**
*
*/
internal object StoryDefinitionConfigurationMongoDAO : StoryDefinitionConfigurationDAO {
private val logger = KotlinLogging.logger {}
@Data(internal = true)
@JacksonData(internal = true)
data class StoryDefinitionConfigurationHistoryCol(
val conf: StoryDefinitionConfiguration,
val deleted: Boolean = false,
val date: Instant = Instant.now()
)
private val col = database.getCollectionOfName<StoryDefinitionConfiguration>("story_configuration")
private val asyncCol = asyncDatabase.getCollectionOfName<StoryDefinitionConfiguration>("story_configuration")
private val historyCol =
database.getCollection<StoryDefinitionConfigurationHistoryCol>("story_configuration_history")
init {
try {
col.ensureIndex(Namespace, BotId)
col.ensureIndex(Namespace, BotId, Intent.name_)
col.ensureUniqueIndex(Namespace, BotId, Intent.name_)
historyCol.ensureIndex(Date)
} catch (e: Exception) {
logger.warn(e)
//there is a misleading data state when creating index
logger.warn("try to remove builtin stories and set the index")
try {
col.deleteMany(CurrentType eq builtin)
col.ensureUniqueIndex(Namespace, BotId, Intent.name_)
} catch (e: Exception) {
logger.error(e)
}
}
}
override fun listenChanges(listener: () -> Unit) {
asyncCol.watch { listener() }
}
override fun getStoryDefinitionById(id: Id<StoryDefinitionConfiguration>): StoryDefinitionConfiguration? {
return col.findOneById(id)
}
override fun getRuntimeStorySettings(namespace: String, botId: String): List<StoryDefinitionConfiguration> {
return col.find(
and(
Namespace eq namespace,
BotId eq botId,
or(StoryTag.values().map { Tags contains it })
)
).toList()
}
override fun getConfiguredStoryDefinitionByNamespaceAndBotIdAndIntent(
namespace: String,
botId: String,
intent: String
): StoryDefinitionConfiguration? {
return col.findOne(
Namespace eq namespace,
BotId eq botId,
CurrentType ne AnswerConfigurationType.builtin,
Intent.name_ eq intent
)
}
override fun getStoryDefinitionByNamespaceAndBotIdAndIntent(
namespace: String,
botId: String,
intent: String
): StoryDefinitionConfiguration? {
return col.findOne(Namespace eq namespace, BotId eq botId, Intent.name_ eq intent)
}
override fun getStoryDefinitionByNamespaceAndBotIdAndStoryId(
namespace: String,
botId: String,
storyId: String
): StoryDefinitionConfiguration? {
return col.findOne(Namespace eq namespace, BotId eq botId, StoryId eq storyId)
}
override fun getStoryDefinitionsByNamespaceAndBotId(
namespace: String,
botId: String
): List<StoryDefinitionConfiguration> {
return col.find(and(Namespace eq namespace, BotId eq botId)).toList()
}
override fun getStoryDefinitionsByNamespaceBotIdStoryId(
namespace: String,
botId: String,
storyId: String
): StoryDefinitionConfiguration? {
return col.findOne(and(Namespace eq namespace, BotId eq botId, StoryId eq storyId))
}
override fun searchStoryDefinitionSummaries(request: StoryDefinitionConfigurationSummaryRequest): List<StoryDefinitionConfigurationSummary> =
col.withDocumentClass<StoryDefinitionConfigurationSummary>()
.find(
Namespace eq request.namespace,
BotId eq request.botId,
if (request.category.isNullOrBlank()) null else Category eq request.category,
request.textSearch?.takeUnless { it.isBlank() }?.let { Name.regex(it.trim(), "i") },
if (request.onlyConfiguredStory) CurrentType ne AnswerConfigurationType.builtin else null
)
.projection(
StoryDefinitionConfigurationSummary::_id,
StoryDefinitionConfigurationSummary::storyId,
StoryDefinitionConfigurationSummary::botId,
StoryDefinitionConfigurationSummary::intent,
StoryDefinitionConfigurationSummary::currentType,
StoryDefinitionConfigurationSummary::name,
StoryDefinitionConfigurationSummary::category,
StoryDefinitionConfigurationSummary::description
)
.safeCollation(Collation.builder().locale(defaultLocale.language).build())
.sort(ascending(StoryDefinitionConfigurationSummary::name))
.toList()
override fun save(story: StoryDefinitionConfiguration) {
val previous = col.findOneById(story._id)
val toSave =
if (previous != null) {
story.copy(version = previous.version + 1)
} else {
story
}
historyCol.save(StoryDefinitionConfigurationHistoryCol(toSave))
col.save(toSave)
}
override fun delete(story: StoryDefinitionConfiguration) {
val previous = col.findOneById(story._id)
if (previous != null) {
historyCol.save(StoryDefinitionConfigurationHistoryCol(previous, true))
}
col.deleteOneById(story._id)
}
override fun createBuiltInStoriesIfNotExist(stories: List<StoryDefinitionConfiguration>) {
stories.forEach {
// unique index throws exception if the story already exists
try {
col.insertOne(it)
} catch (e: Exception) {
logger.trace(e)
}
}
}
}
| 136
| null |
92
| 335
|
abdd2a29771b374e716e9009d62486c6f1d3ba78
| 8,783
|
tock
|
Apache License 2.0
|
app/src/main/kotlin/com/podcreep/mobile/data/local/SubscriptionsDao.kt
|
podcreep
| 131,102,789
| false
|
{"Kotlin": 88876}
|
package com.podcreep.mobile.data.local
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import kotlinx.coroutines.flow.Flow
@Dao
interface SubscriptionsDao {
@Query("SELECT * FROM sub_podcasts")
fun get(): Flow<List<Subscription>>
@Delete
suspend fun delete(vararg subscriptions: Subscription)
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(vararg subscriptions: Subscription)
/*
@Transaction
fun updateAll(sub_podcasts: List<Subscription>) {
val existing = get().value
val toDelete = ArrayList<Subscription>()
existing?.forEach {
if (!sub_podcasts.contains(it)) {
toDelete.add(it)
}
}
if (toDelete.size > 0) {
delete(*toDelete.toTypedArray())
}
insert(*sub_podcasts.toTypedArray())
}
*/
}
| 0
|
Kotlin
|
0
| 0
|
512f7fa6e4369eb5d85fd281036dfcb3daea5da5
| 893
|
android
|
Apache License 2.0
|
app-sample/src/main/kotlin/com/github/omarmiatello/sourceoftruth/appsample/Models.kt
|
omarmiatello
| 364,404,854
| false
| null |
package com.github.omarmiatello.sourceoftruth.appsample
data class ExtV(val id: String, val name: String)
data class IntV(val qr: String?, val name: String, val id: String)
| 1
|
Kotlin
|
0
| 0
|
2cd1ceab0542110a750bc05184d73c0af3d8b93e
| 174
|
source-of-truth
|
MIT License
|
app/common/src/commonJvmMain/kotlin/com/denchic45/studiversity/domain/model/Lesson.kt
|
denchic45
| 435,895,363
| false
| null |
package com.denchic45.studiversity.domain.model
import com.denchic45.studiversity.data.domain.model.EventType
import com.denchic45.stuiversity.api.course.subject.model.SubjectResponse
import com.denchic45.stuiversity.api.user.model.UserResponse
//data class Lesson(
// val subject: SubjectResponse,
// val teachers: List<UserResponse>,
// val task: Task? = null,
//) : EventDetails() {
//
// val isEmpty: Boolean
// get() = subject.isEmpty
//
// private constructor() : this(Subject.createEmpty(), emptyList(), Task.createEmpty())
//
// override fun copy(): Lesson {
// return Lesson(subject, teachers, task)
// }
//
// override val eventType: EventType
// get() = EventType.LESSON
//
// companion object {
// fun createEmpty(): Lesson {
// return Lesson()
// }
// }
//}
| 0
|
Kotlin
|
0
| 5
|
02d19321d16604a052f6dd29aa54be29343991e6
| 848
|
Studiversity
|
Apache License 2.0
|
app/src/main/java/com/example/android/databinding/basicsample/ui/PlainOldActivity.kt
|
sulavtimsina
| 431,893,187
| false
| null |
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.databinding.basicsample.ui
import android.os.Bundle
import android.view.View
import android.widget.ProgressBar
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProviders
import com.example.android.databinding.basicsample.R
import com.example.android.databinding.basicsample.data.SimpleViewModel
class PlainOldActivity : AppCompatActivity() {
// Obtain ViewModel from ViewModelProviders
private val viewModel by lazy { ViewModelProviders.of(this).get(SimpleViewModel::class.java) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.plain_activity)
updateName()
updateLikes()
}
/**
* This method is triggered by the `android:onclick` attribute in the layout. It puts business
* logic in the activity, which is not ideal. We should do something about that.
*/
fun onLike(view: View) {
viewModel.onLike()
updateLikes()
}
/**
* So much findViewById! We'll fix that with Data Binding.
*/
private fun updateName() {
findViewById<TextView>(R.id.plain_name).text = viewModel.name
findViewById<TextView>(R.id.plain_lastname).text = viewModel.lastName
}
/**
* This method has many problems:
* - It's calling findViewById multiple times
* - It has untestable logic
* - It's updating two views when called even if they're not changing
*/
private fun updateLikes() {
findViewById<TextView>(R.id.likes).text = viewModel.likes.toString()
findViewById<ProgressBar>(R.id.progressBar).progress =
(viewModel.likes * 100 / 5).coerceAtMost(100)
}
}
| 0
|
Kotlin
|
0
| 0
|
fb769fc773f95e7223be1a195147d2b0d21509a5
| 2,314
|
DatabindingDemo
|
Apache License 2.0
|
app/src/main/java/es/upm/bienestaremocional/domain/repository/questionnaire/OneOffLonelinessRepository.kt
|
Emotional-Wellbeing
| 531,973,820
| false
|
{"Kotlin": 848751}
|
package es.upm.bienestaremocional.domain.repository.questionnaire
import android.util.Range
import es.upm.bienestaremocional.data.database.entity.oneoff.OneOffLoneliness
import java.time.ZonedDateTime
interface OneOffLonelinessRepository : QuestionnaireRepository<OneOffLoneliness> {
override suspend fun insert(element: OneOffLoneliness): Long
override suspend fun update(element: OneOffLoneliness)
override suspend fun get(id: Long): OneOffLoneliness?
override suspend fun getAll(): List<OneOffLoneliness>
override suspend fun getAllFromCurrentWeek(): List<OneOffLoneliness>
override suspend fun getAllFromLastSevenDays(): List<OneOffLoneliness>
override suspend fun getAllFromRange(
range: Range<ZonedDateTime>,
onlyCompleted: Boolean
): List<OneOffLoneliness>
override suspend fun getAllFromYesterday(): List<OneOffLoneliness>
override suspend fun getLastElement(): OneOffLoneliness?
}
| 0
|
Kotlin
|
0
| 2
|
5e62029c06dbd6f460de6d381c8dbd512b4eee91
| 948
|
App
|
Apache License 2.0
|
src/main/kotlin/com/valaphee/tesseract/entity/player/InputCorrectPacket.kt
|
valaphee
| 400,115,259
| false
| null |
/*
* MIT License
*
* Copyright (c) 2021, Valaphee.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.valaphee.tesseract.entity.player
import com.valaphee.foundry.math.Float3
import com.valaphee.tesseract.net.Packet
import com.valaphee.tesseract.net.PacketBuffer
import com.valaphee.tesseract.net.PacketHandler
import com.valaphee.tesseract.net.PacketReader
/**
* @author <NAME>
*/
class InputCorrectPacket(
val position: Float3,
val positionDelta: Float3,
val onGround: Boolean,
val tick: Long
) : Packet() {
override val id get() = 0xA1
override fun write(buffer: PacketBuffer, version: Int) {
buffer.writeFloat3(position)
buffer.writeFloat3(positionDelta)
buffer.writeBoolean(onGround)
buffer.writeVarULong(tick)
}
override fun handle(handler: PacketHandler) = handler.inputCorrect(this)
override fun toString() = "InputCorrectPacket(position=$position, positionDelta=$positionDelta, onGround=$onGround, tick=$tick)"
}
/**
* @author <NAME>
*/
object InputCorrectPacketReader : PacketReader {
override fun read(buffer: PacketBuffer, version: Int) = InputCorrectPacket(buffer.readFloat3(), buffer.readFloat3(), buffer.readBoolean(), buffer.readVarULong())
}
| 0
|
Kotlin
|
2
| 19
|
184ad06676128f05d4a81534e183192af60eed00
| 2,285
|
tesseract
|
MIT License
|
src/main/kotlin/br/ufpe/liber/controllers/BooksController.kt
|
Liber-UFPE
| 749,911,767
| false
|
{"Kotlin": 131497, "JavaScript": 4978, "Dockerfile": 2242, "Shell": 2142, "SCSS": 1154}
|
package br.ufpe.liber.controllers
import br.ufpe.liber.Templates
import br.ufpe.liber.services.BooksRepository
import io.micronaut.http.HttpResponse
import io.micronaut.http.MediaType
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
import io.micronaut.http.annotation.Produces
import io.micronaut.http.context.ServerRequestContext
import java.util.Optional
@Controller
@Produces(MediaType.TEXT_HTML)
class BooksController(private val templates: Templates, private val booksRepository: BooksRepository) : KteController {
@Get("/livro/{bookNumber}/ano/{year}/pagina/{pageNumber}")
fun show(bookNumber: Int, year: Int, pageNumber: Int, query: Optional<String>): HttpResponse<KteWriteable> =
booksRepository
.get(bookNumber)
.flatMap { book ->
book.page(pageNumber, year).map { page ->
ok(templates.booksShow(book, page, query))
}
}
.orElse(notFound(templates.notFound(currentRequestPath())))
private fun currentRequestPath(): String = ServerRequestContext.currentRequest<Any>()
.map { it.path }
.orElse("")
}
| 1
|
Kotlin
|
0
| 0
|
669578d398c5bc6f257040d6889ec2021198fcde
| 1,184
|
pereira-da-costa
|
Apache License 2.0
|
client/src/main/kotlin/phraseapp/repositories/operations/Downloader.kt
|
Decathlon
| 360,882,777
| false
|
{"Kotlin": 134130}
|
package phraseapp.repositories.operations
import kotlinx.coroutines.coroutineScope
import phraseapp.internal.platforms.Platform
import phraseapp.internal.printers.FileOperation
import phraseapp.internal.xml.Resource
import phraseapp.network.DEFAULT_ALLOWED_LOCALE_CODES
import phraseapp.network.DEFAULT_EXCEPTIONS
import phraseapp.network.DEFAULT_OVERRIDE_DEFAULT_FILE
import phraseapp.network.DEFAULT_PLACEHOLDER
import phraseapp.network.DEFAULT_REGEX
import phraseapp.network.PhraseAppNetworkDataSource
import phraseapp.parsers.xml.DEFAULT_IGNORE_COMMENTS
import phraseapp.repositories.operations.helpers.LocalHelper
import phraseapp.repositories.operations.helpers.PrinterHelper
import phraseapp.repositories.operations.helpers.ReducerHelper
class Downloader(
platform: Platform,
buildDir: String,
fileOperation: FileOperation,
private val network: PhraseAppNetworkDataSource,
) {
private val localHelper = LocalHelper(platform)
private val reducerHelper = ReducerHelper(platform)
private val printerHelper = PrinterHelper(platform, buildDir, fileOperation)
suspend fun download(
resFolders: Map<String, List<String>>,
overrideDefaultFile: Boolean = DEFAULT_OVERRIDE_DEFAULT_FILE,
exceptions: Map<String, String> = DEFAULT_EXCEPTIONS,
placeholder: Boolean = DEFAULT_PLACEHOLDER,
localeNameRegex: String = DEFAULT_REGEX,
ignoreComments: Boolean = DEFAULT_IGNORE_COMMENTS,
allowedLocaleCodes: List<String> = DEFAULT_ALLOWED_LOCALE_CODES,
) = coroutineScope {
val strings = localHelper.getStringsFileByResFolder(resFolders = resFolders)
val locales = network.downloadAllLocales(
exceptions = exceptions,
placeHolder = placeholder,
localeNameRegex = localeNameRegex,
allowedLocaleCodes = allowedLocaleCodes
)
val resources = reducerHelper.reduceKeysForAllStringsFilesAndForAllLocales(
strings = strings,
remoteStrings = locales,
ignoreComments = ignoreComments
)
printerHelper.printResources(
configurations = resources,
overrideDefaultFile = overrideDefaultFile
)
printerHelper.printLocales(types = getTypes(resources))
return@coroutineScope resources
}
private fun getTypes(configurations: Map<String, Map<ResFolderType, Resource>>): List<ResFolderType> =
configurations.entries.first().value.keys.toList()
}
sealed class ResFolderType(open val language: String, val isDefault: Boolean)
class LanguageType(language: String, isDefault: Boolean) : ResFolderType(language, isDefault)
class LocaleType(language: String, val country: String, isDefault: Boolean) :
ResFolderType(language, isDefault)
| 4
|
Kotlin
|
7
| 11
|
3b71c3dcbe7570191249730c61b1ca5069a61c7a
| 2,793
|
gradle-plugin-phraseapp
|
Apache License 2.0
|
client/src/main/kotlin/phraseapp/repositories/operations/Downloader.kt
|
Decathlon
| 360,882,777
| false
|
{"Kotlin": 134130}
|
package phraseapp.repositories.operations
import kotlinx.coroutines.coroutineScope
import phraseapp.internal.platforms.Platform
import phraseapp.internal.printers.FileOperation
import phraseapp.internal.xml.Resource
import phraseapp.network.DEFAULT_ALLOWED_LOCALE_CODES
import phraseapp.network.DEFAULT_EXCEPTIONS
import phraseapp.network.DEFAULT_OVERRIDE_DEFAULT_FILE
import phraseapp.network.DEFAULT_PLACEHOLDER
import phraseapp.network.DEFAULT_REGEX
import phraseapp.network.PhraseAppNetworkDataSource
import phraseapp.parsers.xml.DEFAULT_IGNORE_COMMENTS
import phraseapp.repositories.operations.helpers.LocalHelper
import phraseapp.repositories.operations.helpers.PrinterHelper
import phraseapp.repositories.operations.helpers.ReducerHelper
class Downloader(
platform: Platform,
buildDir: String,
fileOperation: FileOperation,
private val network: PhraseAppNetworkDataSource,
) {
private val localHelper = LocalHelper(platform)
private val reducerHelper = ReducerHelper(platform)
private val printerHelper = PrinterHelper(platform, buildDir, fileOperation)
suspend fun download(
resFolders: Map<String, List<String>>,
overrideDefaultFile: Boolean = DEFAULT_OVERRIDE_DEFAULT_FILE,
exceptions: Map<String, String> = DEFAULT_EXCEPTIONS,
placeholder: Boolean = DEFAULT_PLACEHOLDER,
localeNameRegex: String = DEFAULT_REGEX,
ignoreComments: Boolean = DEFAULT_IGNORE_COMMENTS,
allowedLocaleCodes: List<String> = DEFAULT_ALLOWED_LOCALE_CODES,
) = coroutineScope {
val strings = localHelper.getStringsFileByResFolder(resFolders = resFolders)
val locales = network.downloadAllLocales(
exceptions = exceptions,
placeHolder = placeholder,
localeNameRegex = localeNameRegex,
allowedLocaleCodes = allowedLocaleCodes
)
val resources = reducerHelper.reduceKeysForAllStringsFilesAndForAllLocales(
strings = strings,
remoteStrings = locales,
ignoreComments = ignoreComments
)
printerHelper.printResources(
configurations = resources,
overrideDefaultFile = overrideDefaultFile
)
printerHelper.printLocales(types = getTypes(resources))
return@coroutineScope resources
}
private fun getTypes(configurations: Map<String, Map<ResFolderType, Resource>>): List<ResFolderType> =
configurations.entries.first().value.keys.toList()
}
sealed class ResFolderType(open val language: String, val isDefault: Boolean)
class LanguageType(language: String, isDefault: Boolean) : ResFolderType(language, isDefault)
class LocaleType(language: String, val country: String, isDefault: Boolean) :
ResFolderType(language, isDefault)
| 4
|
Kotlin
|
7
| 11
|
3b71c3dcbe7570191249730c61b1ca5069a61c7a
| 2,793
|
gradle-plugin-phraseapp
|
Apache License 2.0
|
corekit/src/main/java/com/laohu/kit/util/crash/CrashSaver.kt
|
huyongli
| 386,322,592
| false
| null |
package com.laohu.kit.util.crash
import android.content.Context
import android.text.TextUtils
import com.laohu.kit.extensions.orFalse
import com.laohu.kit.util.MD5
import java.io.BufferedWriter
import java.io.File
import java.io.FileReader
import java.io.FileWriter
import java.io.IOException
import java.io.LineNumberReader
import java.io.PrintWriter
import java.io.StringWriter
import java.io.Writer
import java.text.SimpleDateFormat
import java.util.*
object CrashSaver {
fun save(
context: Context,
throwable: Throwable?,
uncaught: Boolean,
appendedSnapshot: Map<String, String>?
) {
if (throwable == null) {
return
}
var writer: Writer? = null
var printWriter: PrintWriter? = null
var stackTrace = ""
try {
writer = StringWriter()
printWriter = PrintWriter(writer)
throwable.printStackTrace(printWriter)
var cause = throwable.cause
while (cause != null) {
cause.printStackTrace(printWriter)
cause = cause.cause
}
stackTrace = writer.toString()
} catch (e: Exception) {
e.printStackTrace()
} finally {
try {
writer?.close()
printWriter?.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
val signature = stackTrace.replace("\\([^\\(]*\\)".toRegex(), "")
val filename = MD5.getStringMD5(signature)
if (TextUtils.isEmpty(filename)) {
return
}
val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
val timestamp = sdf.format(Date())
var mBufferedWriter: BufferedWriter? = null
try {
val file = File(context.getExternalFilesDir(null), "crash/$filename.log")
if (!file.parentFile?.exists().orFalse()) { // 如果文件夹不存在,则先创建文件夹
file.parentFile?.mkdirs()
}
var count = 1
if (file.exists()) {
var reader: LineNumberReader? = null
try {
reader = LineNumberReader(FileReader(file))
val line = reader.readLine()
if (line != null && line.startsWith("count")) {
var index = line.indexOf(":")
if (index != -1) {
var countStr = line.substring(++index)
countStr = countStr.trim { it <= ' ' }
count = countStr.toInt()
count++
}
}
} catch (e: Exception) {
e.printStackTrace()
} finally {
if (reader != null) {
try {
reader.close()
} catch (e: Exception) {
e.printStackTrace()
}
}
}
file.delete()
}
file.createNewFile()
mBufferedWriter = BufferedWriter(FileWriter(file, true)) // 追加模式写文件
val snapshot: MutableMap<String, String> =
CrashSnapshot.snapshot(context, uncaught, timestamp, count)
if (appendedSnapshot != null) {
snapshot.putAll(appendedSnapshot)
}
val content = buildSnapshotString(snapshot, stackTrace)
mBufferedWriter.append(content)
mBufferedWriter.flush()
} catch (e: Exception) {
e.printStackTrace()
} finally {
try {
mBufferedWriter?.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
private fun buildSnapshotString(snapshot: Map<String, String>, trace: String): String {
val iterator = snapshot.entries.iterator()
val sb = StringBuilder()
while (iterator.hasNext()) {
val entry = iterator.next()
sb.append(entry.key).append(entry.value)
sb.append(System.getProperty("line.separator"))
}
sb.append(System.getProperty("line.separator"))
sb.append("**----------------------***")
sb.append(System.getProperty("line.separator"))
sb.append(trace)
sb.append(System.getProperty("line.separator"))
sb.append(System.getProperty("line.separator"))
sb.append(System.getProperty("line.separator"))
return sb.toString()
}
}
| 0
|
Kotlin
|
0
| 0
|
36990176c66902a30606636f469743f3ac94a480
| 4,650
|
AndroidKit
|
Apache License 2.0
|
app/src/main/java/com/domain/cats/app/presentation/FactsViewModel.kt
|
izabelacdsa-zz
| 278,426,456
| false
| null |
package com.domain.cats.app.presentation
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.domain.cats.app.data.FactsRepository
import com.domain.cats.app.domain.models.Cat
import io.reactivex.Scheduler
import io.reactivex.disposables.CompositeDisposable
// TODO: Faça o disposable.add que fara a limpeza de todos os dados não mais necessários dentro do contêiner.
// TODO: subscribeOn(ioScheduler) especifica que os dados vão passar na thread ioScheduler (request network).
// TODO: observeOn() informa que os dados vão passar na main thread.
// TODO: doOnSubscribe - faça algo quando subscrever algo que é o loading true
// TODO: doFinally() fala que quando o observable terminar de observar ele finalmente faça algo que e tirar o loading.
// TODO: No subscribe acontecera o callback que é mostrar a lista de gatos e caso de erro mostre o erro com o erroException.
// TODO: Alterar o código para utilizar ObservableTransformer para os fluxos de loading e error
// TODO: Qual emitter type (Observable, Flowable, Maybe, Single, Completable) que melhor pode ser utilizado no fluxo reativo do app?
// TODO: Caso seja necessário um diferente do que é utilizado no app, alterar no código para que utilize esse outro emitter type.
class FactsViewModel(
private val repository: FactsRepository,
private val ioScheduler: Scheduler, // Scheduler for IO
private val mainScheduler: Scheduler // Scheduler for UI/Main
) : ViewModel() {
private val disposable = CompositeDisposable()
val loading = MutableLiveData<Boolean>()
val error = MutableLiveData<Throwable>()
val catsFacts = MutableLiveData<List<Cat>>()
override fun onCleared() {
disposable.clear()
super.onCleared()
}
fun fetchFacts() {
// TODO: implement fetchFacts method
// TODO: after implemented fetchFacts change this to Observable Transformer
}
}
| 0
|
Kotlin
|
0
| 0
|
42af0cb725ce6f6f2c85f16d244131cb9811b2ac
| 1,923
|
cats-project-rxjava
|
The Unlicense
|
repl/src/commonMain/kotlin/it/unibo/tuprolog/ui/repl/TuPrologUtils.kt
|
tuProlog
| 230,784,338
| false
| null |
package it.unibo.tuprolog.ui.repl
import com.github.ajalt.clikt.core.ProgramResult
import com.github.ajalt.clikt.output.TermUi
import com.github.ajalt.clikt.output.defaultCliktConsole
import it.unibo.tuprolog.core.format
import it.unibo.tuprolog.core.operators.OperatorSet
import it.unibo.tuprolog.core.parsing.ParseException
import it.unibo.tuprolog.solve.Solution
import it.unibo.tuprolog.solve.SolutionFormatter
import it.unibo.tuprolog.solve.exception.HaltException
object TuPrologUtils {
private fun printSolution(sol: Solution, operatorSet: OperatorSet) {
when (sol) {
is Solution.Yes -> {
printYesSolution(sol, operatorSet)
}
is Solution.No -> {
printNoSolution(sol, operatorSet)
}
is Solution.Halt -> {
printHaltSolution(sol, operatorSet)
}
}
}
private fun printYesSolution(sol: Solution.Yes, operatorSet: OperatorSet) {
TermUi.echo(sol.format(SolutionFormatter.withOperators(operatorSet)))
}
private fun printHaltSolution(sol: Solution.Halt, operatorSet: OperatorSet) {
when (val ex = sol.exception) {
is HaltException -> {
TermUi.echo("goodbye.")
throw ProgramResult(ex.exitStatus)
}
else -> TermUi.echo(sol.format(SolutionFormatter.withOperators(operatorSet)))
}
}
fun printParseException(e: ParseException) {
TermUi.echo("# ${e.message?.capitalize()}", err = true)
}
private fun printEndOfSolutions() {
// do nothing
}
fun readQuery(): String {
val query: String? = TermUi.prompt("?-", promptSuffix = " ")
return when {
query == null -> {
throw NullInputException("The standard input has been close unexpectedly")
}
query.trim().endsWith('.') -> {
query
}
else -> {
readQueryMultiline(query)
}
}
}
private fun readQueryMultiline(query: String): String {
val longQuery = StringBuilder(query)
var lastRead = query
while (!lastRead.trim().endsWith('.')) {
lastRead = TermUi.prompt(">", promptSuffix = " ")
?: throw NullInputException("The standard input has been closed unexpectedly")
longQuery.append(lastRead)
}
return longQuery.toString()
}
@Suppress("UNUSED_PARAMETER")
private fun printNoSolution(sol: Solution.No, operatorSet: OperatorSet) {
TermUi.echo(sol.format(SolutionFormatter.withOperators(operatorSet)))
}
fun printSolutions(solutions: Iterator<Solution>, operatorSet: OperatorSet) {
var first = true
while (solutions.hasNext()) {
if (!first) {
val cmd = defaultCliktConsole().promptForLine("", false)?.trim()
if (cmd != ";") break
} else {
first = false
}
printSolution(solutions.next(), operatorSet)
}
printEndOfSolutions()
}
fun printNumSolutions(solutions: Iterator<Solution>, maxSolutions: Int, operatorSet: OperatorSet) {
var i = 0
while (i < maxSolutions && solutions.hasNext()) {
i++
printSolution(solutions.next(), operatorSet)
}
printEndOfSolutions()
}
}
| 68
| null |
10
| 61
|
7af42835335575b2297d411798017f9ec62e032a
| 3,444
|
2p-kt
|
Apache License 2.0
|
app/src/main/java/com/example/ecd_app/ContactActivity.kt
|
MukundiCode
| 515,576,284
| false
|
{"Kotlin": 178003, "PHP": 32471, "CSS": 7410}
|
package com.example.ecd_app
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.synnapps.carouselview.CarouselView
import com.synnapps.carouselview.ImageListener
/**
* @author <NAME>
* ContactActivity contains Bhabisanas story, carousel images with staff-parent interactions
*/
class ContactActivity : AppCompatActivity() {
var imageArray: ArrayList<Int> = ArrayList()//image list to display
lateinit var carouselView: CarouselView
/**
*onCreate function called to set view details
* @param savedInstanceState saved bundle state
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_contact)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.title = "Information"
val facebookImage : ImageView = findViewById(R.id.imageFacebook)
val instagramImage : ImageView = findViewById(R.id.imageInstagram)
val whatsappImage : ImageView = findViewById(R.id.imageWhatsapp)
val ecdImage : ImageView = findViewById(R.id.imageBbpPortal)
/**
* Code to check if application package is installed on the phone
* @param packageName name of package checked
* @return true if installed, false otherwise
*/
fun isAppInstalled(packageName: String): Boolean {
val pm: PackageManager = getPackageManager()
return try {
pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES)//getting info
true
} catch (e: PackageManager.NameNotFoundException) {
false
}
}
/**
* Redirect to Facebook
*/
facebookImage.setOnClickListener(){
val url: String = "https://www.facebook.com/bhabhisanababyproject/"
val fb = Intent(Intent.ACTION_VIEW)
fb.data = Uri.parse(url)
startActivity(fb)
}
/**
* Redirect to Instagram
*/
instagramImage.setOnClickListener(){
val url: String = "https://www.instagram.com/bhabhisanababyproject/?igshid=YmMyMTA2M2Y="
val ig = Intent(Intent.ACTION_VIEW)
ig.data = Uri.parse(url)
startActivity(ig)
}
/**
* Redirect to WhatsApp
*/
whatsappImage.setOnClickListener(){
val result = isAppInstalled("com.whatsapp")//checking if whatsapp is installed
if(result){
val url: String = "https://chat.whatsapp.com/HrqX8TOScucI2LDIUpEXvI"//Bhabisana group chat
val whatsapp = Intent(Intent.ACTION_VIEW)
whatsapp.data = Uri.parse(url)
startActivity(whatsapp)
}else{
Toast.makeText(this@ContactActivity, "Install WhatsApp first", Toast.LENGTH_LONG).show()//showing whatsapp is not installed
}
}
/**
* Redirect to BBP webportal
*/
ecdImage.setOnClickListener(){
val url: String = "https://youandyourbaby.bhabhisana.org.za/"
val ecd = Intent(Intent.ACTION_VIEW)
ecd.data = Uri.parse(url)
startActivity(ecd)
}
//Adding images to carousel
imageArray.add(R.drawable.one)
imageArray.add(R.drawable.two)
imageArray.add(R.drawable.three)
imageArray.add(R.drawable.four)
carouselView=findViewById(R.id.carouselView)
carouselView.pageCount=imageArray.size
carouselView.setImageListener(imageListener)
}
//setting carouselView images
var imageListener = ImageListener { position, imageView -> imageView.setImageResource(imageArray[position]) }
}
| 0
|
Kotlin
|
2
| 0
|
36f04f3d373fc5536863a0901e508056c55e364a
| 3,964
|
ECD-App
|
MIT License
|
app/src/main/java/com/frogchair/android/feature/fight/FightActivity.kt
|
klapocius
| 588,174,308
| false
| null |
package com.frogchair.android.feature.fight
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.view.animation.TranslateAnimation
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.frogchair.android.R
import com.frogchair.android.common.utils.animateUpDown
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class FightActivity : AppCompatActivity() {
companion object {
const val ANIM_ATTACK_DURATION = 300L
fun navigate(context: Context) = Intent(context, FightActivity::class.java)
}
private val stepTextView: TextView by lazy { findViewById(R.id.fight_step_text) }
private val enemy1View: View by lazy { findViewById(R.id.fight_enemy_1) }
private val enemy2View: View by lazy { findViewById(R.id.fight_enemy_2) }
private val enemy3View: View by lazy { findViewById(R.id.fight_enemy_3) }
private val ally1View: View by lazy { findViewById(R.id.fight_ally_1) }
private val ally2View: View by lazy { findViewById(R.id.fight_ally_2) }
private val ally3View: View by lazy { findViewById(R.id.fight_ally_3) }
private val swipeView: SwipeView by lazy { findViewById(R.id.fight_swipe_view) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_fight)
initSwipeView()
animateEnemies()
}
private fun animateEnemies() {
enemy1View.animateUpDown()
enemy2View.animateUpDown()
enemy3View.animateUpDown()
}
private fun initSwipeView() {
swipeView.listener = object : SwipeView.Listener {
override fun onSwipeFinished(lineInfo1: LineInfo, lineInfo2: LineInfo, lineInfo3: LineInfo) {
animateFirstLine()
}
}
}
private fun animateFirstLine() {
ally1View.visibility = View.VISIBLE
ally2View.visibility = View.VISIBLE
ally3View.visibility = View.VISIBLE
val enterAnim = AnimationUtils.loadAnimation(applicationContext, R.anim.anim_translate_left_right)
enterAnim.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationEnd(animation: Animation?) = onEnterAnimationEnd()
override fun onAnimationStart(animation: Animation?) {}
override fun onAnimationRepeat(animation: Animation?) {}
})
ally1View.startAnimation(enterAnim)
ally2View.startAnimation(enterAnim)
ally3View.startAnimation(enterAnim)
}
private fun onEnterAnimationEnd() {
ally2View.animateUpDown()
ally3View.animateUpDown()
animateAllyAttack(ally1View, enemy3View) {
ally1View.animateUpDown()
animateAlly2Attack()
}
}
private fun animateAlly2Attack() {
animateAllyAttack(ally2View, enemy1View) {
ally2View.animateUpDown()
animateAlly3Attack()
}
}
private fun animateAlly3Attack() {
animateAllyAttack(ally3View, enemy2View) {
ally3View.animateUpDown()
stepTextView.text = "Wow such strenght"
closeScreen()
}
}
private fun closeScreen() {
GlobalScope.launch {
delay(1000)
finish()
}
}
private fun animateAllyAttack(allyView: View, enemyView: View, onAnimationEnd: () -> Unit) {
allyView.animation?.cancel()
val anim = TranslateAnimation(
0f, enemyView.x - allyView.x - enemyView.width / 2,
0f, enemyView.y - allyView.y
).apply {
duration = ANIM_ATTACK_DURATION
repeatCount = 1
repeatMode = Animation.REVERSE
setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation?) {}
override fun onAnimationEnd(animation: Animation?) = onAnimationEnd()
override fun onAnimationRepeat(animation: Animation?) {
enemyView.visibility = View.GONE //dead
}
})
}
allyView.startAnimation(anim)
}
}
| 0
|
Kotlin
|
0
| 0
|
67bda4289092126f5939637f9ebfa28ea04a97dc
| 4,381
|
frogchair-android
|
FSF All Permissive License
|
compiler/tests-spec/testData/codegen/box/linked/expressions/constant-literals/boolean-literals/p-1/pos/2.11.kt
|
JetBrains
| 3,432,266
| false
| null |
// HELPERS: REFLECT
/*
* KOTLIN CODEGEN BOX SPEC TEST (POSITIVE)
*
* SECTIONS: constant-literals, boolean-literals
* PARAGRAPH: 1
* SENTENCE: [2] These are strong keywords which cannot be used as identifiers unless escaped.
* NUMBER: 11
* DESCRIPTION: The use of Boolean literals as the identifier (with backtick) in the function.
* NOTE: this test data is generated by FeatureInteractionTestDataGenerator. DO NOT MODIFY CODE MANUALLY!
*/
fun `true`(): Boolean {
return true
}
fun Boolean.`false`() = true
fun <T> T.`true`() = listOf(0).`false`()
inline fun <reified T, K> K?.`false`(x1: T = 10 as T)
where K : List<T>,
K : Iterable<T>,
T : Comparable<T>,
T : Number = false
fun box(): String? {
if (!`true`()) return null
if (null.`false`<Int, List<Int>>()) return null
if (false.`true`()) return null
if (!false.`false`()) return null
if (Any().`true`()) return null
if (!checkFunctionName(::`true`, "true")) return null
if (!checkFunctionName(Boolean::`false`, "false")) return null
if (!checkFunctionName(Boolean::`true`, "true")) return null
if (!checkFunctionName(List<Int>::`false`, "false")) return null
if (!checkFunctionName(Nothing?::`true`, "true")) return null
return "OK"
}
| 181
| null |
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 1,303
|
kotlin
|
Apache License 2.0
|
port_http_client/src/test/kotlin/com/hexagonkt/http/client/ClientTest.kt
|
aljacinto
| 212,715,947
| true
|
{"Kotlin": 321767, "HTML": 22455, "Scala": 3558, "JavaScript": 2701, "Groovy": 1844, "Dockerfile": 1694, "CSS": 704}
|
package com.hexagonkt.http.client
import com.hexagonkt.helpers.require
import com.hexagonkt.http.server.Call
import com.hexagonkt.http.server.Server
import com.hexagonkt.http.server.jetty.JettyServletAdapter
import com.hexagonkt.serialization.Json
import com.hexagonkt.serialization.serialize
import org.asynchttpclient.Response
import org.testng.annotations.AfterClass
import org.testng.annotations.BeforeClass
import org.testng.annotations.BeforeMethod
import org.testng.annotations.Test
import java.io.File
@Test
class ClientTest {
private var handler: Call.() -> Unit = {}
private val server: Server by lazy {
Server(JettyServletAdapter()) {
post("/*") { handler() }
get("/*") { handler() }
head("/*") { handler() }
put("/*") { handler() }
delete("/*") { handler() }
trace("/*") { handler() }
options("/*") { handler() }
patch("/*") { handler() }
}
}
private val client by lazy {
Client("http://localhost:${server.runtimePort}", Json.contentType)
}
@BeforeClass
fun startup() {
server.start()
}
@AfterClass
fun shutdown() {
server.stop()
}
@BeforeMethod
fun resetHandler() {
handler = {
response.headers["content-type"] = listOf("application/json;charset=utf-8")
response.headers["body"] = listOf(request.body)
ok(request.body)
}
}
fun `JSON requests works as expected`() {
val expectedBody = "{\n \"foo\" : \"fighters\",\n \"es\" : \"áéíóúÁÉÍÓÚñÑ\"\n}"
val requestBody = mapOf("foo" to "fighters", "es" to "áéíóúÁÉÍÓÚñÑ")
val body = client.post("/", requestBody, Json.contentType).responseBody
assert(body.trim() == expectedBody)
val body2 = client.post("/", body = requestBody).responseBody
assert(body2.trim() == expectedBody)
client.get("/")
client.get("/")
}
fun `HTTP methods with objects work ok`() {
val parameter = mapOf("key" to "value")
checkResponse(client.get("/"), null)
checkResponse(client.head("/"), null)
checkResponse(client.post("/", parameter), parameter)
checkResponse(client.put("/", parameter), parameter)
checkResponse(client.delete("/", parameter), parameter)
checkResponse(client.trace("/", parameter), parameter)
checkResponse(client.options("/", parameter), parameter)
checkResponse(client.patch("/", parameter), parameter)
}
fun `HTTP methods with objects work ok with default client`() {
val parameter = mapOf("key" to "value")
val url = "http://localhost:${server.runtimePort}"
val contentType = Json.contentType
checkResponse(get(url), null)
checkResponse(head(url), null)
checkResponse(post(url, parameter, contentType), parameter)
checkResponse(put(url, parameter, contentType), parameter)
checkResponse(delete(url, parameter, contentType), parameter)
checkResponse(trace(url, parameter, contentType), parameter)
checkResponse(options(url, parameter, contentType), parameter)
checkResponse(patch(url, parameter, contentType), parameter)
}
fun `Parameters are set properly` () {
val endpoint = "http://localhost:${server.runtimePort}"
val h = mapOf("header1" to listOf("val1", "val2"))
val c = Client(endpoint, Json.contentType, false, h, "user", "password", true)
assert(c.contentType == Json.contentType)
assert(!c.useCookies)
assert(c.headers == h)
handler = {
response.headers["auth"] = listOf(request.headers.require("Authorization").first())
response.headers["head1"] = request.headers.require("header1")
}
val r = c.get("/auth")
assert (r.headers.get("auth").startsWith("Basic"))
assert (r.headers.getAll("head1").contains("val1"))
assert (r.headers.getAll("head1").contains("val2"))
assert (r.statusCode == 200)
}
fun `Files are sent in base64` () {
handler = { response.headers["file64"] = listOf(request.body) }
val file = File("src/test/resources/logback-test.xml").let {
if (it.exists()) it
else File("port_http_client/src/test/resources/logback-test.xml")
}
val r = client.post("/file", file)
assert (r.headers.get("file64").isNotEmpty())
assert (r.statusCode == 200)
}
fun `Strings are sent properly` () {
val r = client.post("/string", "text")
assert (r.headers.get("body").isNotEmpty())
assert (r.statusCode == 200)
}
private fun checkResponse(response: Response, parameter: Map<String, String>?) {
assert(response.statusCode == 200)
assert(response.responseBody.trim() == parameter?.serialize()?.trim() ?: "")
}
}
| 0
|
Kotlin
|
0
| 0
|
b5e84048cb9719a744094eb672e4927c6255c16a
| 4,959
|
hexagon
|
MIT License
|
Kotlin/Code/Kotlin-Coroutines/src/main/kotlin/core/functions/04_AsyncStyle.kt
|
hiloWang
| 203,300,702
| false
| null |
package core.functions
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import kotlin.system.measureTimeMillis
//sampleStart
// note, that we don't have `runBlocking` to the right of `main` in this example
fun main() {
val time = measureTimeMillis {
// we can initiate async actions outside of a coroutine
val one = somethingUsefulOneAsync()
val two = somethingUsefulTwoAsync()
// but waiting for a result must involve either suspending or blocking.
// here we use `runBlocking { ... }` to block the main thread while waiting for the result
runBlocking {
println("The answer is ${one.await() + two.await()}")
}
}
println("Completed in $time ms")
}
//sampleEnd
private suspend fun doSomethingUsefulOne(): Int {
delay(1000L) // pretend we are doing something useful here
return 13
}
private suspend fun doSomethingUsefulTwo(): Int {
delay(1000L) // pretend we are doing something useful here, too
return 29
}
// The result type of somethingUsefulOneAsync is Deferred<Int>
private fun somethingUsefulOneAsync() = GlobalScope.async {
doSomethingUsefulOne()
}
// The result type of somethingUsefulTwoAsync is Deferred<Int>
private fun somethingUsefulTwoAsync() = GlobalScope.async {
doSomethingUsefulTwo()
}
| 0
| null |
15
| 4
|
64a637a86f734e4e80975f4aa93ab47e8d7e8b64
| 1,404
|
notes
|
Apache License 2.0
|
definitions/src/main/kotlin-gen/xyz/urbanmatrix/mavlink/definitions/common/CellularConfigResponse.kt
|
urbanmatrix
| 484,943,163
| false
| null |
package xyz.urbanmatrix.mavlink.definitions.common
import kotlin.Long
import xyz.urbanmatrix.mavlink.api.GeneratedMavEnum
import xyz.urbanmatrix.mavlink.api.GeneratedMavEnumEntry
import xyz.urbanmatrix.mavlink.api.MavEnum
/**
* Possible responses from a CELLULAR_CONFIG message.
*/
@GeneratedMavEnum
public enum class CellularConfigResponse(
public override val `value`: Long,
) : MavEnum {
/**
* Changes accepted.
*/
@GeneratedMavEnumEntry
ACCEPTED(0L),
/**
* Invalid APN.
*/
@GeneratedMavEnumEntry
APN_ERROR(1L),
/**
* Invalid PIN.
*/
@GeneratedMavEnumEntry
PIN_ERROR(2L),
/**
* Changes rejected.
*/
@GeneratedMavEnumEntry
REJECTED(3L),
/**
* PUK is required to unblock SIM card.
*/
@GeneratedMavEnumEntry
CELLULAR_CONFIG_BLOCKED_PUK_REQUIRED(4L),
;
public companion object {
public fun getEntryFromValueOrNull(v: Long): CellularConfigResponse? = when (v) {
0L -> ACCEPTED
1L -> APN_ERROR
2L -> PIN_ERROR
3L -> REJECTED
4L -> CELLULAR_CONFIG_BLOCKED_PUK_REQUIRED
else -> null
}
}
}
| 1
|
Kotlin
|
4
| 9
|
8f480256eeaac5755a2ce5582c338a4b30c7e178
| 1,101
|
mavlink-kotlin
|
Apache License 2.0
|
app/src/main/java/org/kaqui/data/Kanas.kt
|
btp
| 180,280,286
| false
| null |
package org.kaqui.data
data class RawKana(val kana: String, val romaji: String)
data class SimilarKana(val kana: String, val similar: String)
fun getHiraganas() = arrayOf(
RawKana("あ", "a"),
RawKana("い", "i"),
RawKana("う", "u"),
RawKana("え", "e"),
RawKana("お", "o"),
RawKana("か", "ka"),
RawKana("き", "ki"),
RawKana("く", "ku"),
RawKana("け", "ke"),
RawKana("こ", "ko"),
RawKana("さ", "sa"),
RawKana("し", "shi"),
RawKana("す", "su"),
RawKana("せ", "se"),
RawKana("そ", "so"),
RawKana("た", "ta"),
RawKana("ち", "chi"),
RawKana("つ", "tsu"),
RawKana("て", "te"),
RawKana("と", "to"),
RawKana("な", "na"),
RawKana("に", "ni"),
RawKana("ぬ", "nu"),
RawKana("ね", "ne"),
RawKana("の", "no"),
RawKana("は", "ha"),
RawKana("ひ", "hi"),
RawKana("ふ", "fu"),
RawKana("へ", "he"),
RawKana("ほ", "ho"),
RawKana("ま", "ma"),
RawKana("み", "mi"),
RawKana("む", "mu"),
RawKana("め", "me"),
RawKana("も", "mo"),
RawKana("や", "ya"),
RawKana("ゆ", "yu"),
RawKana("よ", "yo"),
RawKana("ら", "ra"),
RawKana("り", "ri"),
RawKana("る", "ru"),
RawKana("れ", "re"),
RawKana("ろ", "ro"),
RawKana("わ", "wa"),
RawKana("を", "wo"),
RawKana("ん", "n"),
RawKana("が", "ga"),
RawKana("ぎ", "gi"),
RawKana("ぐ", "gu"),
RawKana("げ", "ge"),
RawKana("ご", "go"),
RawKana("ざ", "za"),
RawKana("じ", "ji"),
RawKana("ず", "zu"),
RawKana("ぜ", "ze"),
RawKana("ぞ", "zo"),
RawKana("だ", "da"),
RawKana("ぢ", "ji"),
RawKana("づ", "zu"),
RawKana("で", "de"),
RawKana("ど", "do"),
RawKana("ば", "ba"),
RawKana("び", "bi"),
RawKana("ぶ", "bu"),
RawKana("べ", "be"),
RawKana("ぼ", "bo"),
RawKana("ぱ", "pa"),
RawKana("ぴ", "pi"),
RawKana("ぷ", "pu"),
RawKana("ぺ", "pe"),
RawKana("ぽ", "po")
)
fun getSimilarHiraganas() = arrayOf(
SimilarKana("あ", "お"),
SimilarKana("あ", "や" /* ヤ */),
SimilarKana("い", "り"),
SimilarKana("う", "つ"),
SimilarKana("う", "ら" /* ラ */),
SimilarKana("き", "さ"),
SimilarKana("ぎ", "ざ"),
SimilarKana("き", "ま"),
SimilarKana("く", "へ"),
SimilarKana("ぐ", "べ"),
SimilarKana("せ", "さ" /* サ */),
SimilarKana("ぜ", "ざ" /* ザ */),
SimilarKana("さ", "ち"),
SimilarKana("ざ", "ぢ"),
SimilarKana("し", "れ" /* レ */),
SimilarKana("す", "お"),
SimilarKana("す", "む"),
SimilarKana("そ", "ろ"),
SimilarKana("つ", "ふ" /* フ */),
SimilarKana("づ", "ぶ" /* ブ */),
SimilarKana("の", "め"),
SimilarKana("の", "ぬ"),
SimilarKana("め", "ぬ"),
SimilarKana("わ", "ね"),
SimilarKana("わ", "れ"),
SimilarKana("ね", "れ"),
SimilarKana("ま", "は"),
SimilarKana("ま", "ほ"),
SimilarKana("は", "ほ"),
SimilarKana("ば", "ぼ"),
SimilarKana("る", "ろ")
)
fun getKatakanas() = arrayOf(
RawKana("ア", "a"),
RawKana("イ", "i"),
RawKana("ウ", "u"),
RawKana("エ", "e"),
RawKana("オ", "o"),
RawKana("カ", "ka"),
RawKana("キ", "ki"),
RawKana("ク", "ku"),
RawKana("ケ", "ke"),
RawKana("コ", "ko"),
RawKana("サ", "sa"),
RawKana("シ", "shi"),
RawKana("ス", "su"),
RawKana("セ", "se"),
RawKana("ソ", "so"),
RawKana("タ", "ta"),
RawKana("チ", "chi"),
RawKana("ツ", "tsu"),
RawKana("テ", "te"),
RawKana("ト", "to"),
RawKana("ナ", "na"),
RawKana("ニ", "ni"),
RawKana("ヌ", "nu"),
RawKana("ネ", "ne"),
RawKana("ノ", "no"),
RawKana("ハ", "ha"),
RawKana("ヒ", "hi"),
RawKana("フ", "fu"),
RawKana("ヘ", "he"),
RawKana("ホ", "ho"),
RawKana("マ", "ma"),
RawKana("ミ", "mi"),
RawKana("ム", "mu"),
RawKana("メ", "me"),
RawKana("モ", "mo"),
RawKana("ヤ", "ya"),
RawKana("ユ", "yu"),
RawKana("ヨ", "yo"),
RawKana("ラ", "ra"),
RawKana("リ", "ri"),
RawKana("ル", "ru"),
RawKana("レ", "re"),
RawKana("ロ", "ro"),
RawKana("ワ", "wa"),
RawKana("ヲ", "wo"),
RawKana("ン", "n"),
RawKana("ガ", "ga"),
RawKana("ギ", "gi"),
RawKana("グ", "gu"),
RawKana("ゲ", "ge"),
RawKana("ゴ", "go"),
RawKana("ザ", "za"),
RawKana("ジ", "ji"),
RawKana("ズ", "zu"),
RawKana("ゼ", "ze"),
RawKana("ゾ", "zo"),
RawKana("ダ", "da"),
RawKana("ヂ", "ji"),
RawKana("ヅ", "zu"),
RawKana("デ", "de"),
RawKana("ド", "do"),
RawKana("バ", "ba"),
RawKana("ビ", "bi"),
RawKana("ブ", "bu"),
RawKana("ベ", "be"),
RawKana("ボ", "bo"),
RawKana("パ", "pa"),
RawKana("ピ", "pi"),
RawKana("プ", "pu"),
RawKana("ペ", "pe"),
RawKana("ポ", "po")
)
fun getSimilarKatakanas() = arrayOf(
SimilarKana("ア", "ヤ"),
SimilarKana("ウ", "ワ"),
SimilarKana("ラ", "ウ" /* う */),
SimilarKana("オ", "ホ"),
SimilarKana("ク", "ケ"),
SimilarKana("ク", "タ"),
SimilarKana("グ", "ゲ"),
SimilarKana("グ", "ダ"),
SimilarKana("コ", "ユ"),
SimilarKana("サ", "セ" /* せ */),
SimilarKana("ザ", "ゼ" /* ぜ */),
SimilarKana("シ", "ツ"),
SimilarKana("シ", "ソ"),
SimilarKana("シ", "ノ"),
SimilarKana("シ", "ン"),
SimilarKana("ツ", "ソ"),
SimilarKana("ツ", "ノ"),
SimilarKana("ツ", "ン"),
SimilarKana("ソ", "ノ"),
SimilarKana("ソ", "ン"),
SimilarKana("ノ", "ン"),
SimilarKana("ジ", "ヅ"),
SimilarKana("ジ", "ゾ"),
SimilarKana("ヅ", "ゾ"),
SimilarKana("セ", "ヒ"),
SimilarKana("ゼ", "ビ"),
SimilarKana("チ", "テ"),
SimilarKana("ヂ", "デ"),
SimilarKana("ナ", "メ"),
SimilarKana("フ", "ツ" /* つ */),
SimilarKana("ブ", "ヅ" /* づ */),
SimilarKana("レ", "シ" /* し */)
)
| 0
|
Kotlin
|
0
| 0
|
9d828245c1726a9cca8a085d8b736862a1b75457
| 6,342
|
kakngo
|
MIT License
|
src/main/kotlin/com/cuupa/opengarden/displayobjects/PlantDO.kt
|
Cuupa
| 478,063,266
| false
| null |
package com.cuupa.opengarden.displayobjects
data class PlantDO(
var name: String = "",
var bionomalName: String = "",
var order: String = "",
var family: String = "",
var genus: String = "",
var species: String = "",
var light: String = "",
var light_ordinal: Int = -1,
var spread: String = "",
var rowSpacing: String = "",
var height: String = "",
var minGarminationTemperature: String = "",
var crossPolination: String = "",
var minGarminationTime: String = "",
var maxGarminationTime: String = "",
var minTemperatureSingle: String = "",
var minTemperaturePeriod: String = "",
var minIdealTemperature: String = "",
var maxIdealTemperature: String = "",
var minTemperatureFruitDevelopmentDay: String = "",
var maxTemperatureFruitDevelopmentDay: String = "",
var minTemperatureFruitDevelopmentNight: String = "",
var maxTemperatureFruitDevelopmentNight: String = "",
var frostResistent: String = "",
var climbingAid: String = "",
var waterRequirement: String = "",
val waterRequirement_ordinal: Int = -1,
var waterSoil: String = "",
var waterSoilBoolean: Boolean = true,
var waterleafs: String = "",
var waterleafsBoolean: Boolean = false
) {
}
| 14
|
Kotlin
|
0
| 0
|
c71b87dbdb4e97afb42a3dc7546a17cd8e8c8b5e
| 1,270
|
open-garden
|
MIT License
|
src/main/kotlin/network/commercio/sdk/entities/mint/ExchangeTradePosition.kt
|
commercionetwork
| 216,051,921
| false
| null |
package network.commercio.sdk.entities.mint
import com.fasterxml.jackson.annotation.JsonProperty
import network.commercio.sacco.models.types.StdCoin
import java.util.*
data class ExchangeTradePosition(
@JsonProperty("created_at") val createdAt: Date,
val id: String,
val owner: String,
@JsonProperty("exchange_rate") val exchangeRate: String,
val collateral: String,
val credits: StdCoin
)
| 17
|
Kotlin
|
1
| 2
|
0d40b844872d7159bce0b817fd1a1518b5943494
| 415
|
commercio-sdk.kt
|
MIT License
|
app/src/main/java/com/coolweather/coolweatherjetpack/ui/fragment/TestFragment1.kt
|
wangcheng319
| 221,865,680
| false
|
{"Java": 255741, "Kotlin": 78154}
|
package com.coolweather.coolweatherjetpack.ui.fragment
import android.Manifest
import android.app.ProgressDialog
import android.content.Context.TELEPHONY_SERVICE
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.CountDownTimer
import android.telephony.TelephonyManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.app.ActivityCompat
import androidx.fragment.app.Fragment
import com.coolweather.coolweatherjetpack.R
import com.coolweather.coolweatherjetpack.util.LogUtils
import com.coolweather.coolweatherjetpack.util.UniqueIDUtils
import kotlinx.android.synthetic.main.fragment_test1.*
import org.jetbrains.anko.support.v4.toast
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
class TestFragment1 : Fragment() {
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_test1, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
button4.setOnClickListener { getAndroidId() }
button5.setOnClickListener { getSerialNumber() }
button6.setOnClickListener { getMac() }
button7.setOnClickListener { getPhoneNum() }
button8.setOnClickListener { toFlutter() }
}
private fun toFlutter() {
// startActivity(io.flutter.embedding.android.FlutterActivity.createDefaultIntent(requireActivity()))
}
private fun getPhoneNum() {
if (ActivityCompat.checkSelfPermission(
requireActivity(),
Manifest.permission.READ_SMS
) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
requireActivity(),
Manifest.permission.READ_PHONE_NUMBERS
) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
requireActivity(),
Manifest.permission.READ_PHONE_STATE
) != PackageManager.PERMISSION_GRANTED
) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
ActivityCompat.requestPermissions(requireActivity(),
arrayOf(Manifest.permission.READ_SMS,
Manifest.permission.READ_PHONE_NUMBERS,
Manifest.permission.READ_PHONE_STATE),100)
return
}else{
val tm = requireActivity().getSystemService(TELEPHONY_SERVICE) as TelephonyManager
LogUtils.i("getPhoneNum1:"+tm.line1Number)
LogUtils.i("getPhoneNum2"+tm.groupIdLevel1)
toast("getPhoneNum1:"+tm.line1Number)
}
}
private fun getMac() {
LogUtils.i("设备唯一码:"+UniqueIDUtils.getUniqueID(requireActivity()))
}
private fun getSerialNumber() {
LogUtils.i("getSerialNumber")
}
private fun getAndroidId() {
var progressDialog = ProgressDialog(requireActivity())
progressDialog.show()
// Thread.sleep(5*1000)
// progressDialog.dismiss()
/** 倒计时60秒,一次1秒 */
/** 倒计时60秒,一次1秒 */
object : CountDownTimer(10 * 1000, 1000) {
override fun onTick(millisUntilFinished: Long) {
}
override fun onFinish() {
progressDialog.dismiss()
}
}.start()
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
getPhoneNum()
}
companion object {
@JvmStatic
fun newInstance(param1: String, param2: String) =
TestFragment1().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
}
| 1
| null |
1
| 1
|
fca562ac5d2d4850cff538e929fd9114fbafca22
| 4,856
|
mvvmdemo
|
Apache License 2.0
|
content/crash/src/main/kotlin/br/com/mrocigno/bigbrother/crash/CrashTask.kt
|
mrocigno
| 574,215,368
| false
|
{"Kotlin": 343969, "HTML": 7133}
|
package br.com.mrocigno.bigbrother.crash
import android.app.Activity
import br.com.mrocigno.bigbrother.core.BigBrotherTask
import java.lang.ref.WeakReference
class CrashTask : BigBrotherTask() {
override fun onActivityResume(activity: Activity) {
val currentObserver = Thread.getDefaultUncaughtExceptionHandler()
val default = if (currentObserver is CrashObserver) {
currentObserver.activity.clear()
currentObserver.default
} else {
currentObserver
}
Thread.setDefaultUncaughtExceptionHandler(
CrashObserver(
WeakReference(activity),
default
)
)
}
}
| 0
|
Kotlin
|
0
| 4
|
8deac7d4cf1b1395e5c23dc3b788266beb1fa19b
| 701
|
big-brother
|
Apache License 2.0
|
app/src/main/java/com/rakibstudio/newsappmvvm/db/ArticleDatabase.kt
|
rakibcse99
| 463,874,208
| false
|
{"Kotlin": 37299}
|
package com.rakibstudio.newsappmvvm.db
import androidx.room.Database
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import com.rakibstudio.newsappmvvm.model.Article
@Database(
entities = [Article::class],
version = 1
)
@TypeConverters(Converters::class)
abstract class ArticleDatabase : RoomDatabase() {
abstract fun getArticleDao(): ArticleDao
}
| 0
|
Kotlin
|
0
| 2
|
4f6e65010964946d316b44dd3a8fc49f059b2af6
| 385
|
SimpleMVVM_News_APIs
|
Apache License 2.0
|
app/src/main/kotlin/day04/Day04.kt
|
KingOfDog
| 433,706,881
| false
| null |
package day04
import common.InputRepo
import common.readSessionCookie
import common.solve
fun main(args: Array<String>) {
val day = 4
val input = InputRepo(args.readSessionCookie()).get(day = day)
solve(day, input, ::solveDay04Part1, ::solveDay04Part2)
}
fun solveDay04Part1(input: List<String>): Int {
val numbers = parseNumbers(input)
val boards = parseBoards(input)
var number: Int = 0
var hasWon = false
while (!hasWon && numbers.isNotEmpty()) {
number = numbers.removeFirst()
boards.forEach { it.applyNumber(number) }
hasWon = boards.any { it.hasWon() }
}
val winningBoard = boards.first { it.hasWon() }
return winningBoard.sumOfRemainingNumbers() * number
}
fun solveDay04Part2(input: List<String>): Int {
val numbers = parseNumbers(input)
val boards = parseBoards(input)
var number: Int = 0
val boardsWon = boards.map { false }.toTypedArray()
var lastWinningBoardIndex = -1
while (numbers.isNotEmpty() && boardsWon.any { !it }) {
number = numbers.removeFirst()
boards.forEachIndexed { index, board ->
board.applyNumber(number)
if (board.hasWon() && !boardsWon[index]) {
boardsWon[index] = true
lastWinningBoardIndex = index
}
}
}
val lastWinningBoard = boards[lastWinningBoardIndex]
return lastWinningBoard.sumOfRemainingNumbers() * number
}
private fun parseBoards(input: List<String>) =
input.subList(2, input.size).filterNot { it == "" }.windowed(5, 5, false)
.map {
it.map { row ->
row.split(Regex("\\s+")).map { cell -> cell.toInt() }
}
}
.map { BingoBoard(it) }
private fun parseNumbers(input: List<String>) =
input[0].split(",").map { it.toInt() }.toMutableList()
class BingoBoard(input: List<List<Int>>) {
private val width = input[0].size
private val height = input.size
private val numbers: Array<Array<Cell>> =
input.map { it.map { number -> Cell(number, false) }.toTypedArray() }.toTypedArray()
init {
input.forEach {
assert(it.size == width)
}
}
fun applyNumber(number: Int) {
numbers.forEach { row ->
row.forEach {
if (it.number == number)
it.checked = true
}
}
}
fun hasWon(): Boolean {
val options = getOptions()
return options.any { it.areAllChecked() }
}
fun sumOfRemainingNumbers(): Int = numbers.flatten().filterNot { it.checked }.sumOf { it.number }
private fun getOptions(): Array<Array<Cell>> = arrayOf(
*getRows(),
*getColumns(),
)
private fun getRows(): Array<Array<Cell>> = numbers
private fun getColumns(): Array<Array<Cell>> = numbers.transpose()
}
data class Cell(val number: Int, var checked: Boolean)
fun Array<Cell>.areAllChecked(): Boolean =
all { it.checked }
fun Array<Array<Cell>>.transpose(): Array<Array<Cell>> {
val output = Array(this[0].size) { Array(size) { Cell(0, false) } }
forEachIndexed { index, row ->
row.forEachIndexed { index2, c ->
output[index2][index] = c
}
}
return output
}
| 0
|
Kotlin
|
0
| 0
|
576e5599ada224e5cf21ccf20757673ca6f8310a
| 3,277
|
advent-of-code-kt
|
Apache License 2.0
|
libraries/tools/kotlin-gradle-plugin/src/common/kotlin/org/jetbrains/kotlin/gradle/logging/gradleLoggingUtils.kt
|
JetBrains
| 3,432,266
| false
| null |
/*
* Copyright 2010-2018 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.gradle.logging
import org.gradle.api.logging.Logger
import org.jetbrains.kotlin.compilerRunner.KotlinLogger
internal fun Logger.kotlinInfo(message: String) {
this.info("[KOTLIN] $message")
}
internal fun Logger.kotlinDebug(message: String) {
this.debug("[KOTLIN] $message")
}
internal fun Logger.kotlinWarn(message: String) {
this.warn("[KOTLIN] $message")
}
internal inline fun Logger.kotlinDebug(message: () -> String) {
if (isDebugEnabled) {
kotlinDebug(message())
}
}
internal inline fun KotlinLogger.kotlinError(message: () -> String) {
error("[KOTLIN] ${message()}")
}
internal inline fun KotlinLogger.kotlinWarn(message: () -> String) {
warn("[KOTLIN] ${message()}")
}
internal inline fun KotlinLogger.kotlinInfo(message: () -> String) {
info("[KOTLIN] ${message()}")
}
internal inline fun KotlinLogger.kotlinDebug(message: () -> String) {
if (isDebugEnabled) {
debug("[KOTLIN] ${message()}")
}
}
internal inline fun <T> KotlinLogger.logTime(action: String, fn: () -> T): T {
val startNs = System.nanoTime()
val result = fn()
val endNs = System.nanoTime()
val timeNs = endNs - startNs
val timeMs = timeNs.toDouble() / 1_000_000
debug(String.format("%s took %.2f ms", action, timeMs))
return result
}
| 181
| null |
5771
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 1,542
|
kotlin
|
Apache License 2.0
|
app/src/androidTest/java/com/github/leonardoz/kanbapp/BoardColumnsInstrumentedTestSuite.kt
|
LeonardoZ
| 161,324,422
| false
| null |
package com.github.leonardoz.kanbapp
import com.github.leonardoz.kanbapp.view.dialog.ChangeColumnDialogTest
import com.github.leonardoz.kanbapp.view.dialog.ChangeNameDialogTest
import com.github.leonardoz.kanbapp.view.dialog.CreateColumnDialogTest
import com.github.leonardoz.kanbapp.view.fragment.BoardFragmentTest
import com.github.leonardoz.kanbapp.view.fragment.BoardsListFragmentTest
import com.github.leonardoz.kanbapp.view.fragment.CreateBoardFragmentTest
import com.github.leonardoz.kanbapp.view.fragment.ManageColumnsFragmentTest
import org.junit.runner.RunWith
import org.junit.runners.Suite
@RunWith(Suite::class)
@Suite.SuiteClasses(
BoardFragmentTest::class,
CreateColumnDialogTest::class,
ManageColumnsFragmentTest::class,
ChangeColumnDialogTest::class
)
class BoardInstrumentedTest
| 0
|
Kotlin
|
0
| 0
|
55715f293518fc6b4a0bf839238629cbca134807
| 814
|
kanbapp
|
MIT License
|
jenjin-core/src/main/kotlin/com/binarymonks/jj/core/api/ClockAPI.kt
|
lgwillmore
| 79,716,845
| false
|
{"Kotlin": 419262, "Java": 381851, "OpenEdge ABL": 8978, "GLSL": 3774}
|
package com.binarymonks.jj.core.api
interface ClockAPI {
/**
* The current loop delta as a Double.
*/
val delta: Double
/**
* The current loop delta as a Float.
*/
val deltaFloat: Float
/**
* The total elapsed time as a Double
*/
val time: Double
/**
* The total elapsed time as a Float
*/
val timeFloat: Float
/**
* Lets you schedule a function to occur after a delay, and then to repeat.
* Be aware to cancel scheduled tasks if you no longer need them. For example when a scene gets destroyed.
*
* @property function The function to call.
* @property delaySeconds The delay in seconds to at first call the function, and then between successive repeats.
* @property name Name of the scheduled task. Useful for debugging.
*
* @return The id of the scheduled task. Use this to cancel the task.
*/
fun schedule(function: () -> Unit, delaySeconds: Float, repeat: Int = 1, name: String? = null): Int
/**
* Lets you schedule a function to occur after a random windowed delay, and then to repeat.
* Be aware to cancel scheduled tasks if you no longer need them. For example when a scene gets destroyed.
*
* @property function The function to call.
* @property delayMinSeconds The minimum delay in seconds to at first call the function, and then between successive repeats.
* @property delayMaxSeconds The maximum delay in seconds to at first call the function, and then between successive repeats.
* @property name Name of the scheduled task. Useful for debugging.
*
* @return The id of the scheduled task. Use this to cancel the task.
*/
fun schedule(function: () -> Unit, delayMinSeconds: Float, delayMaxSeconds: Float, repeat: Int = 1, name: String? = null): Int
/**
* Cancel a scheduled task by id.
*
* Will complete silently if the id does not exist or the task is already complete.
*/
fun cancel(id: Int)
}
| 4
|
Kotlin
|
1
| 7
|
5b958f6b9a10eb342fb3fa190154029723d3593d
| 2,026
|
jenjin
|
Apache License 2.0
|
android-animated-stick-view/src/main/java/at/steinbacher/android_animated_stick_view/Rectangle.kt
|
geckogecko
| 254,393,896
| false
| null |
package at.steinbacher.android_animated_stick_view
import android.content.Context
import android.graphics.Paint
import android.graphics.PointF
import android.graphics.drawable.Drawable
import android.graphics.drawable.VectorDrawable
import androidx.core.graphics.drawable.DrawableCompat
import org.json.JSONObject
class Rectangle(val topLeft: PointF,
val bottomRight: PointF,
paint: Paint,
tag: String)
: Simple(paint, tag){
private var vectorDrawableInt: Int = -1
private var vectorDrawable: VectorDrawable? = null
companion object {
fun fromJson(jsonObject: JSONObject, context: Context): Rectangle {
val rectangle = Rectangle(pointFromJson(jsonObject.getJSONObject("topLeft")),
pointFromJson(jsonObject.getJSONObject("bottomRight")),
paintFromJson(jsonObject.getJSONObject("paint")),
jsonObject.getString("tag"))
if(jsonObject.has("drawable")) {
rectangle.setVectorDrawable(jsonObject.getInt("drawable"), context)
}
return rectangle
}
}
fun setVectorDrawable(vectorDrawableInt: Int, context: Context) {
this.vectorDrawableInt = vectorDrawableInt
vectorDrawable = context.resources.getDrawable(vectorDrawableInt, context.theme) as VectorDrawable?
}
fun getVectorDrawable() = vectorDrawable
override fun getCopy(): Simple {
return Rectangle(PointF(topLeft.x, topLeft.y),
PointF(bottomRight.x, bottomRight.y),
paint,
tag)
}
override fun getSimpleName() = "Rectangle"
override fun toJson()= JSONObject().also {
it.put("topLeft", pointToJson(topLeft))
it.put("bottomRight", pointToJson(bottomRight))
it.put("paint", paintToJson(paint))
if(vectorDrawableInt != -1) {
it.put("drawable", vectorDrawableInt)
}
it.put("tag", tag)
}
}
| 0
|
Kotlin
|
0
| 1
|
9e5932bdc912cd1a6a816c36bd90fed390d8fe4e
| 1,987
|
android-animated-stick-view
|
Apache License 2.0
|
ktor-server/ktor-server-host-common/jvm/src/io/ktor/server/engine/ClassLoaders.kt
|
ktorio
| 40,136,600
| false
| null |
/*
* Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.server.engine
import java.lang.reflect.*
import java.net.*
internal fun ClassLoader.allURLs(): Set<URL> {
val parentUrls = parent?.allURLs() ?: emptySet()
if (this is URLClassLoader) {
val urls = urLs.filterNotNull().toSet()
return urls + parentUrls
}
val ucp = urlClassPath() ?: return parentUrls
return parentUrls + ucp
}
/**
* This only works in JDK9+ with VM option `--add-opens java.base/jdk.internal.loader=ALL-UNNAMED`
* This is required since [allURLs] function is unable to lookup url list due to modules and class loaders
* reorganisation in JDK9+. However, if failed, it fallbacks to [urlClassPathByPackagesList] implementation
* that should always work.
*/
private fun ClassLoader.urlClassPath(): List<URL>? {
try {
val ucpField = javaClass.findURLClassPathField() ?: return null
ucpField.isAccessible = true
val ucpInstance = ucpField.get(this) ?: return null
val getURLsMethod = ucpInstance.javaClass.getMethod("getURLs") ?: return null
getURLsMethod.isAccessible = true
@Suppress("UNCHECKED_CAST")
val urls = getURLsMethod.invoke(ucpInstance) as Array<URL>?
return urls?.toList()
} catch (_: Throwable) {
return try {
urlClassPathByPackagesList()
} catch (_: Throwable) {
null
}
}
}
/**
* Extract classloader's packages list and guess URLs by package segments.
* Unlike the old way, this doesn't require any black magic so works well on all JDKs
* from JDK6 to the latest.
*/
private fun ClassLoader.urlClassPathByPackagesList(): List<URL>? {
val allPackagePaths = ClassLoaderDelegate(this).packagesList().map { it.replace('.', '/') }
.flatMapTo(HashSet<String>()) { packageName ->
val segments = packageName.split('/')
(1..segments.size).map { segments.subList(0, it).joinToString("/") } + packageName
}.sortedBy { it.count { character -> character == '/' } } + ""
return allPackagePaths.flatMap { path -> getResources(path)?.toList() ?: emptyList() }
.distinctBy { it.path.substringBefore('!') }
}
private fun Class<*>.findURLClassPathField(): Field? {
declaredFields.firstOrNull { it.name == "ucp" && it.type.simpleName == "URLClassPath" }?.let { return it }
return superclass?.findURLClassPathField() ?: return null
}
/**
* This is auxillary classloader that is not used for loading classes. The purpose is just
* to get access to [getPackages] function that is unfortunately protected.
*/
private class ClassLoaderDelegate(delegate: ClassLoader) : ClassLoader(delegate) {
internal fun packagesList(): List<String> = getPackages().map { it.name }
}
| 269
| null |
806
| 9,709
|
9e0eb99aa2a0a6bc095f162328525be1a76edb21
| 2,864
|
ktor
|
Apache License 2.0
|
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/editor/typepicker/TypePickerScreen.kt
|
Waboodoo
| 34,525,124
| false
|
{"Kotlin": 1970466, "HTML": 200869, "CSS": 2316, "Python": 1548}
|
package ch.rmy.android.http_shortcuts.activities.editor.typepicker
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.HelpOutline
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
import ch.rmy.android.http_shortcuts.R
import ch.rmy.android.http_shortcuts.components.BackButton
import ch.rmy.android.http_shortcuts.components.SimpleScaffold
import ch.rmy.android.http_shortcuts.components.ToolbarIcon
import ch.rmy.android.http_shortcuts.components.bindViewModel
import ch.rmy.android.http_shortcuts.data.domains.categories.CategoryId
@Composable
fun TypePickerScreen(
categoryId: CategoryId,
) {
val (viewModel, _) = bindViewModel<TypePickerViewModel.InitData, Unit, TypePickerViewModel>(
TypePickerViewModel.InitData(categoryId)
)
SimpleScaffold(
viewState = Unit,
title = stringResource(R.string.create_shortcut),
backButton = BackButton.ARROW,
actions = {
ToolbarIcon(
Icons.AutoMirrored.Filled.HelpOutline,
contentDescription = stringResource(R.string.button_show_help),
onClick = viewModel::onHelpButtonClicked,
)
},
) {
TypePickerContent(
onShortcutTypeSelected = viewModel::onCreationDialogOptionSelected,
onCurlImportSelected = viewModel::onCurlImportOptionSelected,
)
}
}
| 26
|
Kotlin
|
105
| 999
|
34ec1652d431d581c3c275335eb4dbcf24ced9f5
| 1,461
|
HTTP-Shortcuts
|
MIT License
|
src/app/src/main/java/com/huawei/cardreader/kotlin/scannedcardlist/activity/ScannedCardListActivity.kt
|
huaweicodelabs
| 449,227,900
| false
|
{"Java": 206242, "Kotlin": 172491}
|
/*
* Copyright (c) Huawei Technologies Co., Ltd. 2020-2021. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.huawei.cardreader.kotlin.scannedcardlist.activity
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.os.AsyncTask
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import com.huawei.cardreader.R
import com.huawei.cardreader.databinding.ActivityQrCodeGeneratorMainBinding
import com.huawei.cardreader.kotlin.bankcardscan.activity.BankCard
import com.huawei.cardreader.kotlin.generalcardscan.activity.GeneralCardActivity
import com.huawei.cardreader.kotlin.scannedcardlist.adapter.BankCardListAdapter
import com.huawei.cardreader.kotlin.scannedcardlist.adapter.BankCardListAdapter.BankAdapterCallback
import com.huawei.cardreader.kotlin.scannedcardlist.adapter.GeneralcardListAdapter
import com.huawei.cardreader.kotlin.scannedcardlist.adapter.GeneralcardListAdapter.AdapterCallback
import com.huawei.cardreader.kotlin.scannedcardlist.model.QRcodmodel
import com.huawei.cardreader.kotlin.scannedcardlist.roomdb.BusinessCardEntity
import com.huawei.cardreader.kotlin.scannedcardlist.roomdb.DatabaseClient.Companion.getInstance
import com.huawei.cardreader.kotlin.utils.Constants
import com.huawei.cardreader.kotlin.utils.Constants.CARD_TYPE_TO_SAVE
import com.huawei.cardreader.kotlin.utils.Constants.IS_DELETED
import com.huawei.cardreader.kotlin.utils.DataConverter.deCodeString
import com.huawei.hms.hmsscankit.ScanUtil
import com.huawei.hms.hmsscankit.WriterException
import com.huawei.hms.ml.scan.HmsBuildBitmapOption
import com.huawei.hms.ml.scan.HmsScan
import java.util.*
/**
* The type Qr code generator main activity.
*/
class ScannedCardListActivity : AppCompatActivity(), AdapterCallback,
BankAdapterCallback {
private val type = HmsScan.QRCODE_SCAN_TYPE
private var cardType: String? = null
private var mActivityQrCodeGeneratorMainBinding: ActivityQrCodeGeneratorMainBinding? =
null
private var shouldExecuteOnResume = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mActivityQrCodeGeneratorMainBinding =
DataBindingUtil.setContentView(this, R.layout.activity_qr_code_generator_main)
Objects.requireNonNull(supportActionBar)?.setDisplayHomeAsUpEnabled(true)
shouldExecuteOnResume = false
initComponent()
}
/* Initialize component and fetch datas from local room db**/
private fun initComponent() {
if (intent.getStringExtra(CARD_TYPE_TO_SAVE) != null) {
cardType = intent.getStringExtra(CARD_TYPE_TO_SAVE)
}
mActivityQrCodeGeneratorMainBinding!!.relScan.setOnClickListener { view: View? ->
openScannerActivity() }
mActivityQrCodeGeneratorMainBinding!!.relBottomScan.setOnClickListener { view: View? ->
openScannerActivity() }
datafromRoomdb
}
/**
* Navigate to respective activity from list of cards screen
*/
private fun openScannerActivity() {
if (cardType.equals(
Constants.BANKCARD,
ignoreCase = true
)
) {
val intent = Intent(this@ScannedCardListActivity, BankCard::class.java)
startActivity(intent)
} else {
val intent =
Intent(this@ScannedCardListActivity, GeneralCardActivity::class.java)
startActivity(intent)
}
}
/**
* Retrive card details data from room db
*/
private val datafromRoomdb: Unit
private get() {
@SuppressLint("StaticFieldLeak")
class GetTasks :
AsyncTask<Void?, Void?, List<BusinessCardEntity?>?>() {
override fun doInBackground(vararg voids: Void?): List<BusinessCardEntity?>? {
return allCards
}
override fun onPostExecute(tasks: List<BusinessCardEntity?>?) {
super.onPostExecute(tasks)
val businessCardEntityList: MutableList<BusinessCardEntity> =
ArrayList()
val bankCardEntityList: MutableList<BusinessCardEntity> =
ArrayList()
val options = HmsBuildBitmapOption.Creator()
.setBitmapMargin(0).create()
setCardDetails(
tasks, businessCardEntityList, bankCardEntityList,
options
)
}
}
val gt = GetTasks()
gt.execute()
}
private fun setCardDetails(
tasks: List<BusinessCardEntity?>?,
businessCardEntityList: MutableList<BusinessCardEntity>,
bankCardEntityList: MutableList<BusinessCardEntity>,
options: HmsBuildBitmapOption
) {
var stringBuilder: StringBuilder
val dataset = ArrayList<QRcodmodel>()
val dataset1 = ArrayList<QRcodmodel>()
var qrBitmap: Bitmap?
val width = 200
val height = 200
try {
for (i in tasks!!.indices) {
val qRcodmodel = QRcodmodel()
val userDetails = BusinessCardEntity()
if (tasks[i]!!.cardType.equals(
Constants.BUSINESS_CARD,
ignoreCase = true
)
) {
userDetails.id = tasks[i]!!.id
userDetails.name = tasks[i]!!.name
userDetails.mobileno = tasks[i]!!.mobileno
userDetails.companyname = tasks[i]!!.companyname
userDetails.emailid = tasks[i]!!.emailid
userDetails.address = tasks[i]!!.address
userDetails.website = tasks[i]!!.website
userDetails.jobtitle = tasks[i]!!.jobtitle
userDetails.image = tasks[i]!!.image
userDetails.cardType = tasks[i]!!.cardType
businessCardEntityList.add(userDetails)
stringBuilder = StringBuilder()
stringBuilder.append(resources.getString(R.string.qrName))
.append(deCodeString(userDetails.name!!))
.append(System.lineSeparator())
stringBuilder.append(resources.getString(R.string.qrMobileno))
.append(deCodeString(userDetails.mobileno!!))
.append(System.lineSeparator())
stringBuilder.append(resources.getString(R.string.qrCompanyName))
.append(deCodeString(userDetails.companyname!!))
.append(System.lineSeparator())
stringBuilder.append(resources.getString(R.string.qrEmailId))
.append(deCodeString(userDetails.emailid!!))
.append(System.lineSeparator())
stringBuilder.append(resources.getString(R.string.qrCardType))
.append(userDetails.cardType).append(System.lineSeparator())
qrBitmap =
ScanUtil.buildBitmap(stringBuilder.toString(), type, width, height, options)
qRcodmodel.businesscardUserDetailsList = businessCardEntityList
qRcodmodel.bitmap = qrBitmap
dataset.add(qRcodmodel)
} else if (tasks[i]!!.cardType.equals(
Constants.AADHARCARD,
ignoreCase = true
)
) {
userDetails.id = tasks[i]!!.id
userDetails.name = tasks[i]!!.name
userDetails.aadharid = tasks[i]!!.aadharid
userDetails.gender = tasks[i]!!.gender
userDetails.fathername = tasks[i]!!.fathername
userDetails.dob = tasks[i]!!.dob
userDetails.address = tasks[i]!!.address
userDetails.cardType = tasks[i]!!.cardType
userDetails.image = tasks[i]!!.image
businessCardEntityList.add(userDetails)
stringBuilder = StringBuilder()
stringBuilder.append(resources.getString(R.string.qrName))
.append(deCodeString(userDetails.name!!))
.append(System.lineSeparator())
stringBuilder.append(resources.getString(R.string.qrCardType))
.append(userDetails.cardType).append(System.lineSeparator())
stringBuilder.append(resources.getString(R.string.qrAadhaarId))
.append(deCodeString(userDetails.aadharid!!))
.append(System.lineSeparator())
stringBuilder.append(resources.getString(R.string.qrDOB))
.append(deCodeString(userDetails.dob!!))
.append(System.lineSeparator())
qrBitmap =
ScanUtil.buildBitmap(stringBuilder.toString(), type, width, height, options)
qRcodmodel.businesscardUserDetailsList = businessCardEntityList
qRcodmodel.bitmap = qrBitmap
dataset.add(qRcodmodel)
} else if (tasks[i]!!.cardType.equals(
Constants.PANCARD,
ignoreCase = true
)
) {
userDetails.id = tasks[i]!!.id
userDetails.name = tasks[i]!!.name
userDetails.pannumber = tasks[i]!!.pannumber
userDetails.fathername = tasks[i]!!.fathername
userDetails.dob = tasks[i]!!.dob
userDetails.cardType = tasks[i]!!.cardType
userDetails.image = tasks[i]!!.image
businessCardEntityList.add(userDetails)
stringBuilder = StringBuilder()
stringBuilder.append(resources.getString(R.string.qrName))
.append(deCodeString(userDetails.name!!))
.append(System.lineSeparator())
stringBuilder.append(resources.getString(R.string.qrCardType))
.append(userDetails.cardType).append(System.lineSeparator())
stringBuilder.append(resources.getString(R.string.qrPanNumber))
.append(deCodeString(userDetails.pannumber!!))
.append(System.lineSeparator())
stringBuilder.append(resources.getString(R.string.qrDOB))
.append(deCodeString(userDetails.dob!!))
.append(System.lineSeparator())
qrBitmap =
ScanUtil.buildBitmap(stringBuilder.toString(), type, width, height, options)
qRcodmodel.businesscardUserDetailsList = businessCardEntityList
qRcodmodel.bitmap = qrBitmap
dataset.add(qRcodmodel)
} else {
userDetails.id = tasks[i]!!.id
userDetails.name = tasks[i]!!.name
userDetails.accountnumber = tasks[i]!!.accountnumber
userDetails.cardType = tasks[i]!!.cardType
userDetails.issuer = tasks[i]!!.issuer
userDetails.expirydate = tasks[i]!!.expirydate
userDetails.banktype = tasks[i]!!.banktype
userDetails.bankorganization = tasks[i]!!.bankorganization
userDetails.image = tasks[i]!!.image
bankCardEntityList.add(userDetails)
stringBuilder = StringBuilder()
stringBuilder.append(resources.getString(R.string.qrName))
.append(deCodeString(userDetails.name!!))
.append(System.lineSeparator())
stringBuilder.append(resources.getString(R.string.qrAcNumber))
.append(deCodeString(userDetails.accountnumber!!))
.append(System.lineSeparator())
stringBuilder.append(resources.getString(R.string.qrCardType))
.append(userDetails.cardType).append(System.lineSeparator())
stringBuilder.append(resources.getString(R.string.qrIssuer))
.append(userDetails.issuer).append(System.lineSeparator())
stringBuilder.append(resources.getString(R.string.qrBankType))
.append(userDetails.banktype).append(System.lineSeparator())
stringBuilder.append(resources.getString(R.string.qrExpiryDate))
.append(deCodeString(userDetails.expirydate!!))
.append(System.lineSeparator())
stringBuilder.append(resources.getString(R.string.qrBankOrganization))
.append(
deCodeString(userDetails.bankorganization!!)
).append(System.lineSeparator())
qrBitmap =
ScanUtil.buildBitmap(stringBuilder.toString(), type, width, height, options)
qRcodmodel.businesscardUserDetailsList = bankCardEntityList
qRcodmodel.bitmap = qrBitmap
dataset1.add(qRcodmodel)
}
}
} catch (e: WriterException) {
}
initRecyclerview(dataset, dataset1, cardType)
}
private val allCards: List<BusinessCardEntity?>?
get() = getInstance(applicationContext)
?.appDatabase
?.businessCardEntityDao()!!.all
/*Initialize Generlcards and Bankcard recyclerview**/
private fun initRecyclerview(
dataset: ArrayList<QRcodmodel>?,
dataset1: ArrayList<QRcodmodel>?,
cardType: String?
) {
if (cardType.equals(
Constants.BANKCARD,
ignoreCase = true
)
) {
if (dataset1 != null && dataset1.size > 0) {
val mBankCardListAdapter = BankCardListAdapter(this, dataset1)
mBankCardListAdapter.setmBankAdapterCallback(this)
mActivityQrCodeGeneratorMainBinding!!.bankcardRecyclerview.visibility = View.VISIBLE
mActivityQrCodeGeneratorMainBinding!!.bankcardRecyclerview.setHasFixedSize(true)
mActivityQrCodeGeneratorMainBinding!!.bankcardRecyclerview.layoutManager =
LinearLayoutManager(this)
mActivityQrCodeGeneratorMainBinding!!.bankcardRecyclerview.adapter =
mBankCardListAdapter
} else {
mActivityQrCodeGeneratorMainBinding!!.liListempty.visibility = View.VISIBLE
mActivityQrCodeGeneratorMainBinding!!.relBottomScan.visibility = View.GONE
}
} else {
if (dataset != null && dataset.size > 0) {
val mAdapter = GeneralcardListAdapter(this, dataset)
mAdapter.setmAdapterCallback(this)
mActivityQrCodeGeneratorMainBinding!!.recyclerView.visibility = View.VISIBLE
mActivityQrCodeGeneratorMainBinding!!.recyclerView.setHasFixedSize(true)
mActivityQrCodeGeneratorMainBinding!!.recyclerView.layoutManager =
LinearLayoutManager(this)
mActivityQrCodeGeneratorMainBinding!!.recyclerView.adapter = mAdapter
} else {
mActivityQrCodeGeneratorMainBinding!!.liListempty.visibility = View.VISIBLE
mActivityQrCodeGeneratorMainBinding!!.relBottomScan.visibility = View.GONE
}
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.itemId
if (id == android.R.id.home) {
onBackPressed()
return true
}
return super.onOptionsItemSelected(item)
}
override fun onResume() {
super.onResume()
if (shouldExecuteOnResume) {
datafromRoomdb
} else {
shouldExecuteOnResume = true
}
}
override fun onMethodCallback(id: Int) {
@SuppressLint("StaticFieldLeak")
class DeleteTask :
AsyncTask<Void?, Void?, Int>() {
protected override fun doInBackground(vararg voids: Void?): Int {
getInstance(applicationContext)!!.appDatabase
?.businessCardEntityDao()
?.deleteById(id)
return 0
}
override fun onPostExecute(aVoid: Int) {
super.onPostExecute(aVoid)
if (IS_DELETED) {
mActivityQrCodeGeneratorMainBinding!!.liListempty.visibility = View.VISIBLE
mActivityQrCodeGeneratorMainBinding!!.relBottomScan.visibility = View.GONE
}
}
}
val st = DeleteTask()
st.execute()
}
}
| 1
| null |
1
| 1
|
4d838e3b78fda9ae967ab03067254b998b206ee9
| 17,941
|
CardReader
|
Apache License 2.0
|
src/main/java/org/samoxive/safetyjim/config/Config.kt
|
SosiskaDBMG
| 195,842,972
| true
|
{"Kotlin": 184566, "Python": 1253}
|
package org.samoxive.safetyjim.config
import com.uchuhimo.konf.ConfigSpec
object JimConfig : ConfigSpec("jim") {
val version by required<String>()
val token by required<String>()
val default_prefix by required<String>()
val shard_count by required<Int>()
}
object DatabaseConfig : ConfigSpec("database") {
val user by required<String>()
val pass by required<String>()
val host by required<String>()
val port by required<Int>()
val database by required<String>()
val jdbc_url by required<String>()
}
object OauthConfig : ConfigSpec("oauth") {
val client_id by required<String>()
val client_secret by required<String>()
val redirect_uri by required<String>()
}
object ServerConfig : ConfigSpec("server") {
val self_url by required<String>()
val recaptcha_secret by required<String>()
val secret by required<String>()
val port by required<Int>()
}
| 0
|
Kotlin
|
0
| 0
|
c585de5f5b66f7d5275fed094076b593fddc72ed
| 918
|
SafetyJim
|
MIT License
|
kachetor/src/androidMain/kotlin/com/vipulasri/kachetor/FileSystemProvider.android.kt
|
vipulasri
| 754,452,913
| false
|
{"Kotlin": 27843}
|
/*
* Copyright 2024 Vipul Asri
*
* 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.vipulasri.kachetor
import android.content.Context
import okio.FileSystem
import okio.Path
import okio.Path.Companion.toPath
import java.util.concurrent.atomic.AtomicReference
internal actual object FileSystemProvider {
private var context = AtomicReference<Context>(null)
fun initialize(context: Context?) {
this.context.set(context)
}
actual val fileSystem: FileSystem
get() = FileSystem.SYSTEM
actual val cacheDirectoryPath: Path?
get() = context.get().cacheDir.absolutePath.toPath()
}
| 0
|
Kotlin
|
0
| 12
|
cc228665de4da48fba1ce74a38a8e6e2ba72f27e
| 1,144
|
kachetor
|
Apache License 2.0
|
app/src/main/java/com/theone/demo/ui/fragment/project/ProjectFragment.kt
|
Theoneee
| 473,409,123
| false
|
{"Kotlin": 616409, "Java": 410498}
|
package com.theone.demo.ui.fragment.project
import android.content.Context
import androidx.lifecycle.Observer
import com.qmuiteam.qmui.arch.QMUIFragment
import com.theone.common.ext.appViewModels
import com.theone.demo.ui.fragment.gzh.WxGzhItemFragment
import com.theone.demo.viewmodel.AppViewModel
import com.theone.demo.viewmodel.ProjectViewModel
import com.theone.mvvm.core.base.fragment.BaseTabInTitleFragment
import com.theone.mvvm.core.data.entity.QMUIItemBean
import com.theone.mvvm.core.app.ext.qmui.addTab
import com.theone.mvvm.core.app.ext.showErrorPage
import com.theone.mvvm.core.app.widge.indicator.SkinScaleTransitionPagerTitleView
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView
// ┏┓ ┏┓
//┏┛┻━━━┛┻┓
//┃ ┃
//┃ ━ ┃
//┃ ┳┛ ┗┳ ┃
//┃ ┃
//┃ ┻ ┃
//┃ ┃
//┗━┓ ┏━┛
// ┃ ┃ 神兽保佑
// ┃ ┃ 永无BUG!
// ┃ ┗━━━┓
// ┃ ┣┓
// ┃ ┏┛
// ┗┓┓┏━┳┓┏┛
// ┃┫┫ ┃┫┫
// ┗┻┛ ┗┻┛
/**
* @author The one
* @date 2021/3/2 0002
* @describe TODO
* @email <EMAIL>
* @remark
*/
class ProjectFragment : BaseTabInTitleFragment<ProjectViewModel>() {
private val mAppVm: AppViewModel by appViewModels()
override fun isLazyLoadData(): Boolean = false
override fun initTabAndFragments(
tabs: MutableList<QMUIItemBean>,
fragments: MutableList<QMUIFragment>
) {
if (getViewModel().isReload) {
getViewModel().wxRequest.getResponseLiveData().value?.forEach {
tabs.addTab(it.name)
fragments.add(
WxGzhItemFragment.newInstance(
it.id
)
)
}
} else {
getViewModel().getRequest().getResponseLiveData().value?.forEach {
tabs.addTab(it.name)
fragments.add(
ProjectItemFragment.newInstance(
it.id
)
)
}
}
}
override fun createObserver() {
getViewModel().wxRequest.run {
getResponseLiveData().observe(this@ProjectFragment, Observer {
startInit()
})
getErrorLiveData().observe(this@ProjectFragment, Observer {
showErrorPage(it.msg) {
onPageReLoad()
}
})
}
getViewModel().getRequest().run {
getResponseLiveData().observe(this@ProjectFragment, Observer {
startInit()
})
getErrorLiveData().observe(this@ProjectFragment, Observer {
showErrorPage(it.msg) {
onPageReLoad()
}
})
}
mAppVm.notifyFragment.observe(this) {
getViewModel().isReload = !getViewModel().isReload
onPageReLoad()
}
}
override fun getPagerTitleView(context: Context): SimplePagerTitleView {
return SkinScaleTransitionPagerTitleView(context)
}
override fun getNavIndicator(context: Context): IPagerIndicator? = null
override fun isNeedChangeStatusBarMode(): Boolean = true
}
| 0
|
Kotlin
|
4
| 6
|
66e7dd671635352c8039bc3bf47a715620347448
| 3,321
|
QMUI-MVVM
|
Apache License 2.0
|
educational-core/src/com/jetbrains/edu/learning/newproject/ui/coursePanel/ErrorStateHyperlinkListener.kt
|
renuacpro
| 390,257,792
| true
|
{"Kotlin": 3480129, "HTML": 1875210, "Java": 531269, "CSS": 12158, "Python": 5553, "JavaScript": 315}
|
package com.jetbrains.edu.learning.newproject.ui.coursePanel
import com.intellij.ide.DataManager
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.PluginsAdvertiser
import com.intellij.util.ui.UIUtil
import com.jetbrains.edu.learning.EduLogInListener
import com.jetbrains.edu.learning.EduNames
import com.jetbrains.edu.learning.EduSettings
import com.jetbrains.edu.learning.EduUtils
import com.jetbrains.edu.learning.actions.SwitchTaskPanelAction
import com.jetbrains.edu.learning.checkio.CheckiOConnectorProvider
import com.jetbrains.edu.learning.checkio.courseFormat.CheckiOCourse
import com.jetbrains.edu.learning.courseFormat.ext.configurator
import com.jetbrains.edu.learning.newproject.ui.CoursesPanel
import com.jetbrains.edu.learning.newproject.ui.ErrorState
import com.jetbrains.edu.learning.newproject.ui.browseHyperlink
import com.jetbrains.edu.learning.statistics.EduCounterUsageCollector
import com.jetbrains.edu.learning.stepik.StepikAuthorizer
import com.jetbrains.edu.learning.stepik.StepikNames
import com.jetbrains.edu.learning.stepik.hyperskill.api.HyperskillConnector
import javax.swing.JTextPane
import javax.swing.event.HyperlinkEvent
import javax.swing.event.HyperlinkListener
class ErrorStateHyperlinkListener : HyperlinkListener {
override fun hyperlinkUpdate(e: HyperlinkEvent?) {
if (e?.eventType != HyperlinkEvent.EventType.ACTIVATED) return
val coursePanel = UIUtil.getParentOfType(CoursePanel::class.java, e?.source as? JTextPane) ?: return
val coursesPanel = UIUtil.getParentOfType(CoursesPanel::class.java, e?.source as? JTextPane) ?: return
when (val state = coursePanel.errorState) {
is ErrorState.CheckiOLoginRequired -> {
val course = coursePanel.course as CheckiOCourse
addCheckiOLoginListener(coursePanel, coursesPanel)
//for Checkio course name matches platform name
EduCounterUsageCollector.loggedIn(course.name, EduCounterUsageCollector.AuthorizationPlace.START_COURSE_DIALOG)
}
is ErrorState.JetBrainsAcademyLoginNeeded -> {
addLoginListener(coursePanel, coursesPanel)
HyperskillConnector.getInstance().doAuthorize(
Runnable { coursePanel.hideErrorPanel() },
Runnable { coursesPanel.setButtonsEnabled(true) },
Runnable { coursesPanel.hideLoginPanel() },
Runnable { coursesPanel.scheduleUpdateAfterLogin() }
)
}
is ErrorState.StepikLoginRequired, ErrorState.NotLoggedIn -> {
addLoginListener(coursePanel, coursesPanel)
// TODO: Update course list
StepikAuthorizer.doAuthorize { EduUtils.showOAuthDialog() }
EduCounterUsageCollector.loggedIn(StepikNames.STEPIK, EduCounterUsageCollector.AuthorizationPlace.START_COURSE_DIALOG)
}
ErrorState.JCEFRequired -> invokeSwitchUILibrary(coursePanel)
ErrorState.IncompatibleVersion -> PluginsAdvertiser.installAndEnable(setOf(PluginId.getId(EduNames.PLUGIN_ID))) {}
is ErrorState.RequirePlugins -> {
val pluginStringIds = state.pluginIds.mapTo(HashSet()) { it.id }
PluginsAdvertiser.installAndEnable(pluginStringIds) {}
}
ErrorState.RestartNeeded -> {
DialogWrapper.findInstance(coursesPanel)?.close(DialogWrapper.OK_EXIT_CODE)
ApplicationManager.getApplication().exit(true, true, true)
}
is ErrorState.CustomSevereError -> state.action?.run()
else -> browseHyperlink(state.message)
}
}
private fun addCheckiOLoginListener(coursePanel: CoursePanel, coursesPanel: CoursesPanel) {
val course = coursePanel.course
val checkiOConnectorProvider = (course?.configurator as CheckiOConnectorProvider?)!!
val checkiOOAuthConnector = checkiOConnectorProvider.oAuthConnector
checkiOOAuthConnector.doAuthorize(
Runnable { coursesPanel.hideLoginPanel() },
Runnable { coursePanel.hideErrorPanel() },
Runnable { doValidation(coursePanel) }
)
}
private fun addLoginListener(coursePanel: CoursePanel, coursesPanel: CoursesPanel) {
val connection = ApplicationManager.getApplication().messageBus.connect()
connection.subscribe(EduSettings.SETTINGS_CHANGED, object : EduLogInListener {
override fun userLoggedOut() {}
override fun userLoggedIn() {
coursePanel.hideErrorPanel()
coursesPanel.hideLoginPanel()
doValidation(coursePanel)
connection.disconnect()
coursesPanel.scheduleUpdateAfterLogin()
}
})
}
private fun invokeSwitchUILibrary(coursePanel: CoursePanel) {
val switchUILibraryAction = SwitchTaskPanelAction.ACTION_ID
val action = ActionManager.getInstance().getAction(switchUILibraryAction)
if (action == null) {
Logger.getInstance(CoursesPanel::class.java).error("$switchUILibraryAction action not found")
return
}
action.actionPerformed(
AnActionEvent.createFromAnAction(
action, null,
ActionPlaces.UNKNOWN,
DataManager.getInstance().getDataContext(coursePanel)
)
)
doValidation(coursePanel)
}
private fun doValidation(coursePanel: CoursePanel) {
var languageError: ErrorState = ErrorState.NothingSelected
val course = coursePanel.course
if (course != null) {
val languageSettingsMessage = coursePanel.validateSettings(course)
languageError = languageSettingsMessage?.let { ErrorState.LanguageSettingsError(it) } ?: ErrorState.None
}
val errorState = ErrorState.forCourse(course).merge(languageError)
coursePanel.setError(errorState)
coursePanel.setButtonsEnabled(errorState.courseCanBeStarted)
}
}
| 0
| null |
0
| 0
|
5088a2c364cb296220bff2937e91babc40d76632
| 5,970
|
educational-plugin
|
Apache License 2.0
|
module_bookshelf/src/main/kotlin/com/crow/module_bookshelf/ui/view/BaseErrorViewStub.kt
|
crowforkotlin
| 610,636,509
| false
|
{"Kotlin": 1225238, "C++": 3504, "CMake": 2776, "Makefile": 1968}
|
package com.crow.module_bookshelf.ui.view
import android.view.View
import android.view.ViewStub
import androidx.lifecycle.Lifecycle
import com.crow.base.ui.view.BaseViewStub
import com.crow.base.ui.view.IBaseViewStub
import com.crow.module_bookshelf.databinding.BookshelfLottieLayoutBinding
/*************************
* @Machine: RedmiBook Pro 15 Win11
* @Package: com.crow.base.ui.view
* @Time: 2023/10/29 21:02
* @Author: CrowForKotlin
* @Description: BaseViewStub
* @formatter:on
**************************/
class BookshelfViewStub(
viewStub: ViewStub,
lifecycle: Lifecycle,
mBinding: IBaseViewStub<BookshelfLottieLayoutBinding>
) : BaseViewStub<BookshelfLottieLayoutBinding>(
mViewStub = viewStub,
mLifecycle = lifecycle,
mOnBinding = mBinding
) {
override fun bindViewBinding(view: View): BookshelfLottieLayoutBinding { return BookshelfLottieLayoutBinding.bind(view) }
}
fun bookshelfViewStub(viewStub: ViewStub, lifecyle: Lifecycle, onLayout: (BookshelfLottieLayoutBinding) -> Unit): BookshelfViewStub {
return BookshelfViewStub(
viewStub = viewStub,
lifecycle = lifecyle,
mBinding = { _, binding ->onLayout(binding) }
)
}
| 17
|
Kotlin
|
30
| 467
|
14745e7c9125ddbac00b20365dba22b9231d51e1
| 1,200
|
CopyMangaX
|
Apache License 2.0
|
app/src/main/kotlin/taiwan/no1/app/mvp/presenters/adapter/MovieCastAdapterPresenter.kt
|
bearfong
| 88,131,690
| true
|
{"Kotlin": 306879, "Java": 197491}
|
package taiwan.no1.app.mvp.presenters.adapter
import com.hwangjr.rxbus.RxBus
import com.touchin.constant.RxbusTag
import taiwan.no1.app.api.config.TMDBConfig
import taiwan.no1.app.mvp.contracts.adapter.MovieCastAdapterContract.Presenter
import taiwan.no1.app.mvp.contracts.adapter.MovieCastAdapterContract.View
import taiwan.no1.app.mvp.models.FilmCastsModel
import taiwan.no1.app.ui.fragments.CastDetailFragment
import taiwan.no1.app.ui.fragments.ViewPagerMainCtrlFragment
/**
*
* @author Jieyi
* @since 2/21/17
*/
class MovieCastAdapterPresenter: BaseAdapterPresenter<View, FilmCastsModel.CastBean>(), Presenter {
override fun init(viewHolder: View, model: FilmCastsModel.CastBean) {
super.init(viewHolder, model)
this.viewHolder.showCastProfilePhoto(TMDBConfig.BASE_IMAGE_URL + this.model.profile_path)
this.viewHolder.showCastInfo(this.model.character.orEmpty(), this.model.name.orEmpty())
}
override fun onItemClicked(tag: Int) {
RxBus.get().post(RxbusTag.FRAGMENT_CHILD_NAVIGATOR, hashMapOf(
Pair(ViewPagerMainCtrlFragment.NAVIGATOR_ARG_FRAGMENT,
CastDetailFragment.newInstance(model.id.toString(), tag)),
Pair(ViewPagerMainCtrlFragment.NAVIGATOR_ARG_TAG, tag)))
}
}
| 0
|
Kotlin
|
0
| 0
|
95ed2604d30585a29f602d516e3889dcd7dda042
| 1,289
|
mvp-magazine
|
Apache License 2.0
|
src/main/kotlin/icu/windea/sqlfox/handler/SqlPairHandler.kt
|
DragonKnightOfBreeze
| 433,675,477
| false
| null |
package icu.windea.sqlfox.handler
import com.alibaba.druid.DbType
import icu.windea.sqlfox.defaultDbType
import icu.windea.sqlfox.getSqlHandler
class SqlPairHandler(
val sourceSql: String,
val targetSql: String,
val sourceDbType: DbType = defaultDbType,
val targetDbType: DbType = defaultDbType
){
val sourceHandler: SqlHandler = getSqlHandler(sourceSql, sourceDbType)
val targetHandler: SqlHandler = getSqlHandler(targetSql, targetDbType)
}
| 0
|
Kotlin
|
0
| 0
|
fb6de30372f17b02fe02779ae50fd0df2597c7a6
| 467
|
Sql-Fox
|
MIT License
|
app/src/androidTest/java/io/github/omisie11/coronatracker/data/local/dao/CountriesDaoTest.kt
|
OMIsie11
| 248,815,717
| false
| null |
package com.flight.louis.flighttracker.data.local.dao
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.room.Room
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import louis.flight.status.info.data.local.AppDatabase
import louis.flight.status.info.data.local.model.Country
import com.flight.louis.flighttracker.testCountry1
import com.flight.louis.flighttracker.testCountry2
import com.flight.louis.flighttracker.testCountry3
import com.flight.louis.flighttracker.testCountry4
import com.flight.louis.flighttracker.testCountry5
import com.flight.louis.flighttracker.testCountry6
import java.util.concurrent.Executors
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.take
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.TestCoroutineDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.setMain
import louis.flight.status.info.data.local.dao.CountriesDao
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@ExperimentalCoroutinesApi
@RunWith(AndroidJUnit4::class)
class CountriesDaoTest {
private lateinit var database: AppDatabase
private lateinit var countriesDao: CountriesDao
private val testDispatcher = TestCoroutineDispatcher()
private val testCountries = listOf(
testCountry3,
testCountry4,
testCountry1,
testCountry2,
testCountry5,
testCountry6
)
@get:Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()
@Before
fun setup() {
Dispatchers.setMain(testDispatcher)
val context = InstrumentationRegistry.getInstrumentation().targetContext
database = Room
.inMemoryDatabaseBuilder(context, AppDatabase::class.java)
.setTransactionExecutor(Executors.newSingleThreadExecutor())
.build()
countriesDao = database.countriesDao()
}
@After
fun cleanup() {
database.close()
Dispatchers.resetMain()
testDispatcher.cleanupTestCoroutines()
}
@Test
fun testInsertAndGetCountries() = runBlocking {
countriesDao.insert(testCountries)
val result: List<Country> = countriesDao.getCountriesFlow().take(1).toList()[0]
assertThat(result.size, equalTo(testCountries.size))
for (i in result.indices) {
assertThat(result[i].name, equalTo(testCountries[i].name))
}
}
@Test
fun testInsertAndGetCountriesNames() = runBlocking {
countriesDao.insert(testCountries)
val expected: MutableList<String> = mutableListOf()
testCountries.forEach { country ->
expected.add(country.name)
}
val result: List<String> = countriesDao.getCountriesNamesFlow().take(1).toList()[0]
assertThat(result.size, equalTo(expected.size))
for (i in result.indices) {
assertThat(result[i], equalTo(expected[i]))
}
}
@Test
fun testReplaceCountriesData() = runBlocking {
// Replace 2 times to check if there will be no duplicated data
countriesDao.replace(testCountries)
countriesDao.replace(testCountries)
val result: List<Country> = countriesDao.getCountriesFlow().take(1).toList()[0]
assertThat(result.size, equalTo(testCountries.size))
}
@Test
fun testDeleteCountries() = runBlocking {
countriesDao.replace(testCountries)
countriesDao.delete()
val result: List<Country> = countriesDao.getCountriesFlow().take(1).toList()[0]
assertThat(result.size, equalTo(0))
}
}
| 0
|
Kotlin
|
8
| 20
|
d3054dfb3bce52e4a3c33667aed2e837818a283b
| 3,908
|
CovidNow
|
Apache License 2.0
|
sample/src/main/java/com/dd/SampleApplication.kt
|
DeloitteAU
| 171,209,419
| false
|
{"Kotlin": 16059}
|
package com.dd
import android.app.Application
class SampleApplication : Application() {
override fun onCreate() {
super.onCreate()
DDMock.install(this)
}
}
| 3
|
Kotlin
|
7
| 2
|
914872f274ab5da6d8a9d2f812b7b64774287595
| 164
|
ddmock-android
|
MIT License
|
src/main/kotlin/messages/MessageLoggerPong.kt
|
FrozenTear7
| 260,285,886
| false
| null |
package messages
import genotypes.BestGenotype
class MessageLoggerPong(val bestGenotype: BestGenotype) : IMessage
| 0
|
Kotlin
|
0
| 0
|
09c3ed16dad0d647991dbc3ff99af97168701f35
| 115
|
cea-tk
|
MIT License
|
src/main/kotlin/org/rust/lang/core/types/ty/Ty.kt
|
weiyuefei
| 142,649,139
| true
|
{"Kotlin": 2750391, "Rust": 77473, "Lex": 18933, "HTML": 9582, "Shell": 760, "Java": 586, "RenderScript": 318}
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.types.ty
import com.intellij.util.BitUtil
import org.rust.ide.presentation.tyToString
import org.rust.lang.core.psi.RsStructItem
import org.rust.lang.core.psi.ext.namedFields
import org.rust.lang.core.psi.ext.positionalFields
import org.rust.lang.core.types.*
import org.rust.lang.core.types.infer.TypeFoldable
import org.rust.lang.core.types.infer.TypeFolder
import org.rust.lang.core.types.infer.TypeVisitor
import org.rust.lang.core.types.infer.substitute
/**
* Represents both a type, like `i32` or `S<Foo, Bar>`, as well
* as an unbound constructor `S`.
*
* The name `Ty` is short for `Type`, inspired by the Rust
* compiler.
*/
abstract class Ty(flags: TypeFlags = 0) : Kind(flags), TypeFoldable<Ty> {
override fun foldWith(folder: TypeFolder): Ty = folder.foldTy(this)
override fun superFoldWith(folder: TypeFolder): Ty = this
override fun visitWith(visitor: TypeVisitor): Boolean = visitor.visitTy(this)
override fun superVisitWith(visitor: TypeVisitor): Boolean = false
/**
* Bindings between formal type parameters and actual type arguments.
*/
open val typeParameterValues: Substitution get() = emptySubstitution
/**
* User visible string representation of a type
*/
final override fun toString(): String = tyToString(this)
}
enum class Mutability {
MUTABLE,
IMMUTABLE;
val isMut: Boolean get() = this == MUTABLE
companion object {
fun valueOf(mutable: Boolean): Mutability =
if (mutable) MUTABLE else IMMUTABLE
}
}
fun Ty.getTypeParameter(name: String): TyTypeParameter? {
return typeParameterValues.typeParameterByName(name)
}
val Ty.hasTyInfer
get(): Boolean = BitUtil.isSet(flags, HAS_TY_INFER_MASK)
val Ty.hasTyTypeParameters
get(): Boolean = BitUtil.isSet(flags, HAS_TY_TYPE_PARAMETER_MASK)
val Ty.hasTyProjection
get(): Boolean = BitUtil.isSet(flags, HAS_TY_PROJECTION_MASK)
val Ty.hasReEarlyBounds
get(): Boolean = BitUtil.isSet(flags, HAS_RE_EARLY_BOUND_MASK)
val Ty.needToSubstitute
get(): Boolean = hasTyTypeParameters || hasReEarlyBounds
tailrec fun Ty.isSized(): Boolean {
return when (this) {
is TyPrimitive,
is TyReference,
is TyPointer,
is TyArray,
is TyFunction -> true
is TySlice, is TyTraitObject -> false
is TyTypeParameter -> isSized
is TyAdt -> {
val item = item as? RsStructItem ?: return true
val namedFields = item.namedFields
val tupleFields = item.positionalFields
val typeRef = when {
namedFields.isNotEmpty() -> namedFields.last().typeReference
tupleFields.isNotEmpty() -> tupleFields.last().typeReference
else -> null
}
val type = typeRef?.type?.substitute(typeParameterValues) ?: return true
type.isSized()
}
is TyTuple -> types.last().isSized()
else -> true
}
}
| 0
|
Kotlin
|
0
| 0
|
faa0443ce511af60066b323f2da872a432c8d9b8
| 3,108
|
intellij-rust
|
MIT License
|
src/main/kotlin/com/icmpecho/linebot/event/model/Emoji.kt
|
icmpecho
| 273,939,908
| false
| null |
package com.icmpecho.linebot.event.model
import kotlinx.serialization.Serializable
@Serializable
data class Emoji(
val index: Int,
val length: Int,
val productId: String,
val emojiId: String
)
| 0
|
Kotlin
|
0
| 0
|
fd6ad068d91fb2c2a73884c0cef0948d935d3cf7
| 210
|
ktor-line-bot
|
MIT License
|
compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/Focusable.kt
|
RikkaW
| 389,105,112
| false
| null |
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.focus.focusModifier
import androidx.compose.ui.focus.isFocused
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.platform.debugInspectorInfo
import androidx.compose.ui.semantics.focused
import androidx.compose.ui.semantics.semantics
/**
* Configure component to be focusable via focus system or accessibility "focus" event.
*
* Add this modifier to the element to make it focusable within its bounds.
*
* @sample androidx.compose.foundation.samples.FocusableSample
*
* @param enabled Controls the enabled state. When `false`, element won't participate in the focus
* @param interactionState [InteractionState] that will be updated to contain [Interaction.Focused]
* when this focusable is focused
*/
fun Modifier.focusable(
enabled: Boolean = true,
interactionState: InteractionState? = null,
) = composed(
inspectorInfo = debugInspectorInfo {
name = "focusable"
properties["enabled"] = enabled
properties["interactionState"] = interactionState
}
) {
var isFocused by remember { mutableStateOf(false) }
DisposableEffect(Unit) {
onDispose {
interactionState?.removeInteraction(Interaction.Focused)
}
}
DisposableEffect(enabled) {
if (!enabled) {
interactionState?.removeInteraction(Interaction.Focused)
}
onDispose { }
}
if (enabled) {
Modifier
.semantics {
this.focused = isFocused
}
.onFocusChanged {
isFocused = it.isFocused
if (isFocused) {
interactionState?.addInteraction(Interaction.Focused)
} else {
interactionState?.removeInteraction(Interaction.Focused)
}
}
.focusModifier()
} else {
Modifier
}
}
| 6
| null |
482
| 7
|
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
| 2,848
|
androidx
|
Apache License 2.0
|
api-sqlite/src/test/kotlin/de/md5lukas/waypoints/api/sqlite/SQLiteWaypointTest.kt
|
Sytm
| 211,378,928
| false
|
{"Kotlin": 445837, "Java": 10057}
|
package de.md5lukas.waypoints.api.sqlite
import de.md5lukas.waypoints.api.DummyDatabaseConfiguration
import de.md5lukas.waypoints.api.FolderTest
import de.md5lukas.waypoints.api.SQLiteManager
import de.md5lukas.waypoints.api.base.DatabaseManager
class SQLiteFolderTest : FolderTest() {
override fun createDatabaseManager(): DatabaseManager {
return SQLiteManager(plugin, DummyDatabaseConfiguration, null, true)
}
}
| 3
|
Kotlin
|
8
| 28
|
b31e54acb0cb8e93c9713492b1c1a0759f1045ed
| 426
|
waypoints
|
MIT License
|
list/src/main/java/com/vip/list/listener/OnItemTouchListener.kt
|
AbnerMing888
| 581,379,171
| false
| null |
package com.vip.list.listener
import android.content.Context
import android.graphics.Rect
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import android.view.animation.LinearInterpolator
import android.widget.LinearLayout
import android.widget.Scroller
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.vip.list.R
import com.vip.list.base.BaseViewHolder
import kotlin.math.abs
/**
*AUTHOR:AbnerMing
*DATE:2022/11/10
*INTRODUCE:
*/
class OnItemTouchListener : View.OnTouchListener {
private var mScroller: Scroller? = null
private var mMaxLength: Float? = null
private var mTouchSlop: Int? = null
private var mContext: Context? = null
private var mRecyclerView: RecyclerView? = null
private var xDown = 0
private var yDown = 0
private var xMove = 0
private var yMove = 0
private var mCurSelectPosition = 0//选中的item索引
private var mIsFirst = true//记录第一次touch
private var mMoveWidth = 0//记录连续移动的长度
private var mHiddenWidth = 0//隐藏部分长度
private var mCurItemLayout: LinearLayout? = null
private var mLastItemLayout: LinearLayout? = null
/**
* AUTHOR:AbnerMing
* INTRODUCE:初始化基本信息
*/
fun init(recyclerView: RecyclerView) {
mRecyclerView = recyclerView
mContext = recyclerView.context
//滑动到最小距离
mTouchSlop = ViewConfiguration.get(mContext).scaledTouchSlop
//滑动的最大距离
mMaxLength = (180 * mContext?.resources?.displayMetrics?.density!! + 0.5f)
//初始化Scroller
mScroller = Scroller(mContext, LinearInterpolator(mContext, null))
}
override fun onTouch(p0: View?, e: MotionEvent?): Boolean {
val x = e?.x?.toInt()!!
val y = e.y.toInt()
when (e.action) {
MotionEvent.ACTION_DOWN -> {
//按下
//记录当前按下的坐标
xDown = x
yDown = y
//计算选中哪个Item
val firstPosition = (mRecyclerView?.layoutManager as LinearLayoutManager)
.findFirstVisibleItemPosition()
val itemRect = Rect()
val count: Int = mRecyclerView?.childCount!!
for (i in 0 until count) {
val child: View = mRecyclerView?.getChildAt(i)!!
if (child.visibility == View.VISIBLE) {
child.getHitRect(itemRect)
if (itemRect.contains(x, y)) {
mCurSelectPosition = firstPosition + i
break
}
}
}
if (mIsFirst) { //第一次时,不用重置上一次的Item
mIsFirst = false
} else {
//屏幕再次接收到点击时,恢复上一次Item的状态
if (mLastItemLayout != null && mMoveWidth > 0) {
//将Item右移,恢复原位
scrollRight(mLastItemLayout!!, 0 - mMoveWidth)
//清空变量
mHiddenWidth = 0
mMoveWidth = 0
}
}
//取到当前选中的Item,赋给mCurItemLayout,以便对其进行左移
val item: View = mRecyclerView?.getChildAt(mCurSelectPosition - firstPosition)!!
//获取当前选中的Item
val childViewHolder = mRecyclerView?.getChildViewHolder(item) as BaseViewHolder
// mCurItemLayout = childViewHolder.findView<LinearLayout>(R.id.ll_item)
//这里将删除按钮的宽度设为可以移动的距离
mHiddenWidth = 100
}
MotionEvent.ACTION_MOVE -> {
//移动
xMove = x
yMove = y
val dx = xMove - xDown //为负时:手指向左滑动;为正时:手指向右滑动。这与Android的屏幕坐标定义有关
val dy = yMove - yDown //
//左滑
if (dx < 0 && abs(dx) > mTouchSlop!! && abs(dy) < mTouchSlop!!) {
var newScrollX = abs(dx)
if (mMoveWidth >= mHiddenWidth) { //超过了,不能再移动了
newScrollX = 0
} else if (mMoveWidth + newScrollX > mHiddenWidth) { //这次要超了,
newScrollX = mHiddenWidth - mMoveWidth
}
//左滑,每次滑动手指移动的距离
scrollLeft(mCurItemLayout!!, newScrollX)
//对移动的距离叠加
mMoveWidth += newScrollX
} else if (dx > 0) { //右滑
//执行右滑,这里没有做跟随,瞬间恢复
mCurItemLayout?.let {
scrollRight(it, 0 - mMoveWidth)
}
mMoveWidth = 0
}
}
MotionEvent.ACTION_UP -> {
mCurItemLayout?.let {
//抬起
val scrollX = it.scrollX
if (mHiddenWidth > mMoveWidth) {
val toX = mHiddenWidth - mMoveWidth
mMoveWidth = if (scrollX > mHiddenWidth / 2) { //超过一半长度时松开,则自动滑到左侧
scrollLeft(it, toX)
mHiddenWidth
} else { //不到一半时松开,则恢复原状
scrollRight(it, 0 - mMoveWidth)
0
}
}
mLastItemLayout = it
}
}
}
return false
}
/**
* AUTHOR:AbnerMing
* INTRODUCE:向左滑动
*/
private fun scrollLeft(item: View, scrollX: Int) {
item.scrollBy(scrollX, 0)
}
/**
* AUTHOR:AbnerMing
* INTRODUCE:向右滑动
*/
private fun scrollRight(item: View, scrollX: Int) {
item.scrollBy(scrollX, 0)
}
}
| 2
| null |
3
| 42
|
a91377c5b4ceb9cca29521ecc39413cb6324c2c5
| 5,811
|
VipList
|
Apache License 2.0
|
src/main/kotlin/translations/reference/usages.kt
|
MiniDigger
| 377,270,151
| false
| null |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.translations.reference
import com.demonwav.mcdev.translations.TranslationConstants
import com.demonwav.mcdev.translations.TranslationFiles
import com.demonwav.mcdev.translations.lang.LangLexerAdapter
import com.demonwav.mcdev.translations.lang.gen.psi.LangTypes
import com.intellij.json.JsonElementTypes
import com.intellij.json.JsonLexer
import com.intellij.lang.cacheBuilder.DefaultWordsScanner
import com.intellij.lang.cacheBuilder.WordsScanner
import com.intellij.lang.findUsages.FindUsagesProvider
import com.intellij.psi.PsiElement
import com.intellij.psi.tree.TokenSet
sealed class TranslationFindUsagesProvider : FindUsagesProvider {
override fun canFindUsagesFor(element: PsiElement) =
TranslationFiles.toTranslation(element) != null && element.containingFile?.virtualFile.let {
TranslationFiles.getLocale(it) == TranslationConstants.DEFAULT_LOCALE
}
override fun getHelpId(psiElement: PsiElement): String? =
null
override fun getType(element: PsiElement) =
TranslationFiles.toTranslation(element)?.let { "translation" } ?: ""
override fun getDescriptiveName(element: PsiElement) =
TranslationFiles.toTranslation(element)?.key ?: ""
override fun getNodeText(element: PsiElement, useFullName: Boolean) =
TranslationFiles.toTranslation(element)?.let { "${it.key}=${it.text}" } ?: ""
}
class JsonFindUsagesProvider : TranslationFindUsagesProvider() {
override fun getWordsScanner(): WordsScanner? =
DefaultWordsScanner(
JsonLexer(),
TokenSet.create(JsonElementTypes.DOUBLE_QUOTED_STRING, JsonElementTypes.SINGLE_QUOTED_STRING),
TokenSet.create(JsonElementTypes.BLOCK_COMMENT, JsonElementTypes.LINE_COMMENT),
TokenSet.EMPTY
)
}
class LangFindUsagesProvider : TranslationFindUsagesProvider() {
override fun getWordsScanner(): WordsScanner? =
DefaultWordsScanner(
LangLexerAdapter(),
TokenSet.create(LangTypes.KEY),
TokenSet.create(LangTypes.COMMENT),
TokenSet.EMPTY
)
}
| 204
| null |
152
| 2
|
bd863f55119e86ad0ad005ea9a35f71da0a07f17
| 2,251
|
MinecraftDev
|
MIT License
|
src/test/kotlin/uk/gov/justice/digital/hmpps/approvedpremisesapi/integration/seed/SeedTemporaryAccommodationPremisesTest.kt
|
ministryofjustice
| 515,276,548
| false
| null |
package uk.gov.justice.digital.hmpps.approvedpremisesapi.integration
import io.github.bluegroundltd.kfactory.Factory
import io.github.bluegroundltd.kfactory.Yielded
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance
import uk.gov.justice.digital.hmpps.approvedpremisesapi.api.model.SeedFileType
import uk.gov.justice.digital.hmpps.approvedpremisesapi.seed.CsvBuilder
import uk.gov.justice.digital.hmpps.approvedpremisesapi.seed.TemporaryAccommodationPremisesSeedCsvRow
import uk.gov.justice.digital.hmpps.approvedpremisesapi.util.randomStringMultiCaseWithNumbers
@TestInstance(TestInstance.Lifecycle.PER_METHOD)
class SeedTemporaryAccommodationPremisesTest : SeedTestBase() {
@Test
fun `Attempting to create a Temporary Accommodation Premises with an invalid Probation Region logs an error`() {
withCsv(
"invalid-probation-ta",
temporaryAccommodationPremisesSeedCsvRowsToCsv(
listOf(
TemporaryAccommodationPremisesSeedCsvRowFactory()
.withProbationRegion("Not Real Region")
.produce(),
),
),
)
seedService.seedData(SeedFileType.temporaryAccommodationPremises, "invalid-probation-ta")
assertThat(logEntries).anyMatch {
it.level == "error" &&
it.message == "Error on row 1:" &&
it.throwable != null &&
it.throwable.message == "Probation Region Not Real Region does not exist"
}
}
@Test
fun `Attempting to create a Temporary Accommodation Premises with an invalid Local Authority Area logs an error`() {
val probationRegion = probationRegionEntityFactory.produceAndPersist {
withApArea(apAreaEntityFactory.produceAndPersist())
}
withCsv(
"invalid-local-authority-ta",
temporaryAccommodationPremisesSeedCsvRowsToCsv(
listOf(
TemporaryAccommodationPremisesSeedCsvRowFactory()
.withProbationRegion(probationRegion.name)
.withLocalAuthorityArea("Not Real Authority")
.produce(),
),
),
)
seedService.seedData(SeedFileType.temporaryAccommodationPremises, "invalid-local-authority-ta")
assertThat(logEntries).anyMatch {
it.level == "error" &&
it.message == "Error on row 1:" &&
it.throwable != null &&
it.throwable.message == "Local Authority Area Not Real Authority does not exist"
}
}
@Test
fun `Creating a new Temporary Accommodation Premises persists correctly`() {
val probationRegion = probationRegionEntityFactory.produceAndPersist {
withApArea(apAreaEntityFactory.produceAndPersist())
}
val probationDeliveryUnit = probationDeliveryUnitFactory.produceAndPersist {
withProbationRegion(probationRegion)
}
val localAuthorityArea = localAuthorityEntityFactory.produceAndPersist()
val csvRow = TemporaryAccommodationPremisesSeedCsvRowFactory()
.withProbationRegion(probationRegion.name)
.withLocalAuthorityArea(localAuthorityArea.name)
.withPdu(probationDeliveryUnit.name)
.withCharacteristics(listOf("Park nearby", "Pub nearby"))
.produce()
withCsv(
"new-ta-premises",
temporaryAccommodationPremisesSeedCsvRowsToCsv(
listOf(
csvRow,
),
),
)
seedService.seedData(SeedFileType.temporaryAccommodationPremises, "new-ta-premises")
val persistedPremises = temporaryAccommodationPremisesRepository.findByName(csvRow.name)
assertThat(persistedPremises).isNotNull
assertThat(persistedPremises!!.addressLine1).isEqualTo(csvRow.addressLine1)
assertThat(persistedPremises.addressLine2).isEqualTo(csvRow.addressLine2)
assertThat(persistedPremises.town).isEqualTo(csvRow.town)
assertThat(persistedPremises.postcode).isEqualTo(csvRow.postcode)
assertThat(persistedPremises.probationRegion.name).isEqualTo(csvRow.probationRegion)
assertThat(persistedPremises.localAuthorityArea!!.name).isEqualTo(csvRow.localAuthorityArea)
assertThat(persistedPremises.probationDeliveryUnit!!.name).isEqualTo(csvRow.pdu)
assertThat(persistedPremises.characteristics.map { it.name }).isEqualTo(csvRow.characteristics)
assertThat(persistedPremises.notes).isEqualTo(csvRow.notes)
}
@Test
fun `Updating an existing Temporary Accommodation Premises persists correctly`() {
val originalProbationRegion = probationRegionEntityFactory.produceAndPersist {
withApArea(apAreaEntityFactory.produceAndPersist())
}
val originalProbationDeliveryUnit = probationDeliveryUnitFactory.produceAndPersist {
withProbationRegion(originalProbationRegion)
}
val updatedProbationRegion = probationRegionEntityFactory.produceAndPersist {
withApArea(apAreaEntityFactory.produceAndPersist())
}
val updateProbationDeliveryUnit = probationDeliveryUnitFactory.produceAndPersist {
withProbationRegion(updatedProbationRegion)
}
val originalLocalAuthorityArea = localAuthorityEntityFactory.produceAndPersist()
val updatedLocalAuthorityArea = localAuthorityEntityFactory.produceAndPersist()
val existingPremises = temporaryAccommodationPremisesEntityFactory.produceAndPersist {
withName("ta-premises-to-update")
withProbationRegion(originalProbationRegion)
withLocalAuthorityArea(originalLocalAuthorityArea)
withProbationDeliveryUnit(originalProbationDeliveryUnit)
}
val csvRow = TemporaryAccommodationPremisesSeedCsvRowFactory()
.withName(existingPremises.name)
.withProbationRegion(updatedProbationRegion.name)
.withLocalAuthorityArea(updatedLocalAuthorityArea.name)
.withPdu(updateProbationDeliveryUnit.name)
.withCharacteristics(listOf("Park nearby"))
.produce()
withCsv(
"update-ta-premises",
temporaryAccommodationPremisesSeedCsvRowsToCsv(
listOf(
csvRow,
),
),
)
seedService.seedData(SeedFileType.temporaryAccommodationPremises, "update-ta-premises")
val persistedPremises = temporaryAccommodationPremisesRepository.findByName(csvRow.name)
assertThat(persistedPremises).isNotNull
assertThat(persistedPremises!!.addressLine1).isEqualTo(csvRow.addressLine1)
assertThat(persistedPremises.addressLine2).isEqualTo(csvRow.addressLine2)
assertThat(persistedPremises.town).isEqualTo(csvRow.town)
assertThat(persistedPremises.postcode).isEqualTo(csvRow.postcode)
assertThat(persistedPremises.probationRegion.name).isEqualTo(csvRow.probationRegion)
assertThat(persistedPremises.localAuthorityArea!!.name).isEqualTo(csvRow.localAuthorityArea)
assertThat(persistedPremises.probationDeliveryUnit!!.name).isEqualTo(csvRow.pdu)
assertThat(persistedPremises.characteristics.map { it.name }).isEqualTo(csvRow.characteristics)
assertThat(persistedPremises.notes).isEqualTo(csvRow.notes)
}
private fun temporaryAccommodationPremisesSeedCsvRowsToCsv(rows: List<TemporaryAccommodationPremisesSeedCsvRow>): String {
val builder = CsvBuilder()
.withUnquotedFields(
"Property reference",
"Address Line 1",
"Address Line 2 (optional)",
"City/Town",
"Postcode",
"Region",
"Local authority / Borough",
"Probation delivery unit (PDU)",
// Sample of characteristics
"Pub nearby",
"Park nearby",
"School nearby",
// Sample of characteristics
"Optional notes",
)
.newRow()
rows.forEach {
builder
.withQuotedField(it.name)
.withQuotedField(it.addressLine1)
.withQuotedField(it.addressLine2 ?: "")
.withQuotedField(it.town ?: "")
.withQuotedField(it.postcode)
.withQuotedField(it.probationRegion)
.withQuotedField(it.localAuthorityArea)
.withQuotedField(it.pdu)
.withUnquotedField(it.characteristics.contains("Pub nearby").toString().uppercase())
.withUnquotedField(it.characteristics.contains("Park nearby").toString().uppercase())
.withUnquotedField(it.characteristics.contains("School nearby").toString().uppercase())
.withQuotedField(it.notes)
.newRow()
}
return builder.build()
}
}
class TemporaryAccommodationPremisesSeedCsvRowFactory : Factory<TemporaryAccommodationPremisesSeedCsvRow> {
private var name: Yielded<String> = { randomStringMultiCaseWithNumbers(10) }
private var addressLine1: Yielded<String> = { randomStringMultiCaseWithNumbers(10) }
private var addressLine2: Yielded<String?> = { randomStringMultiCaseWithNumbers(10) }
private var town: Yielded<String?> = { randomStringMultiCaseWithNumbers(10) }
private var postcode: Yielded<String> = { randomStringMultiCaseWithNumbers(6) }
private var probationRegion: Yielded<String> = { randomStringMultiCaseWithNumbers(5) }
private var localAuthorityArea: Yielded<String> = { randomStringMultiCaseWithNumbers(5) }
private var pdu: Yielded<String> = { randomStringMultiCaseWithNumbers(5) }
private var characteristics: Yielded<List<String>> = { listOf() }
private var notes: Yielded<String> = { randomStringMultiCaseWithNumbers(20) }
fun withName(name: String) = apply {
this.name = { name }
}
fun withAddressLine1(addressLine1: String) = apply {
this.addressLine1 = { addressLine1 }
}
fun withAddressLine2(addressLine2: String?) = apply {
this.addressLine2 = { addressLine2 }
}
fun withTown(town: String?) = apply {
this.town = { town }
}
fun withPostcode(postcode: String) = apply {
this.postcode = { postcode }
}
fun withProbationRegion(probationRegion: String) = apply {
this.probationRegion = { probationRegion }
}
fun withLocalAuthorityArea(localAuthorityArea: String) = apply {
this.localAuthorityArea = { localAuthorityArea }
}
fun withPdu(pdu: String) = apply {
this.pdu = { pdu }
}
fun withCharacteristics(characteristics: List<String>) = apply {
this.characteristics = { characteristics }
}
fun withNotes(notes: String) = apply {
this.notes = { notes }
}
override fun produce() = TemporaryAccommodationPremisesSeedCsvRow(
name = this.name(),
addressLine1 = this.addressLine1(),
addressLine2 = this.addressLine2(),
town = this.town(),
postcode = this.postcode(),
probationRegion = this.probationRegion(),
localAuthorityArea = this.localAuthorityArea(),
pdu = this.pdu(),
characteristics = this.characteristics(),
notes = this.notes(),
)
}
| 3
| null |
2
| 5
|
5b02281acd56772dc5d587f8cd4678929a191ac0
| 10,519
|
hmpps-approved-premises-api
|
MIT License
|
android/src/main/java/com/instantpaysmsdetection/SmsHelper.kt
|
InstantPay
| 752,256,974
| false
|
{"Kotlin": 24707, "JavaScript": 4236, "TypeScript": 2450, "Ruby": 2049, "Objective-C++": 328, "Swift": 327, "C": 103, "Objective-C": 67}
|
package com.instantpaysmsdetection
import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.WritableMap
import com.google.android.gms.auth.api.phone.SmsRetriever
import com.google.android.gms.tasks.OnFailureListener
import com.google.android.gms.tasks.OnSuccessListener
class SmsHelper {
private val SUCCESS: String = "SUCCESS"
private val FAILED: String = "FAILED"
private lateinit var DATA: String
private var responsePromise: Promise? = null
private var mContext: ReactApplicationContext? = null
private var mReceiver: BroadcastReceiver? = null
private var cActivity: Activity? = null
private val onSuccessListener = OnSuccessListener<Void> {
val isRegister: Boolean = tryToRegisterReceiver()
var isSuccess = "Unknow"
if(isRegister){
isSuccess = "Success"
}
var actCode = "ListenForSmsDetect";
if(InstantpaySmsDetectionModule.isRequestForConsentSms){
actCode = "ListenForSmsConsent"
}
resolve("${isSuccess}, Please check on listener", SUCCESS, "", actCode)
}
private val onFailureListener = OnFailureListener {
unregisterReceiverIfNeeded()
resolve("Failed to register the SMS listener", FAILED)
}
/**
* Start Method to register service
*/
fun startRetriever(context : ReactApplicationContext, activity : Activity, promise: Promise){
unregisterReceiverIfNeeded()
responsePromise = promise
mContext = context
cActivity = activity
val smsRetrieverClient = SmsRetriever.getClient(context)
val tasks = smsRetrieverClient.startSmsRetriever()
tasks.addOnSuccessListener(onSuccessListener)
tasks.addOnFailureListener(onFailureListener)
}
/**
* Request one-time consent to read an SMS verification code
*/
fun requestSmsConsent(senderPhoneNumber: String? = null, context : ReactApplicationContext, activity : Activity, promise: Promise){
unregisterReceiverIfNeeded()
responsePromise = promise
mContext = context
cActivity = activity
val smsRetrieverClient = SmsRetriever.getClient(context)
val tasks = smsRetrieverClient.startSmsUserConsent(senderPhoneNumber)
tasks.addOnSuccessListener(onSuccessListener)
tasks.addOnFailureListener(onFailureListener)
}
/**
* Register Broadcast to read sms
*/
private fun tryToRegisterReceiver() : Boolean{
mReceiver = SmsBroadcastReceiver(mContext!!, cActivity!!)
val intentFilter = IntentFilter(SmsRetriever.SMS_RETRIEVED_ACTION)
try {
if(Build.VERSION.SDK_INT >= 34 && mContext!!.applicationInfo.targetSdkVersion >= 34){
mContext!!.registerReceiver(mReceiver, intentFilter, Context.RECEIVER_EXPORTED)
}
else{
mContext!!.registerReceiver(mReceiver, intentFilter)
}
return true
}
catch (e: Exception){
resolve("Something went wrong #TRRSDP1", FAILED, "", "", e.message.toString())
return false
}
}
/**
* Un-Register the Broadcast
*/
private fun unregisterReceiverIfNeeded(){
if (mReceiver == null) {
return;
}
try {
mContext!!.unregisterReceiver(mReceiver);
} catch (e: Exception) {
resolve("Something went wrong #URRSDP1", FAILED, "", "", e.message.toString())
}
}
/**
* Help to return data to React native
*/
private fun resolve(message: String,status: String = FAILED,data: String = "",actCode: String = "", exceptionMessage: String = "") {
if (responsePromise == null) {
return;
}
val map: WritableMap = Arguments.createMap()
map.putString("status", status)
map.putString("message", message)
if(data.isNotEmpty()){
map.putString("data", data)
}
if(actCode.isNotEmpty()){
map.putString("actCode", actCode)
}
if(exceptionMessage.isNotEmpty()){
map.putString("exceptionMessage", exceptionMessage)
}
responsePromise!!.resolve(map)
responsePromise = null
}
}
| 0
|
Kotlin
|
1
| 0
|
b84f85f141973d2fd7121e9104708878ae95c517
| 4,616
|
react-native-instantpay-sms-detection
|
MIT License
|
src/k_02_estructuraIF/Ejemplo4.kt
|
liquisbert
| 209,602,066
| true
|
{"Kotlin": 29694}
|
package k_02_estructuraIF
fun main() {
print("Ingrese el primer valor: ")
val valor1 = readLine()!!.toInt()
print("Ingrese el segundo valor: ")
val valor2 = readLine()!!.toInt()
if (valor1 < valor2) {
val suma = valor1.plus(valor2)
val resta = valor1.minus(valor2)
println("La suma de los dos valores es: $suma")
println("La resta de los dos valores es: $resta")
} else {
val producto = valor1.times(valor2)
val division = valor1.div(valor2)
println("El producto de los dos valores es: $producto")
println("La división de los dos valores es: $division")
}
}
| 0
| null |
0
| 0
|
709a910ae55700935a6bd1aa7a3842ce5bfc4bf3
| 650
|
KotlinStudyJam
|
MIT License
|
src/main/java/org/bitlap/geocoding/core/impl/RegionInterpreterVisitor.kt
|
IceMimosa
| 132,923,880
| false
| null |
package org.bitlap.geocoding.core.impl
import org.bitlap.geocoding.core.AddressPersister
import org.bitlap.geocoding.core.TermIndexVisitor
import org.bitlap.geocoding.index.TermIndexEntry
import org.bitlap.geocoding.index.TermIndexItem
import org.bitlap.geocoding.index.TermType
import org.bitlap.geocoding.model.Division
import org.bitlap.geocoding.model.RegionEntity
import org.bitlap.geocoding.model.RegionType.City
import org.bitlap.geocoding.model.RegionType.CityLevelDistrict
import org.bitlap.geocoding.model.RegionType.District
import org.bitlap.geocoding.model.RegionType.PlatformL4
import org.bitlap.geocoding.model.RegionType.Province
import org.bitlap.geocoding.model.RegionType.ProvinceLevelCity1
import org.bitlap.geocoding.model.RegionType.ProvinceLevelCity2
import org.bitlap.geocoding.model.RegionType.Street
import org.bitlap.geocoding.model.RegionType.Town
import org.bitlap.geocoding.model.RegionType.Village
import java.util.ArrayDeque
/**
* Desc: 基于倒排索引搜索匹配省市区行政区划的访问者
* Mail: <EMAIL>
* Created by IceMimosa
* Date: 2017/1/12
*/
open class RegionInterpreterVisitor (
// 地址持久层对象
val persister: AddressPersister,
val strict: Boolean
) : TermIndexVisitor {
private var currentLevel = 0
private var deepMostLevel = 0
private var currentPos = -1
private var deepMostPos = -1
private var fullMatchCount = 0
private var deepMostFullMatchCount = 0
private val deepMostDivision = Division()
private val curDivision = Division()
private val stack = ArrayDeque<TermIndexItem>()
companion object {
private val ambiguousChars = mutableListOf('市', '县', '区', '镇', '乡')
}
/**
* 开始一轮词条匹配。
*/
override fun startRound() {
currentLevel++
}
/**
* 匹配到一个索引条目,由访问者确定是否是可接受的匹配项。
* 索引条目 [entry] 下的items一定包含一个或多个索引对象
*
* @return 可以接受返回true, 否则返回false。对于可以接受的索引条目调用 [endVisit] 结束访问
*/
override fun visit(entry: TermIndexEntry, text: String, pos: Int): Boolean {
// 找到最匹配的 被索引对象. 没有匹配对象,匹配不成功,返回
val acceptableItem = findAcceptableItem(entry, text, pos) ?: return false
// acceptableItem可能为TermType.Ignore类型,此时其value并不是RegionEntity对象,因此下面region的值可能为null
val region = acceptableItem.value as? RegionEntity
// 更新当前状态
stack.push(acceptableItem) // 匹配项压栈
// 使用全名匹配的词条数
if (isFullMatch(entry, region))
fullMatchCount++
currentPos = positioning(region, entry, text, pos) // 当前结束的位置
updateCurrentDivisionState(region, entry) // 刷新当前已经匹配上的省市区
return true
}
private fun findAcceptableItem(entry: TermIndexEntry, text: String, pos: Int): TermIndexItem? {
var mostPriority = -1
var acceptableItem: TermIndexItem? = null
// 每个 被索引对象循环,找出最匹配的
loop@ for (item in entry.items) {
// 仅处理省市区类型的 被索引对象,忽略其它类型的
if (!isAcceptableItemType(item.type!!)) continue
//省市区中的特殊名称
if (item.type == TermType.Ignore) {
if (acceptableItem == null) {
mostPriority = 4
acceptableItem = item
}
continue
}
val region = item.value as RegionEntity
// 从未匹配上任何一个省市区,则从全部被索引对象中找出一个级别最高的
if (!curDivision.hasProvince()) {
// 在为匹配上任务省市区情况下, 由于 `xx路` 的xx是某县区/市区/省的别名, 如江苏路, 绍兴路等等, 导致错误的匹配。
// 如 延安路118号, 错误匹配上了延安县
if (!isFullMatch(entry, region) && pos + 1 <= text.length - 1) {
if (region.type == Province
|| region.type == City
|| region.type == CityLevelDistrict || region.type == District
|| region.type == Street || region.type == PlatformL4
|| region.type == Town) { // 县区或街道
// 如果是某某路, 街等
when (text[pos + 1]) {
'路', '街', '巷', '道' -> continue@loop
}
}
}
if (mostPriority == -1) {
mostPriority = region.type.value
acceptableItem = item
}
if (region.type.value < mostPriority) {
mostPriority = region.type.value
acceptableItem = item
}
continue
}
// 对于省市区全部匹配, 并且当前term属于非完全匹配的时候
// 需要忽略掉当前term, 以免污染已经匹配的省市区
if (!isFullMatch(entry, region) && hasThreeDivision()) {
when (region.type) {
Province -> {
if (region.id != curDivision.province!!.id) {
continue@loop
}
}
City, CityLevelDistrict -> {
if (region.id != curDivision.city!!.id) {
continue@loop
}
}
District -> {
if (region.id != curDivision.district!!.id) {
continue@loop
}
}
else -> { }
}
}
// 已经匹配上部分省市区,按下面规则判断最匹配项
// 高优先级的排除情况
if (!isFullMatch(entry, region) && pos + 1 <= text.length - 1) { // 使用别名匹配,并且后面还有一个字符
// 1. 湖南益阳沅江市万子湖乡万子湖村
// 错误匹配方式:提取省市区时,将【万子湖村】中的字符【万子湖】匹配成【万子湖乡】,剩下一个【村】。
// 2. 广东广州白云区均和街新市镇
// 白云区下面有均和街道,街道、乡镇使用别名匹配时,后续字符不能是某些行政区域和道路关键字符
if (region.type == Province
|| region.type == City
|| region.type in listOf(CityLevelDistrict, District)
|| region.type == Street
|| region.type == Town) { //街道、乡镇
when (text[pos + 1]) {
'区', '县', '乡', '镇', '村', '街', '路' -> continue@loop
'大' -> if (pos + 2 <= text.length - 1) {
val c = text[pos + 2]
if (c == '街' || c == '道') continue@loop
}
}
}
}
// 1. 匹配度最高的情况,正好是下一级行政区域
if (region.parentId == curDivision.leastRegion().id) {
acceptableItem = item
break
}
// 2. 中间缺一级的情况。
if (mostPriority == -1 || mostPriority > 2) {
val parent = persister.getRegion(region.parentId)
// 2.1 缺地级市
if (!curDivision.hasCity() && curDivision.hasProvince() && region.type == District
&& curDivision.province!!.id == parent!!.parentId) {
mostPriority = 2
acceptableItem = item
continue
}
// 2.2 缺区县
if (!curDivision.hasDistrict() && curDivision.hasCity()
&& (region.type == Street || region.type == Town
|| region.type == PlatformL4 || region.type == Village)
&& curDivision.city!!.id == parent!!.parentId) {
mostPriority = 2
acceptableItem = item
continue
}
}
// 3. 地址中省市区重复出现的情况
if (mostPriority == -1 || mostPriority > 3) {
if (curDivision.hasProvince() && curDivision.province!!.id == region.id ||
curDivision.hasCity() && curDivision.city!!.id == region.id ||
curDivision.hasDistrict() && curDivision.district!!.id == region.id ||
curDivision.hasStreet() && curDivision.street!!.id == region.id ||
curDivision.hasTown() && curDivision.town!!.id == region.id ||
curDivision.hasVillage() && curDivision.village!!.id == region.id) {
mostPriority = 3
acceptableItem = item
continue
}
}
// 4. 容错
if (mostPriority == -1 || mostPriority > 4) {
// 4.1 新疆阿克苏地区阿拉尔市
// 到目前为止,新疆下面仍然有地级市【阿克苏地区】
//【阿拉尔市】是县级市,以前属于地级市【阿克苏地区】,目前已变成新疆的省直辖县级行政区划
// 即,老的行政区划关系为:新疆->阿克苏地区->阿拉尔市
// 新的行政区划关系为:
// 新疆->阿克苏地区
// 新疆->阿拉尔市
// 错误匹配方式:新疆 阿克苏地区 阿拉尔市,会导致在【阿克苏地区】下面无法匹配到【阿拉尔市】
// 正确匹配结果:新疆 阿拉尔市
if (region.type == CityLevelDistrict
&& curDivision.hasProvince() && curDivision.province!!.id == region.parentId) {
mostPriority = 4
acceptableItem = item
continue
}
// 4.2 地级市-区县从属关系错误,但区县对应的省份正确,则将使用区县的地级市覆盖已匹配的地级市
// 主要是地级市的管辖范围有调整,或者由于外部系统地级市与区县对应关系有调整导致
if (region.type == District // 必须是普通区县
&& curDivision.hasCity() && curDivision.hasProvince()
&& isFullMatch(entry, region) // 使用的全名匹配
&& curDivision.city!!.id != region.parentId) {
val city = persister.getRegion(region.parentId)!! // 区县的地级市
if (city.parentId == curDivision.province!!.id && !hasThreeDivision()) {
mostPriority = 4
acceptableItem = item
continue
}
}
}
// 5. 街道、乡镇,且不符合上述情况
if (region.type == Street || region.type == Town
|| region.type == Village || region.type == PlatformL4) {
if (!curDivision.hasDistrict()) {
var parent = persister.getRegion(region.parentId) // parent为区县
parent = persister.getRegion(parent!!.parentId) // parent为地级市
if (curDivision.hasCity() && curDivision.city!!.id == parent!!.id) {
mostPriority = 5
acceptableItem = item
continue
}
} else if (region.parentId == curDivision.district!!.id) {
//已经匹配上区县
mostPriority = 5
acceptableItem = item
continue
}
}
}
return acceptableItem
}
private fun isFullMatch(entry: TermIndexEntry, region: RegionEntity?): Boolean {
if (region == null) return false
if (entry.key!!.length == region.name.length) return true
if (region.type == Street && region.name.endsWith("街道") && region.name.length == entry.key!!.length + 1)
return true //xx街道,使用别名xx镇、xx乡匹配上的,认为是全名匹配
return false
}
/**
* 索引对象是否是可接受的省市区等类型。
*/
private fun isAcceptableItemType(type: TermType): Boolean {
return when (type) {
TermType.Province, TermType.City, TermType.District,
TermType.Street, TermType.Town, TermType.Village, TermType.Ignore -> true
else -> false
}
}
/**
* 当前是否已经完全匹配了省市区了
*/
private fun hasThreeDivision(): Boolean {
return (curDivision.hasProvince() && curDivision.hasCity() && curDivision.hasDistrict())
&& (curDivision.city!!.parentId == curDivision.province!!.id)
&& (curDivision.district!!.parentId == curDivision.city!!.id)
}
private fun positioning(acceptedRegion: RegionEntity?, entry: TermIndexEntry, text: String, pos: Int): Int {
if (acceptedRegion == null) return pos
// 需要调整指针的情况
// 1. 山东泰安肥城市桃园镇桃园镇山东省泰安市肥城县桃园镇东伏村
// 错误匹配方式:提取省市区时,将【肥城县】中的字符【肥城】匹配成【肥城市】,剩下一个【县】
if ((acceptedRegion.type == City || acceptedRegion.type == District
|| acceptedRegion.type == Street)
&& !isFullMatch(entry, acceptedRegion) && pos + 1 <= text.length - 1) {
val c = text[pos + 1]
if (ambiguousChars.contains(c)) { //后续跟着特殊字符
for (child in acceptedRegion.children ?: arrayListOf()) {
if (child.name[0] == c) return pos
}
return pos + 1
}
// fix: 如果已经匹配最低等级
if (curDivision.hasTown() || curDivision.hasStreet()) {
// 如果不是特殊字符的, 由于存在 `xx小区, xx苑, xx是以镇名字命名的情况`
if (!ambiguousChars.contains(c)) {
deepMostPos = currentPos // 则不移动当前指针
}
}
}
return pos
}
/**
* 更新当前已匹配区域对象的状态。
* @param region
*/
private fun updateCurrentDivisionState(region: RegionEntity?, entry: TermIndexEntry) {
if (region == null) return
// region为重复项,无需更新状态
if (region == curDivision.province || region == curDivision.city
|| region == curDivision.district || region == curDivision.street
|| region == curDivision.town || region == curDivision.village)
return
// 非严格模式 || 只有一个父项
val needUpdateCityAndProvince = !strict || (entry.items.size == 1)
when (region.type) {
Province, ProvinceLevelCity1 -> {
curDivision.province = region
curDivision.city = null
}
City, ProvinceLevelCity2 -> {
curDivision.city = region
if (!curDivision.hasProvince())
curDivision.province = persister.getRegion(region.parentId)
}
CityLevelDistrict -> {
curDivision.city = region
curDivision.district = region
if (!curDivision.hasProvince())
curDivision.province = persister.getRegion(region.parentId)
}
District -> {
curDivision.district = region
//成功匹配了区县,则强制更新地级市
curDivision.city = persister.getRegion(curDivision.district!!.parentId)
if (!curDivision.hasProvince())
curDivision.province = persister.getRegion(curDivision.city!!.parentId)
}
Street, PlatformL4 -> {
if (!curDivision.hasStreet()) curDivision.street = region
if (!curDivision.hasDistrict()) curDivision.district = persister.getRegion(region.parentId)
if (needUpdateCityAndProvince) {
updateCityAndProvince(curDivision.district)
}
}
Town -> {
if (!curDivision.hasTown()) curDivision.town = region
if (!curDivision.hasDistrict()) curDivision.district = persister.getRegion(region.parentId)
if (needUpdateCityAndProvince) {
updateCityAndProvince(curDivision.district)
}
}
Village -> {
if (!curDivision.hasVillage()) curDivision.village = region
if (!curDivision.hasDistrict()) curDivision.district = persister.getRegion(region.parentId)
if (needUpdateCityAndProvince) {
updateCityAndProvince(curDivision.district)
}
}
else -> { }
}
}
private fun updateCityAndProvince(distinct: RegionEntity?) {
if (distinct == null) return
if (!curDivision.hasCity()) {
curDivision.city = persister.getRegion(distinct.parentId)?.also { city ->
if (!curDivision.hasProvince()) {
curDivision.province = persister.getRegion(city.parentId)
}
}
}
}
/**
* [visit] 接受某个索引项之后当前匹配的指针位置
*/
override fun position(): Int {
return this.currentPos
}
/**
* 结束索引访问
*/
override fun endVisit(entry: TermIndexEntry, text: String, pos: Int) {
this.checkDeepMost()
val indexTerm = stack.pop() // 当前访问的索引对象出栈
currentPos = pos - entry.key!!.length // 恢复当前位置指针
val region = indexTerm.value as? RegionEntity
if (isFullMatch(entry, region)) fullMatchCount++ //更新全名匹配的数量
if (indexTerm.type == TermType.Ignore) return //如果是忽略项,无需更新当前已匹配的省市区状态
// 扫描一遍stack,找出街道street、乡镇town、村庄village,以及省市区中级别最低的一个least
var least: RegionEntity? = null
var street: RegionEntity? = null
var town: RegionEntity? = null
var village: RegionEntity? = null
stack.forEach {
if (it.type == TermType.Ignore) return@forEach
val r = it.value as RegionEntity
when (r.type) {
Street, PlatformL4 -> {
street = r
return@forEach
}
Town -> {
town = r
return@forEach
}
Village -> {
village = r
return@forEach
}
else -> { }
}
if (least == null) {
least = r
return@forEach
}
}
if (street == null) curDivision.street = null // 剩余匹配项中没有街道了
if (town == null) curDivision.town = null // 剩余匹配项中没有乡镇了
if (village == null) curDivision.village = null // 剩余匹配项中没有村庄了
// 只有街道、乡镇、村庄都没有时,才开始清空省市区
if (curDivision.hasStreet() || curDivision.hasTown() || curDivision.hasVillage()) return
if (least != null) {
when (least!!.type) {
Province, ProvinceLevelCity1 -> {
curDivision.city = null
curDivision.district = null
return
}
City, ProvinceLevelCity2 -> {
curDivision.district = null
return
}
else -> return
}
}
// least为null,说明stack中什么都不剩了
curDivision.province = null
curDivision.city = null
curDivision.district = null
}
/**
* 结束一轮词条匹配。
*/
override fun endRound() {
this.checkDeepMost()
currentLevel--
}
private fun checkDeepMost() {
if (stack.size > deepMostLevel) {
deepMostLevel = stack.size
deepMostPos = currentPos
deepMostFullMatchCount = fullMatchCount
deepMostDivision.province = curDivision.province
deepMostDivision.city = curDivision.city
deepMostDivision.district = curDivision.district
deepMostDivision.street = curDivision.street
deepMostDivision.town = curDivision.town
deepMostDivision.village = curDivision.village
}
}
/**
* 是否匹配上了结果
*/
override fun hasResult(): Boolean {
return deepMostPos > 0 && deepMostDivision.hasDistrict()
}
/**
* 获取访问后的对象
*/
override fun devision(): Division {
return deepMostDivision
}
override fun matchCount(): Int {
return deepMostLevel
}
override fun fullMatchCount(): Int {
return deepMostFullMatchCount
}
/**
* 获取最终匹配结果的终止位置
*/
override fun endPosition(): Int {
return deepMostPos
}
/**
* 状态复位
*/
override fun reset() {
currentLevel = 0
deepMostLevel = 0
currentPos = -1
deepMostPos = -1
fullMatchCount = 0
deepMostFullMatchCount = 0
deepMostDivision.province = null
deepMostDivision.city = null
deepMostDivision.district = null
deepMostDivision.street = null
deepMostDivision.town = null
deepMostDivision.village = null
curDivision.province = null
curDivision.city = null
curDivision.district = null
curDivision.street = null
curDivision.town = null
curDivision.village = null
}
}
| 6
| null |
85
| 230
|
887721ce590faf6d80a148f704dc8ff7e7fd80d8
| 20,169
|
geocoding
|
MIT License
|
app/src/main/java/br/com/sommelier/presentation/login/res/LoginStringResource.kt
|
ronaldocoding
| 665,333,427
| false
|
{"Kotlin": 508863}
|
package br.com.sommelier.presentation.login.res
sealed class LoginStringResource {
object Empty : LoginStringResource()
object BlankEmail : LoginStringResource()
object InvalidEmail : LoginStringResource()
object BlankPassword : LoginStringResource()
}
| 0
|
Kotlin
|
0
| 1
|
9aa7b8add777d3d8b7051710dd2c528167720294
| 270
|
sommelier
|
MIT License
|
src/main/kotlin/com/amulet/cavinist/persistence/repository/CrudRepository.kt
|
antoine-mulet
| 254,576,347
| false
| null |
package com.amulet.cavinist.persistence.repository
import com.amulet.cavinist.persistence.data.Entity
import org.springframework.dao.*
import org.springframework.data.repository.reactive.ReactiveCrudRepository
import reactor.core.publisher.Mono
import java.util.UUID
abstract class CrudRepository<T : Entity> {
abstract val crudRepository: ReactiveCrudRepository<T, UUID>
fun save(entity: T): Mono<T> =
crudRepository.save(entity)
.onErrorMap {
when (it) {
is DataIntegrityViolationException ->
DataIntegrityViolationException("${entity.description()} already exists.")
is OptimisticLockingFailureException ->
OutdatedVersionException("Failed to update ${entity.name()} with id '${entity.id}' because version is outdated.")
else -> it
}
}
fun findById(id: UUID): Mono<T> = crudRepository.findById(id)
}
| 0
|
Kotlin
|
0
| 0
|
8696e46534547287c8f18c99753d878e8654f4cf
| 1,025
|
cavinist
|
Apache License 2.0
|
app/src/main/java/com/ms/catlife/theme/Color.kt
|
morganesoula
| 446,932,843
| false
| null |
package com.ms.catlife.theme
import androidx.compose.ui.graphics.Color
val md_theme_light_primary = Color(0xFF7E5700)
val md_theme_light_onPrimary = Color(0xFFFFFFFF)
val md_theme_light_secondary = Color(0xFF2D6B27)
val md_theme_light_onSecondary = Color(0xFFFFFFFF)
val md_theme_light_error = Color(0xFFBA1A1A)
val md_theme_light_onError = Color(0xFFFFFFFF)
val md_theme_light_background = Color(0xFFF8FDFF)
val md_theme_light_onBackground = Color(0xFF001F25)
val md_theme_light_surface = Color(0xFFe3dace)
val md_theme_light_onSurface = Color(0xFF001F25)
val md_theme_light_backgroundSwitch = Color(0xFFDAE2E4)
val md_theme_dark_primary = Color(0xFFD0BCFF)
val md_theme_dark_onPrimary = Color(0xFF432C00)
val md_theme_dark_secondary = Color(0xFFFBBB4A)
val md_theme_dark_onSecondary = Color(0xFF003A03)
val md_theme_dark_error = Color(0xFFFFB4AB)
val md_theme_dark_onError = Color(0xFF690005)
val md_theme_dark_background = Color(0xFF1C1B1F)
val md_theme_dark_onBackground = Color(0xFFFFD8E4)
val md_theme_dark_surface = Color(0xFF633B48)
val md_theme_dark_onSurface = Color(0xFFFFD8E4)
val md_theme_dark_backgroundSwitch = Color(0xFF3a313a)
| 0
|
Kotlin
|
0
| 2
|
80eb98072fd3326ae13503b2dc150a20f6574742
| 1,145
|
catlife
|
Apache License 2.0
|
src/main/kotlin/ac/github/oa/internal/core/condition/OccupationCondition.kt
|
ShirosakiMio
| 707,539,187
| false
|
{"Kotlin": 284577, "Java": 6919, "JavaScript": 1159}
|
package ac.github.oa.internal.core.condition
import ac.github.oa.internal.core.attribute.equip.AdaptItem
import ac.github.oa.util.Strings.hasString
import org.bukkit.entity.LivingEntity
import org.bukkit.entity.Player
import taboolib.platform.util.sendLang
object OccupationCondition : ICondition {
val CHECK: (Player, String) -> Boolean = { player, s ->
player.hasPermission(s)
}
override fun post(livingEntity: LivingEntity, adaptItem: AdaptItem): Boolean {
if (livingEntity is Player) {
val item = adaptItem.item
val config = options("occupation")
val list = config.getStringList("keyword")
val lore = item.itemMeta!!.lore!!
if (lore.hasString(list)) {
val map = config.getStringList("pattern").map {
val split = it.split(" ")
Pair(split[0], split[1])
}
val data = map.firstOrNull { lore.any { s -> s.contains(it.first) } }
if (data != null && !CHECK(livingEntity, data.second)) {
livingEntity.sendLang("condition-occupation-not-enough", item.itemMeta!!.displayName, data.first)
return false
}
}
}
return true
}
}
| 0
|
Kotlin
|
0
| 0
|
2ed0dddc083b4a844efcff4fb1cd236a06c0482d
| 1,304
|
OriginAttribute
|
Creative Commons Zero v1.0 Universal
|
src/main/kotlin/com/delta/GameState.kt
|
delta-summer-camp-team
| 668,869,095
| false
| null |
package com.delta
data class GameState(
var playerID: PlayerID? = null,
var game: Tilous? = null,
var phase: GamePhase = GamePhase.NOT_STARTED
) {
// Может быть вам захочется написать здесь несколько методов,
// которые сделают вашу жизнь удобнее.
// fun gameStarted() = ...
// fun isMyTurn() = ...
// fun isOtherTurn() = ...
// fun isNotStarted() = ...
}
| 0
|
Kotlin
|
0
| 0
|
305f16d80f0aacd1b15337addb1b9e1764eab892
| 389
|
TilousClient
|
MIT License
|
macaron-statemachine/src/commonMain/kotlin/tech/fika/macaron/statemachine/nodes/LifecycleNode.kt
|
fika-tech
| 521,779,126
| false
|
{"Kotlin": 65936}
|
package tech.fika.macaron.statemachine.nodes
import tech.fika.macaron.core.contract.Action
import tech.fika.macaron.core.contract.State
data class LifecycleNode<A : Action, S : State>(
val onCreate: (ListenerNode<A, S>) -> Unit = {},
val onStart: (ListenerNode<A, S>) -> Unit = {},
val onResume: (ListenerNode<A, S>) -> Unit = {},
val onPause: (ListenerNode<A, S>) -> Unit = {},
val onStop: (ListenerNode<A, S>) -> Unit = {},
val onDestroy: () -> Unit = {},
)
| 1
|
Kotlin
|
3
| 18
|
f24c990e75925729809df9108c7bca72c55c7334
| 485
|
Macaron
|
MIT License
|
geo/src/commonMain/kotlin/io/data2viz/geo/projection/Gnomonic.kt
|
data2viz
| 89,368,762
| false
|
{"Kotlin": 2202712, "HTML": 32617, "JavaScript": 12122}
|
/*
* Copyright (c) 2018-2019. data2viz sàrl.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.data2viz.geo.projection
import io.data2viz.geo.geometry.clip.anglePreClip
import io.data2viz.geo.projection.common.*
import io.data2viz.math.deg
import kotlin.math.atan
import kotlin.math.cos
import kotlin.math.sin
public fun gnomonicProjection(init: Projection.() -> Unit = {}): Projection =
projection(GnomonicProjector()) {
anglePreClip = 60.0.deg
scale = 144.049
init()
}
public class GnomonicProjector : Projector {
override fun project(lambda: Double, phi: Double): DoubleArray {
val cy = cos(phi)
val k = cos(lambda) * cy
return doubleArrayOf(
cy * sin(lambda) / k,
sin(phi) / k
)
}
override fun invert(x: Double, y: Double): DoubleArray = azimuthalInvert(::atan)(x, y)
}
| 80
|
Kotlin
|
29
| 400
|
bc4ed872c526264727f868f5127e48462301dbf8
| 1,413
|
data2viz
|
Apache License 2.0
|
app/src/main/java/co/hellocode/micro/tablayout/TabAdapter.kt
|
bellebethcooper
| 145,940,807
| false
| null |
package co.hellocode.micro.tablayout
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import co.hellocode.micro.tablayout.fragments.DiscoverFragment
import co.hellocode.micro.tablayout.fragments.MediaFragment
import co.hellocode.micro.tablayout.fragments.MentionsFragment
import co.hellocode.micro.tablayout.fragments.TimelineFragment
class TabAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
override fun getItem(position: Int): Fragment? = when (position) {
0 -> TimelineFragment.newInstance()
1 -> MentionsFragment.newInstance()
2 -> DiscoverFragment.newInstance()
3 -> MediaFragment.newInstance()
else -> null
}
override fun getPageTitle(position: Int): CharSequence = when (position) {
0 -> "Timeline"
1 -> "Mentions"
2 -> "Discover"
3 -> "Photos"
else -> ""
}
override fun getCount(): Int = 4
}
| 24
| null |
3
| 12
|
d360b703e7663dfcf3133b78210b7e77b25456b8
| 1,001
|
pico
|
MIT License
|
app/src/main/java/fi/tanskudaa/whatdoin/data/ActivityDatabase.kt
|
tanskudaa
| 780,935,974
| false
|
{"Kotlin": 35841}
|
package fi.tanskudaa.whatdoin.data
import android.content.Context
import androidx.room.AutoMigration
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
const val DATABASE_VERSION = 2
@Database(
version = DATABASE_VERSION,
entities = [Activity::class],
autoMigrations = [
AutoMigration(1, 2)
],
exportSchema = true
)
abstract class ActivityDatabase : RoomDatabase() {
abstract fun activityDao(): ActivityDao
companion object {
@Volatile
private var Instance: ActivityDatabase? = null
fun getDatabase(context: Context): ActivityDatabase {
return Instance ?: synchronized(this) {
Room.databaseBuilder(context, ActivityDatabase::class.java, "app_db")
.build()
.also { Instance = it }
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
3b800b96480c6347afe71ea9ff1684e9681a836a
| 900
|
whatdoin
|
MIT License
|
src/test/kotlin/sample/model/asset/CashInOutTest.kt
|
jkazama
| 145,971,105
| false
| null |
package sample.model.asset
import org.hamcrest.Matchers.*
import org.junit.Assert.assertThat
import org.junit.Assert.fail
import org.junit.Test
import sample.ActionStatusType
import sample.EntityTestSupport
import sample.ErrorKeys
import sample.ValidationException
import sample.model.DomainErrorKeys
import sample.model.account.Account
import sample.model.account.FiAccount
import sample.model.master.SelfFiAccount
import java.math.BigDecimal
import java.time.LocalDate
//low: 簡易な正常系検証が中心。依存するCashflow/CashBalanceの単体検証パスを前提。
class CashInOutTest : EntityTestSupport() {
override fun setupPreset() {
targetEntities(Account::class.java, FiAccount::class.java, SelfFiAccount::class.java,
CashInOut::class.java, Cashflow::class.java, CashBalance::class.java)
}
override fun before() {
// 残高1000円の口座(test)を用意
val baseDay = businessDay.day()
tx {
fixtures().selfFiAcc(Remarks.CashOut, ccy).save(rep())
fixtures().acc(accId).save(rep())
fixtures().fiAcc(accId, Remarks.CashOut, ccy).save(rep())
fixtures().cb(accId, baseDay, ccy, "1000").save(rep())
}
}
@Test
fun 振込入出金を検索する() {
val baseDay = businessDay.day()
val basePlus1Day = businessDay.day(1)
val basePlus2Day = businessDay.day(2)
tx {
fixtures().cio(accId, "300", true).save(rep())
//low: ちゃんとやると大変なので最低限の検証
assertThat(
CashInOut.find(rep(), findParam(baseDay, basePlus1Day)),
hasSize(1))
assertThat(
CashInOut.find(rep(), findParam(baseDay, basePlus1Day, ActionStatusType.Unprocessed)),
hasSize(1))
assertThat(
CashInOut.find(rep(), findParam(baseDay, basePlus1Day, ActionStatusType.Processed)),
empty())
assertThat(
CashInOut.find(rep(), findParam(basePlus1Day, basePlus2Day, ActionStatusType.Unprocessed)),
empty())
}
}
private fun findParam(fromDay: LocalDate, toDay: LocalDate, vararg statusTypes: ActionStatusType): FindCashInOut {
return FindCashInOut(ccy, statusTypes.toList(), fromDay, toDay)
}
@Test
fun 振込出金依頼をする() {
val baseDay = businessDay.day()
val basePlus3Day = businessDay.day(3)
tx {
// 超過の出金依頼 [例外]
try {
CashInOut.withdraw(rep(), businessDay, RegCashOut(accId, ccy, BigDecimal("1001")))
fail()
} catch (e: ValidationException) {
assertThat(e.message, `is`(AssetErrorKeys.CashInOutWithdrawAmount))
}
// 0円出金の出金依頼 [例外]
try {
CashInOut.withdraw(rep(), businessDay, RegCashOut(accId, ccy, BigDecimal.ZERO))
fail()
} catch (e: ValidationException) {
assertThat(e.message, `is`(DomainErrorKeys.AbsAmountZero))
}
// 通常の出金依頼
val normal = CashInOut.withdraw(rep(), businessDay, RegCashOut(accId, ccy, BigDecimal("300")))
assertThat(normal, allOf(
hasProperty("accountId", `is`(accId)), hasProperty("currency", `is`(ccy)),
hasProperty("absAmount", `is`(BigDecimal(300))), hasProperty("withdrawal", `is`(true)),
hasProperty("requestDay", `is`(baseDay)),
hasProperty("eventDay", `is`(baseDay)),
hasProperty("valueDay", `is`(basePlus3Day)),
hasProperty("targetFiCode", `is`(Remarks.CashOut + "-" + ccy)),
hasProperty("targetFiAccountId", `is`("FI$accId")),
hasProperty("selfFiCode", `is`(Remarks.CashOut + "-" + ccy)),
hasProperty("selfFiAccountId", `is`("xxxxxx")),
hasProperty("statusType", `is`(ActionStatusType.Unprocessed)),
hasProperty("cashflowId", `is`(nullValue()))))
// 拘束額を考慮した出金依頼 [例外]
try {
CashInOut.withdraw(rep(), businessDay, RegCashOut(accId, ccy, BigDecimal("701")))
fail()
} catch (e: ValidationException) {
assertThat(e.message, `is`(AssetErrorKeys.CashInOutWithdrawAmount))
}
}
}
@Test
fun 振込出金依頼を取消する() {
val baseDay = businessDay.day()
tx {
// CF未発生の依頼を取消
val normal = fixtures().cio(accId, "300", true).save(rep())
assertThat(normal.cancel(rep()), hasProperty("statusType", `is`(ActionStatusType.Cancelled)))
// 発生日を迎えた場合は取消できない [例外]
val today = fixtures()
.cio(accId, "300", true).copy(eventDay = baseDay)
.save(rep())
try {
today.cancel(rep())
fail()
} catch (e: ValidationException) {
assertThat(e.message, `is`(AssetErrorKeys.CashInOutBeforeEqualsDay))
}
}
}
@Test
fun 振込出金依頼を例外状態とする() {
val baseDay = businessDay.day()
tx {
val normal = fixtures().cio(accId, "300", true).save(rep())
assertThat(normal.error(rep()), hasProperty("statusType", `is`(ActionStatusType.Error)))
// 処理済の時はエラーにできない [例外]
val today = fixtures().cio(accId, "300", true)
.copy(eventDay = baseDay, statusType = ActionStatusType.Processed)
.save(rep())
try {
today.error(rep())
fail()
} catch (e: ValidationException) {
assertThat(e.message, `is`(ErrorKeys.ActionUnprocessing))
}
}
}
@Test
fun 発生日を迎えた振込入出金をキャッシュフロー登録する() {
val baseDay = businessDay.day()
val basePlus3Day = businessDay.day(3)
tx {
// 発生日未到来の処理 [例外]
val future = fixtures().cio(accId, "300", true).save(rep())
try {
future.process(rep())
fail()
} catch (e: ValidationException) {
assertThat(e.message, `is`(AssetErrorKeys.CashInOutAfterEqualsDay))
}
// 発生日到来処理
val normal = fixtures().cio(accId, "300", true)
.copy(eventDay = baseDay)
.save(rep())
assertThat(normal.process(rep()), allOf(
hasProperty("statusType", `is`(ActionStatusType.Processed)),
hasProperty("cashflowId", not(nullValue()))))
// 発生させたキャッシュフローの検証
assertThat(Cashflow.load(rep(), normal.cashflowId!!), allOf(
hasProperty("accountId", `is`(accId)),
hasProperty("currency", `is`(ccy)),
hasProperty("amount", `is`(BigDecimal("-300"))),
hasProperty("cashflowType", `is`(CashflowType.CashOut)),
hasProperty("remark", `is`(Remarks.CashOut)),
hasProperty("eventDay", `is`(baseDay)),
hasProperty("valueDay", `is`(basePlus3Day)),
hasProperty("statusType", `is`(ActionStatusType.Unprocessed))))
}
}
companion object {
private const val ccy = "JPY"
private const val accId = "test"
}
}
| 1
| null |
1
| 7
|
8d03ce29d4988325c0e369c54b9b784071c3da29
| 7,399
|
sample-boot-kotlin
|
MIT License
|
platform/external-system-impl/src/com/intellij/openapi/externalSystem/statistics/ExternalSystemActionsCollector.kt
|
boreas320
| 50,176,794
| false
| null |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.statistics
import com.intellij.internal.statistic.collectors.fus.actions.persistence.ActionsCollectorImpl
import com.intellij.internal.statistic.eventLog.FeatureUsageData
import com.intellij.internal.statistic.service.fus.collectors.FUCounterUsageLogger
import com.intellij.internal.statistic.service.fus.collectors.UsageDescriptorKeyValidator
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.externalSystem.model.ProjectSystemId
import com.intellij.openapi.project.Project
class ExternalSystemActionsCollector {
companion object {
@JvmStatic
fun trigger(project: Project?,
systemId: ProjectSystemId?,
featureId: String,
place: String?,
isFromContextMenu: Boolean,
vararg additionalContextData: Pair<String, String>) {
val data = FeatureUsageData().addOS().addProject(project)
if (place != null) {
data.addPlace(place).addData("context_menu", isFromContextMenu)
}
for (each in additionalContextData) {
data.addData(each.first, each.second)
}
addSystemId(data, systemId)
FUCounterUsageLogger.getInstance().logEvent("build.tools.actions", UsageDescriptorKeyValidator.ensureProperKey(featureId), data)
}
private fun addSystemId(data: FeatureUsageData,
systemId: ProjectSystemId?) {
data.addData("system_id", systemId?.let { getAnonymizedSystemId(it) } ?: "undefined.system")
}
@JvmStatic
fun trigger(project: Project?,
systemId: ProjectSystemId?,
action: AnAction,
event: AnActionEvent) {
ActionsCollectorImpl.record("build.tools.actions", project, action, event) { data -> addSystemId(data, systemId) }
}
@JvmStatic
fun trigger(project: Project?,
systemId: ProjectSystemId?,
featureId: String,
event: AnActionEvent,
vararg additionalContextData: Pair<String, String>) {
trigger(project, systemId, featureId, event.place, event.isFromContextMenu, *additionalContextData)
}
}
}
| 1
| null |
1
| 1
|
f00ecbdee0408928d3b6581c817fbf3760f7e913
| 2,395
|
intellij-community
|
Apache License 2.0
|
src/commonMain/kotlin/com/adyen/model/transferwebhooks/CALocalAccountIdentification.kt
|
tjerkw
| 733,432,442
| false
|
{"Kotlin": 5043126, "Makefile": 6356}
|
/**
* Transfer webhooks
*
* Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds.
*
* The version of the OpenAPI document: 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 com.adyen.model.transferwebhooks
import kotlinx.serialization.*
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.encoding.*
/**
*
*
* @param accountNumber The 5- to 12-digit bank account number, without separators or whitespace.
* @param institutionNumber The 3-digit institution number, without separators or whitespace.
* @param transitNumber The 5-digit transit number, without separators or whitespace.
* @param type **caLocal**
* @param accountType The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**.
*/
@Serializable
data class CALocalAccountIdentification (
/* The 5- to 12-digit bank account number, without separators or whitespace. */
@SerialName(value = "accountNumber") @Required val accountNumber: kotlin.String,
/* The 3-digit institution number, without separators or whitespace. */
@SerialName(value = "institutionNumber") @Required val institutionNumber: kotlin.String,
/* The 5-digit transit number, without separators or whitespace. */
@SerialName(value = "transitNumber") @Required val transitNumber: kotlin.String,
/* **caLocal** */
@SerialName(value = "type") @Required val type: CALocalAccountIdentification.Type = Type.CaLocal,
/* The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**. */
@SerialName(value = "accountType") val accountType: CALocalAccountIdentification.AccountType? = AccountType.Checking
) {
/**
* **caLocal**
*
* Values: CaLocal
*/
@Serializable
enum class Type(val value: kotlin.String) {
@SerialName(value = "caLocal") CaLocal("caLocal");
}
/**
* The bank account type. Possible values: **checking** or **savings**. Defaults to **checking**.
*
* Values: Checking,Savings
*/
@Serializable
enum class AccountType(val value: kotlin.String) {
@SerialName(value = "checking") Checking("checking"),
@SerialName(value = "savings") Savings("savings");
}
}
| 0
|
Kotlin
|
0
| 0
|
2da5aea5519b2dfa84454fe1665e9699edc87507
| 2,688
|
adyen-kotlin-multiplatform-api-library
|
MIT License
|
tegral-di/tegral-di-core/src/main/kotlin/guru/zoroark/tegral/di/extensions/ExtensibleEnvironmentContext.kt
|
utybo
| 491,247,680
| false
|
{"Kotlin": 1066259, "Nix": 2449, "Shell": 8}
|
/*
* 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 guru.zoroark.tegral.di.extensions
import guru.zoroark.tegral.di.environment.Declarations
import guru.zoroark.tegral.di.environment.EnvironmentContext
/**
* A context for [ExtensibleInjectionEnvironment]s. Provides both the regular set of declarations plus a subcontext for
* the meta-environment.
*/
class ExtensibleEnvironmentContext(
/**
* The declarations for this context, similar to [EnvironmentContext.declarations].
*/
val declarations: Declarations,
/**
* A (non-extensible) environment context for use in the meta-environment.
*/
val metaContext: EnvironmentContext
)
| 26
|
Kotlin
|
4
| 37
|
fa4284047f2ce7ba9ee78e92d8c67954716e9dcc
| 1,189
|
Tegral
|
Apache License 2.0
|
app/src/main/java/com/pandacorp/noteui/domain/usecase/note/RemoveNoteUseCase.kt
|
MrRuslanYT
| 547,794,682
| false
| null |
package com.pandacorp.noteui.domain.usecase.note
import com.pandacorp.noteui.domain.model.NoteItem
import com.pandacorp.noteui.domain.repository.NoteRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class RemoveNoteUseCase(private val repository: NoteRepository) {
suspend operator fun invoke(noteItem: NoteItem) = withContext(Dispatchers.IO) {
repository.remove(noteItem)
}
}
| 0
|
Kotlin
|
0
| 0
|
2baec55561a22a0b9191a9169c0be58a767bf92f
| 431
|
NoteUI
|
Apache License 2.0
|
sam-java-core/src/main/kotlin/software/elborai/api/services/blocking/TransactionServiceImpl.kt
|
DefinitelyATestOrg
| 787,029,081
| false
|
{"Kotlin": 13368521, "Shell": 3638, "Dockerfile": 366}
|
// File generated from our OpenAPI spec by Stainless.
package software.elborai.api.services.blocking
import software.elborai.api.core.ClientOptions
import software.elborai.api.core.RequestOptions
import software.elborai.api.core.http.HttpMethod
import software.elborai.api.core.http.HttpRequest
import software.elborai.api.core.http.HttpResponse.Handler
import software.elborai.api.errors.IncreaseError
import software.elborai.api.models.Transaction
import software.elborai.api.models.TransactionListPage
import software.elborai.api.models.TransactionListParams
import software.elborai.api.models.TransactionRetrieveParams
import software.elborai.api.services.errorHandler
import software.elborai.api.services.jsonHandler
import software.elborai.api.services.withErrorHandler
class TransactionServiceImpl
constructor(
private val clientOptions: ClientOptions,
) : TransactionService {
private val errorHandler: Handler<IncreaseError> = errorHandler(clientOptions.jsonMapper)
private val retrieveHandler: Handler<Transaction> =
jsonHandler<Transaction>(clientOptions.jsonMapper).withErrorHandler(errorHandler)
/** Retrieve a Transaction */
override fun retrieve(
params: TransactionRetrieveParams,
requestOptions: RequestOptions
): Transaction {
val request =
HttpRequest.builder()
.method(HttpMethod.GET)
.addPathSegments("transactions", params.getPathParam(0))
.putAllQueryParams(clientOptions.queryParams)
.putAllQueryParams(params.getQueryParams())
.putAllHeaders(clientOptions.headers)
.putAllHeaders(params.getHeaders())
.build()
return clientOptions.httpClient.execute(request, requestOptions).let { response ->
response
.use { retrieveHandler.handle(it) }
.apply {
if (requestOptions.responseValidation ?: clientOptions.responseValidation) {
validate()
}
}
}
}
private val listHandler: Handler<TransactionListPage.Response> =
jsonHandler<TransactionListPage.Response>(clientOptions.jsonMapper)
.withErrorHandler(errorHandler)
/** List Transactions */
override fun list(
params: TransactionListParams,
requestOptions: RequestOptions
): TransactionListPage {
val request =
HttpRequest.builder()
.method(HttpMethod.GET)
.addPathSegments("transactions")
.putAllQueryParams(clientOptions.queryParams)
.putAllQueryParams(params.getQueryParams())
.putAllHeaders(clientOptions.headers)
.putAllHeaders(params.getHeaders())
.build()
return clientOptions.httpClient.execute(request, requestOptions).let { response ->
response
.use { listHandler.handle(it) }
.apply {
if (requestOptions.responseValidation ?: clientOptions.responseValidation) {
validate()
}
}
.let { TransactionListPage.of(this, params, it) }
}
}
}
| 1
|
Kotlin
|
0
| 0
|
896c77d132ececb8926a3b29f08ea09c98355ecd
| 3,287
|
sam-java
|
Apache License 2.0
|
core/presentation/src/main/java/com/pilinhas/android/core/presentation/constants/AlphaConstants.kt
|
pilinhasapp
| 587,541,347
| false
| null |
package com.pilinhas.android.core.presentation.constants
object AlphaConstants {
const val Disabled = 0.38f
const val Background = 0.5f
}
| 0
|
Kotlin
|
0
| 0
|
075edd796b36203b4950567aecd303e22a330b43
| 146
|
Android
|
MIT License
|
src/main/kotlin/trik/testsys/webclient/controller/StudentController.kt
|
Pupsen-Vupsen
| 627,349,038
| false
|
{"Kotlin": 108374, "HTML": 80239, "CSS": 2402, "Dockerfile": 861}
|
package trik.testsys.webclient.controller
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.http.*
import org.springframework.ui.Model
import org.springframework.util.LinkedMultiValueMap
import org.springframework.util.MultiValueMap
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.client.RestTemplate
import org.springframework.web.multipart.MultipartFile
import trik.testsys.webclient.util.handler.GradingSystemErrorHandler
import trik.testsys.webclient.entity.impl.WebUser
import trik.testsys.webclient.models.ResponseMessage
import trik.testsys.webclient.service.impl.*
import java.time.LocalDateTime
@RestController
@RequestMapping("\${app.testsys.api.prefix}/student")
class StudentController(@Value("\${app.grading-system.path}") val gradingSystemUrl: String) {
private val logger: Logger = LoggerFactory.getLogger(this::class.java)
@Autowired
private lateinit var studentService: StudentService
@Autowired
private lateinit var groupService: GroupService
@Autowired
private lateinit var webUserService: WebUserService
@Autowired
private lateinit var solutionService: SolutionService
@Autowired
private lateinit var taskService: TaskService
private val restTemplate = RestTemplate()
@GetMapping("/registration")
fun registration(@RequestParam groupAccessToken: String, model: Model): Any {
logger.info("[${groupAccessToken.padStart(80)}]: Client trying to register.")
val group = groupService.getGroupByAccessToken(groupAccessToken) ?: run {
logger.info("[${groupAccessToken.padStart(80)}]: Invalid group token.")
return ResponseEntity
.status(HttpStatus.FORBIDDEN)
.body(ResponseMessage(403, "Invalid group token!"))
}
if (!group.isAccessible) {
logger.info("[${groupAccessToken.padStart(80)}]: Group is not accessible.")
return ResponseEntity
.status(HttpStatus.FORBIDDEN)
.body(ResponseMessage(403, "Group is not accessible!"))
}
logger.info("[${groupAccessToken.padStart(80)}]: Group token is valid.")
model.addAttribute("groupAccessToken", groupAccessToken)
return model
}
@PostMapping("/create")
fun createStudent(@RequestParam groupAccessToken: String, @RequestParam username: String, model: Model): Any {
logger.info("[${groupAccessToken.padStart(80)}]: Client trying to create student.")
val group = groupService.getGroupByAccessToken(groupAccessToken) ?: run {
logger.info("[${groupAccessToken.padStart(80)}]: Invalid group token.")
return ResponseEntity
.status(HttpStatus.FORBIDDEN)
.body(ResponseMessage(403, "Invalid group token!"))
}
if (!group.isAccessible) {
logger.info("[${groupAccessToken.padStart(80)}]: Group is not accessible.")
return ResponseEntity
.status(HttpStatus.FORBIDDEN)
.body(ResponseMessage(403, "Group is not accessible!"))
}
logger.info("[${groupAccessToken.padStart(80)}]: Group token is valid.")
val webUser = webUserService.saveWebUser(username)
logger.info("[${groupAccessToken.padStart(80)}]: Web user created.")
val student = studentService.save(webUser, group)
logger.info("[${groupAccessToken.padStart(80)}]: Student created.")
model.addAttribute("id", student.id)
model.addAttribute("username", username)
model.addAttribute("accessToken", webUser.accessToken)
return model
}
@GetMapping
fun getAccess(@RequestParam accessToken: String, model: Model): Any {
logger.info("[${accessToken.padStart(80)}]: Client trying to access student page.")
val status = validateStudent(accessToken)
if (status == WebUser.Status.NOT_FOUND || status == WebUser.Status.ADMIN) {
logger.info("[${accessToken.padStart(80)}]: Client is not a student.")
return ResponseEntity
.status(HttpStatus.FORBIDDEN)
.body(ResponseMessage(403, "You are not a student!"))
}
logger.info("[${accessToken.padStart(80)}]: Client is a student.")
val webUser = webUserService.getWebUserByAccessToken(accessToken)!!
val student = studentService.getByWebUser(webUser)!!
val group = student.group
if (!group.isAccessible) {
logger.info("[${group.accessToken.padStart(80)}]: Group is not accessible.")
return ResponseEntity
.status(HttpStatus.FORBIDDEN)
.body(ResponseMessage(403, "Group is not accessible!"))
}
model.addAttribute("tasks", student.group.tasks.sortedBy { it.id })
model.addAttribute("solutions", student.solutions.sortedBy { it.date })
model.addAttribute("id", student.id)
model.addAttribute("username", webUser.username)
model.addAttribute("accessToken", accessToken)
model.addAttribute("groupName", student.group.name)
return model
}
@PostMapping("/solution/upload")
fun uploadSolution(
@RequestParam accessToken: String,
@RequestParam taskId: Long,
@RequestBody file: MultipartFile,
model: Model
): Any {
restTemplate.errorHandler = GradingSystemErrorHandler()
logger.info("[${accessToken.padStart(80)}]: Client trying to upload solution.")
val status = validateStudent(accessToken)
if (status == WebUser.Status.NOT_FOUND || status == WebUser.Status.ADMIN) {
logger.info("[${accessToken.padStart(80)}]: Client is not a student.")
return ResponseEntity
.status(HttpStatus.FORBIDDEN)
.body(ResponseMessage(403, "You are not a student!"))
}
logger.info("[${accessToken.padStart(80)}]: Client is a student.")
model.addAttribute("accessToken", accessToken)
val webUser = webUserService.getWebUserByAccessToken(accessToken)!!
val student = studentService.getByWebUser(webUser)!!
val group = student.group
if (!group.isAccessible) {
logger.info("[${group.accessToken.padStart(80)}]: Group is not accessible.")
return ResponseEntity
.status(HttpStatus.FORBIDDEN)
.body(ResponseMessage(403, "Group is not accessible!"))
}
val task = taskService.getTaskById(taskId) ?: run {
logger.info("[${accessToken.padStart(80)}]: Invalid task id.")
return ResponseEntity
.status(HttpStatus.FORBIDDEN)
.body(ResponseMessage(403, "Invalid task id!"))
}
val deadline = task.deadline
if (deadline != null && deadline < LocalDateTime.now()) {
logger.info("[${accessToken.padStart(80)}]: Deadline is over.")
//TODO: add normal page
return ResponseEntity
.status(HttpStatus.FORBIDDEN)
.body(ResponseMessage(403, "Deadline is over!"))
}
val taskName = "${task.id}: ${task.name}"
val headers = HttpHeaders()
headers.setBasicAuth("user1", "super")
headers.contentType = MediaType.MULTIPART_FORM_DATA
val body: MultiValueMap<String, Any> = LinkedMultiValueMap()
body.add("file", file.resource)
body.add("task_name", taskName)
body.add("student_id", student.id!!)
val url = "$gradingSystemUrl/submissions/submission/upload"
val submissionInfo = restTemplate.postForEntity(
url,
HttpEntity(body, headers),
Map::class.java
)
if (submissionInfo.statusCodeValue == 422) {
logger.info("[${accessToken.padStart(80)}]: Invalid file.")
model.addAttribute("isCreated", false)
model.addAttribute(
"message",
"Вы отправили некорректный формат файла. Попробуйте отправить файл с расширением .qrs."
)
return model
}
if (submissionInfo.statusCode == HttpStatus.INTERNAL_SERVER_ERROR) {
logger.info("[${accessToken.padStart(80)}]: Something went wrong on grading system server.")
model.addAttribute("isCreated", false)
model.addAttribute(
"message",
"Что-то пошло не так на сервере системы проверки. Обратитесь к администратору и попробуйте позже."
)
return model
}
model.addAttribute("isCreated", true)
val solution =
solutionService.saveSolution(student.id, taskId, submissionInfo.body!!["id"].toString().toLong())!!
logger.info("[${accessToken.padStart(80)}]: Solution uploaded.")
model.addAttribute("id", solution.id)
model.addAttribute("taskName", solution.task.name)
return model
}
private fun validateStudent(accessToken: String): Enum<*> {
val webUser = webUserService.getWebUserByAccessToken(accessToken) ?: run {
return WebUser.Status.NOT_FOUND
}
val student = studentService.getByWebUser(webUser) ?: run {
return WebUser.Status.ADMIN
}
return WebUser.Status.WEB_USER
}
}
| 10
|
Kotlin
|
1
| 0
|
823301cb669a92bbe265c46d9a1094069ed90d67
| 9,831
|
trik-testsys-web-client
|
Apache License 2.0
|
Olebo/src/jvmMain/kotlin/model/dao/DAO.kt
|
TristanBoulesteix
| 158,809,102
| false
| null |
package jdr.exia.model.dao
import jdr.exia.OLEBO_VERSION_CODE
import jdr.exia.localization.*
import jdr.exia.model.element.Element
import jdr.exia.model.tools.DatabaseException
import jdr.exia.system.OLEBO_DIRECTORY
import jdr.exia.update.downloadAndExit
import jdr.exia.view.tools.showConfirmMessage
import jdr.exia.view.tools.windowAncestor
import kotlinx.coroutines.*
import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.SchemaUtils
import org.jetbrains.exposed.sql.Table
import org.jetbrains.exposed.sql.transactions.TransactionManager
import org.jetbrains.exposed.sql.transactions.transaction
import java.io.File
import java.sql.Connection
import javax.swing.JButton
import javax.swing.JOptionPane
import kotlin.system.exitProcess
object DAO : CoroutineScope by CoroutineScope(Dispatchers.IO) {
const val DATABASE_NAME = "database.db"
private val filePath = "${OLEBO_DIRECTORY}db${File.separator}$DATABASE_NAME"
private val url = "jdbc:sqlite:$filePath"
var database: Database = getDatabase()
private set
fun refreshDatabase() {
database = getDatabase()
}
@JvmName("get")
private fun getDatabase() = try {
File(filePath).apply {
this.parentFile.mkdirs()
this.createNewFile()
}
// Initialisation of data and create database connection
Database.connect(url, "org.sqlite.JDBC").also {
TransactionManager.manager.defaultIsolationLevel = Connection.TRANSACTION_SERIALIZABLE
transaction {
// Check database version
SchemaUtils.createMissingTablesAndColumns(BaseInfo)
val version = BaseInfo.versionBase
if (version == null || OLEBO_VERSION_CODE >= version || showUpdateMessageWarn()) {
BaseInfo.initialize()
val oleboTables = tables
SchemaUtils.createMissingTablesAndColumns(*oleboTables)
oleboTables.forEach {
if (it is Initializable)
it.initialize()
}
dropLegacyTables()
// Delete all elements that where removed from scenes
launch { transaction { Element.find { InstanceTable.deleted eq true }.forEach(Element::delete) } }
}
}
}
} catch (e: Exception) {
throw DatabaseException(e)
}
@OptIn(DelicateCoroutinesApi::class)
private fun showUpdateMessageWarn(): Boolean {
var userContinue = false
val update = JButton(StringLocale[STR_UPDATE]).apply {
this.addActionListener {
windowAncestor?.dispose()
GlobalScope.launch {
downloadAndExit(
onExitSuccess = { exitProcess(0) },
onDownloadFailure = { error("Unable to update") }
)
}
}
}
val reset = JButton(StringLocale[STR_RESET]).apply {
this.addActionListener {
windowAncestor?.dispose()
showConfirmMessage(
windowAncestor,
StringLocale[ST_WARNING_CONFIG_RESET],
StringLocale[STR_RESET],
confirm = true
) {
reset()
restart()
}
}
}
val continueButton = JButton(StringLocale[STR_CONTINUE]).apply {
this.addActionListener {
windowAncestor?.dispose()
userContinue = true
}
}
val exit = JButton(StringLocale[STR_EXIT]).apply { this.addActionListener { windowAncestor?.dispose() } }
JOptionPane.showOptionDialog(
null,
StringLocale[ST_DB_VERSION_MISMATCH_MESSAGE],
StringLocale[STR_DB_VERSION_MISMATCH],
JOptionPane.NO_OPTION,
JOptionPane.ERROR_MESSAGE,
null,
arrayOf(update, reset, continueButton, exit),
exit
)
return if (!userContinue) exitProcess(100) else userContinue
}
@OptIn(ExperimentalStdlibApi::class)
private fun dropLegacyTables() = launch {
transaction {
val legacyTables = buildList {
add(object : Table("Priority") {})
}.toTypedArray()
SchemaUtils.drop(*legacyTables)
}
}
}
| 0
|
Kotlin
|
0
| 1
|
263438ba7218f604c75369cdf29edf8232948cde
| 4,530
|
Olebo
|
Apache License 2.0
|
src/main/java/com/example/examplemod/settings/ToggleSetting.kt
|
kerbybit
| 217,620,682
| true
|
{"Kotlin": 99256, "GLSL": 957}
|
package com.example.examplemod.settings
import club.sk1er.elementa.components.UIBlock
import club.sk1er.elementa.components.UIText
import club.sk1er.elementa.constraints.ChildBasedSizeConstraint
import club.sk1er.elementa.constraints.PixelConstraint
import club.sk1er.elementa.constraints.RelativeConstraint
import club.sk1er.elementa.constraints.animation.Animations
import club.sk1er.elementa.dsl.*
import com.example.examplemod.settings.components.Toggle
import net.minecraft.client.Minecraft
import java.awt.Color
class ToggleSetting(name: String, description: String) : SettingObject() {
private val drawBox = UIBlock().constrain {
height = ChildBasedSizeConstraint()
width = RelativeConstraint()
color = Color(0, 0, 0, 0).asConstraint()
} childOf this
private val title = UIText(name).constrain {
x = 3.pixels()
y = 3.pixels()
width = PixelConstraint(Minecraft.getMinecraft().fontRendererObj.getStringWidth(name) * 2f)
height = 18.pixels()
color = Color(255, 255, 255, 10).asConstraint()
} childOf drawBox
private val text = UIText(description).constrain {
x = 3.pixels()
y = 25.pixels()
color = Color(255, 255, 255, 10).asConstraint()
} childOf drawBox
private val toggle = Toggle()
init {
toggle childOf drawBox
}
override fun animateIn() {
super.animateIn()
drawBox.constrain { y = 10.pixels() }
drawBox.animate {
setYAnimation(Animations.OUT_EXP, 0.5f, 0.pixels())
setColorAnimation(Animations.OUT_EXP, 0.5f, Color(0, 0, 0, 100).asConstraint())
}
title.animate { setColorAnimation(Animations.OUT_EXP, 0.5f, Color.WHITE.asConstraint())}
text.animate { setColorAnimation(Animations.OUT_EXP, 0.5f, Color.WHITE.asConstraint()) }
toggle.fadeIn()
}
override fun animateOut() {
super.animateOut()
drawBox.constrain { y = 0.pixels() }
drawBox.animate {
setYAnimation(Animations.OUT_EXP, 0.5f, (-10).pixels())
setColorAnimation(Animations.OUT_EXP, 0.5f, Color(0, 0, 0, 0).asConstraint())
}
title.animate { setColorAnimation(Animations.OUT_EXP, 0.5f, Color(255, 255, 255, 10).asConstraint())}
text.animate { setColorAnimation(Animations.OUT_EXP, 0.5f, Color(255, 255, 255, 10).asConstraint()) }
toggle.fadeOut()
}
}
| 0
| null |
0
| 0
|
9b12a74b0f0e3be87ffb239a0ad9e9b731177df7
| 2,431
|
Elementa
|
MIT License
|
usvm-core/src/main/kotlin/org/usvm/ps/InterleavedPathSelector.kt
|
UnitTestBot
| 586,907,774
| false
|
{"Kotlin": 2626055, "Java": 476812}
|
package org.usvm.ps
import org.usvm.UPathSelector
/**
* An interleaved path selector.
*
* [update], [remove] and [add] operations are executed on each path selector. A pointer to the next path selector
* advances when [add] is called.
*/
class InterleavedPathSelector<State>(
private val selectors: List<UPathSelector<State>>,
) : UPathSelector<State> {
init {
require(selectors.size >= 2) { "Cannot create interleaved path selector from less than 2 selectors" }
}
constructor(vararg selectors: UPathSelector<State>) : this(selectors.toList())
private var ptr = 0
override fun isEmpty() = selectors[ptr].isEmpty() && selectors.all { it.isEmpty() }
override fun peek(): State {
val begin = ptr
while (selectors[ptr].isEmpty()) {
ptr = (ptr + 1) % selectors.size
if (ptr == begin) {
error("Empty queue")
}
}
return selectors[ptr].peek()
}
override fun update(state: State) {
selectors.forEach { it.update(state) }
}
override fun add(states: Collection<State>) {
selectors.forEach { it.add(states) }
ptr = (ptr + 1) % selectors.size
}
override fun remove(state: State) {
selectors.forEach { it.remove(state) }
}
}
| 36
|
Kotlin
|
4
| 9
|
6064702156c536f95e0e213e5416714967ad9150
| 1,304
|
usvm
|
Apache License 2.0
|
python/testSrc/com/jetbrains/env/PyEnvWrappingException.kt
|
ingokegel
| 72,937,917
| false
| null |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.env
/**
* Runtime exception that does not require signature change but wraps real exception.
* See its usages
*/
internal class PyEnvWrappingException(val causeException: Exception)
: RuntimeException("Wraps $causeException", causeException)
| 0
| null |
0
| 2
|
b07eabd319ad5b591373d63c8f502761c2b2dfe8
| 410
|
intellij-community
|
Apache License 2.0
|
app/src/main/java/com/github/vipulasri/timelineview/sample/model/Orientation.kt
|
vipulasri
| 48,049,436
| false
| null |
package com.github.vipulasri.timelineview.sample.model
/**
* Created by <NAME> on 07-06-2016.
*/
enum class Orientation {
VERTICAL,
HORIZONTAL
}
| 7
| null |
648
| 3,734
|
963ac7a9e49aba33c06e3bf52b5a4b938fecec54
| 157
|
Timeline-View
|
Apache License 2.0
|
app/src/main/java/com/atilsamancioglu/artbookhilttesting/ArtBookApplication.kt
|
Sakthidaran3112
| 715,269,600
| false
|
{"Kotlin": 25171}
|
package com.example.artbook
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class ArtBookApplication : Application()
| 0
|
Kotlin
|
0
| 0
|
dc65e29c0b2706a2ff39429a154335cf762c33e2
| 159
|
ArtBook
|
Apache License 2.0
|
app/src/main/java/com/wavesplatform/wallet/v2/ui/home/wallet/assets/token_burn/TokenBurnActivity.kt
|
wavesplatform
| 98,419,999
| false
| null |
/*
* Created by Eduard Zaydel on 1/4/2019
* Copyright © 2019 Waves Platform. All rights reserved.
*/
package com.wavesplatform.wallet.v2.ui.home.wallet.assets.token_burn
import android.content.Intent
import android.os.Bundle
import com.arellomobile.mvp.presenter.InjectPresenter
import com.arellomobile.mvp.presenter.ProvidePresenter
import com.jakewharton.rxbinding2.widget.RxTextView
import com.wavesplatform.wallet.R
import com.wavesplatform.wallet.v1.util.MoneyUtil
import com.wavesplatform.wallet.v2.data.Constants
import com.wavesplatform.wallet.v2.data.analytics.AnalyticEvents
import com.wavesplatform.wallet.v2.data.analytics.analytics
import com.wavesplatform.wallet.v2.ui.base.view.BaseActivity
import com.wavesplatform.wallet.v2.ui.home.wallet.assets.token_burn.confirmation.TokenBurnConfirmationActivity
import com.wavesplatform.wallet.v2.util.*
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.activity_token_burn.*
import kotlinx.android.synthetic.main.content_commission.*
import pers.victor.ext.click
import pers.victor.ext.gone
import pers.victor.ext.isNetworkConnected
import pers.victor.ext.visiable
import java.math.BigDecimal
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class TokenBurnActivity : BaseActivity(), TokenBurnView {
@Inject
@InjectPresenter
lateinit var presenter: TokenBurnPresenter
@ProvidePresenter
fun providePresenter(): TokenBurnPresenter = presenter
override fun configLayoutRes() = R.layout.activity_token_burn
override fun onCreate(savedInstanceState: Bundle?) {
overridePendingTransition(R.anim.slide_in_right, R.anim.null_animation)
super.onCreate(savedInstanceState)
}
override fun onViewReady(savedInstanceState: Bundle?) {
setStatusBarColor(R.color.basic50)
setNavigationBarColor(R.color.basic50)
setupToolbar(toolbar_view, true, getString(R.string.token_burn_toolbar_title), R.drawable.ic_toolbar_back_black)
presenter.assetBalance = intent.getParcelableExtra(
KEY_INTENT_ASSET_BALANCE)
presenter.loadWavesBalance()
image_asset_icon.setAsset(presenter.assetBalance)
text_asset_name.text = presenter.assetBalance.getName()
text_asset_value.text = presenter.assetBalance.getDisplayAvailableBalance()
text_use_total_balance.click {
edit_amount.setText(presenter.assetBalance.getDisplayAvailableBalance().clearBalance())
}
edit_amount.applyFilterStartWithDot()
eventSubscriptions.add(RxTextView.textChanges(edit_amount)
.skipInitialValue()
.map(CharSequence::toString)
.debounce(500, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
.map {
if (it.isNotEmpty()) {
presenter.quantityValidation = true
horizontal_amount_suggestion.gone()
text_quantity_error.text = ""
text_quantity_error.gone()
} else {
presenter.quantityValidation = false
horizontal_amount_suggestion.visiable()
text_quantity_error.text = getString(R.string.token_burn_validation_is_required_error)
text_quantity_error.visiable()
}
return@map it
}
.filter {
it.isNotEmpty()
}
.map {
if (it.toDouble() != 0.0) {
val isValid = it.toBigDecimal() <= presenter.assetBalance.getDisplayAvailableBalance().clearBalance().toBigDecimal() && it.toBigDecimal() != BigDecimal.ZERO
presenter.quantityValidation = isValid
if (isValid) {
text_quantity_error.text = ""
text_quantity_error.gone()
} else {
text_quantity_error.text = getString(R.string.token_burn_validation_amount_insufficient_error)
text_quantity_error.visiable()
}
makeButtonEnableIfValid()
return@map Pair(isValid, it)
} else {
presenter.quantityValidation = false
return@map Pair(false, it)
}
}
.map {
if (it.first) {
presenter.wavesBalance.getAvailableBalance().notNull { wavesBalance ->
if (wavesBalance < presenter.fee) {
presenter.quantityValidation = false
linear_fees_error.visiable()
} else {
presenter.quantityValidation = true
linear_fees_error.gone()
}
}
}
}
.compose(RxUtil.applyObservableDefaultSchedulers())
.subscribe({ isValid ->
makeButtonEnableIfValid()
}, {
it.printStackTrace()
}))
button_continue.click {
analytics.trackEvent(AnalyticEvents.BurnTokenContinueTapEvent)
launchActivity<TokenBurnConfirmationActivity>(REQUEST_BURN_CONFIRM) {
putExtra(KEY_INTENT_ASSET_BALANCE, presenter.assetBalance)
putExtra(KEY_INTENT_BLOCKCHAIN_FEE, presenter.fee)
putExtra(KEY_INTENT_AMOUNT, edit_amount.text.toString())
}
}
presenter.loadCommission(presenter.assetBalance.assetId)
}
override fun needToShowNetworkMessage() = true
override fun onNetworkConnectionChanged(networkConnected: Boolean) {
super.onNetworkConnectionChanged(networkConnected)
if (networkConnected) {
// enable quick action tab
button_continue.isEnabled = presenter.isAllFieldsValid()
} else {
// disable quick action tab
button_continue.isEnabled = false
}
}
private fun makeButtonEnableIfValid() {
button_continue.isEnabled = presenter.isAllFieldsValid() && isNetworkConnected()
}
override fun onBackPressed() {
finish()
overridePendingTransition(R.anim.null_animation, R.anim.slide_out_right)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
REQUEST_BURN_CONFIRM -> {
when (resultCode) {
Constants.RESULT_OK -> {
setResult(Constants.RESULT_OK)
finish()
}
Constants.RESULT_SMART_ERROR -> {
showAlertAboutScriptedAccount()
}
}
}
}
}
override fun showCommissionLoading() {
progress_bar_fee_transaction.show()
text_fee_transaction.gone()
button_continue.isEnabled = false
}
override fun showCommissionSuccess(unscaledAmount: Long) {
text_fee_transaction.text = MoneyUtil.getWavesStripZeros(unscaledAmount)
progress_bar_fee_transaction.hide()
text_fee_transaction.visiable()
makeButtonEnableIfValid()
}
override fun showCommissionError() {
text_fee_transaction.text = "-"
showError(R.string.common_error_commission_receiving, R.id.root)
progress_bar_fee_transaction.hide()
text_fee_transaction.visiable()
makeButtonEnableIfValid()
}
override fun onDestroy() {
progress_bar_fee_transaction.hide()
super.onDestroy()
}
companion object {
const val KEY_INTENT_ASSET_BALANCE = "asset_balance"
const val KEY_INTENT_AMOUNT = "amount"
const val KEY_INTENT_BLOCKCHAIN_FEE = "blockchain_fee"
const val REQUEST_BURN_CONFIRM = 10001
}
}
| 2
| null |
52
| 55
|
5f4106576dc4fe377a355d045f638e7469cd6abe
| 8,309
|
WavesWallet-android
|
MIT License
|
kotlin-mui-icons/src/main/generated/mui/icons/material/SensorDoorSharp.kt
|
JetBrains
| 93,250,841
| false
| null |
// Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/SensorDoorSharp")
@file:JsNonModule
package mui.icons.material
@JsName("default")
external val SensorDoorSharp: SvgIconComponent
| 12
|
Kotlin
|
5
| 983
|
a99345a0160a80a7a90bf1adfbfdc83a31a18dd6
| 212
|
kotlin-wrappers
|
Apache License 2.0
|
app/src/main/java/com/srg/codetestrickmorty/common/di/modules/RemoteModule.kt
|
sebrodgar
| 353,656,877
| false
| null |
package com.srg.codetestrickmorty.common.di.modules
import android.content.Context
import com.chuckerteam.chucker.api.ChuckerCollector
import com.chuckerteam.chucker.api.ChuckerInterceptor
import com.google.gson.GsonBuilder
import com.srg.codetestrickmorty.common.adapters.LocalDateTimeAdapter
import dagger.Module
import dagger.Provides
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.time.LocalDateTime
import java.util.concurrent.TimeUnit
@Module
object RemoteModule {
private const val READ_TIMEOUT_SECONDS = 40L
private const val WRITE_TIMEOUT_SECONDS = 40L
@Provides
fun provideRetrofitService(context: Context): Retrofit = Retrofit.Builder()
.baseUrl("https://rickandmortyapi.com/api/")
.client(provideOkHttpClient(context))
.addConverterFactory(
GsonConverterFactory.create(
GsonBuilder().registerTypeAdapter(
LocalDateTime::class.java,
LocalDateTimeAdapter()
).create()
)
)
.build()
private fun provideOkHttpClient(context: Context): OkHttpClient =
OkHttpClient.Builder()
.readTimeout(READ_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.writeTimeout(WRITE_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.addInterceptor(
ChuckerInterceptor.Builder(context)
.collector(ChuckerCollector(context))
.maxContentLength(250000L)
.redactHeaders(emptySet())
.alwaysReadResponseBody(false)
.build()
)
.build()
}
| 0
|
Kotlin
|
0
| 0
|
dfb2f16f8d12809bc97f17cbe4a267df46bf3ffa
| 1,703
|
code-test-rick-morty
|
Apache License 2.0
|
lib_base/src/main/java/com/karashok/lib_base/ui/fgt/BaseDialogFgt.kt
|
KaraShok
| 201,876,500
| false
| null |
package com.karashok.lib_base.ui.fgt
import android.app.Dialog
import android.content.DialogInterface
import android.os.Bundle
import androidx.annotation.LayoutRes
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import com.karashok.lib_base.R
import com.karashok.lib_base.widget.cancelable_dialog.CancelableDialog
import com.karashok.lib_base.widget.cancelable_dialog.DismissListener
import com.karashok.lib_base.widget.cancelable_dialog.PreCancelCallback
import com.karashok.lib_base.widget.cancelable_dialog.ShouldCancelCallback
/**
* @author KaraShokZ (张耀中)
* DESCRIPTION
* @name BaseDialogFgt
* @date 2019/08/01 20:44
**/
open abstract class BaseDialogFgt: DialogFragment(), PreCancelCallback, ShouldCancelCallback {
companion object{
val DEFAULT_DIM: Float = 0.8F
}
private var mDismissListener: DismissListener? = null
private var mCancelOnTouchOutside: Boolean = true
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setStyle(DialogFragment.STYLE_NO_TITLE, theme)
}
/**
* 如果需要设置主题,请重写这个函数,并返回一个主题
*/
override fun getTheme(): Int {
return R.style.styleLibBaseDialogFgt
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val dialog = CancelableDialog(requireActivity(), theme)
val window = dialog.window
window.setDimAmount(getDimAmount())
dialog.mPreCancelCallback = this
dialog.mShouldCancelCallback = this
return super.onCreateDialog(savedInstanceState)
}
/**
* dialog 非内容区域的黑色透明度,默认 0.8
*/
protected open fun getDimAmount(): Float {
return DEFAULT_DIM
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view: View = inflater.inflate(getLayoutRes(),container,false)
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
bindView(view)
}
override fun show(manager: FragmentManager, tag: String?) {
val ft = manager.beginTransaction()
ft.add(this, tag)
ft.commitAllowingStateLoss()
}
override fun show(transaction: FragmentTransaction, tag: String?): Int {
return super.show(transaction, tag)
}
/**
* 安全的显示 dialog
*/
fun showAllowingStateLoss(fmgr: FragmentManager) {
show(fmgr, getFragmentTag())
}
@LayoutRes
abstract fun getLayoutRes(): Int
abstract fun bindView(v: View)
/**
* 点击返回按钮, dialog 是否应该消失
*/
override fun shouldCancelOnBackPressed(): Boolean {
return true
}
/**
* 点击 dialog 的 外围 是否应该消失
*/
override fun shouldCancelOnTouchOutside(): Boolean {
return mCancelOnTouchOutside
}
fun setCancelOnTouchOutside(cancelOnTouchOutside: Boolean) {
mCancelOnTouchOutside = cancelOnTouchOutside
}
/**
* cancel 之前的回调
*/
override fun onPreCancel() {}
override fun dismiss() {
dismissAllowingStateLoss()
}
fun setOnDismissListener(listener: DismissListener) {
mDismissListener = listener
}
override fun onDismiss(dialog: DialogInterface) {
super.onDismiss(dialog)
mDismissListener?.let {
it.onDismiss()
}
}
fun getFragmentTag(): String {
return "lib_base_dialog_fgt_" + getIdentityString()
}
protected fun getIdentityString(): String {
return Integer.toHexString(System.identityHashCode(this))
}
}
| 0
|
Kotlin
|
0
| 1
|
ac84f9c0758ab9cde999656d3d6b157bf4ac7bdd
| 3,811
|
MVVM-Android-For-Kotlin
|
Apache License 2.0
|
src/main/kotlin/com/github/michaelbull/advent2023/day20/PulseStrength.kt
|
michaelbull
| 726,012,340
| false
|
{"Kotlin": 182829}
|
package com.github.michaelbull.advent2023.day20
sealed interface PulseStrength
data object HighPulse : PulseStrength
data object LowPulse : PulseStrength
| 0
|
Kotlin
|
0
| 1
|
045b8fa21e45b17de76cf021d662865b010920ef
| 156
|
advent-2023
|
ISC License
|
sample/src/main/java/com/doool/gooey/samples/CircleRotation.kt
|
D000L
| 437,907,424
| false
| null |
package com.doool.gooey.samples
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.animateOffsetAsState
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.animation.core.withInfiniteAnimationFrameMillis
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.TransformOrigin
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.unit.dp
import com.doool.gooey.gooeyBackground
import com.doool.gooey.gooeyEffect
import kotlin.random.Random
fun RandomOffset() = Offset(
Random.nextFloat(), Random.nextFloat()
)
@Composable
fun CircleRotation(modifier: Modifier = Modifier) {
Box(
modifier
.fillMaxSize()
.gooeyEffect(),
contentAlignment = Alignment.Center
) {
val positions = remember { mutableStateListOf<Offset>() }
val pivots = remember { mutableStateListOf<Offset>() }
val rotates = remember { mutableStateListOf<Float>() }
for (i in 0..3) {
positions.add(RandomOffset() * 200f - Offset(100f, 100f))
pivots.add(RandomOffset() * 1f - Offset(0.5f, 0.5f))
rotates.add(90f * i)
}
LaunchedEffect(Unit) {
while (true) {
withInfiniteAnimationFrameMillis {
for (i in 0..3) {
if (it % 10 == Random.nextLong(10)) {
positions[i] = RandomOffset() * 200f - Offset(100f, 100f)
pivots[i] = RandomOffset() * 0.4f - Offset(0.2f, 0.2f)
}
if (it % 20 == Random.nextLong(20)) {
rotates[i] = Random.nextFloat() * 720f - 360f
}
}
}
}
}
val progress by rememberInfiniteTransition().animateFloat(
initialValue = 0f, targetValue = 360f, animationSpec = infiniteRepeatable(
tween(2000, easing = LinearEasing), repeatMode = RepeatMode.Restart
)
)
val colors = remember { listOf(Color.Red, Color.Blue, Color.Green, Color.Magenta) }
for (i in 0..3) {
val position by animateOffsetAsState(targetValue = positions[i], tween(2000))
val pivot by animateOffsetAsState(targetValue = pivots[i], tween(2000))
val rotate by animateFloatAsState(targetValue = rotates[i], tween(2000))
Box(
modifier = Modifier
.size(30.dp + 20.dp.times(i))
.graphicsLayer(
rotationZ = progress + rotate,
translationX = position.x,
translationY = position.y,
transformOrigin = TransformOrigin(pivot.x, pivot.x)
)
.gooeyBackground(
shape = CircleShape, color = colors[i]
)
)
}
}
}
| 0
| null |
0
| 9
|
351dd7eddd4efba8572cfb677a43649e608b43dd
| 3,859
|
Gooey
|
Apache License 2.0
|
src/main/kotlin/org/rooftop/netx/redis/RedisStreamTransactionDispatcher.kt
|
rooftop-MSA
| 751,298,974
| false
|
{"Kotlin": 53287}
|
package org.rooftop.netx.redis
import jakarta.annotation.PostConstruct
import org.rooftop.netx.api.TransactionCommitHandler
import org.rooftop.netx.api.TransactionJoinHandler
import org.rooftop.netx.api.TransactionRollbackHandler
import org.rooftop.netx.api.TransactionStartHandler
import org.rooftop.netx.engine.AbstractTransactionDispatcher
import org.rooftop.netx.idl.Transaction
import org.rooftop.netx.idl.TransactionState
import org.rooftop.netx.meta.TransactionHandler
import org.springframework.context.ApplicationContext
import org.springframework.data.redis.connection.stream.ReadOffset
import org.springframework.data.redis.connection.stream.StreamOffset
import org.springframework.data.redis.core.ReactiveRedisTemplate
import reactor.core.publisher.Mono
import kotlin.reflect.KClass
import kotlin.reflect.KFunction
import kotlin.reflect.full.declaredMemberFunctions
class RedisStreamTransactionDispatcher(
private val applicationContext: ApplicationContext,
private val reactiveRedisTemplate: ReactiveRedisTemplate<String, ByteArray>,
private val redisStreamTransactionRemover: RedisStreamTransactionRemover,
private val nodeGroup: String,
) : AbstractTransactionDispatcher() {
@PostConstruct
@Suppress("Unchecked_cast")
override fun initHandlers() {
val transactionHandler = findHandlers(TransactionHandler::class)
transactionHandler.forEach { handler ->
handler::class.declaredMemberFunctions
.filter { it.returnType.classifier == Mono::class }
.forEach { function ->
function.annotations
.forEach { annotation ->
runCatching {
val transactionState = matchedTransactionState(annotation)
transactionHandlerFunctions.putIfAbsent(
transactionState,
mutableListOf()
)
transactionHandlerFunctions[transactionState]?.add(function as KFunction<Mono<Any>> to handler)
}
}
}
}
}
private fun <T : Annotation> findHandlers(type: KClass<T>): List<Any> {
return applicationContext.getBeansWithAnnotation(type.java)
.entries.asSequence()
.map { it.value }
.toList()
}
private fun matchedTransactionState(annotation: Annotation): TransactionState {
return when (annotation) {
is TransactionStartHandler -> TransactionState.TRANSACTION_STATE_START
is TransactionCommitHandler -> TransactionState.TRANSACTION_STATE_COMMIT
is TransactionJoinHandler -> TransactionState.TRANSACTION_STATE_JOIN
is TransactionRollbackHandler -> TransactionState.TRANSACTION_STATE_ROLLBACK
else -> throw notMatchedTransactionHandlerException
}
}
override fun findOwnTransaction(transaction: Transaction): Mono<Transaction> {
return reactiveRedisTemplate.opsForStream<String, String>()
.read(StreamOffset.create(transaction.id, ReadOffset.from("0")))
.map { Transaction.parseFrom(it.value["data"]?.toByteArray()) }
.filter { it.group == nodeGroup }
.filter { hasUndo(it) }
.next()
}
private fun hasUndo(transaction: Transaction): Boolean =
transaction.state == TransactionState.TRANSACTION_STATE_JOIN
|| transaction.state == TransactionState.TRANSACTION_STATE_START
override fun ack(transaction: Transaction, messageId: String): Mono<Pair<Transaction, String>> {
return reactiveRedisTemplate.opsForStream<String, ByteArray>()
.acknowledge(transaction.id, nodeGroup, messageId)
.map { transaction to messageId }
.switchIfEmpty(
Mono.error {
error("Fail to ack transaction transactionId \"${transaction.id}\" messageId \"$messageId\"")
}
)
}
override fun deleteElastic(
transaction: Transaction,
messageId: String
) = redisStreamTransactionRemover.deleteElastic(transaction)
private companion object {
private val notMatchedTransactionHandlerException =
IllegalStateException("Cannot find matched Transaction handler")
}
}
| 3
|
Kotlin
|
0
| 0
|
ccbccfc7e5c22aedd807071af292025685111ef6
| 4,453
|
Netx
|
Apache License 2.0
|
annotation/src/main/kotlin/net/myna/mnbt/annotations/FieldValueProvider.kt
|
Cmyna
| 594,304,817
| false
| null |
package net.myna.mnbt.annotations
import java.lang.Exception
import java.lang.RuntimeException
import java.lang.reflect.Field
/**
* an abstract class that can provide default value for a field in Tag->Object conversion.
* it is used with annotation [Ignore], when we try to convert a compound tag to an java object.
* The converter will ignore read sub tag with name mapped to field, and use value from this provider instead.
*
* it is suggested to let class implement this interface has empty constructor, so the annotation handler can create it safely
*
* [provide] function should not rely any runtime context, or [StateException] may be threw from caller
*/
interface FieldValueProvider {
/**
* provide a default value for a field
* @param field: the field type containing the value
*/
fun provide(field: Field):Any?
/**
* for catching any Exceptions from FieldValueProvider.provide(), and throws this exception out
*/
class StateException(exception: Exception):RuntimeException() {
override val cause: Throwable = exception
override val message: String = "Exception throws when invoking FieldValueProvider.provide() method"
}
companion object {
/**
* try provide value by field. Capturing any Exception and throw as [StateException]
* @throws [StateException] if any Exceptions caught in method
*
*/
fun FieldValueProvider.tryProvide(field: Field):Any? {
return try {
this.provide(field)
} catch (exception:Exception) {
throw FieldValueProvider.StateException(exception)
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
b8117d297ae41748ffc5c74f3c087784c83026cb
| 1,694
|
mnbt-in-development-
|
Apache License 2.0
|
plugin/src/main/kotlin/dev/triumphteam/triumphchat/listeners/PlayerListener.kt
|
TriumphTeam
| 294,288,510
| false
|
{"Kotlin": 128629}
|
/*
* Copyright (c) 2020 HeartPattern and Spikot authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.heartpattern.spikot.test
import io.heartpattern.spikot.bean.AfterInitialize
import io.heartpattern.spikot.bean.BeforeDestroy
import io.heartpattern.spikot.bean.Component
import io.heartpattern.spikot.bean.inject
import io.heartpattern.spikot.scope.BeanDefinitionRegistryScopeInstance
import mu.KotlinLogging
import org.bukkit.Bukkit
import org.bukkit.event.EventHandler
import org.bukkit.event.player.PlayerJoinEvent
import org.bukkit.event.player.PlayerQuitEvent
@Component
class TestEventComponent {
private val logger = KotlinLogging.logger {}
private val injected: TestComponent by inject()
private val scope by inject<BeanDefinitionRegistryScopeInstance>()
@AfterInitialize
fun initialize() {
logger.info("Enable test event component")
}
@BeforeDestroy
fun destroy() {
logger.info("Disable test event component")
}
@EventHandler
private fun PlayerJoinEvent.onPlayerJoin() {
Bukkit.broadcastMessage("Hello, ${player.name}")
}
@EventHandler
private fun onPlayerQuit(event: PlayerQuitEvent) {
Bukkit.broadcastMessage("Bye, ${event.player.name}")
}
}
| 0
|
Kotlin
|
2
| 2
|
fa22204ac59d5eff46f26089e4eae9e7f3593d29
| 2,298
|
triumph-chat
|
MIT License
|
app/src/main/java/org/fossasia/openevent/general/MainActivity.kt
|
G-LOKi
| 178,464,508
| false
| null |
package org.fossasia.openevent.general
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.NavigationUI.setupWithNavController
import com.google.android.material.snackbar.Snackbar
import kotlinx.android.synthetic.main.activity_main.navigation
import kotlinx.android.synthetic.main.activity_main.navigationAuth
import kotlinx.android.synthetic.main.activity_main.mainFragmentCoordinatorLayout
import org.fossasia.openevent.general.auth.EditProfileFragment
import org.fossasia.openevent.general.utils.Utils.navAnimGone
import org.fossasia.openevent.general.utils.Utils.navAnimVisible
class MainActivity : AppCompatActivity() {
private lateinit var navController: NavController
private var currentFragmentId: Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
setTheme(R.style.AppTheme)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val hostFragment = supportFragmentManager.findFragmentById(R.id.frameContainer)
if (hostFragment is NavHostFragment)
navController = hostFragment.navController
setupBottomNavigationMenu(navController)
navController.addOnDestinationChangedListener { _, destination, _ ->
currentFragmentId = destination.id
handleNavigationVisibility(currentFragmentId)
}
}
private fun setupBottomNavigationMenu(navController: NavController) {
setupWithNavController(navigation, navController)
setupWithNavController(navigationAuth, navController)
navigation.setOnNavigationItemReselectedListener {
val hostFragment = supportFragmentManager.findFragmentById(R.id.frameContainer)
if (hostFragment is NavHostFragment) {
val currentFragment = hostFragment.childFragmentManager.fragments.first()
if (currentFragment is ScrollToTop) currentFragment.scrollToTop()
}
}
}
private fun handleNavigationVisibility(id: Int) {
when (id) {
R.id.eventsFragment,
R.id.searchFragment,
R.id.profileFragment,
R.id.orderUnderUserFragment,
R.id.favoriteFragment -> navAnimVisible(navigation, this@MainActivity)
else -> navAnimGone(navigation, this@MainActivity)
}
when (id) {
R.id.loginFragment,
R.id.signUpFragment -> navAnimVisible(navigationAuth, this@MainActivity)
else -> navAnimGone(navigationAuth, this@MainActivity)
}
}
override fun onBackPressed() {
when (currentFragmentId) {
R.id.loginFragment,
R.id.signUpFragment -> {
navController.popBackStack(R.id.eventsFragment, false)
Snackbar.make(
mainFragmentCoordinatorLayout, R.string.sign_in_canceled, Snackbar.LENGTH_SHORT
).show()
}
R.id.orderCompletedFragment -> navController.popBackStack(R.id.eventDetailsFragment, false)
R.id.welcomeFragment -> finish()
R.id.editProfileFragment -> {
// Calls the handleBackPress method in EditProfileFragment
val hostFragment = supportFragmentManager.findFragmentById(R.id.frameContainer) as? NavHostFragment
(hostFragment?.childFragmentManager?.fragments?.get(0) as? EditProfileFragment)?.handleBackPress()
}
else -> super.onBackPressed()
}
}
/**
* Called by EditProfileFragment to go to previous fragment
*/
fun onSuperBackPressed() {
super.onBackPressed()
}
}
interface ScrollToTop {
fun scrollToTop()
}
| 0
| null |
0
| 1
|
7e6d70dbfcbeb014ac9dc02ccfd66cc575697c87
| 3,830
|
open-event-android
|
Apache License 2.0
|
litho-widget-kotlin/src/main/kotlin/com/facebook/litho/widget/collection/CollectionGroupSectionSpec.kt
|
facebook
| 80,179,724
| false
| null |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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.facebook.litho.widget.collection
import com.facebook.litho.ComponentContext
import com.facebook.litho.annotations.Prop
import com.facebook.litho.sections.ChangesInfo
import com.facebook.litho.sections.Children
import com.facebook.litho.sections.SectionContext
import com.facebook.litho.sections.annotations.GroupSectionSpec
import com.facebook.litho.sections.annotations.OnCreateChildren
import com.facebook.litho.sections.annotations.OnDataBound
import com.facebook.litho.sections.annotations.OnDataRendered
import com.facebook.litho.sections.annotations.OnRefresh
import com.facebook.litho.sections.annotations.OnViewportChanged
@GroupSectionSpec
object CollectionGroupSectionSpec {
@JvmStatic
@OnCreateChildren
fun onCreateChildren(c: SectionContext?, @Prop childrenBuilder: Children.Builder): Children =
childrenBuilder.build()
@JvmStatic
@OnDataBound
fun onDataBound(
c: SectionContext,
@Prop(optional = true) onDataBound: ((ComponentContext) -> Unit)?
) {
onDataBound?.invoke(c)
}
@JvmStatic
@OnViewportChanged
fun onViewportChanged(
c: SectionContext,
firstVisibleIndex: Int,
lastVisibleIndex: Int,
totalCount: Int,
firstFullyVisibleIndex: Int,
lastFullyVisibleIndex: Int,
@Prop(optional = true)
onViewportChanged: ((ComponentContext, Int, Int, Int, Int, Int) -> Unit)?
) {
onViewportChanged?.invoke(
c,
firstVisibleIndex,
lastVisibleIndex,
totalCount,
firstFullyVisibleIndex,
lastFullyVisibleIndex)
}
@JvmStatic
@OnRefresh
fun onRefresh(c: SectionContext, @Prop(optional = true) onPullToRefresh: (() -> Unit)?) {
onPullToRefresh?.invoke()
}
@JvmStatic
@OnDataRendered
fun onDataRendered(
c: SectionContext,
isDataChanged: Boolean,
isMounted: Boolean,
monoTimestampMs: Long,
firstVisibleIndex: Int,
lastVisibleIndex: Int,
changesInfo: ChangesInfo,
globalOffset: Int,
@Prop(optional = true)
onDataRendered:
((ComponentContext, Boolean, Boolean, Long, Int, Int, ChangesInfo, Int) -> Unit)?
) {
onDataRendered?.invoke(
c,
isDataChanged,
isMounted,
monoTimestampMs,
firstVisibleIndex,
lastVisibleIndex,
changesInfo,
globalOffset)
}
}
| 115
| null |
743
| 7,515
|
106d1e99dc132194d6004c3b7bff70c327310526
| 2,984
|
litho
|
Apache License 2.0
|
app/src/main/kotlin/no/nav/k9punsj/domenetjenester/SoknadService.kt
|
navikt
| 216,808,662
| false
| null |
package no.nav.k9punsj.domenetjenester
import no.nav.k9.kodeverk.dokument.Brevkode
import no.nav.k9.søknad.Søknad
import no.nav.k9punsj.domenetjenester.repository.SøknadRepository
import no.nav.k9punsj.felles.dto.SøknadEntitet
import no.nav.k9punsj.hentCorrelationId
import no.nav.k9punsj.innsending.InnsendingClient
import no.nav.k9punsj.integrasjoner.dokarkiv.SafDtos
import no.nav.k9punsj.integrasjoner.dokarkiv.SafGateway
import no.nav.k9punsj.journalpost.JournalpostService
import no.nav.k9punsj.metrikker.SøknadMetrikkService
import no.nav.k9punsj.utils.objectMapper
import org.slf4j.LoggerFactory
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Service
import java.util.UUID
import kotlin.coroutines.coroutineContext
@Service
internal class SoknadService(
private val journalpostService: JournalpostService,
private val søknadRepository: SøknadRepository,
private val innsendingClient: InnsendingClient,
private val søknadMetrikkService: SøknadMetrikkService,
private val safGateway: SafGateway
) {
internal suspend fun sendSøknad(
søknad: Søknad,
brevkode: Brevkode,
journalpostIder: MutableSet<String>
): Pair<HttpStatus, String>? {
val journalpostIdListe = journalpostIder.toList()
val journalposterKanSendesInn = journalpostService.kanSendeInn(journalpostIdListe)
val punsjetAvSaksbehandler = søknadRepository.hentSøknad(søknad.søknadId.id)?.endret_av!!.replace("\"", "")
if (!journalposterKanSendesInn) {
return HttpStatus.CONFLICT to "En eller alle journalpostene $journalpostIder har blitt sendt inn fra før"
}
val journalposter = safGateway.hentJournalposter(journalpostIdListe)
val journalposterMedTypeUtgaaende = journalposter.filterNotNull()
.filter { it.journalposttype.equals(SafDtos.JournalpostType.U) }
.map { it.journalpostId }
.toSet()
if (journalposterMedTypeUtgaaende.isNotEmpty()) {
return HttpStatus.CONFLICT to "Journalposter av type utgående ikke støttet: $journalposterMedTypeUtgaaende"
}
val journalposterMedStatusFeilregistrert = journalposter.filterNotNull()
.filter { it.journalstatus != null }
.filter { it.journalstatus!!.equals(SafDtos.Journalstatus.FEILREGISTRERT.toString()) }
.map { it.journalpostId }
.toSet()
if (journalposterMedStatusFeilregistrert.isNotEmpty()) {
return HttpStatus.CONFLICT to "Journalposter med status feilregistrert ikke støttet: $journalposterMedStatusFeilregistrert"
}
val correlationId = try {
coroutineContext.hentCorrelationId()
} catch (e: Exception) {
UUID.randomUUID().toString()
}
try {
innsendingClient.sendSøknad(
søknadId = søknad.søknadId.id,
søknad = søknad,
correlationId = correlationId,
tilleggsOpplysninger = mapOf(
PunsjetAvSaksbehandler to punsjetAvSaksbehandler,
Søknadtype to brevkode.kode
)
)
} catch (e: Exception) {
logger.error("Feil vid innsending av søknad for journalpostIder: ${søknad.journalposter}")
return Pair(HttpStatus.INTERNAL_SERVER_ERROR, e.stackTraceToString())
}
leggerVedPayload(søknad, journalpostIder)
journalpostService.settAlleTilFerdigBehandlet(journalpostIdListe)
logger.info("Punsj har market disse journalpostIdene $journalpostIder som ferdigbehandlet")
søknadRepository.markerSomSendtInn(søknad.søknadId.id)
søknadMetrikkService.publiserMetrikker(søknad)
return null
}
suspend fun hentSøknad(søknadId: String): SøknadEntitet? {
return søknadRepository.hentSøknad(søknadId)
}
suspend fun opprettSøknad(søknad: SøknadEntitet): SøknadEntitet {
return søknadRepository.opprettSøknad(søknad)
}
suspend fun oppdaterSøknad(søknad: SøknadEntitet) {
søknadRepository.oppdaterSøknad(søknad)
}
suspend fun hentAlleSøknaderForBunke(bunkerId: String): List<SøknadEntitet> {
return søknadRepository.hentAlleSøknaderForBunke(bunkerId)
}
suspend fun hentSistEndretAvSaksbehandler(søknadId: String): String {
return søknadRepository.hentSøknad(søknadId)?.endret_av!!.replace("\"", "")
}
private suspend fun leggerVedPayload(
søknad: Søknad,
journalpostIder: MutableSet<String>
) {
val writeValueAsString = objectMapper().writeValueAsString(søknad)
journalpostIder.forEach {
val journalpost = journalpostService.hent(it)
val medPayload = journalpost.copy(payload = writeValueAsString)
journalpostService.lagre(medPayload)
}
}
companion object {
private val logger = LoggerFactory.getLogger(SoknadService::class.java)
private const val PunsjetAvSaksbehandler = "saksbehandler"
private const val Søknadtype = "søknadtype"
}
}
| 9
|
Kotlin
|
2
| 1
|
d42013d04a36b05bce1750c912ae186626f45049
| 5,132
|
k9-punsj
|
MIT License
|
overlord-server/src/main/kotlin/tv/dotstart/overlord/server/listener/ServerInitializationListener.kt
|
dotStart
| 260,457,926
| false
|
{"Kotlin": 211624}
|
/*
* Copyright (C) 2020 <NAME> <<EMAIL>>
* and other copyright owners as documented in the project's IP log.
*
* 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 tv.dotstart.overlord.server.listener
import kotlinx.dnq.query.isEmpty
import org.springframework.boot.context.event.ApplicationReadyEvent
import org.springframework.boot.info.BuildProperties
import org.springframework.context.ApplicationListener
import org.springframework.stereotype.Component
import org.springframework.transaction.annotation.Transactional
import tv.dotstart.overlord.server.entity.ServerConfiguration
import tv.dotstart.overlord.server.entity.security.User
import tv.dotstart.overlord.server.entity.security.audit.UserAuditAction
import tv.dotstart.overlord.server.entity.security.audit.UserAuditLogEntry
import tv.dotstart.overlord.server.util.nextString
import tv.dotstart.overlord.shared.delegate.log
import java.security.SecureRandom
const val passwordCharMap = "abcdefghijklmnopqrstuvwxyz0123456789!$%&/=?"
/**
* Handles successful server startups.
*
* The primary purpose of this listener is to initialize the application for first use as well as to
* log any version jumps (e.g. updates).
*
* @author [<NAME>](mailto:<EMAIL>)
* @date 27/06/2020
*/
@Component
class ServerInitializationListener(
private val buildInfo: BuildProperties?) : ApplicationListener<ApplicationReadyEvent> {
companion object {
private val logger by log()
}
@Transactional
override fun onApplicationEvent(event: ApplicationReadyEvent) {
val config = ServerConfiguration.get()
logger.info("Server installation date: ${config.installedAt}")
if (this.buildInfo != null) {
if (config.currentVersion != this.buildInfo.version) {
logger.info("Application version has been altered")
config.currentVersion = this.buildInfo.version
}
} else {
logger.warn("Build information is unavailable - Application version will not be updated")
}
if (User.all().isEmpty) {
val random = SecureRandom()
val password = random.nextString(12)
val adminUser = User.new {
this.name = "admin"
this.displayName = "Administrator"
this.updatePassword(<PASSWORD>)
}
adminUser.auditLog.add(
UserAuditLogEntry.new {
action = UserAuditAction.CREATED
})
logger.info("")
logger.info("")
logger.info("An administrator user has been created for initial application configuration")
logger.info(
"Replacement of the standard username and password is recommended to increase application security")
logger.info("")
logger.info("Username: admin")
logger.info("Password: <PASSWORD>")
logger.info("")
logger.info("Important: This password will not be printed again")
logger.info("")
logger.info("")
}
}
}
| 6
|
Kotlin
|
1
| 0
|
c1050766a48c44a7464b0350eff2f70c906c1ba4
| 3,392
|
overlord
|
Apache License 2.0
|
analysis/analysis-api-impl-base/tests/org/jetbrains/kotlin/analysis/api/impl/base/test/symbols/AbstractSymbolTest.kt
|
JetBrains
| 3,432,266
| false
| null |
/*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.analysis.api.impl.base.test.symbols
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.impl.barebone.test.FrontendApiTestConfiguratorService
import org.jetbrains.kotlin.analysis.api.impl.base.test.test.framework.AbstractHLApiSingleFileTest
import org.jetbrains.kotlin.analysis.api.symbols.DebugSymbolRenderer
import org.jetbrains.kotlin.analysis.api.symbols.KtSymbol
import org.jetbrains.kotlin.analysis.api.symbols.pointers.KtSymbolPointer
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.test.builders.TestConfigurationBuilder
import org.jetbrains.kotlin.test.directives.model.DirectiveApplicability
import org.jetbrains.kotlin.test.directives.model.SimpleDirectivesContainer
import org.jetbrains.kotlin.test.model.TestModule
import org.jetbrains.kotlin.test.services.TestServices
import org.jetbrains.kotlin.test.services.assertions
abstract class AbstractSymbolTest(configurator: FrontendApiTestConfiguratorService) : AbstractHLApiSingleFileTest(configurator) {
override fun configureTest(builder: TestConfigurationBuilder) {
super.configureTest(builder)
with(builder) {
useDirectives(SymbolTestDirectives)
}
}
abstract fun KtAnalysisSession.collectSymbols(ktFile: KtFile, testServices: TestServices): List<KtSymbol>
override fun doTestByFileStructure(ktFile: KtFile, module: TestModule, testServices: TestServices) {
val createPointers = SymbolTestDirectives.DO_NOT_CHECK_SYMBOL_RESTORE !in module.directives
val pointersWithRendered = analyseOnPooledThreadInReadAction(ktFile) {
collectSymbols(ktFile, testServices).map { symbol ->
PointerWithRenderedSymbol(
if (createPointers) symbol.createPointer() else null,
with(DebugSymbolRenderer) { renderExtra(symbol) }
)
}
}
compareResults(pointersWithRendered, testServices)
configurator.doOutOfBlockModification(ktFile)
if (createPointers) {
restoreSymbolsInOtherReadActionAndCompareResults(ktFile, pointersWithRendered, testServices)
}
}
private fun compareResults(
pointersWithRendered: List<PointerWithRenderedSymbol>,
testServices: TestServices,
) {
val actual = pointersWithRendered.joinToString(separator = "\n\n") { it.rendered }
testServices.assertions.assertEqualsToTestDataFileSibling(actual)
}
private fun restoreSymbolsInOtherReadActionAndCompareResults(
ktFile: KtFile,
pointersWithRendered: List<PointerWithRenderedSymbol>,
testServices: TestServices,
) {
val restored = analyseOnPooledThreadInReadAction(ktFile) {
pointersWithRendered.map { (pointer, expectedRender) ->
val restored = pointer!!.restoreSymbol()
?: error("Symbol $expectedRender was not restored")
with(DebugSymbolRenderer) { renderExtra(restored) }
}
}
val actual = restored.joinToString(separator = "\n\n")
testServices.assertions.assertEqualsToTestDataFileSibling(actual)
}
}
private object SymbolTestDirectives : SimpleDirectivesContainer() {
val DO_NOT_CHECK_SYMBOL_RESTORE by directive(
description = "Symbol restoring for some symbols in current test is not supported yet",
applicability = DirectiveApplicability.Global
)
}
private data class PointerWithRenderedSymbol(val pointer: KtSymbolPointer<*>?, val rendered: String)
| 125
| null |
4813
| 39,375
|
83d2d2cfcfc3d9903c902ca348f331f89bed1076
| 3,813
|
kotlin
|
Apache License 2.0
|
app/src/main/java/io/homeassistant/companion/android/onboarding/integration/MobileAppIntegrationFragment.kt
|
nesror
| 328,856,313
| true
| null |
package io.homeassistant.companion.android.onboarding.integration
import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.PowerManager
import android.provider.Settings
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.compose.ui.platform.ComposeView
import androidx.core.content.getSystemService
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import com.google.android.material.composethemeadapter.MdcTheme
import dagger.hilt.android.AndroidEntryPoint
import io.homeassistant.companion.android.common.util.DisabledLocationHandler
import io.homeassistant.companion.android.database.AppDatabase
import io.homeassistant.companion.android.database.sensor.Sensor
import io.homeassistant.companion.android.onboarding.OnboardApp
import io.homeassistant.companion.android.onboarding.OnboardingViewModel
import io.homeassistant.companion.android.sensors.LocationSensorManager
import io.homeassistant.companion.android.common.R as commonR
@AndroidEntryPoint
class MobileAppIntegrationFragment : Fragment() {
companion object {
private const val BACKGROUND_REQUEST = 99
private const val LOCATION_REQUEST_CODE = 0
}
private var dialog: AlertDialog? = null
private val viewModel by activityViewModels<OnboardingViewModel>()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return ComposeView(requireContext()).apply {
setContent {
MdcTheme {
MobileAppIntegrationView(
onboardingViewModel = viewModel,
openPrivacyPolicy = this@MobileAppIntegrationFragment::openPrivacyPolicy,
onLocationTrackingChanged = this@MobileAppIntegrationFragment::onLocationTrackingChanged,
onFinishClicked = this@MobileAppIntegrationFragment::onComplete
)
}
}
}
}
private fun onLocationTrackingChanged(isChecked: Boolean) {
var checked = isChecked
if (isChecked) {
val locationEnabled = DisabledLocationHandler.isLocationEnabled(requireContext())
val permissionOk = LocationSensorManager().checkPermission(
requireContext(),
LocationSensorManager.backgroundLocation.id
)
if (!locationEnabled) {
DisabledLocationHandler.showLocationDisabledWarnDialog(
requireActivity(),
arrayOf(getString(LocationSensorManager.backgroundLocation.name))
)
checked = false
} else if (!permissionOk) {
dialog = AlertDialog.Builder(requireContext())
.setTitle(commonR.string.enable_location_tracking)
.setMessage(commonR.string.enable_location_tracking_prompt)
.setPositiveButton(android.R.string.ok) { _, _ ->
requestPermissions(LocationSensorManager.backgroundLocation.id)
}
.setNegativeButton(android.R.string.cancel) { _, _ -> }
.create()
dialog?.show()
checked = false
}
}
setLocationTracking(checked)
viewModel.locationTrackingEnabled.value = checked
}
private fun requestPermissions(sensorId: String) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
this@MobileAppIntegrationFragment.requestPermissions(
LocationSensorManager().requiredPermissions(sensorId)
.toList().minus(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
.toTypedArray(),
LOCATION_REQUEST_CODE
)
} else {
this@MobileAppIntegrationFragment.requestPermissions(
LocationSensorManager().requiredPermissions(sensorId),
LOCATION_REQUEST_CODE
)
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
dialog?.dismiss()
if (permissions.contains(Manifest.permission.ACCESS_FINE_LOCATION) &&
Build.VERSION.SDK_INT >= Build.VERSION_CODES.R
) {
requestPermissions(
arrayOf(Manifest.permission.ACCESS_BACKGROUND_LOCATION),
LOCATION_REQUEST_CODE
)
}
if (requestCode == LOCATION_REQUEST_CODE) {
val hasPermission = grantResults.all { it == PackageManager.PERMISSION_GRANTED }
viewModel.locationTrackingEnabled.value = hasPermission
setLocationTracking(hasPermission)
requestBackgroundAccess()
}
}
private fun setLocationTracking(enabled: Boolean) {
val sensorDao = AppDatabase.getInstance(requireContext()).sensorDao()
arrayOf(
LocationSensorManager.backgroundLocation,
LocationSensorManager.zoneLocation,
LocationSensorManager.singleAccurateLocation
).forEach { basicSensor ->
var sensorEntity = sensorDao.get(basicSensor.id)
if (sensorEntity != null) {
sensorEntity.enabled = enabled
sensorEntity.lastSentState = ""
sensorDao.update(sensorEntity)
} else {
sensorEntity = Sensor(basicSensor.id, enabled, false, "")
sensorDao.add(sensorEntity)
}
}
}
@SuppressLint("BatteryLife")
private fun requestBackgroundAccess() {
val intent: Intent
if (!isIgnoringBatteryOptimizations()) {
intent = Intent(
Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS,
Uri.parse("package:${activity?.packageName}")
)
startActivityForResult(intent, BACKGROUND_REQUEST)
}
}
private fun isIgnoringBatteryOptimizations(): Boolean {
return Build.VERSION.SDK_INT <= Build.VERSION_CODES.M ||
context?.getSystemService<PowerManager>()
?.isIgnoringBatteryOptimizations(activity?.packageName ?: "")
?: false
}
private fun onComplete() {
val retData = OnboardApp.Output(
url = viewModel.manualUrl.value,
authCode = viewModel.authCode,
deviceName = viewModel.deviceName.value,
deviceTrackingEnabled = viewModel.locationTrackingEnabled.value
)
activity?.setResult(Activity.RESULT_OK, retData.toIntent())
activity?.finish()
}
private fun openPrivacyPolicy() {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(getString(commonR.string.privacy_url)))
startActivity(intent)
}
}
| 83
|
Kotlin
|
371
| 61
|
b36bb0f67fd884b0f8c938c048b51134063784f2
| 7,288
|
Home-Assistant-Companion-for-Android
|
Apache License 2.0
|
src/main/kotlin/tsuzuru/common/presentation/controller/impl/AbstractControllerImpl.kt
|
tmyksj
| 325,959,108
| false
| null |
package tsuzuru.common.presentation.controller.impl
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.ui.Model
import org.springframework.validation.BindingResult
import org.springframework.web.servlet.ModelAndView
import org.springframework.web.servlet.View
import org.springframework.web.servlet.mvc.support.RedirectAttributes
import tsuzuru.common.presentation.exception.PresentationException
import kotlin.reflect.KClass
abstract class AbstractControllerImpl {
fun body(
status: HttpStatus,
informationMessageList: List<String> = listOf(),
warningMessageList: List<String> = listOf(),
errorMessageList: List<String> = listOf(),
): Any {
return ResponseEntity(
mapOf(
"informationMessageList" to informationMessageList,
"warningMessageList" to warningMessageList,
"errorMessageList" to errorMessageList,
), status
)
}
fun <T> body(
status: HttpStatus,
body: T,
informationMessageList: List<String> = listOf(),
warningMessageList: List<String> = listOf(),
errorMessageList: List<String> = listOf(),
): Any {
return ResponseEntity(
mapOf(
"body" to body,
"informationMessageList" to informationMessageList,
"warningMessageList" to warningMessageList,
"errorMessageList" to errorMessageList,
), status
)
}
fun checkErrors(bindingResult: BindingResult) {
if (bindingResult.hasErrors()) {
throw BadRequestException()
}
}
fun redirect(
redirectAttributes: RedirectAttributes,
location: String,
informationMessageList: List<String> = listOf(),
warningMessageList: List<String> = listOf(),
errorMessageList: List<String> = listOf(),
): Any {
redirectAttributes.addFlashAttribute("informationMessageList", informationMessageList)
redirectAttributes.addFlashAttribute("warningMessageList", warningMessageList)
redirectAttributes.addFlashAttribute("errorMessageList", errorMessageList)
return "redirect:${location}"
}
fun view(
model: Model,
status: HttpStatus,
view: View? = null,
layout: String? = null,
template: String? = null,
informationMessageList: List<String> = listOf(),
warningMessageList: List<String> = listOf(),
errorMessageList: List<String> = listOf(),
): Any {
val modelAndView = ModelAndView()
modelAndView.status = status
if (view != null) {
modelAndView.view = view
} else {
modelAndView.addObject("layout", layout)
modelAndView.addObject("template", template)
modelAndView.viewName = layout ?: template ?: throw IllegalArgumentException()
}
modelAndView.addObject("informationMessageList", informationMessageList)
modelAndView.addObject("warningMessageList", warningMessageList)
modelAndView.addObject("errorMessageList", errorMessageList)
modelAndView.addAllObjects(model.asMap())
return modelAndView
}
class BadRequestException : PresentationException()
class Try<T>(
private val block: () -> T,
) {
fun catch(vararg type: KClass<out Throwable>, catchBlock: (e: Throwable) -> T): CatchBlock<T> {
return CatchBlock(block, listOf(type.toList() to catchBlock))
}
class CatchBlock<T>(
private val block: () -> T,
private val catchBlockList: List<Pair<Collection<KClass<out Throwable>>, (e: Throwable) -> T>>,
) {
fun catch(vararg type: KClass<out Throwable>, catchBlock: (e: Throwable) -> T): CatchBlock<T> {
return CatchBlock(block, catchBlockList + listOf(type.toList() to catchBlock))
}
fun rcurl(): T {
return try {
block()
} catch (e: Throwable) {
catchBlockList.find { it.first.contains(e::class) }?.second?.let { it(e) } ?: throw e
}
}
}
}
}
| 3
|
Kotlin
|
0
| 0
|
b7f42ffe09a5e123397d30f61aeb6c1eb9eb0e17
| 4,312
|
tsuzuru
|
Apache License 2.0
|
example/src/main/java/com/aureusapps/android/expandablelayout/CodeActivity.kt
|
UdaraWanasinghe
| 534,710,346
| false
| null |
package com.aureusapps.android.expandablelayout
import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import android.view.Gravity
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.view.animation.DecelerateInterpolator
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.setMargins
import androidx.core.view.setPadding
import com.aureusapps.android.extensions.addView
import com.aureusapps.android.extensions.dp
import com.aureusapps.android.extensions.generateLayoutParams
import com.aureusapps.android.extensions.setTextStyle
import com.google.android.material.button.MaterialButton
@Suppress("NestedLambdaShadowedImplicitParameter")
class CodeActivity : AppCompatActivity() {
private lateinit var expandableLayout: ExpandableLayout
private lateinit var materialButton: MaterialButton
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val rootView = LinearLayout(this)
.apply {
layoutParams = ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT)
gravity = Gravity.CENTER
orientation = LinearLayout.VERTICAL
}
.addView {
MaterialButton(it.context)
.apply {
materialButton = this
layoutParams = it.generateLayoutParams(WRAP_CONTENT, WRAP_CONTENT)
setText(R.string.collapse)
setOnClickListener {
expandableLayout.toggleExpanded()
}
}
}
.addView {
ExpandableLayout(it.context)
.apply {
expandableLayout = this
layoutParams = LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT)
.apply {
setMargins(8.dp)
}
expandDirection = ExpandableLayout.DIRECTION_VERTICAL
setExpanded(true)
animationInterpolator = DecelerateInterpolator()
animationDuration = 2000
contentGravity = ExpandableLayout.GRAVITY_CENTER
setBackgroundResource(R.drawable.frame)
addExpandStateChangeListener(
object : ExpandableLayout.OnExpandStateChangeListener {
override fun onStateChanged(
expandableLayout: ExpandableLayout,
isExpanded: Boolean
) {
materialButton.setText(if (isExpanded) R.string.collapse else R.string.expand)
}
}
)
}
.addView {
TextView(it.context)
.apply {
layoutParams = FrameLayout.LayoutParams(
WRAP_CONTENT,
WRAP_CONTENT
)
setText(R.string.hello_world)
setTextStyle(R.style.TextAppearance_MaterialComponents_Headline2)
setPadding(16.dp)
setTextColor(Color.YELLOW)
textAlignment = TextView.TEXT_ALIGNMENT_CENTER
setTypeface(typeface, Typeface.BOLD)
}
}
}
setContentView(rootView)
}
}
| 0
|
Kotlin
|
0
| 0
|
170bbfb0fffab42d641641cc157133854db26d9e
| 4,032
|
android-expandable-layout
|
MIT License
|
library/src/main/java/com/sa90/onepreference/adapter/HeaderDiffUtil.kt
|
saurabharora90
| 74,263,935
| false
| null |
package com.sa90.onepreference.adapter
import androidx.recyclerview.widget.DiffUtil
import com.sa90.onepreference.model.Header
class HeaderDiffUtil : DiffUtil.ItemCallback<Header>() {
override fun areItemsTheSame(oldItem: Header, newItem: Header): Boolean {
return false
}
override fun areContentsTheSame(oldItem: Header, newItem: Header): Boolean {
return false
}
}
| 0
|
Kotlin
|
1
| 26
|
2c4c0d0c36c27dcd1030da507fe239cfbd0dbe54
| 402
|
OnePreference
|
Apache License 2.0
|
kotlin-electron/src/jsMain/generated/electron/common/DidNavigateEvent.kt
|
JetBrains
| 93,250,841
| false
|
{"Kotlin": 11411371, "JavaScript": 154302}
|
package electron.common
typealias DidNavigateEvent = electron.core.DidNavigateEvent
| 28
|
Kotlin
|
173
| 1,250
|
9e9dda28cf74f68b42a712c27f2e97d63af17628
| 86
|
kotlin-wrappers
|
Apache License 2.0
|
confluence-plugin/src/main/java/com/networkedassets/git4c/interfaces/rest/MacroRest.kt
|
rpaasche
| 321,741,515
| true
|
{"Kotlin": 798728, "JavaScript": 351426, "Java": 109291, "Groovy": 55451, "CSS": 37375, "ANTLR": 19544, "Gherkin": 15007, "HTML": 14268, "Shell": 4490, "Ruby": 1378, "Batchfile": 1337, "PowerShell": 716}
|
package com.networkedassets.git4c.interfaces.rest
import com.atlassian.plugins.rest.common.security.AnonymousAllowed
import com.atlassian.sal.api.user.UserManager
import com.networkedassets.git4c.application.Plugin
import com.networkedassets.git4c.boundary.*
import com.networkedassets.git4c.boundary.inbound.*
import com.networkedassets.git4c.delivery.executor.execution.BackendDispatcher
import com.networkedassets.git4c.delivery.executor.result.ServiceApi
import com.networkedassets.git4c.utils.SerializationUtils.deserialize
import com.networkedassets.git4c.utils.dispatchAndPresentHttp
import com.networkedassets.git4c.utils.info
import org.slf4j.LoggerFactory
import java.net.URLDecoder
import java.util.concurrent.TimeUnit
import javax.servlet.http.HttpServletRequest
import javax.ws.rs.*
import javax.ws.rs.core.Context
import javax.ws.rs.core.MediaType
import javax.ws.rs.core.Response
@Path("/documentation/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
class MacroRest(
val plugin: Plugin,
val userManager: UserManager
) : ServiceApi {
private val log = LoggerFactory.getLogger(MacroRest::class.java)
override val dispatcher: BackendDispatcher<Response, Response> get() = plugin.components.dispatching.dispatcherHttp
init {
log.info { "Initializing REST for Git4C Confluence Plugin" }
}
@GET
@AnonymousAllowed
@Path("/")
fun healthcheck(): Response {
return dispatchAndPresentHttp { HealthCheckCommand() }
}
@POST
@Path("/creation")
fun createNewDocumentationsMacro(documentationJson: String, @Context req: HttpServletRequest): Response {
val documentation = deserialize(documentationJson, DocumentationMacro::class.java)
//Anonymous is not allowed
val username = req.getUsername()!!
return dispatchAndPresentHttp { CreateDocumentationsMacroCommand(documentation, username) }
}
@GET
@Path("/creation/result/{requestId}")
fun getCreateNewDocumentationsMacroResult(@PathParam("requestId") requestId: String): Response {
return dispatchAndPresentHttp { CreateDocumentationsMacroResultRequest(requestId) }
}
@GET
@AnonymousAllowed
@Path("/{uuid}")
fun getMacro(@PathParam("uuid") macroId: String, @Context req: HttpServletRequest): Response {
val username = req.getUsername()
return dispatchAndPresentHttp({ GetDocumentationsMacroByDocumentationsMacroIdQuery(macroId.urlDecode(), username) }, 5, TimeUnit.MINUTES)
}
@GET
@AnonymousAllowed
@Path("/{uuid}/tree")
fun getDocumentationsContentTree(@PathParam("uuid") macroId: String, @Context req: HttpServletRequest): Response {
val username = req.getUsername()
return dispatchAndPresentHttp { GetDocumentationsContentTreeByDocumentationsMacroIdQuery(macroId.urlDecode(), username) }
}
@GET
@AnonymousAllowed
@Path("/{uuid}/defaultBranch")
fun getDocumentationsDefaultBranch(@PathParam("uuid") macroId: String, @Context req: HttpServletRequest): Response {
val username = req.getUsername()
return dispatchAndPresentHttp { GetDocumentationsDefaultBranchByDocumentationsMacroIdQuery(macroId.urlDecode(), username) }
}
@POST
@AnonymousAllowed
@Path("/{uuid}/file/commits")
fun getFileCommitHistoryForDocumentationsMacroUuid(@PathParam("uuid") macroId: String, documentationJson: String, @Context req: HttpServletRequest): Response {
val username = req.getUsername()
val documentation = deserialize(documentationJson, DetailsToGetFile::class.java)
return dispatchAndPresentHttp { GetCommitHistoryForFileByMacroIdQuery(macroId.urlDecode(), documentation, username) }
}
@GET
@AnonymousAllowed
@Path("/{uuid}/file/commits/result/{requestId}")
fun getFileCommitHistoryForDocumentationsMacroUuidResult(@PathParam("requestId") requestId: String): Response {
return dispatchAndPresentHttp { GetCommitHistoryForFileResultRequest(requestId) }
}
@GET
@Path("/request/publishFile/result/{id}")
fun publishFileResult(@PathParam("id") requestId: String): Response {
return dispatchAndPresentHttp { PublishFileResultRequest(requestId) }
}
@POST
@Path("/{uuid}/file/publishFile")
fun publishFile(@PathParam("uuid") macroId: String, documentationJson: String, @Context req: HttpServletRequest): Response {
val username = req.getUsername()
val file = deserialize(documentationJson, FileToSave::class.java)
return dispatchAndPresentHttp { PublishFileCommand(username, macroId, file) }
}
@POST
@AnonymousAllowed
@Path("/{uuid}/file/preview")
fun previewFile(@PathParam("uuid") macroId: String, documentationJson: String, @Context req: HttpServletRequest): Response {
val username = req.getUsername()
val file = deserialize(documentationJson, FileToGeneratePreview::class.java)
return dispatchAndPresentHttp { PreviewFileCommand(username, macroId, file) }
}
@GET
@AnonymousAllowed
@Path("/{uuid}/file/preview/result/{requestId}")
fun previewFileResult(@PathParam("requestId") requestId: String): Response {
return dispatchAndPresentHttp { PreviewFileResultRequest(requestId) }
}
@POST
@AnonymousAllowed
@Path("/{uuid}/refresh")
fun forceRefreshExistingDocumentationsMacro(@PathParam("uuid") macroId: String, @Context req: HttpServletRequest): Response {
val username = req.getUsername()
return dispatchAndPresentHttp { RefreshDocumentationsMacroCommand(macroId.urlDecode(), username) }
}
@POST
@AnonymousAllowed
@Path("/{uuid}/branches")
fun getBranchesForDocumentationsMacroUuid(@PathParam("uuid") macroId: String, @Context req: HttpServletRequest): Response {
val username = req.getUsername()
return dispatchAndPresentHttp { GetBranchesByDocumentationsMacroIdQuery(macroId, username) }
}
@GET
@AnonymousAllowed
@Path("/{uuid}/branches/result/{requestId}")
fun getBranchesForDocumentationsMacroUuidResult(@PathParam("requestId") requestId: String): Response {
return dispatchAndPresentHttp { GetBranchesByDocumentationsMacroIdResultRequest(requestId) }
}
@GET
@AnonymousAllowed
@Path("/{uuid}/globs")
fun getGlobsForDocumentationsMacroUuid(@PathParam("uuid") macroId: String, @Context req: HttpServletRequest): Response {
val username = req.getUsername()
return dispatchAndPresentHttp { GetGlobsByDocumentationsMacroIdQuery(macroId, username) }
}
@GET
@AnonymousAllowed
@Path("/{uuid}/extractorData")
fun getExtractorDataForDocumentationsMacroUuid(@PathParam("uuid") macroId: String, @Context req: HttpServletRequest): Response {
val username = req.getUsername()
return dispatchAndPresentHttp { GetExtractionDataByDocumentationsMacroIdQuery(macroId, username) }
}
@POST
@AnonymousAllowed
@Path("/{uuid}/latestRevision")
fun getLatestRevisionForDocumentationsMacroUuid(@PathParam("uuid") macroId: String, @Context req: HttpServletRequest): Response {
val username = req.getUsername()
return dispatchAndPresentHttp({ GetLatestRevisionByDocumentationsMacroIdQuery(macroId, username) })
}
@GET
@AnonymousAllowed
@Path("/{uuid}/latestRevision/result/{requestId}")
fun getLatestRevisionForDocumentationsMacroUuidResult(@PathParam("requestId") requestId: String): Response {
return dispatchAndPresentHttp({ GetLatestRevisionByDocumentationsMacroIdResultRequest(requestId) })
}
@POST
@AnonymousAllowed
@Path("/{uuid}/doc-item")
fun getSpecificDocumentItem(@PathParam("uuid") macroId: String, documentationJson: String, @Context req: HttpServletRequest): Response {
val username = req.getUsername()
val file = deserialize(documentationJson, RequestedFile::class.java)
return dispatchAndPresentHttp { GetDocumentItemInDocumentationsMacroQuery(macroId.urlDecode(), file.file, username) }
}
@POST
@AnonymousAllowed
@Path("/{uuid}/editBranch")
fun getTemporaryEditBranch(@PathParam("uuid") macroId: String): Response {
return dispatchAndPresentHttp { GetTemporaryEditBranchCommand(macroId) }
}
@GET
@AnonymousAllowed
@Path("/{uuid}/editBranch/{requestId}")
fun getTemporaryEditBranchResult(@PathParam("requestId") requestId: String): Response {
return dispatchAndPresentHttp { GetTemporaryEditBranchResultCommand(requestId) }
}
@POST
@Path("/{uuid}/verify")
fun verifyDocumentationByDocumentationMacroUuid(@PathParam("uuid") macroId: String): Response {
return dispatchAndPresentHttp { VerifyDocumentationMacroByDocumentationsMacroIdQuery(macroId) }
}
@GET
@Path("/{uuid}/verify/result/{requestId}")
fun verifyDocumentationByDocumentationMacroUuidResult(@PathParam("requestId") requestId: String): Response {
return dispatchAndPresentHttp { VerifyDocumentationMacroByDocumentationsMacroIdResultRequest(requestId) }
}
@GET
@AnonymousAllowed
@Path("/{uuid}/repository")
fun getRepositoryInfoForMacro(@PathParam("uuid") uuid: String, @Context req: HttpServletRequest): Response {
val username = req.getUsername()
return dispatchAndPresentHttp { GetRepositoryInfoForMacroCommand(uuid, username) }
}
@DELETE
@Path("/remove/all")
fun removeAllData(@Context req: HttpServletRequest): Response {
val username = req.getUsername()
if (username == null || !userManager.isAdmin(username)) {
return Response.status(Response.Status.FORBIDDEN).build()
}
return dispatchAndPresentHttp { RemoveAllDataCommand() }
}
@DELETE
@Path("/remove/unused")
fun removeUnusedData(@Context req: HttpServletRequest): Response {
val username = req.getUsername()
if (username == null || !userManager.isAdmin(username)) {
return Response.status(Response.Status.FORBIDDEN).build()
}
return dispatchAndPresentHttp { RemoveUnusedDataCommand() }
}
@POST
@AnonymousAllowed
@Path("/{uuid}/temporary")
fun createTemporaryDocumentationsContent(@PathParam("uuid") macroId: String, documentationJson: String, @Context req: HttpServletRequest): Response {
val username = req.getUsername()
val documentation = deserialize(documentationJson, Branch::class.java)
return dispatchAndPresentHttp({ CreateTemporaryDocumentationsContentCommand(macroId, documentation.branch, username) }, 5, TimeUnit.MINUTES)
}
@GET
@Path("/predefine")
fun getAllPredefinedRepositories(): Response {
return dispatchAndPresentHttp { GetAllPredefinedRepositoriesCommand() }
}
@POST
@Path("/predefine/{uuid}/files")
fun getPredefinedRepositoryFiles(@PathParam("uuid") predefineRepositoryId: String, documentationJson: String): Response {
val branch = deserialize(documentationJson, Branch::class.java)
return dispatchAndPresentHttp { GetFilesListForPredefinedRepositoryQuery(predefineRepositoryId, branch) }
}
@GET
@Path("/predefine/{uuid}/files/result/{requestId}")
fun getPredefinedRepositoryFilesResult(@PathParam("requestId") requestId: String): Response {
return dispatchAndPresentHttp { GetFilesListForPredefinedRepositoryResultRequest(requestId) }
}
@POST
@Path("/predefine/{uuid}/file")
fun getPredefinedRepositoryFile(@PathParam("uuid") predefineRepositoryId: String, documentationJson: String): Response {
val documentation = deserialize(documentationJson, DetailsToGetFile::class.java)
return dispatchAndPresentHttp { GetFileContentForPredefinedRepositoryQuery(predefineRepositoryId, documentation) }
}
@GET
@Path("/predefine/{uuid}/file/result/{requestId}")
fun getPredefinedRepositoryFileResult(@PathParam("requestId") requestId: String): Response {
return dispatchAndPresentHttp { GetFileContentForPredefinedRepositoryResultRequest(requestId) }
}
@POST
@Path("/predefine/{uuid}/methods")
fun getPredefinedRepositoryMethods(@PathParam("uuid") predefineRepositoryId: String, documentationJson: String): Response {
val documentation = deserialize(documentationJson, DetailsToGetMethods::class.java)
return dispatchAndPresentHttp { GetMethodsForPredefinedRepositoryQuery(predefineRepositoryId, documentation) }
}
@GET
@Path("/predefine/{uuid}/methods/result/{requestId}")
fun getPredefinedRepositoryMethodsResult(@PathParam("requestId") requestId: String): Response {
return dispatchAndPresentHttp { GetMethodsForPredefinedRepositoryResultRequest(requestId) }
}
@POST
@Path("/predefine")
fun createPredefinedRepository(repositoryJson: String): Response {
val repository = deserialize(repositoryJson, PredefinedRepository::class.java)
return dispatchAndPresentHttp { CreatePredefinedRepositoryCommand(repository) }
}
@GET
@Path("/predefine/result/{requestId}")
fun createPredefinedRepositoryResult(@PathParam("requestId") requestId: String): Response {
return dispatchAndPresentHttp { CreatePredefinedRepositoryResultRequest(requestId) }
}
@POST
@Path("/predefine/{uuid}/modify")
fun modifyPredefinedRepository(@PathParam("uuid") repositoryId: String, repositoryJson: String): Response {
val repository = deserialize(repositoryJson, PredefinedRepository::class.java)
return dispatchAndPresentHttp { ModifyPredefinedRepositoryCommand(repositoryId, repository) }
}
@GET
@Path("/predefine/{uuid}/modify/result/{requestId}")
fun modifyPredefinedRepository(@PathParam("requestId") requestId: String): Response {
return dispatchAndPresentHttp { ModifyPredefinedRepositoryResultRequest(requestId) }
}
@POST
@Path("/predefine/{uuid}/details")
fun getPredefinedRepository(@PathParam("uuid") repositoryId: String): Response {
return dispatchAndPresentHttp { GetPredefinedRepositoryCommand(repositoryId) }
}
@GET
@Path("/predefine/{uuid}/details/result/{requestId}")
fun getPredefinedRepositoryResult(@PathParam("requestId") requestId: String): Response {
return dispatchAndPresentHttp { GetPredefinedRepositoryResultRequest(requestId) }
}
@POST
@Path("/predefine/{uuid}/branches")
fun getPredefinedRepositoryBranches(@PathParam("uuid") repositoryId: String): Response {
return dispatchAndPresentHttp { GetPredefinedRepositoryBranchesQuery(repositoryId) }
}
@GET
@Path("/predefine/{uuid}/branches/result/{requestId}")
fun getPredefinedRepositoryBranchesResult(@PathParam("requestId") requestId: String): Response {
return dispatchAndPresentHttp { GetPredefinedRepositoryBranchesResultRequest(requestId) }
}
@DELETE
@Path("/predefine/{uuid}")
fun deletePredefinedRepository(@PathParam("uuid") repositoryId: String): Response {
return dispatchAndPresentHttp { RemovePredefinedRepositoryCommand(repositoryId) }
}
@POST
@Path("/repository/branches")
fun getBranchesForRepository(documentationJson: String): Response {
val repositoryToGetBranches = deserialize(documentationJson, RepositoryToGetBranches::class.java)
return dispatchAndPresentHttp { GetBranchesQuery(repositoryToGetBranches) }
}
@GET
@Path("/repository/branches/result/{requestId}")
fun getBranchesForRepositoryResult(@PathParam("requestId") requestId: String): Response {
return dispatchAndPresentHttp { GetBranchesResultRequest(requestId) }
}
@POST
@Path("/repository/{uuid}/branches")
fun getBranchesForExistingRepository(@PathParam("uuid") repositoryId: String): Response {
return dispatchAndPresentHttp { GetExistingRepositoryBranchesQuery(repositoryId) }
}
@GET
@Path("/repository/{uuid}/branches/result/{requestId}")
fun getBranchesForExistingRepositoryResult(@PathParam("requestId") requestId: String): Response {
return dispatchAndPresentHttp { GetExistingRepositoryBranchesResultRequest(requestId) }
}
@POST
@Path("/repository/{uuid}/files")
fun getFilesForExistingRepository(@PathParam("uuid") repositoryId: String, documentationJson: String): Response {
val requestedBranch = deserialize(documentationJson, Branch::class.java)
return dispatchAndPresentHttp { GetFilesListForExistingRepositoryQuery(repositoryId, requestedBranch) }
}
@GET
@Path("/repository/{uuid}/files/result/{requestId}")
fun getFilesForExistingRepositoryResult(@PathParam("requestId") requestId: String): Response {
return dispatchAndPresentHttp { GetFilesListForExistingRepositoryResultRequest(requestId) }
}
@POST
@Path("/repository/{uuid}/file")
fun getFileForExistingRepository(@PathParam("uuid") repositoryId: String, documentationJson: String): Response {
val detailsToGetFile = deserialize(documentationJson, DetailsToGetFile::class.java)
return dispatchAndPresentHttp { GetFileContentForExistingRepositoryQuery(repositoryId, detailsToGetFile) }
}
@GET
@Path("/repository/{uuid}/file/result/{requestId}")
fun getFileForExistingRepositoryResult(@PathParam("requestId") requestId: String): Response {
return dispatchAndPresentHttp { GetFileContentForExistingRepositoryResultRequest(requestId) }
}
@POST
@Path("/repository/{uuid}/methods")
fun getMethodsForExistingRepository(@PathParam("uuid") repositoryId: String, documentationJson: String): Response {
val detailsToGetMethods = deserialize(documentationJson, DetailsToGetMethods::class.java)
return dispatchAndPresentHttp { GetMethodsForExistingRepositoryQuery(repositoryId, detailsToGetMethods) }
}
@GET
@Path("/repository/{uuid}/methods/result/{requestId}")
fun getMethodsForExistingRepository(@PathParam("requestId") requestId: String): Response {
return dispatchAndPresentHttp { GetMethodsForExistingRepositoryResultRequest(requestId) }
}
@POST
@Path("/repository/verify")
fun verifyRepository(documentationJson: String): Response {
val repositoryToVerify = deserialize(documentationJson, RepositoryToVerify::class.java)
return dispatchAndPresentHttp { VerifyRepositoryCommand(repositoryToVerify) }
}
@POST
@Path("/repository/verify/result/{requestId}")
fun verifyRepositoryResult(@PathParam("requestId") requestId: String): Response {
return dispatchAndPresentHttp { VerifyRepositoryResultRequest(requestId) }
}
@POST
@Path("/repository/files")
fun getFilesForRepository(documentationJson: String): Response {
val documentationToGetFiles = deserialize(documentationJson, RepositoryToGetFiles::class.java)
return dispatchAndPresentHttp { GetFilesListForRepositoryQuery(documentationToGetFiles) }
}
@GET
@Path("/repository/files/result/{requestId}")
fun getFilesForRepositoryResult(@PathParam("requestId") requestId: String): Response {
return dispatchAndPresentHttp { GetFilesListForRepositoryResultRequest(requestId) }
}
@POST
@Path("/repository/file")
fun getFileForRepository(documentationJson: String): Response {
val documentationToGetFiles = deserialize(documentationJson, RepositoryToGetFile::class.java)
return dispatchAndPresentHttp { GetFileContentForRepositoryQuery(documentationToGetFiles) }
}
@GET
@Path("/repository/file/result/{requestId}")
fun getFileForRepositoryResult(@PathParam("requestId") requestId: String): Response {
return dispatchAndPresentHttp { GetFileContentForRepositoryResultRequest(requestId) }
}
@POST
@Path("/repository/file/methods")
fun getMethodsForDocumentationsMacro(documentationJson: String): Response {
val documentationToGetMethods = deserialize(documentationJson, RepositoryToGetMethods::class.java)
return dispatchAndPresentHttp { GetMethodsForRepositoryQuery(documentationToGetMethods) }
}
@GET
@Path("/repository/file/methods/result/{requestId}")
fun getMethodsForDocumentationsMacroResult(@PathParam("requestId") requestId: String): Response {
return dispatchAndPresentHttp { GetMethodsForRepositoryResultRequest(requestId) }
}
@POST
@Path("/glob")
fun defaultGlobCreate(documentationJson: String): Response {
val defaultGlobToCreate = deserialize(documentationJson, PredefinedGlobToCreate::class.java)
return dispatchAndPresentHttp { CreatePredefinedGlobCommand(defaultGlobToCreate) }
}
@DELETE
@Path("/glob")
fun deleteAllGlobs(): Response {
return dispatchAndPresentHttp { DeleteAllPredefinedGlobsCommand() }
}
@GET
@Path("/glob")
fun getAllDefaultGlobs(): Response {
return dispatchAndPresentHttp { GetAllPredefinedGlobsQuery() }
}
@HEAD
@Path("/glob")
fun restoreDefaultGlobs(): Response {
return dispatchAndPresentHttp { RestoreDefaultPredefinedGlobsCommand() }
}
@DELETE
@Path("/glob/{uuid}")
fun deleteGlobById(@PathParam("uuid") defaultGlobId: String): Response {
return dispatchAndPresentHttp { DeletePredefinedGlobByIdCommand(defaultGlobId) }
}
@GET
@Path("/glob/{uuid}")
fun getGlobById(@PathParam("uuid") defaultGlobId: String): Response {
return dispatchAndPresentHttp { GetPredefinedGlobByIdQuery(defaultGlobId) }
}
@POST
@Path("/spaces")
fun getAllSpacesWithGit4CMacro(): Response {
return dispatchAndPresentHttp { GetSpacesWithMacroQuery() }
}
@GET
@Path("/spaces/result/{uuid}")
fun getAllSpacesWithGit4CMacroResult(@PathParam("uuid") id: String): Response {
return dispatchAndPresentHttp { GetSpacesWithMacroResultRequest(id) }
}
@POST
@Path("/settings/repository/predefine/force")
fun forceUsersToUsePredefinedRepositiores(documentationJson: String): Response {
val toForce = deserialize(documentationJson, ForcePredefinedRepositoriesInfo::class.java)
return dispatchAndPresentHttp { ForceUsersToUsePredefinedRepositoriesCommand(toForce) }
}
@GET
@Path("/settings/repository/predefine/force")
fun forceUsersToUsePredefinedRepositiores(): Response {
return dispatchAndPresentHttp { GetForceUsersToUsePredefinedRepositoriesSettingQuery() }
}
@GET
@Path("/repository/usages")
fun getRepoositoryUsagesForUser(@Context req: HttpServletRequest): Response {
//Anonymous it not allowed
val username = req.getUsername()!!
return dispatchAndPresentHttp { GetRepositoryUsagesForUserQuery(username) }
}
@POST
@Path("/database/macroLocation/refresh")
fun refreshMacroLocationDatabase(@Context req: HttpServletRequest): Response {
val username = req.getUsername()
if (username == null || !userManager.isAdmin(username)) {
return Response.status(Response.Status.FORBIDDEN).build()
}
return dispatchAndPresentHttp { RefreshMacroLocationsCommand() }
}
@GET
@Path("/database/macroLocation/refresh/{uuid}")
fun refreshMacroLocationDatabaseResult(@Context req: HttpServletRequest, @PathParam("uuid") uuid: String): Response {
val username = req.getUsername()
if (username == null || !userManager.isAdmin(username)) {
return Response.status(Response.Status.FORBIDDEN).build()
}
return dispatchAndPresentHttp { RefreshMacroLocationsResultCommand(uuid) }
}
@GET
@Path("/executors")
fun getExecutorThreadNumbers(@Context req: HttpServletRequest): Response {
val username = req.getUsername()
if (username == null || !userManager.isAdmin(username)) {
return Response.status(Response.Status.FORBIDDEN).build()
}
return dispatchAndPresentHttp { GetExecutorThreadNumbersQuery() }
}
@POST
@Path("/executors")
fun updateExecutorThreadNumbers(@Context req: HttpServletRequest, json: String): Response? {
val username = req.getUsername()
if (username == null || !userManager.isAdmin(username)) {
return Response.status(Response.Status.FORBIDDEN).build()
}
val data = deserialize(json, ExecutorThreadNumbersIn::class.java)
return dispatchAndPresentHttp { SaveExecutorThreadNumbersQuery(data) }
}
private fun String.urlDecode() = URLDecoder.decode(this, "UTF-8")
private fun HttpServletRequest.getUsername(): String? = userManager.getRemoteUsername(this)
}
| 0
|
Kotlin
|
0
| 0
|
e55391b33cb70d66bbf5f36ba570fb8822f10953
| 24,789
|
git4c
|
Apache License 2.0
|
app/src/test/kotlin/in/rcard/fes/portfolio/ChangePortfolioUseCaseTest.kt
|
rcardin
| 718,094,065
| false
|
{"Kotlin": 78894, "Java": 11940}
|
package `in`.rcard.fes.portfolio
import arrow.core.left
import arrow.core.right
import `in`.rcard.fes.env.Clock
import `in`.rcard.fes.portfolio.PortfolioCommand.BuyStocks
import `in`.rcard.fes.portfolio.PortfolioCommand.SellStocks
import `in`.rcard.fes.portfolio.PortfolioError.PriceNotAvailable
import `in`.rcard.fes.stock.FindStockPriceBySymbol
import `in`.rcard.fes.stock.StockPricesError.StockPricesGenericError
import `in`.rcard.fes.stock.StockPricesError.StockPricesNotFoundError
import io.kotest.assertions.arrow.core.shouldBeLeft
import io.kotest.assertions.arrow.core.shouldBeRight
import io.kotest.core.spec.style.ShouldSpec
import io.mockk.coEvery
import io.mockk.mockk
import java.time.Instant
private val NOW_MILLIS = Instant.now().toEpochMilli()
private val FIXED_CLOCK =
object : Clock {
override suspend fun currentTimeMillis(): Long = NOW_MILLIS
}
class ChangePortfolioUseCaseTest : ShouldSpec({
val findStockPriceBySymbol = mockk<FindStockPriceBySymbol>()
val portfolioService = mockk<PortfolioService>()
context("The change of a portfolio") {
should("retrieve the price of the stock to purchase") {
coEvery {
findStockPriceBySymbol.findPriceBySymbol(Stock("AAPL"))
} returns Money(100.0).right()
coEvery {
portfolioService.handle(
BuyStocks(
PortfolioId("123"),
NOW_MILLIS,
Stock("AAPL"),
Quantity(100),
Money(100.0),
),
)
} returns PortfolioId("123").right()
with(FIXED_CLOCK) {
val changePortfolioUseCase = changePortfolioUseCase(portfolioService, findStockPriceBySymbol)
val actualPortfolioId =
changePortfolioUseCase.changePortfolio(
ChangePortfolio(
PortfolioId("123"),
Stock("AAPL"),
Quantity(100),
),
)
actualPortfolioId.shouldBeRight(PortfolioId("123"))
}
}
should("retrieve the price of the stock to sell") {
coEvery {
findStockPriceBySymbol.findPriceBySymbol(Stock("AAPL"))
} returns Money(100.0).right()
coEvery {
portfolioService.handle(
SellStocks(
PortfolioId("123"),
NOW_MILLIS,
Stock("AAPL"),
Quantity(100),
Money(100.0),
),
)
} returns PortfolioId("123").right()
with(FIXED_CLOCK) {
val changePortfolioUseCase = changePortfolioUseCase(portfolioService, findStockPriceBySymbol)
val actualPortfolioId =
changePortfolioUseCase.changePortfolio(
ChangePortfolio(
PortfolioId("123"),
Stock("AAPL"),
Quantity(-100),
),
)
actualPortfolioId.shouldBeRight(PortfolioId("123"))
}
}
should("return a PriceNotAvailable if the stock symbol is not available") {
coEvery {
findStockPriceBySymbol.findPriceBySymbol(Stock("AAPL"))
} returns StockPricesNotFoundError(Stock("AAPL")).left()
with(FIXED_CLOCK) {
val changePortfolioUseCase = changePortfolioUseCase(portfolioService, findStockPriceBySymbol)
val actualPortfolioId =
changePortfolioUseCase.changePortfolio(
ChangePortfolio(
PortfolioId("123"),
Stock("AAPL"),
Quantity(100),
),
)
actualPortfolioId.shouldBeLeft(PriceNotAvailable(PortfolioId("123"), Stock("AAPL")))
}
}
should("return a PersistenceError if there is an unexpected error during the connection with the db") {
coEvery {
findStockPriceBySymbol.findPriceBySymbol(Stock("AAPL"))
} returns StockPricesGenericError.left()
with(FIXED_CLOCK) {
val changePortfolioUseCase = changePortfolioUseCase(portfolioService, findStockPriceBySymbol)
val actualPortfolioId =
changePortfolioUseCase.changePortfolio(
ChangePortfolio(
PortfolioId("123"),
Stock("AAPL"),
Quantity(100),
),
)
actualPortfolioId.shouldBeLeft(InfrastructureError.PersistenceError)
}
}
}
})
| 0
|
Kotlin
|
0
| 0
|
1134beecbcea6a3ff9407fe2bcd94324fb70b319
| 5,055
|
functional-event-sourcing-in-kotlin
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.