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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
code/assurance/src/main/java/com/adobe/marketing/mobile/assurance/internal/ui/pin/dialpad/DialPadView.kt
|
adobe
| 574,649,367
| false
|
{"Kotlin": 484837, "Java": 352519, "Shell": 4242, "Makefile": 2984, "HTML": 2928}
|
/*
Copyright 2023 Adobe. All rights reserved.
This file is licensed to you 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 REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/
package com.adobe.marketing.mobile.assurance.internal.ui.pin.dialpad
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import com.adobe.marketing.mobile.assurance.R
import com.adobe.marketing.mobile.assurance.internal.ui.AssuranceUiTestTags
import com.adobe.marketing.mobile.assurance.internal.ui.common.AssuranceHeader
import com.adobe.marketing.mobile.assurance.internal.ui.common.AssuranceSubHeader
import com.adobe.marketing.mobile.assurance.internal.ui.pin.PinScreenAction
import com.adobe.marketing.mobile.assurance.internal.ui.pin.PinScreenState
import com.adobe.marketing.mobile.assurance.internal.ui.theme.AssuranceTheme
import com.adobe.marketing.mobile.assurance.internal.ui.theme.AssuranceTheme.backgroundColor
/**
* DialPadView is the landing view for the Pin screen. It displays the pin feedback row,
* dial pad and action buttons for operating on the session.
* @param pinScreenState the state of the pin screen
* @param onAction the callback invoked when an action is performed on the pin screen
*/
@Composable
internal fun DialPadView(
pinScreenState: State<PinScreenState>,
onAction: (action: PinScreenAction) -> Unit
) {
Box(
modifier = Modifier
.fillMaxSize()
.background(backgroundColor)
.padding(horizontal = AssuranceTheme.dimensions.padding.xxLarge)
.testTag(AssuranceUiTestTags.PinScreen.DIAL_PAD_VIEW)
) {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(AssuranceTheme.dimensions.spacing.medium)
) {
AssuranceHeader()
AssuranceSubHeader(text = stringResource(id = R.string.pin_connect_enter_pin_text))
InputFeedbackRow(input = pinScreenState.value.pin)
NumberRow(listOf("1", "2", "3"), onClick = { action -> onAction(action) })
NumberRow(listOf("4", "5", "6"), onClick = { action -> onAction(action) })
NumberRow(listOf("7", "8", "9"), onClick = { action -> onAction(action) })
SymbolRow(onClick = { action -> onAction(action) })
}
ActionButtonRow(
modifier = Modifier
.fillMaxWidth()
.align(Alignment.BottomStart)
.padding(bottom = AssuranceTheme.dimensions.padding.medium),
pinScreenState = pinScreenState,
onAction = { action -> onAction(action) }
)
}
}
| 7
|
Kotlin
|
9
| 2
|
94d183046fc3a6190e74c01d85293e9cbf8ad810
| 3,594
|
aepsdk-assurance-android
|
Apache License 2.0
|
clients/kotlin/generated/src/test/kotlin/org/openapitools/client/models/CatalogsProductGroupFilterKeysTest.kt
|
oapicf
| 489,369,143
| false
|
{"Markdown": 13009, "YAML": 64, "Text": 6, "Ignore List": 43, "JSON": 688, "Makefile": 2, "JavaScript": 2261, "F#": 1305, "XML": 1120, "Shell": 44, "Batchfile": 10, "Scala": 4677, "INI": 23, "Dockerfile": 14, "Maven POM": 22, "Java": 13384, "Emacs Lisp": 1, "Haskell": 75, "Swift": 551, "Ruby": 1149, "Cabal Config": 2, "OASv3-yaml": 16, "Go": 2224, "Go Checksums": 1, "Go Module": 4, "CMake": 9, "C++": 6688, "TOML": 3, "Rust": 556, "Nim": 541, "Perl": 540, "Microsoft Visual Studio Solution": 2, "C#": 1645, "HTML": 545, "Xojo": 1083, "Gradle": 20, "R": 1079, "JSON with Comments": 8, "QMake": 1, "Kotlin": 3280, "Python": 1, "Crystal": 1060, "ApacheConf": 2, "PHP": 3940, "Gradle Kotlin DSL": 1, "Protocol Buffer": 538, "C": 1598, "Ada": 16, "Objective-C": 1098, "Java Properties": 2, "Erlang": 1097, "PlantUML": 1, "robots.txt": 1, "HTML+ERB": 2, "Lua": 1077, "SQL": 512, "AsciiDoc": 1, "CSS": 3, "PowerShell": 1083, "Elixir": 5, "Apex": 1054, "Visual Basic 6.0": 3, "TeX": 1, "ObjectScript": 1, "OpenEdge ABL": 1, "Option List": 2, "Eiffel": 583, "Gherkin": 1, "Dart": 538, "Groovy": 539, "Elm": 31}
|
/**
*
* 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 org.openapitools.client.models
import io.kotlintest.shouldBe
import io.kotlintest.specs.ShouldSpec
import org.openapitools.client.models.CatalogsProductGroupFilterKeys
import org.openapitools.client.models.AvailabilityFilter
import org.openapitools.client.models.BrandFilter
import org.openapitools.client.models.CatalogsProductGroupCurrencyCriteria
import org.openapitools.client.models.CatalogsProductGroupMultipleGenderCriteria
import org.openapitools.client.models.CatalogsProductGroupMultipleStringCriteria
import org.openapitools.client.models.CatalogsProductGroupMultipleStringListCriteria
import org.openapitools.client.models.CatalogsProductGroupPricingCriteria
import org.openapitools.client.models.ConditionFilter
import org.openapitools.client.models.CurrencyFilter
import org.openapitools.client.models.CustomLabel0Filter
import org.openapitools.client.models.CustomLabel1Filter
import org.openapitools.client.models.CustomLabel2Filter
import org.openapitools.client.models.CustomLabel3Filter
import org.openapitools.client.models.CustomLabel4Filter
import org.openapitools.client.models.GenderFilter
import org.openapitools.client.models.GoogleProductCategory0Filter
import org.openapitools.client.models.GoogleProductCategory1Filter
import org.openapitools.client.models.GoogleProductCategory2Filter
import org.openapitools.client.models.GoogleProductCategory3Filter
import org.openapitools.client.models.GoogleProductCategory4Filter
import org.openapitools.client.models.GoogleProductCategory5Filter
import org.openapitools.client.models.GoogleProductCategory6Filter
import org.openapitools.client.models.ItemGroupIdFilter
import org.openapitools.client.models.ItemIdFilter
import org.openapitools.client.models.MaxPriceFilter
import org.openapitools.client.models.MinPriceFilter
import org.openapitools.client.models.ProductType0Filter
import org.openapitools.client.models.ProductType1Filter
import org.openapitools.client.models.ProductType2Filter
import org.openapitools.client.models.ProductType3Filter
import org.openapitools.client.models.ProductType4Filter
class CatalogsProductGroupFilterKeysTest : ShouldSpec() {
init {
// uncomment below to create an instance of CatalogsProductGroupFilterKeys
//val modelInstance = CatalogsProductGroupFilterKeys()
// to test the property `MIN_PRICE`
should("test MIN_PRICE") {
// uncomment below to test the property
//modelInstance.MIN_PRICE shouldBe ("TODO")
}
// to test the property `MAX_PRICE`
should("test MAX_PRICE") {
// uncomment below to test the property
//modelInstance.MAX_PRICE shouldBe ("TODO")
}
// to test the property `CURRENCY`
should("test CURRENCY") {
// uncomment below to test the property
//modelInstance.CURRENCY shouldBe ("TODO")
}
// to test the property `ITEM_ID`
should("test ITEM_ID") {
// uncomment below to test the property
//modelInstance.ITEM_ID shouldBe ("TODO")
}
// to test the property `AVAILABILITY`
should("test AVAILABILITY") {
// uncomment below to test the property
//modelInstance.AVAILABILITY shouldBe ("TODO")
}
// to test the property `BRAND`
should("test BRAND") {
// uncomment below to test the property
//modelInstance.BRAND shouldBe ("TODO")
}
// to test the property `CONDITION`
should("test CONDITION") {
// uncomment below to test the property
//modelInstance.CONDITION shouldBe ("TODO")
}
// to test the property `CUSTOM_LABEL_0`
should("test CUSTOM_LABEL_0") {
// uncomment below to test the property
//modelInstance.CUSTOM_LABEL_0 shouldBe ("TODO")
}
// to test the property `CUSTOM_LABEL_1`
should("test CUSTOM_LABEL_1") {
// uncomment below to test the property
//modelInstance.CUSTOM_LABEL_1 shouldBe ("TODO")
}
// to test the property `CUSTOM_LABEL_2`
should("test CUSTOM_LABEL_2") {
// uncomment below to test the property
//modelInstance.CUSTOM_LABEL_2 shouldBe ("TODO")
}
// to test the property `CUSTOM_LABEL_3`
should("test CUSTOM_LABEL_3") {
// uncomment below to test the property
//modelInstance.CUSTOM_LABEL_3 shouldBe ("TODO")
}
// to test the property `CUSTOM_LABEL_4`
should("test CUSTOM_LABEL_4") {
// uncomment below to test the property
//modelInstance.CUSTOM_LABEL_4 shouldBe ("TODO")
}
// to test the property `ITEM_GROUP_ID`
should("test ITEM_GROUP_ID") {
// uncomment below to test the property
//modelInstance.ITEM_GROUP_ID shouldBe ("TODO")
}
// to test the property `GENDER`
should("test GENDER") {
// uncomment below to test the property
//modelInstance.GENDER shouldBe ("TODO")
}
// to test the property `PRODUCT_TYPE_4`
should("test PRODUCT_TYPE_4") {
// uncomment below to test the property
//modelInstance.PRODUCT_TYPE_4 shouldBe ("TODO")
}
// to test the property `PRODUCT_TYPE_3`
should("test PRODUCT_TYPE_3") {
// uncomment below to test the property
//modelInstance.PRODUCT_TYPE_3 shouldBe ("TODO")
}
// to test the property `PRODUCT_TYPE_2`
should("test PRODUCT_TYPE_2") {
// uncomment below to test the property
//modelInstance.PRODUCT_TYPE_2 shouldBe ("TODO")
}
// to test the property `PRODUCT_TYPE_1`
should("test PRODUCT_TYPE_1") {
// uncomment below to test the property
//modelInstance.PRODUCT_TYPE_1 shouldBe ("TODO")
}
// to test the property `PRODUCT_TYPE_0`
should("test PRODUCT_TYPE_0") {
// uncomment below to test the property
//modelInstance.PRODUCT_TYPE_0 shouldBe ("TODO")
}
// to test the property `GOOGLE_PRODUCT_CATEGORY_6`
should("test GOOGLE_PRODUCT_CATEGORY_6") {
// uncomment below to test the property
//modelInstance.GOOGLE_PRODUCT_CATEGORY_6 shouldBe ("TODO")
}
// to test the property `GOOGLE_PRODUCT_CATEGORY_5`
should("test GOOGLE_PRODUCT_CATEGORY_5") {
// uncomment below to test the property
//modelInstance.GOOGLE_PRODUCT_CATEGORY_5 shouldBe ("TODO")
}
// to test the property `GOOGLE_PRODUCT_CATEGORY_4`
should("test GOOGLE_PRODUCT_CATEGORY_4") {
// uncomment below to test the property
//modelInstance.GOOGLE_PRODUCT_CATEGORY_4 shouldBe ("TODO")
}
// to test the property `GOOGLE_PRODUCT_CATEGORY_3`
should("test GOOGLE_PRODUCT_CATEGORY_3") {
// uncomment below to test the property
//modelInstance.GOOGLE_PRODUCT_CATEGORY_3 shouldBe ("TODO")
}
// to test the property `GOOGLE_PRODUCT_CATEGORY_2`
should("test GOOGLE_PRODUCT_CATEGORY_2") {
// uncomment below to test the property
//modelInstance.GOOGLE_PRODUCT_CATEGORY_2 shouldBe ("TODO")
}
// to test the property `GOOGLE_PRODUCT_CATEGORY_1`
should("test GOOGLE_PRODUCT_CATEGORY_1") {
// uncomment below to test the property
//modelInstance.GOOGLE_PRODUCT_CATEGORY_1 shouldBe ("TODO")
}
// to test the property `GOOGLE_PRODUCT_CATEGORY_0`
should("test GOOGLE_PRODUCT_CATEGORY_0") {
// uncomment below to test the property
//modelInstance.GOOGLE_PRODUCT_CATEGORY_0 shouldBe ("TODO")
}
}
}
| 0
|
Java
|
0
| 2
|
dcd328f1e62119774fd8ddbb6e4bad6d7878e898
| 8,213
|
pinterest-sdk
|
MIT License
|
features/dd-sdk-android-trace/src/test/kotlin/com/datadog/trace/common/sampling/SpanSamplingRulesFileTest.kt
|
DataDog
| 219,536,756
| false
|
{"Gradle Kotlin DSL": 47, "YAML": 10, "Markdown": 31, "Python": 1, "Proguard": 9, "Shell": 3, "Java Properties": 1, "Text": 4, "Ignore List": 29, "Batchfile": 1, "EditorConfig": 1, "Kotlin": 1587, "XML": 137, "CMake": 4, "C++": 16, "JSON": 111, "TOML": 1, "INI": 1, "Java": 317, "C": 6, "CODEOWNERS": 1}
|
/*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2016-Present Datadog, Inc.
*/
package com.datadog.trace.common.sampling
import org.junit.jupiter.api.io.TempDir
import java.io.File
internal class SpanSamplingRulesFileTest : SpanSamplingRulesTest() {
@TempDir
lateinit var tempDir: File
override fun deserializeRules(jsonRules: String): SpanSamplingRules {
return SpanSamplingRules.deserializeFile(createRulesFile(jsonRules))
}
fun createRulesFile(rules: String): String {
val p = File(tempDir, "single-span-sampling-rules.json")
p.createNewFile()
p.writeText(rules)
return p.toString()
}
}
| 1
| null |
1
| 1
|
61e5b9975e228dd38518924b702fddda885a5727
| 831
|
dd-sdk-android
|
Apache License 2.0
|
dialog-simple/src/main/java/me/reezy/cosmo/dialog/simple/LoadingDialog.kt
|
czy1121
| 532,288,959
| false
| null |
package me.reezy.cosmo.dialog.simple
import android.content.Context
import android.view.View
import android.widget.*
import me.reezy.cosmo.dialog.simple.R
import me.reezy.cosmo.dialog.CustomDialog
class LoadingDialog(context: Context, compact: Boolean = false, text: String = context.getString(R.string.toosimple_loading_text)) : CustomDialog(context) {
init {
setView(R.layout.toosimple_loading)
if (compact) {
require<View>(android.R.id.widget_frame).setPadding(0, 0, 0, 0)
require<TextView>(android.R.id.text1).visibility = View.GONE
} else{
require<TextView>(android.R.id.text1).text = text
}
}
}
| 0
|
Kotlin
|
0
| 0
|
561f02ad7517b2e2e8aadeef93368bb4d5e5a510
| 683
|
dialog
|
Apache License 2.0
|
app/src/main/java/com/example/nasagridapp/app/utils/SnapHelperOneByOne.kt
|
AdityaV025
| 501,602,171
| false
|
{"Kotlin": 26505}
|
package com.example.nasagridapp.app.utils
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSnapHelper
import androidx.recyclerview.widget.RecyclerView
class SnapHelperOneByOne(private val isVertical: Boolean) : LinearSnapHelper() {
override fun findTargetSnapPosition(
layoutManager: RecyclerView.LayoutManager,
velocityX: Int,
velocityY: Int
): Int {
if (layoutManager !is RecyclerView.SmoothScroller.ScrollVectorProvider) {
return RecyclerView.NO_POSITION
}
val currentView = findSnapView(layoutManager) ?: return RecyclerView.NO_POSITION
val myLayoutManager = layoutManager as LinearLayoutManager
val position1 = myLayoutManager.findFirstVisibleItemPosition()
val position2 = myLayoutManager.findLastVisibleItemPosition()
var currentPosition = layoutManager.getPosition(currentView)
if (isVertical) {
if (velocityY > 400) {
currentPosition = position2
} else if (velocityY < 400) {
currentPosition = position1
}
} else {
if (velocityX > 400) {
currentPosition = position2
} else if (velocityX < 400) {
currentPosition = position1
}
}
return if (currentPosition == RecyclerView.NO_POSITION) {
RecyclerView.NO_POSITION
} else currentPosition
}
}
| 0
|
Kotlin
|
1
| 0
|
e1f70730fb873163039a1e6ce7c7ff1ac4ffc0fb
| 1,491
|
NasaGridApp
|
Apache License 2.0
|
app/src/main/java/com/example/spygamers/utils/HandleDrawerItemClicked.kt
|
Juicy-Lemonberry
| 748,985,682
| false
|
{"Kotlin": 257724}
|
package com.example.spygamers.utils
import androidx.navigation.NavController
import androidx.navigation.NavHostController
import com.example.spygamers.Screen
import com.example.spygamers.models.DrawerMenuItem
fun handleDrawerItemClicked(drawerItem: DrawerMenuItem, currentDrawerItem: Screen, navController: NavController) {
if (drawerItem.id === currentDrawerItem.route) {
return;
}
navController.navigate(drawerItem.id)
}
| 3
|
Kotlin
|
2
| 1
|
9512696751a6c7dc5e0361f43b3b08097208ea42
| 445
|
SpyGamers-App
|
MIT License
|
app/src/main/java/com/zoomyu/kotlindemo/domain/commands/Command.kt
|
zoomyu
| 93,063,189
| false
| null |
package com.zoomyu.kotlindemo.domain.commands
/**
* Created by yuwei on 17-6-7.
*/
interface Command<out T> {
fun execute(): T
}
| 0
|
Kotlin
|
0
| 0
|
5164722156f2a31e400e3453be62c497deccba26
| 136
|
KotlinDemo
|
MIT License
|
app/src/main/java/com/zhongya/havefun/ui/adapter/personal/CollectAdapter.kt
|
zhongya666
| 392,348,712
| false
| null |
package com.zhongya.havefun.ui.adapter.personal
import android.text.TextUtils
import android.view.View
import android.widget.ImageView
import coil.load
import com.chad.library.adapter.base.BaseDelegateMultiAdapter
import com.chad.library.adapter.base.delegate.BaseMultiTypeDelegate
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.zhongya.havefun.R
import com.zhongya.havefun.app.widget.CollectView
import com.zhongya.havefun.bean.personal.CollectResponse
import com.zhongya.havefun.app.MyApplication
import com.zhongya666.library.ext.setAdapterAnimation
import com.zhongya666.library.ext.shapeBackgroundColor
import com.zhongya666.library.util.SettingUtil
import com.zhongya666.library.util.toHtml
/**
* GitHub/Gitee:zhongya666 2021/7/23 09:54
*
*/
class CollectAdapter(data: ArrayList<CollectResponse>) : BaseDelegateMultiAdapter<CollectResponse, BaseViewHolder>(data){
//文章类型
private val Ariticle = 1
private val Project = 2
private var collectClickListener : ((Int, CollectResponse) -> Unit)? = null
fun setCollectClick( listener :(Int, CollectResponse) -> Unit){
collectClickListener=listener
}
init {
setAdapterAnimation(SettingUtil.getListMode())
// 第一步,设置代理
setMultiTypeDelegate(object : BaseMultiTypeDelegate<CollectResponse>() {
override fun getItemType(data: List<CollectResponse>, position: Int): Int {
//根据是否有图片 判断为文章还是项目
return if (TextUtils.isEmpty(data[position].envelopePic)) Ariticle else Project
}
})
// 第二步,绑定 item 类型
getMultiTypeDelegate()?.let {
it.addItemType(Ariticle, R.layout.home_item_article)
it.addItemType(Project, R.layout.project_item_project_list)
}
}
override fun convert(holder: BaseViewHolder, item: CollectResponse) {
when (holder.itemViewType) {
Ariticle -> {
//文章布局的赋值
item.run {
holder.setText(R.id.tv_author, if (author.isEmpty()) "匿名用户" else author)
holder.setText(R.id.tv_title, title)
holder.setText(R.id.tv_type, chapterName.toHtml())
holder.setText(R.id.tv_time, niceDate)
holder.getView<View>(R.id.tv_type).shapeBackgroundColor(MyApplication.appViewModel.appColor.value!!)
}
}
Project -> {
//项目布局的赋值
item.run {
holder.setText(R.id.tv_title,title)
holder.setText(R.id.tv_content,desc)
holder.setText(R.id.tv_time,niceDate)
holder.setText(R.id.tv_type,chapterName)
holder.getView<ImageView>(R.id.iv_pic).load(envelopePic){
placeholder(R.drawable.default_project_img)
}
if (author.isEmpty()) {
holder.setText(R.id.tv_name, "匿名用户")
} else {
holder.setText(R.id.tv_name, author)
}
}
}
}
holder.getView<CollectView>(R.id.iv_collect).setCollect(item.collect)
holder.getView<CollectView>(R.id.iv_collect).setCollectAction {
collectClickListener?.invoke(holder.absoluteAdapterPosition,item)
}
}
}
| 1
|
Kotlin
|
1
| 9
|
a3cbba971479fe840b51870b42244af646deda62
| 3,406
|
WanApk
|
Apache License 2.0
|
app/src/main/java/com/zhongya/havefun/ui/adapter/personal/CollectAdapter.kt
|
zhongya666
| 392,348,712
| false
| null |
package com.zhongya.havefun.ui.adapter.personal
import android.text.TextUtils
import android.view.View
import android.widget.ImageView
import coil.load
import com.chad.library.adapter.base.BaseDelegateMultiAdapter
import com.chad.library.adapter.base.delegate.BaseMultiTypeDelegate
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.zhongya.havefun.R
import com.zhongya.havefun.app.widget.CollectView
import com.zhongya.havefun.bean.personal.CollectResponse
import com.zhongya.havefun.app.MyApplication
import com.zhongya666.library.ext.setAdapterAnimation
import com.zhongya666.library.ext.shapeBackgroundColor
import com.zhongya666.library.util.SettingUtil
import com.zhongya666.library.util.toHtml
/**
* GitHub/Gitee:zhongya666 2021/7/23 09:54
*
*/
class CollectAdapter(data: ArrayList<CollectResponse>) : BaseDelegateMultiAdapter<CollectResponse, BaseViewHolder>(data){
//文章类型
private val Ariticle = 1
private val Project = 2
private var collectClickListener : ((Int, CollectResponse) -> Unit)? = null
fun setCollectClick( listener :(Int, CollectResponse) -> Unit){
collectClickListener=listener
}
init {
setAdapterAnimation(SettingUtil.getListMode())
// 第一步,设置代理
setMultiTypeDelegate(object : BaseMultiTypeDelegate<CollectResponse>() {
override fun getItemType(data: List<CollectResponse>, position: Int): Int {
//根据是否有图片 判断为文章还是项目
return if (TextUtils.isEmpty(data[position].envelopePic)) Ariticle else Project
}
})
// 第二步,绑定 item 类型
getMultiTypeDelegate()?.let {
it.addItemType(Ariticle, R.layout.home_item_article)
it.addItemType(Project, R.layout.project_item_project_list)
}
}
override fun convert(holder: BaseViewHolder, item: CollectResponse) {
when (holder.itemViewType) {
Ariticle -> {
//文章布局的赋值
item.run {
holder.setText(R.id.tv_author, if (author.isEmpty()) "匿名用户" else author)
holder.setText(R.id.tv_title, title)
holder.setText(R.id.tv_type, chapterName.toHtml())
holder.setText(R.id.tv_time, niceDate)
holder.getView<View>(R.id.tv_type).shapeBackgroundColor(MyApplication.appViewModel.appColor.value!!)
}
}
Project -> {
//项目布局的赋值
item.run {
holder.setText(R.id.tv_title,title)
holder.setText(R.id.tv_content,desc)
holder.setText(R.id.tv_time,niceDate)
holder.setText(R.id.tv_type,chapterName)
holder.getView<ImageView>(R.id.iv_pic).load(envelopePic){
placeholder(R.drawable.default_project_img)
}
if (author.isEmpty()) {
holder.setText(R.id.tv_name, "匿名用户")
} else {
holder.setText(R.id.tv_name, author)
}
}
}
}
holder.getView<CollectView>(R.id.iv_collect).setCollect(item.collect)
holder.getView<CollectView>(R.id.iv_collect).setCollectAction {
collectClickListener?.invoke(holder.absoluteAdapterPosition,item)
}
}
}
| 1
|
Kotlin
|
1
| 9
|
a3cbba971479fe840b51870b42244af646deda62
| 3,406
|
WanApk
|
Apache License 2.0
|
src/main/kotlin/com/brain/ion/graphics/IonGraphics.kt
|
marshallbrain-backup
| 210,874,963
| false
| null |
package com.brain.ion.graphics
import com.brain.ion.components.Component
import com.brain.ion.components.Text
import com.brain.ion.components.vectors.Path
import com.brain.ion.components.vectors.Style
import com.brain.ion.components.vectors.Vector
import java.awt.*
import java.awt.font.TextLayout
import java.awt.geom.AffineTransform
class IonGraphics(
private val bounds: Rectangle = Rectangle(0, 0, 0, 0),
g: Graphics2D = DummyGraphics2D()
) {
val renderQueue: Group = GroupImpl(0, null)
val graphics: Graphics2D
get() = graphicsPrivate.create() as Graphics2D
private var graphicsPrivate: Graphics2D = g
fun setGraphics(g: Graphics) {
graphicsPrivate = g.create() as Graphics2D
graphicsPrivate.color = Color.DARK_GRAY
graphicsPrivate.setClip(bounds.x, bounds.y, bounds.width, bounds.height)
graphicsPrivate.fillRect(bounds.x, bounds.y, bounds.width, bounds.height)
graphicsPrivate.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
graphicsPrivate.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON)
// val text = Text("Test")
// graphicsPrivate.color = Color.white
// val frc = graphicsPrivate.getFontRenderContext()
// val font = Font("Open Sans", Font.BOLD, 18);
// val layout = TextLayout("This is a string", font, frc)
// val at = AffineTransform()
// at.setToTranslation(100.0, 100.0)
// graphics.fill(Path("", Style(), layout.getOutline(at)).getShape())
}
private operator fun Number.plus(i: Number): Number {
return this.toDouble() + i.toDouble()
}
fun draw(component: Component, baseX: Number = 0, baseY: Number = 0) {
if (!component.visible) {
return
}
val x = baseX + component.x
val y = baseY + component.y
if(component is Vector) {
draw(component)
} else {
for (c in component.getCollection(this)) {
when(c) {
is Vector -> draw(c, x, y)
else -> draw(c, x, y)
}
}
}
}
private fun draw(vector: Vector, x: Number = 0, y: Number = 0) {
if(!vector.visible) {
return
}
val graphics = graphics
graphics.translate(x.toDouble(), y.toDouble())
graphics.color = vector.style.fillColor
graphics.fill(vector.getShape())
if (vector.style.strokeColor.alpha != 0) {
graphics.color = vector.style.strokeColor
graphics.stroke = vector.style.strokeProp
// if(vector.style.strokeProp.lineWidth % 2 == 0f) {
// graphics.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
// }
graphics.draw(vector.getShape())
}
}
fun render() {
renderQueue.render(this)
}
private class GroupImpl(
override val index: Int,
override val parent: Renderable?,
private val queue: MutableList<Renderable> = mutableListOf()
): Group, MutableList<Renderable> by queue {
override fun newGroup(): Group {
val group = GroupImpl(size, this)
queue.add(group)
return group
}
override fun render(g: IonGraphics) {
for (c in queue.toList()) {
when(c) {
is Group -> c.render(g)
is Component -> g.draw(c)
}
}
}
}
}
| 7
|
Kotlin
|
0
| 0
|
4998a563c101746080f1fa4f231805067af7c449
| 3,138
|
ion-experiment-1
|
MIT License
|
SunnyWeather/app/src/main/java/com/sunnyweather/android/ui/user/UserWhoLogin.kt
|
plattanus
| 709,212,164
| false
|
{"Kotlin": 44216}
|
package com.sunnyweather.android.ui.user
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
class UserWhoLogin {
companion object StaticParams{
var LOAN_PERSON_Password = "<PASSWORD>"
var LOAN_PERSON_Account = "null"
}
}
| 0
|
Kotlin
|
0
| 0
|
b8abb4b4a47c6cbbafb51491879d264175d40d9c
| 276
|
WeatherApp
|
MIT License
|
data/src/commonMain/kotlin/sources/AppStateSource.kt
|
niallkh
| 855,100,709
| false
|
{"Kotlin": 1942525, "Swift": 25802}
|
package kosh.data.sources
import kosh.domain.state.AppState
import kotlinx.coroutines.flow.Flow
interface AppStateSource {
val state: Flow<AppState>
suspend fun update(update: (AppState) -> AppState): AppState
}
| 0
|
Kotlin
|
0
| 3
|
c08a9f32c0f12bf01eeb366c471b079923ac73ff
| 224
|
kosh
|
MIT License
|
EzXHelper/src/main/java/com/github/kyuubiran/ezxhelper/misc/FinderExceptionMessage.kt
|
KyuubiRan
| 349,098,837
| false
|
{"Kotlin": 140228}
|
@file:Suppress("unused", "MemberVisibilityCanBePrivate")
package com.github.kyuubiran.ezxhelper.misc
import com.github.kyuubiran.ezxhelper.interfaces.INamed
class FinderExceptionMessage {
val exceptionMessageBuilder = StringBuilder()
val msg: String
get() = exceptionMessageBuilder.append("Stacktrace:").toString()
fun <NamedFinder : INamed> ctor(finder: NamedFinder, msg: String) {
exceptionMessageBuilder.apply {
// fix r8 cause name lost
append("[${finder.name}] ")
append(msg)
append("\nConditions:\n")
}
}
fun append(msg: String, newLine: Boolean = true) {
exceptionMessageBuilder.append(msg).apply { if (newLine) append("\n") }
}
fun condition(msg: String) {
exceptionMessageBuilder.append("\t$msg\n")
}
}
| 6
|
Kotlin
|
44
| 362
|
1f40c82b35c5ec1ec4f9526cea8f9539c691ce65
| 838
|
EzXHelper
|
Apache License 2.0
|
confluence-plugin/src/main/java/com/networkedassets/git4c/data/encryption/EncryptedRepository.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.data.encryption
import com.networkedassets.git4c.data.Repository
data class EncryptedRepository(
val uuid: String,
val repository: Repository,
val securityKey: String
)
| 0
|
Kotlin
|
0
| 0
|
e55391b33cb70d66bbf5f36ba570fb8822f10953
| 228
|
git4c
|
Apache License 2.0
|
app/src/main/java/de/truedev/killmyself/EntryActivity.kt
|
alxgrk
| 148,005,054
| false
| null |
package de.truedev.killmyself
import agency.tango.materialintroscreen.MaterialIntroActivity
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.util.Log
class EntryActivity : MaterialIntroActivity() {
private var prefs: SharedPreferences? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
prefs = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE)
if (prefs!!.getBoolean(ONBOARDING_DONE, false)) {
proceed()
return
}
enableLastSlideAlphaExitTransition(true)
backButtonTranslationWrapper
.setEnterTranslation { view, percentage -> view.alpha = percentage }
addSlide(FirstSlide())
addSlide(SecondSlide())
addSlide(ThirdSlide())
addSlide(FourthSlide())
setUpAlarm(this)
}
override fun onFinish() {
super.onFinish()
val cigarette = Cigarette(this)
val life = Life(this)
val daysUntilNow = life.daysUntilNow().toInt()
val cigarettesFromStartDate = daysUntilNow * cigarette.perDay
Log.d(EntryActivity::class.simpleName, "Cigarettes from start date: $cigarettesFromStartDate")
cigarette.total = cigarettesFromStartDate
prefs!!.edit().putBoolean(ONBOARDING_DONE, true).apply()
proceed()
}
private fun proceed() {
val mainIntent = Intent(this, MainActivity::class.java)
startActivity(mainIntent)
finish()
}
companion object {
const val PREFERENCE_NAME = "RauchfreiPreferences"
const val ONBOARDING_DONE = "OnboardingDonePref"
}
}
| 0
|
Kotlin
|
0
| 0
|
b61838adf0012e1d145f2115981db86d6b8bb51b
| 1,760
|
KillMyself
|
Apache License 2.0
|
src/main/kotlin/Main.kt
|
ZengLawrence
| 640,224,866
| false
| null |
import app.App.Companion.app
fun main() {
app {
redis {
host(System.getenv("REDIS_HOST") ?: "localhost")
port(System.getenv("REDIS_PORT")?.toInt() ?: 6379)
}
}.build()
.start(7070)
}
| 0
|
Kotlin
|
0
| 0
|
46b2d236f79fee13132674e7089df295c724d3fe
| 240
|
kotlin-todo
|
MIT License
|
forge-1.12.2/src/main/kotlin/dev/luna5ama/glwrapper/api/GL15Impl.kt
|
Luna5ama
| 594,203,393
| false
|
{"Kotlin": 331635}
|
package dev.luna5ama.glwrapper.api
import dev.luna5ama.kmogus.Arr
open class GL15Impl(tempArr: Arr) : GL15LWJGL2(tempArr)
| 0
|
Kotlin
|
0
| 4
|
6834165eca3ea63dbee7cbb56b6f0a0de8dd3811
| 123
|
gl-wrapper
|
MIT License
|
app/src/main/java/com/pose/composingclocks/core/savestate/HandleStateSaver.kt
|
lotdrops
| 343,812,742
| false
| null |
package com.pose.composingclocks.core.savestate
import androidx.lifecycle.SavedStateHandle
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
class HandleStateSaver(private val savedStateHandle: SavedStateHandle) : StateSaver {
private val trackedValues = mutableMapOf<String, Job>()
override fun <T> getAutoSaveFlow(
scope: CoroutineScope,
key: String,
default: T
): MutableStateFlow<T> {
val flow = MutableStateFlow(getValue(key, default))
val job = scope.launch {
flow.collect { setValue(key, it) }
}
unTrackKey(key)
trackedValues[key] = job
return flow
}
override fun <T> setValue(key: String, value: T): Unit = savedStateHandle.set(key, value)
override fun <T> getValue(key: String): T? = savedStateHandle.get<T>(key)
override fun <T> getValue(key: String, default: T): T = getValue(key) ?: default
override fun unTrackKey(key: String) {
trackedValues.remove(key)?.cancel()
}
}
| 0
|
Kotlin
|
2
| 86
|
fe79ad04d962401362d5693306349afbd1a93b42
| 1,158
|
Composing-Clocks
|
MIT License
|
kotlin/app/src/main/java/net/igorbrejc/timeslack/UIMessage.kt
|
breki
| 240,225,649
| false
| null |
package net.igorbrejc.timeslack
sealed class UIMessage
data class TimerUpdated(val currentTime: SlackerTime) : UIMessage()
data class NextActivityButtonClicked(val currentTime: SlackerTime) :
UIMessage()
| 0
|
Kotlin
|
0
| 0
|
e3bdebac87e73172ff27ebad479a7f5d29ff25e5
| 211
|
TimeSlack
|
MIT License
|
exercise-completed/kotlin/robot-name/src/main/kotlin/RobotName.kt
|
Ale142
| 467,517,865
| true
|
{"Kotlin": 492189, "Shell": 13575}
|
import kotlin.random.Random
class Robot {
companion object {
private var generatedNames: MutableList<String> = emptyList<String>().toMutableList()
}
private var status = false // name generated -> true, false otherwise
private val charsPool: List<Char> = CharRange('A', 'Z').toList()
var name: String =""
get() {
if(status ) return field;
var tempName = "";
do {
tempName = (charsPool.get(Random.nextInt(0, charsPool.size)).toString() + charsPool.get(Random.nextInt(0, charsPool.size)).toString() + Random.nextInt(100, 999)).toString()
}while (generatedNames.contains(tempName))
generatedNames.add(tempName)
status = true
name = tempName
return tempName
}
fun reset() {
generatedNames.remove(name)
status = false
name = ""
}
}
fun main() {
var robot1 = Robot()
var robot2 = Robot()
println("Name of robot1 is ${robot1.name}")
println("Name of robot2 is ${robot2.name}")
robot1.reset()
println("Name of robot1 is ${robot1.name}")
}
| 0
|
Kotlin
|
0
| 0
|
f48013acdc9b16865c14a0de8df1e1394fe3af62
| 1,147
|
kotlin
|
MIT License
|
storage/src/main/java/com/yzq/storage/mmkv/MMKVUser.kt
|
yuzhiqiang1993
| 140,548,996
| false
|
{"Kotlin": 368226, "Java": 153913, "CSS": 3721, "JavaScript": 3215, "HTML": 2415}
|
package com.yzq.storage.mmkv
import com.tencent.mmkv.MMKV
import com.yzq.mmkv.MMKVReadWriteProp
import com.yzq.storage.AppStorage
/**
* @description 用户相关的存储
* @author yuzhiqiang (<EMAIL>)
*/
object MMKVUser {
val mmkv = MMKV.mmkvWithID(
"user",
MMKV.SINGLE_PROCESS_MODE,//单进程模式
"xeonyu",//加密的key
"${AppStorage.Internal.spPath}mmkv_user"//指定存储的路径
)
var hasLogin: Boolean by MMKVReadWriteProp("hasLogin", false, mmkv)
var account: String by MMKVReadWriteProp("account", "", mmkv)
var pwd: String by MMKVReadWriteProp("pwd", "", mmkv)
var token: String by MMKVReadWriteProp("token", "", mmkv)
}
| 0
|
Kotlin
|
0
| 0
|
f65f96b72df77536925e6f0ef56aa27d404ce206
| 658
|
kotlinCommon
|
MIT License
|
storage/src/main/java/com/yzq/storage/mmkv/MMKVUser.kt
|
yuzhiqiang1993
| 140,548,996
| false
|
{"Kotlin": 368226, "Java": 153913, "CSS": 3721, "JavaScript": 3215, "HTML": 2415}
|
package com.yzq.storage.mmkv
import com.tencent.mmkv.MMKV
import com.yzq.mmkv.MMKVReadWriteProp
import com.yzq.storage.AppStorage
/**
* @description 用户相关的存储
* @author yuzhiqiang (<EMAIL>)
*/
object MMKVUser {
val mmkv = MMKV.mmkvWithID(
"user",
MMKV.SINGLE_PROCESS_MODE,//单进程模式
"xeonyu",//加密的key
"${AppStorage.Internal.spPath}mmkv_user"//指定存储的路径
)
var hasLogin: Boolean by MMKVReadWriteProp("hasLogin", false, mmkv)
var account: String by MMKVReadWriteProp("account", "", mmkv)
var pwd: String by MMKVReadWriteProp("pwd", "", mmkv)
var token: String by MMKVReadWriteProp("token", "", mmkv)
}
| 0
|
Kotlin
|
0
| 0
|
f65f96b72df77536925e6f0ef56aa27d404ce206
| 658
|
kotlinCommon
|
MIT License
|
app/src/main/java/com/anangkur/wallpaper/feature/MainActivity.kt
|
anangkur
| 281,979,916
| false
|
{"Kotlin": 109025}
|
package com.anangkur.wallpaper.feature
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.anangkur.wallpaper.R
import com.anangkur.wallpaper.databinding.ActivityMainBinding
import com.anangkur.wallpaper.presentation.getHomeFragment
import com.anangkur.wallpaper.presentation.getSavedFragment
import com.anangkur.wallpaper.presentation.getSearchFragment
class MainActivity: AppCompatActivity(){
private lateinit var binding: ActivityMainBinding
var activeTabId = R.id.home
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
start()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
}
fun start() {
setupNavigationView()
binding.bottomNav.selectedItemId = activeTabId
}
private fun setupNavigationView() {
binding.bottomNav.setOnNavigationItemSelectedListener {
activeTabId = it.itemId
when (it.itemId) {
R.id.home -> {
setFragment(getHomeFragment())
true
}
R.id.search -> {
setFragment(getSearchFragment())
true
}
R.id.saved -> {
setFragment(getSavedFragment())
true
}
else -> false
}
}
}
private fun setFragment(fragment: Fragment) {
supportFragmentManager.beginTransaction().replace(R.id.fragment_container_view, fragment).commit()
}
}
| 6
|
Kotlin
|
1
| 8
|
e893dfec250c6a5bb9440609038d8b3d3c9c471b
| 1,854
|
walla
|
MIT License
|
src/main/kotlin/jp/ac/titech/cs/se/refactorhub/core/model/annotator/autofill/AutofillType.kt
|
salab
| 208,590,763
| false
| null |
package jp.ac.titech.cs.se.refactorhub.core.model.annotator.autofill
import kotlin.reflect.KClass
enum class AutofillType {
Reference,
Surround,
Package;
val klass: KClass<out Autofill>
get() = when (this) {
Reference -> jp.ac.titech.cs.se.refactorhub.core.model.annotator.autofill.impl.Reference::class
Surround -> jp.ac.titech.cs.se.refactorhub.core.model.annotator.autofill.impl.Surround::class
Package -> jp.ac.titech.cs.se.refactorhub.core.model.annotator.autofill.impl.Package::class
}
}
| 0
|
Kotlin
|
0
| 6
|
f876da7bcc7bceed549586f0f0300d20f2108fe0
| 565
|
RefactorHub
|
MIT License
|
openai-client/client/src/jvmTest/kotlin/com/xebia/functional/openai/models/ext/embedding/create/CreateEmbeddingRequestInputSpec.kt
|
xebia-functional
| 629,411,216
| false
|
{"Kotlin": 4240359, "TypeScript": 67083, "Mustache": 18713, "Java": 8890, "CSS": 7836, "JavaScript": 4283, "HTML": 678}
|
package com.xebia.functional.openai.models.ext.embedding.create
import com.xebia.functional.simpleStringArb
import io.kotest.matchers.shouldBe
import io.kotest.property.Arb
import io.kotest.property.arbitrary.int
import io.kotest.property.arbitrary.list
import io.kotest.property.checkAll
import kotlin.test.Test
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.encodeToJsonElement
class CreateEmbeddingRequestInputSpec {
@Test
fun shouldSerializeProperlyStrings() {
runTest {
checkAll<String> { string ->
val v: CreateEmbeddingRequestInput = CreateEmbeddingRequestInput.StringValue(string)
Json.encodeToJsonElement<CreateEmbeddingRequestInput>(v) shouldBe JsonPrimitive(string)
}
}
}
@Test
fun shouldSerializeProperlyStringArrays() {
runTest {
checkAll<List<String>> { list ->
val v: CreateEmbeddingRequestInput = CreateEmbeddingRequestInput.StringArrayValue(list)
Json.encodeToJsonElement<CreateEmbeddingRequestInput>(v) shouldBe
JsonArray(list.map { JsonPrimitive(it) })
}
}
}
@Test
fun shouldSerializeProperlyIntArrays() {
runTest {
checkAll<List<Int>> { list ->
val v: CreateEmbeddingRequestInput = CreateEmbeddingRequestInput.IntArrayValue(list)
Json.encodeToJsonElement<CreateEmbeddingRequestInput>(v) shouldBe
JsonArray(list.map { JsonPrimitive(it) })
}
}
}
@Test
fun shouldSerializeProperlyIntArraysArrays() {
runTest {
checkAll<List<List<Int>>> { lists ->
val v: CreateEmbeddingRequestInput = CreateEmbeddingRequestInput.IntArrayArrayValue(lists)
Json.encodeToJsonElement<CreateEmbeddingRequestInput>(v) shouldBe
JsonArray(lists.map { list -> JsonArray(list.map { JsonPrimitive(it) }) })
}
}
}
@Serializable data class MyValue(val value: CreateEmbeddingRequestInput)
fun toJsonArray(list: List<Int>): String = list.joinToString(",\n", "[", "]") { "$it" }
@Test
fun shouldDeserializeProperlyStrings() {
runTest {
checkAll(simpleStringArb) { string ->
val rawJson = """{ "value": "$string" }"""
Json.decodeFromString<MyValue>(rawJson) shouldBe
MyValue(CreateEmbeddingRequestInput.StringValue(string))
}
}
}
@Test
fun shouldDeserializeProperlyStringArrays() {
runTest {
checkAll(Arb.list(simpleStringArb)) { list ->
val rawJson =
"""
|{
| "value": [
| ${list.joinToString(",\n") { "\"$it\"" }}
| ]
|}
|"""
.trimMargin()
Json.decodeFromString<MyValue>(rawJson) shouldBe
MyValue(CreateEmbeddingRequestInput.StringArrayValue(list))
}
}
}
@Test
fun shouldDeserializeProperlyIntArrays() {
runTest {
checkAll(Arb.list(Arb.int(), range = 1..100)) { list ->
val rawJson =
"""
|{
| "value": ${toJsonArray(list)}
|}
|"""
.trimMargin()
Json.decodeFromString<MyValue>(rawJson) shouldBe
MyValue(CreateEmbeddingRequestInput.IntArrayValue(list))
}
}
}
@Test
fun shouldDeserializeProperlyIntArraysArrays() {
runTest {
checkAll(Arb.list(Arb.list(Arb.int()), range = 1..100)) { lists ->
val rawJson =
"""
|{
| "value": [
| ${lists.joinToString(",\n") { toJsonArray(it) }}
| ]
|}
|"""
.trimMargin()
Json.decodeFromString<MyValue>(rawJson) shouldBe
MyValue(CreateEmbeddingRequestInput.IntArrayArrayValue(lists))
}
}
}
}
| 40
|
Kotlin
|
16
| 162
|
e8a62e98e2a6a2f8958045a8098987583d3e8b0a
| 3,862
|
xef
|
Apache License 2.0
|
app/src/main/java/com/mac/swaps/presentation/components/SearchBar.kt
|
mhmdabouchaker
| 509,566,605
| false
| null |
package com.mac.swaps.presentation.components
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Search
import androidx.compose.runtime.Composable
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
@ExperimentalComposeUiApi
@Composable
fun SearchBar(
query: String,
onQueryChanged: (String) -> Unit,
onExecuteSearch: () -> Unit
){
val keyboardController = LocalSoftwareKeyboardController.current
Surface (
modifier = Modifier
.fillMaxWidth(),
color = MaterialTheme.colors.secondary,
elevation = 8.dp,
){
Column {
Row(modifier =
Modifier.fillMaxWidth()
) {
TextField(
modifier = Modifier
.fillMaxWidth(.9f)
.padding(8.dp),
value = query,
onValueChange = {onQueryChanged(it)},
label = { Text(text = "Search by Favorites")},
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Text,
imeAction = ImeAction.Done
),
keyboardActions = KeyboardActions(
onDone = {
onExecuteSearch()
keyboardController?.hideSoftwareKeyboard()
}
),
leadingIcon = { Icon(Icons.Filled.Search, contentDescription = "Search Icon") },
textStyle = TextStyle(color = MaterialTheme.colors.onSurface),
colors = TextFieldDefaults.textFieldColors(backgroundColor = MaterialTheme.colors.surface)
)
}
}
}
}
| 0
|
Kotlin
|
0
| 1
|
a48fbb658601f3b3137efb2b147ee4f66a780488
| 2,427
|
swaps
|
Apache License 2.0
|
app/src/main/java/com/apex/codeassesment/data/model/Picture.kt
|
MKQasim
| 706,374,916
| false
|
{"Kotlin": 21487, "Java": 2370}
|
package com.apex.codeassesment.data.model
import android.os.Parcelable
import com.squareup.moshi.JsonClass
import kotlinx.parcelize.Parcelize
@Parcelize
@JsonClass(generateAdapter = true)
data class Picture(
val large: String? = null,
val medium: String? = null,
val thumbnail: String? = null
): Parcelable
| 0
|
Kotlin
|
0
| 0
|
a6eb3905b9f318e756cd4c75fd9a808d38a02712
| 314
|
ApexCodeAssesment
|
MIT License
|
app/src/main/java/com/mohandass/botforge/onboarding/ui/OnBoardingUi4Ugc.kt
|
L4TTiCe
| 611,975,837
| false
| null |
// SPDX-FileCopyrightText: 2023 <NAME> (L4TTiCe)
//
// SPDX-License-Identifier: MIT
package com.mohandass.botforge.onboarding.ui
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
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.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.mohandass.botforge.R
@Composable
fun OnBoardingUi4Ugc(
initialUserGenerated: Boolean = true,
saveUserGeneratedContent: (Boolean) -> Unit,
onComplete: () -> Unit
) {
val backgroundColor = colorResource(id = R.color.logoBorder)
val enableUserGeneratedContent = remember { mutableStateOf(initialUserGenerated) }
Box(
contentAlignment = Alignment.Center
) {
Canvas(modifier = Modifier.fillMaxSize()) {
val width = size.width
val height = size.height
drawRect(
color = backgroundColor,
topLeft = Offset(0f, 0f),
size = Size(width, height)
)
}
Column(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top
) {
Image(
modifier = Modifier
.fillMaxWidth(0.25f)
.fillMaxHeight(0.2f),
painter = painterResource(id = R.drawable.logo),
contentDescription = null
)
Column(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Text(
modifier = Modifier
.fillMaxWidth(0.9f),
text = stringResource(id = R.string.on_boarding_title_3),
style = MaterialTheme.typography.displaySmall,
textAlign = TextAlign.Center,
color = Color.White
)
Spacer(modifier = Modifier.height(60.dp))
Text(
modifier = Modifier
.fillMaxWidth(0.9f)
.padding(horizontal = 40.dp)
.padding(20.dp),
text = stringResource(id = R.string.on_boarding_message_3_1),
style = MaterialTheme.typography.bodyLarge.copy(
fontWeight = FontWeight.Medium
),
textAlign = TextAlign.Center,
color = Color.White
)
Spacer(modifier = Modifier.height(20.dp))
UserGeneratedContentSwitch(
title = stringResource(id = R.string.user_generated_content),
description = stringResource(id = R.string.user_generated_content_message),
icon = painterResource(id = R.drawable.baseline_color_lens_24),
switchState = enableUserGeneratedContent,
onCheckChange = {
enableUserGeneratedContent.value = it
saveUserGeneratedContent(it)
}
)
Spacer(modifier = Modifier.height(60.dp))
Button(onClick = onComplete) {
Text(
text = stringResource(id = R.string.get_started),
)
}
Spacer(modifier = Modifier.height(20.dp))
}
}
}
}
@Composable
fun UserGeneratedContentSwitch(
title: String,
description: String,
icon: Painter,
switchState: MutableState<Boolean>,
onCheckChange: (Boolean) -> Unit,
) {
val backgroundColor = colorResource(id = R.color.logoBorder)
Row(
modifier = Modifier
.fillMaxWidth()
.background(backgroundColor)
.padding(8.dp, 20.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Icon(
painter = icon,
contentDescription = null,
modifier = Modifier
.padding(start = 14.dp, end = 16.dp)
.size(26.dp),
tint = Color.White.copy(alpha = 0.8f)
)
Column(
modifier = Modifier
.weight(1f)
.padding(start = 12.dp, end = 8.dp)
) {
Text(
text = title,
maxLines = 1,
style = MaterialTheme.typography.titleMedium,
color = Color.White.copy(alpha = 0.8f)
)
Text(
text = description,
color = Color.White.copy(alpha = 0.8f),
style = MaterialTheme.typography.bodyMedium,
)
}
Switch(
checked = switchState.value,
onCheckedChange = { onCheckChange(it) },
modifier = Modifier.padding(start = 12.dp, end = 12.dp)
)
}
}
@Preview
@Composable
fun OnBoardingUi4Preview() {
OnBoardingUi4Ugc(
saveUserGeneratedContent = { },
onComplete = { }
)
}
| 1
|
Kotlin
|
0
| 27
|
3025ea313d99028c3a796a493b6f35279ee2b6b5
| 6,763
|
BotForge
|
MIT License
|
compose/material3/material3/integration-tests/material3-demos/src/main/java/androidx/compose/material3/demos/IconButtonDemos.kt
|
androidx
| 256,589,781
| false
|
{"Kotlin": 112114129, "Java": 66594571, "C++": 9132142, "AIDL": 635065, "Python": 325169, "Shell": 194520, "TypeScript": 40647, "HTML": 35176, "Groovy": 27178, "ANTLR": 26700, "Svelte": 20397, "CMake": 15512, "C": 15043, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019}
|
/*
* Copyright 2024 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.material3.demos
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.outlined.Edit
import androidx.compose.material.icons.outlined.Lock
import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
import androidx.compose.material3.FilledIconButton
import androidx.compose.material3.FilledIconToggleButton
import androidx.compose.material3.FilledTonalIconButton
import androidx.compose.material3.FilledTonalIconToggleButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.IconButtonDefaults
import androidx.compose.material3.IconButtonDefaults.IconButtonWidthOption.Companion.Narrow
import androidx.compose.material3.IconButtonDefaults.IconButtonWidthOption.Companion.Wide
import androidx.compose.material3.IconButtonShapes
import androidx.compose.material3.IconToggleButton
import androidx.compose.material3.OutlinedIconButton
import androidx.compose.material3.OutlinedIconToggleButton
import androidx.compose.material3.Text
import androidx.compose.material3.minimumInteractiveComponentSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
@OptIn(ExperimentalMaterial3ExpressiveApi::class)
@Composable
fun IconButtonMeasurementsDemo() {
val rowScrollState = rememberScrollState()
Row(modifier = Modifier.horizontalScroll(rowScrollState)) {
val columnScrollState = rememberScrollState()
val padding = 16.dp
Column(
modifier = Modifier.padding(horizontal = padding).verticalScroll(columnScrollState),
) {
Spacer(modifier = Modifier.height(padding + 48.dp))
Text("XSmall", modifier = Modifier.height(48.dp + padding))
Text("Small", modifier = Modifier.height(48.dp + padding))
Text("Medium", modifier = Modifier.height(56.dp + padding))
Text("Large", modifier = Modifier.height(96.dp + padding))
Text("XLarge", modifier = Modifier.height(136.dp + padding))
}
// Default
Column(
modifier =
Modifier.padding(horizontal = padding)
.width(136.dp)
.verticalScroll(columnScrollState),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(padding)
) {
Text("Default", modifier = Modifier.height(48.dp))
// XSmall uniform round icon button
FilledIconButton(
onClick = { /* doSomething() */ },
modifier = Modifier.size(IconButtonDefaults.xSmallContainerSize()),
shape = IconButtonDefaults.xSmallRoundShape
) {
Icon(
Icons.Outlined.Lock,
contentDescription = "Localized description",
modifier = Modifier.size(IconButtonDefaults.xSmallIconSize)
)
}
// Small uniform round icon button
FilledIconButton(
onClick = { /* doSomething() */ },
modifier = Modifier.size(IconButtonDefaults.smallContainerSize()),
shape = IconButtonDefaults.smallRoundShape
) {
Icon(
Icons.Outlined.Lock,
contentDescription = "Localized description",
modifier = Modifier.size(IconButtonDefaults.smallIconSize)
)
}
// Medium uniform round icon button
FilledIconButton(
onClick = { /* doSomething() */ },
modifier = Modifier.size(IconButtonDefaults.mediumContainerSize()),
shape = IconButtonDefaults.mediumRoundShape
) {
Icon(
Icons.Outlined.Lock,
contentDescription = "Localized description",
modifier = Modifier.size(IconButtonDefaults.mediumIconSize)
)
}
// Large uniform round icon button
FilledIconButton(
onClick = { /* doSomething() */ },
modifier = Modifier.size(IconButtonDefaults.largeContainerSize()),
shape = IconButtonDefaults.largeRoundShape
) {
Icon(
Icons.Outlined.Lock,
contentDescription = "Localized description",
modifier = Modifier.size(IconButtonDefaults.largeIconSize)
)
}
// XLarge uniform round icon button
FilledIconButton(
onClick = { /* doSomething() */ },
modifier = Modifier.size(IconButtonDefaults.xLargeContainerSize()),
shape = IconButtonDefaults.xLargeRoundShape
) {
Icon(
Icons.Outlined.Lock,
contentDescription = "Localized description",
modifier = Modifier.size(IconButtonDefaults.xLargeIconSize)
)
}
}
// Narrow
Column(
modifier =
Modifier.padding(horizontal = padding)
.width(104.dp)
.verticalScroll(columnScrollState),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(padding)
) {
Text("Narrow", modifier = Modifier.height(48.dp))
// XSmall narrow round icon button
FilledIconButton(
onClick = { /* doSomething() */ },
modifier = Modifier.size(IconButtonDefaults.xSmallContainerSize(Narrow)),
shape = IconButtonDefaults.xSmallRoundShape
) {
Icon(
Icons.Outlined.Lock,
contentDescription = "Localized description",
modifier = Modifier.size(IconButtonDefaults.xSmallIconSize)
)
}
// Small narrow round icon button
FilledIconButton(
onClick = { /* doSomething() */ },
modifier = Modifier.size(IconButtonDefaults.smallContainerSize(Narrow)),
shape = IconButtonDefaults.smallRoundShape
) {
Icon(
Icons.Outlined.Lock,
contentDescription = "Localized description",
modifier = Modifier.size(IconButtonDefaults.smallIconSize)
)
}
// Medium narrow round icon button
FilledIconButton(
onClick = { /* doSomething() */ },
modifier = Modifier.size(IconButtonDefaults.mediumContainerSize(Narrow)),
shape = IconButtonDefaults.mediumRoundShape
) {
Icon(
Icons.Outlined.Lock,
contentDescription = "Localized description",
modifier = Modifier.size(IconButtonDefaults.mediumIconSize)
)
}
// Large narrow round icon button
FilledIconButton(
onClick = { /* doSomething() */ },
modifier = Modifier.size(IconButtonDefaults.largeContainerSize(Narrow)),
shape = IconButtonDefaults.largeRoundShape
) {
Icon(
Icons.Outlined.Lock,
contentDescription = "Localized description",
modifier = Modifier.size(IconButtonDefaults.largeIconSize)
)
}
// XLarge narrow round icon button
FilledIconButton(
onClick = { /* doSomething() */ },
modifier = Modifier.size(IconButtonDefaults.xLargeContainerSize(Narrow)),
shape = IconButtonDefaults.xLargeRoundShape
) {
Icon(
Icons.Outlined.Lock,
contentDescription = "Localized description",
modifier = Modifier.size(IconButtonDefaults.xLargeIconSize)
)
}
}
// Wide
Column(
modifier =
Modifier.padding(horizontal = padding)
.width(184.dp)
.verticalScroll(columnScrollState),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(padding)
) {
Text("Wide", modifier = Modifier.height(48.dp))
// XSmall wide round icon button
FilledIconButton(
onClick = { /* doSomething() */ },
modifier = Modifier.size(IconButtonDefaults.xSmallContainerSize(Wide)),
shape = IconButtonDefaults.xSmallRoundShape
) {
Icon(
Icons.Outlined.Lock,
contentDescription = "Localized description",
modifier = Modifier.size(IconButtonDefaults.xSmallIconSize)
)
}
// Small wide round icon button
FilledIconButton(
onClick = { /* doSomething() */ },
modifier = Modifier.size(IconButtonDefaults.smallContainerSize(Wide)),
shape = IconButtonDefaults.smallRoundShape
) {
Icon(
Icons.Outlined.Lock,
contentDescription = "Localized description",
modifier = Modifier.size(IconButtonDefaults.smallIconSize)
)
}
// medium wide round icon button
FilledIconButton(
onClick = { /* doSomething() */ },
modifier = Modifier.size(IconButtonDefaults.mediumContainerSize(Wide)),
shape = IconButtonDefaults.mediumRoundShape
) {
Icon(
Icons.Outlined.Lock,
contentDescription = "Localized description",
modifier = Modifier.size(IconButtonDefaults.mediumIconSize)
)
}
// Large wide round icon button
FilledIconButton(
onClick = { /* doSomething() */ },
modifier = Modifier.size(IconButtonDefaults.largeContainerSize(Wide)),
shape = IconButtonDefaults.largeRoundShape
) {
Icon(
Icons.Outlined.Lock,
contentDescription = "Localized description",
modifier = Modifier.size(IconButtonDefaults.largeIconSize)
)
}
// XLarge wide round icon button
FilledIconButton(
onClick = { /* doSomething() */ },
modifier = Modifier.size(IconButtonDefaults.xLargeContainerSize(Wide)),
shape = IconButtonDefaults.xLargeRoundShape
) {
Icon(
Icons.Outlined.Lock,
contentDescription = "Localized description",
modifier = Modifier.size(IconButtonDefaults.xLargeIconSize)
)
}
}
}
}
@OptIn(ExperimentalMaterial3ExpressiveApi::class)
@Composable
fun IconButtonCornerRadiusDemo() {
Column {
val rowScrollState = rememberScrollState()
val padding = 16.dp
// uniform round row
Row(
modifier =
Modifier.height(150.dp)
.horizontalScroll(rowScrollState)
.padding(horizontal = padding),
horizontalArrangement = Arrangement.spacedBy(padding),
verticalAlignment = Alignment.CenterVertically
) {
// xsmall round icon button
OutlinedIconButton(
onClick = { /* doSomething() */ },
modifier = Modifier.size(IconButtonDefaults.xSmallContainerSize()),
shape = IconButtonDefaults.xSmallRoundShape
) {
Icon(
Icons.Outlined.Lock,
contentDescription = "Localized description",
modifier = Modifier.size(IconButtonDefaults.xSmallIconSize)
)
}
// Small round icon button
OutlinedIconButton(
onClick = { /* doSomething() */ },
modifier = Modifier.size(IconButtonDefaults.smallContainerSize()),
shape = IconButtonDefaults.smallRoundShape
) {
Icon(
Icons.Outlined.Lock,
contentDescription = "Localized description",
modifier = Modifier.size(IconButtonDefaults.smallIconSize)
)
}
// Medium round icon button
OutlinedIconButton(
onClick = { /* doSomething() */ },
modifier =
Modifier.minimumInteractiveComponentSize()
.size(IconButtonDefaults.mediumContainerSize()),
shape = IconButtonDefaults.mediumRoundShape
) {
Icon(
Icons.Outlined.Lock,
contentDescription = "Localized description",
modifier = Modifier.size(IconButtonDefaults.mediumIconSize)
)
}
// Large uniform round icon button
OutlinedIconButton(
onClick = { /* doSomething() */ },
modifier =
Modifier.minimumInteractiveComponentSize()
.size(IconButtonDefaults.largeContainerSize()),
shape = IconButtonDefaults.largeRoundShape
) {
Icon(
Icons.Outlined.Lock,
contentDescription = "Localized description",
modifier = Modifier.size(IconButtonDefaults.largeIconSize)
)
}
// XLarge uniform round icon button
OutlinedIconButton(
onClick = { /* doSomething() */ },
modifier =
Modifier.minimumInteractiveComponentSize()
.size(IconButtonDefaults.xLargeContainerSize()),
shape = IconButtonDefaults.xLargeRoundShape
) {
Icon(
Icons.Outlined.Lock,
contentDescription = "Localized description",
modifier = Modifier.size(IconButtonDefaults.xLargeIconSize)
)
}
}
// uniform square row
Row(
modifier =
Modifier.height(150.dp)
.horizontalScroll(rowScrollState)
.padding(horizontal = padding),
horizontalArrangement = Arrangement.spacedBy(padding),
verticalAlignment = Alignment.CenterVertically
) {
// xsmall square icon button
OutlinedIconButton(
onClick = { /* doSomething() */ },
modifier =
Modifier
// .minimumInteractiveComponentSize()
.size(IconButtonDefaults.xSmallContainerSize()),
shape = IconButtonDefaults.xSmallSquareShape
) {
Icon(
Icons.Outlined.Lock,
contentDescription = "Localized description",
modifier = Modifier.size(IconButtonDefaults.xSmallIconSize)
)
}
// Small round icon button
OutlinedIconButton(
onClick = { /* doSomething() */ },
modifier =
Modifier
// .minimumInteractiveComponentSize()
.size(IconButtonDefaults.smallContainerSize()),
shape = IconButtonDefaults.smallSquareShape
) {
Icon(
Icons.Outlined.Lock,
contentDescription = "Localized description",
modifier = Modifier.size(IconButtonDefaults.smallIconSize)
)
}
// Medium round icon button
OutlinedIconButton(
onClick = { /* doSomething() */ },
modifier =
Modifier.minimumInteractiveComponentSize()
.size(IconButtonDefaults.mediumContainerSize()),
shape = IconButtonDefaults.mediumSquareShape
) {
Icon(
Icons.Outlined.Lock,
contentDescription = "Localized description",
modifier = Modifier.size(IconButtonDefaults.mediumIconSize)
)
}
// Large uniform round icon button
OutlinedIconButton(
onClick = { /* doSomething() */ },
modifier =
Modifier.minimumInteractiveComponentSize()
.size(IconButtonDefaults.largeContainerSize()),
shape = IconButtonDefaults.largeSquareShape
) {
Icon(
Icons.Outlined.Lock,
contentDescription = "Localized description",
modifier = Modifier.size(IconButtonDefaults.largeIconSize)
)
}
// XLarge uniform round icon button
OutlinedIconButton(
onClick = { /* doSomething() */ },
modifier =
Modifier.minimumInteractiveComponentSize()
.size(IconButtonDefaults.xLargeContainerSize()),
shape = IconButtonDefaults.xLargeSquareShape
) {
Icon(
Icons.Outlined.Lock,
contentDescription = "Localized description",
modifier = Modifier.size(IconButtonDefaults.xLargeIconSize)
)
}
}
}
}
@OptIn(ExperimentalMaterial3ExpressiveApi::class)
@Composable
fun IconButtonAndToggleButtonsDemo() {
Column {
val rowScrollState = rememberScrollState()
val padding = 16.dp
Row(
modifier =
Modifier.height(150.dp)
.horizontalScroll(rowScrollState)
.padding(horizontal = padding),
horizontalArrangement = Arrangement.spacedBy(padding),
verticalAlignment = Alignment.CenterVertically
) {
Spacer(Modifier.width(72.dp))
Text("Filled")
Text("Tonal")
Text("Outline")
Text("Standard")
}
// icon buttons
Row(
modifier =
Modifier.height(150.dp)
.horizontalScroll(rowScrollState)
.padding(horizontal = padding),
horizontalArrangement = Arrangement.spacedBy(padding),
verticalAlignment = Alignment.CenterVertically
) {
Spacer(Modifier.width(76.dp))
FilledIconButton(onClick = {}) {
Icon(Icons.Outlined.Edit, contentDescription = "Localized description")
}
FilledTonalIconButton(onClick = {}) {
Icon(Icons.Outlined.Edit, contentDescription = "Localized description")
}
OutlinedIconButton(onClick = {}) {
Icon(Icons.Outlined.Edit, contentDescription = "Localized description")
}
IconButton(onClick = {}) {
Icon(Icons.Outlined.Edit, contentDescription = "Localized description")
}
}
// unselected icon toggle buttons
Row(
modifier =
Modifier.height(150.dp)
.horizontalScroll(rowScrollState)
.padding(horizontal = padding),
horizontalArrangement = Arrangement.spacedBy(padding),
verticalAlignment = Alignment.CenterVertically
) {
var checked by remember { mutableStateOf(false) }
Text(
text =
if (!checked) {
"Unselected"
} else {
"Selected"
},
modifier = Modifier.defaultMinSize(minWidth = 76.dp),
)
FilledIconToggleButton(
checked = checked,
onCheckedChange = { checked = it },
shapes =
IconButtonShapes(
shape = IconButtonDefaults.smallRoundShape,
pressedShape = IconButtonDefaults.smallPressedShape,
checkedShape = IconButtonDefaults.smallSquareShape
)
) {
Icon(Icons.Outlined.Edit, contentDescription = "Localized description")
}
FilledTonalIconToggleButton(
checked = checked,
onCheckedChange = { checked = it },
shapes =
IconButtonShapes(
shape = IconButtonDefaults.smallRoundShape,
pressedShape = IconButtonDefaults.smallPressedShape,
checkedShape = IconButtonDefaults.smallSquareShape
)
) {
Icon(Icons.Outlined.Edit, contentDescription = "Localized description")
}
OutlinedIconToggleButton(
checked = checked,
onCheckedChange = { checked = it },
shapes =
IconButtonShapes(
shape = IconButtonDefaults.smallRoundShape,
pressedShape = IconButtonDefaults.smallPressedShape,
checkedShape = IconButtonDefaults.smallSquareShape
)
) {
Icon(Icons.Outlined.Edit, contentDescription = "Localized description")
}
IconToggleButton(
checked = checked,
onCheckedChange = { checked = it },
shapes =
IconButtonShapes(
shape = IconButtonDefaults.smallRoundShape,
pressedShape = IconButtonDefaults.smallPressedShape,
checkedShape = IconButtonDefaults.smallSquareShape
)
) {
Icon(Icons.Outlined.Edit, contentDescription = "Localized description")
}
}
// selected icon toggle buttons
Row(
modifier =
Modifier.height(150.dp)
.horizontalScroll(rowScrollState)
.padding(horizontal = padding),
horizontalArrangement = Arrangement.spacedBy(padding),
verticalAlignment = Alignment.CenterVertically
) {
var checked by remember { mutableStateOf(true) }
Text(
text =
if (!checked) {
"Unselected"
} else {
"Selected"
},
modifier = Modifier.defaultMinSize(minWidth = 76.dp)
)
FilledIconToggleButton(
checked = checked,
onCheckedChange = { checked = it },
shapes =
IconButtonShapes(
shape = IconButtonDefaults.smallRoundShape,
pressedShape = IconButtonDefaults.smallPressedShape,
checkedShape = IconButtonDefaults.smallSquareShape
)
) {
Icon(Icons.Filled.Edit, contentDescription = "Localized description")
}
FilledTonalIconToggleButton(
checked = checked,
onCheckedChange = { checked = it },
shapes =
IconButtonShapes(
shape = IconButtonDefaults.smallRoundShape,
pressedShape = IconButtonDefaults.smallPressedShape,
checkedShape = IconButtonDefaults.smallSquareShape
)
) {
Icon(Icons.Filled.Edit, contentDescription = "Localized description")
}
OutlinedIconToggleButton(
checked = checked,
onCheckedChange = { checked = it },
shapes =
IconButtonShapes(
shape = IconButtonDefaults.smallRoundShape,
pressedShape = IconButtonDefaults.smallPressedShape,
checkedShape = IconButtonDefaults.smallSquareShape
)
) {
Icon(Icons.Filled.Edit, contentDescription = "Localized description")
}
IconToggleButton(
checked = checked,
onCheckedChange = { checked = it },
shapes =
IconButtonShapes(
shape = IconButtonDefaults.smallRoundShape,
pressedShape = IconButtonDefaults.smallPressedShape,
checkedShape = IconButtonDefaults.smallSquareShape
)
) {
Icon(Icons.Filled.Edit, contentDescription = "Localized description")
}
}
}
}
| 29
|
Kotlin
|
1011
| 5,321
|
98b929d303f34d569e9fd8a529f022d398d1024b
| 27,151
|
androidx
|
Apache License 2.0
|
library/src/main/java/com/spisoft/countrycodepickerdialog/models/CountryCode.kt
|
SPSpisoft
| 344,772,772
| true
|
{"Kotlin": 30504}
|
package com.spisoft.countrycodepickerdialog.models
data class CountryCode(val name: String,
val code: String,
val dialCode: String)
| 0
|
Kotlin
|
0
| 0
|
9f825cde7924727d5b357edb7913671758c5de1a
| 178
|
android-countrycodepickerdialog
|
ISC License
|
archipanion-mw/archipanion-mw-server/src/main/kotlin/org/archipanion/mw/server/model/config/query/dynamicDescription/DynamicOperation.kt
|
Archipanion
| 756,965,425
| false
|
{"Kotlin": 78327, "Java": 85}
|
package org.archipanion.mw.server.model.config.query.dynamicDescription
import kotlinx.serialization.Serializable
@Serializable
data class DynamicOperation(
val type: OperationType,
val name: String? = null,
val input: String,
val field: String? = null,
)
| 0
|
Kotlin
|
0
| 0
|
8cae6b82d0e871e73a261679b456ee0b0c2a7a5a
| 275
|
archipanion-engine-middlelayer
|
MIT License
|
src/commonMain/kotlin/eu/vendeli/rethis/commands/SetCommands.kt
|
vendelieu
| 861,014,428
| false
|
{"Kotlin": 213441, "Shell": 1248}
|
package eu.vendeli.rethis.commands
import eu.vendeli.rethis.ReThis
import eu.vendeli.rethis.exception
import eu.vendeli.rethis.types.common.ScanResult
import eu.vendeli.rethis.types.core.*
import eu.vendeli.rethis.types.core.unwrap
import eu.vendeli.rethis.types.options.SScanOption
import eu.vendeli.rethis.utils.safeCast
import eu.vendeli.rethis.utils.writeArg
suspend fun ReThis.sAdd(key: String, vararg members: String): Long = execute(
listOf(
"SADD".toArg(),
key.toArg(),
*members.toArg(),
),
).unwrap() ?: 0
suspend fun ReThis.sCard(key: String): Long = execute(
listOf(
"SCARD".toArg(),
key.toArg(),
),
).unwrap() ?: 0
suspend fun ReThis.sDiff(vararg keys: String): Set<String> = execute(
listOf(
"SDIFF".toArg(),
*keys.toArg(),
),
).unwrapSet<String>()
suspend fun ReThis.sDiffStore(destination: String, vararg keys: String): Long = execute(
listOf(
"SDIFFSTORE".toArg(),
destination.toArg(),
*keys.toArg(),
),
).unwrap() ?: 0
suspend fun ReThis.sInter(vararg keys: String): Set<String> = execute(
listOf(
"SINTER".toArg(),
*keys.toArg(),
),
).unwrapSet<String>()
suspend fun ReThis.sInterStore(destination: String, vararg keys: String): Long = execute(
listOf(
"SINTERSTORE".toArg(),
destination.toArg(),
*keys.toArg(),
),
).unwrap() ?: 0
suspend fun ReThis.sIsMember(key: String, member: String): Boolean = execute(
listOf(
"SISMEMBER".toArg(),
key.toArg(),
member.toArg(),
),
).unwrap<Long>() == 1L
suspend fun ReThis.sMembers(key: String): Set<String> = execute(
listOf(
"SMEMBERS".toArg(),
key.toArg(),
),
).unwrapSet<String>()
suspend fun ReThis.sMove(source: String, destination: String, member: String): Boolean = execute(
listOf(
"SMOVE".toArg(),
source.toArg(),
destination.toArg(),
member.toArg(),
),
).unwrap<Long>() == 1L
suspend fun ReThis.sPop(
key: String,
): String? = execute(
listOf("SPOP".toArg(), key.toArg()),
).unwrap()
suspend fun ReThis.sPop(
key: String,
count: Long,
): Set<String> = execute(
listOf("SPOP".toArg(), key.toArg(), count.toArg()),
).unwrapSet<String>()
suspend fun ReThis.sRandMember(
key: String,
): String? = execute(
listOf("SRANDMEMBER".toArg(), key.toArg()),
).unwrap()
suspend fun ReThis.sRandMember(
key: String,
count: Long,
): List<String> = execute(
listOf("SRANDMEMBER".toArg(), key.toArg(), count.toArg()),
).unwrapList<String>()
suspend fun ReThis.sRem(key: String, vararg members: String): Long = execute(
listOf(
"SREM".toArg(),
key.toArg(),
*members.toArg(),
),
).unwrap() ?: 0
suspend fun ReThis.sScan(
key: String,
cursor: Long,
vararg option: SScanOption,
): ScanResult<String> {
val response = execute(mutableListOf("SSCAN".toArg(), key.toArg(), cursor.toArg()).writeArg(option))
val arrResponse = response.safeCast<RArray>()?.value ?: exception { "Wrong response type" }
val newCursor = arrResponse[0].unwrap<String>() ?: exception { "Missing cursor in response" }
val membersArray = arrResponse[1].safeCast<RArray>()?.value ?: exception { "Missing members in response" }
val members = membersArray.map { it.unwrap<String>() ?: exception { "Invalid member format" } }
return ScanResult(cursor = newCursor, keys = members)
}
suspend fun ReThis.sUnion(vararg keys: String): Set<String> = execute(
listOf(
"SUNION".toArg(),
*keys.toArg(),
),
).unwrapSet<String>()
suspend fun ReThis.sUnionStore(destination: String, vararg keys: String): Long = execute(
listOf(
"SUNIONSTORE".toArg(),
destination.toArg(),
*keys.toArg(),
),
).unwrap() ?: 0
suspend fun ReThis.sInterCard(vararg keys: String, limit: Long? = null): Long = execute(
mutableListOf(
"SINTERCARD".toArg(),
keys.size.toArg(),
*keys.toArg(),
).apply {
limit?.let { writeArg("LIMIT" to it) }
},
).unwrap() ?: 0
suspend fun ReThis.sMisMember(key: String, vararg members: String): List<Boolean> = execute(
listOf(
"SMISMEMBER".toArg(),
key.toArg(),
*members.toArg(),
),
).unwrapList<Long>().map { it == 1L }
| 5
|
Kotlin
|
0
| 7
|
8ae609b5430e9ca9255c5a1cba2bdfc70e316020
| 4,358
|
re.this
|
Apache License 2.0
|
sdk/dc/src/main/java/com/ibm/security/verifysdk/dc/model/OutOfBandCredentialProposalArgs.kt
|
ibm-security-verify
| 430,929,749
| false
|
{"Kotlin": 662580}
|
/*
* Copyright contributors to the IBM Security Verify DC SDK for Android project
*/
package com.ibm.security.verifysdk.dc.model
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.SerialName
@ExperimentalSerializationApi
@Serializable
data class OutOfBandCredentialProposalArgs (
@SerialName("attributes")
val attributes: Map<String, String>,
@SerialName("comment")
val comment: String? = null,
@SerialName("credential_proposal")
val credentialProposal: JsonElement? = null,
@SerialName("cred_def_id")
val credDefId: String? = null,
@SerialName("schema_id")
val schemaId: String? = null,
@SerialName("schema_name")
val schemaName: String? = null,
@SerialName("schema_version")
val schemaVersion: String? = null
)
| 1
|
Kotlin
|
4
| 0
|
5649b763aa7dff56489c650c3dc4e9f12cc11003
| 904
|
verify-sdk-android
|
MIT License
|
app/src/main/kotlin/dvachmovie/worker/InitDBWorker.kt
|
sasfmlzr
| 151,072,454
| false
| null |
package dvachmovie.worker
import android.content.Context
import androidx.annotation.NonNull
import androidx.work.WorkerParameters
import dvachmovie.architecture.base.BaseDBWorker
import dvachmovie.db.model.MovieDBCache
import dvachmovie.di.core.WorkerComponent
import dvachmovie.pipe.db.InsertionMovieListToDBPipe
import dvachmovie.pipe.db.InsertionThreadListToDBPipe
import javax.inject.Inject
class InitDBWorker(@NonNull context: Context,
@NonNull workerParams: WorkerParameters
) : BaseDBWorker(context, workerParams) {
@Inject
lateinit var insertionMovieListToDBPipe: InsertionMovieListToDBPipe
@Inject
lateinit var insertionThreadListToDBPipe: InsertionThreadListToDBPipe
override fun inject(component: WorkerComponent) = component.inject(this)
override suspend fun execute() {
insertionMovieListToDBPipe.execute(MovieDBCache.movieList)
insertionThreadListToDBPipe.execute(MovieDBCache.threadList)
}
}
| 0
|
Kotlin
|
2
| 3
|
84b5a1187ff81c0ca5e71f052129160e425a6247
| 975
|
DvachMovie
|
Apache License 2.0
|
app/src/main/java/com/fengniao/news/net/FNCallback.kt
|
mycolors
| 86,323,081
| false
| null |
package com.fengniao.news.net
interface FNCallback {
fun onReceiveData(function: String, data: String, msg: String)
fun onReceiveError(function: String, errorCode: Int, msg: String)
}
| 0
|
Kotlin
|
0
| 0
|
e217f1f6c855aee6f93e77ebbd90964621a37877
| 196
|
WanXiang
|
Apache License 2.0
|
app/src/main/java/ca/josuelubaki/tmdbclient/domain/usecase/GetArtistsUseCase.kt
|
josue-lubaki
| 582,682,808
| false
|
{"Kotlin": 59940}
|
package ca.josuelubaki.tmdbclient.domain.usecase
import ca.josuelubaki.tmdbclient.data.model.artist.Artist
import ca.josuelubaki.tmdbclient.domain.repository.ArtistRepository
class GetArtistsUseCase(private val artistRepository: ArtistRepository) {
suspend fun execute(): List<Artist>? = artistRepository.getArtists()
}
| 0
|
Kotlin
|
0
| 2
|
f12ec5cd76c9f45d8838cf0dd76c6f0d8ccd2b78
| 326
|
TMBDClient
|
MIT License
|
cortex-analysis/src/main/kotlin/com/hileco/cortex/analysis/processors/JumpIllegalProcessor.kt
|
SkPhilipp
| 303,748,538
| false
|
{"Kotlin": 331330, "Solidity": 7723, "Shell": 1440, "Dockerfile": 879}
|
package com.hileco.cortex.analysis.processors
import com.hileco.cortex.analysis.Graph
import com.hileco.cortex.analysis.edges.FlowMapping
import com.hileco.cortex.analysis.edges.FlowType.INSTRUCTION_JUMP
import com.hileco.cortex.symbolic.ProgramException.Reason.JUMP_TO_ILLEGAL_INSTRUCTION
import com.hileco.cortex.symbolic.ProgramException.Reason.JUMP_TO_OUT_OF_BOUNDS
import com.hileco.cortex.symbolic.instructions.debug.HALT
import com.hileco.cortex.symbolic.instructions.jumps.JUMP_DESTINATION
class JumpIllegalProcessor : Processor {
override fun process(graph: Graph) {
val flowMapping = graph.edgeMapping.get(FlowMapping::class.java).single()
flowMapping.flowsFromSource.values.forEach { flows ->
val onlyJumpFlow = flows.singleOrNull { flow -> flow.type == INSTRUCTION_JUMP }
if (onlyJumpFlow != null) {
val sourceNode = flowMapping.nodePositionMapping[onlyJumpFlow.source]
if (sourceNode != null) {
val targetedNode = flowMapping.nodePositionMapping[onlyJumpFlow.target]
if (targetedNode == null) {
sourceNode.instruction = HALT(JUMP_TO_OUT_OF_BOUNDS)
} else if (targetedNode.instruction !is JUMP_DESTINATION) {
sourceNode.instruction = HALT(JUMP_TO_ILLEGAL_INSTRUCTION)
}
}
}
}
}
}
| 0
|
Kotlin
|
2
| 7
|
5e45e4a3659d4fd7167ae31a58bee7785a869993
| 1,438
|
cortex
|
MIT License
|
api/src/main/kotlin/com/mattmx/ktgui/commands/alpha/ArgumentType.kt
|
Matt-MX
| 530,062,987
| false
|
{"Kotlin": 255573, "Java": 8369}
|
package com.mattmx.ktgui.commands.alpha
enum class ArgumentType {
REQUIRED_SINGLE,
OPTIONAL_SINGLE,
GREEDY
}
| 3
|
Kotlin
|
3
| 24
|
fdc34fce5eeb41f177f890040a58d6c174168434
| 121
|
KtPaperGui
|
Apache License 2.0
|
lightbulb-dialogs/src/main/java/com/github/rooneyandshadows/lightbulb/dialogs/picker_dialog_datetime/DateTimePickerDialog.kt
|
RooneyAndShadows
| 417,583,232
| false
|
{"Kotlin": 402809}
|
package com.github.rooneyandshadows.lightbulb.dialogs.picker_dialog_datetime
import android.content.res.Configuration
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.TimePicker
import androidx.appcompat.widget.AppCompatImageButton
import androidx.appcompat.widget.AppCompatTextView
import com.github.rooneyandshadows.java.commons.date.DateUtilsOffsetDate
import com.github.rooneyandshadows.lightbulb.commons.utils.ResourceUtils
import com.github.rooneyandshadows.lightbulb.dialogs.R
import com.github.rooneyandshadows.lightbulb.dialogs.base.BasePickerDialogFragment
import com.github.rooneyandshadows.lightbulb.dialogs.base.constraints.regular.RegularDialogConstraints
import com.github.rooneyandshadows.lightbulb.dialogs.base.constraints.regular.RegularDialogConstraintsBuilder
import com.github.rooneyandshadows.lightbulb.dialogs.base.internal.DialogTypes
import com.prolificinteractive.materialcalendarview.CalendarDay
import com.prolificinteractive.materialcalendarview.MaterialCalendarView
import java.time.OffsetDateTime
import java.time.ZoneOffset
import java.util.*
@Suppress("UNUSED_PARAMETER")
class DateTimePickerDialog : BasePickerDialogFragment<OffsetDateTime>(DateTimeSelection(null, null)) {
private var showingTimePicker = false
private var calendarView: MaterialCalendarView? = null
private var timePickerView: TimePicker? = null
private var selectionTextValue: AppCompatTextView? = null
private var modeChangeButton: AppCompatImageButton? = null
private var zoneOffset = DEFAULT_OFFSET
var dialogDateFormat = DEFAULT_DATE_FORMAT
private set
override var dialogType: DialogTypes
get() = DialogTypes.NORMAL
set(value) {}
companion object {
private val DEFAULT_OFFSET = ZoneOffset.of(DateUtilsOffsetDate.getLocalTimeZone())
private const val DEFAULT_DATE_FORMAT = "dd MMM HH:mm, yyyy"
private const val SHOWING_TIME_PICKER_TAG = "SHOWING_TIME_PICKER_TAG"
private const val DATE_FORMAT_TAG = "DATE_FORMAT_TEXT"
private const val DATE_OFFSET_TAG = "DATE_OFFSET_TAG"
fun newInstance(): DateTimePickerDialog {
return DateTimePickerDialog()
}
}
@Override
override fun getRegularConstraints(): RegularDialogConstraints {
return RegularDialogConstraintsBuilder(this)
.default()
.withMaxHeightInPercents(90)
.build()
}
@Override
override fun doOnSaveDialogProperties(outState: Bundle) {
super.doOnSaveDialogProperties(outState)
outState.apply {
putString(DATE_OFFSET_TAG, zoneOffset.toString())
putBoolean(SHOWING_TIME_PICKER_TAG, showingTimePicker)
putString(DATE_FORMAT_TAG, dialogDateFormat)
}
}
@Override
override fun doOnRestoreDialogProperties(savedState: Bundle) {
super.doOnRestoreDialogProperties(savedState)
savedState.apply {
showingTimePicker = getBoolean(SHOWING_TIME_PICKER_TAG)
dialogDateFormat = getString(DATE_FORMAT_TAG, dialogDateFormat)
zoneOffset = ZoneOffset.of(getString(DATE_OFFSET_TAG))
}
}
@Override
override fun getDialogLayout(layoutInflater: LayoutInflater): View {
val orientation = resources.configuration.orientation
return if (orientation == Configuration.ORIENTATION_PORTRAIT)
layoutInflater.inflate(R.layout.dialog_picker_datetime_vertical, null)
else layoutInflater.inflate(R.layout.dialog_picker_datetime_horizontal, null)
}
@Override
override fun setupDialogContent(view: View, savedInstanceState: Bundle?) {
val activeSelection = dialogSelection.getActiveSelection()
selectViews(view)
setupHeader(activeSelection)
val context = requireContext()
modeChangeButton?.apply {
background = ResourceUtils.getDrawable(context, R.drawable.dialogs_bg_round_corners_transparent_ripple)
setOnClickListener {
showingTimePicker = !showingTimePicker
syncPickerMode()
}
}
calendarView?.apply {
leftArrow.setTint(ResourceUtils.getColorByAttribute(context, R.attr.colorAccent))
rightArrow.setTint(ResourceUtils.getColorByAttribute(context, R.attr.colorAccent))
if (activeSelection == null) clearSelection()
else {
val selectedDate = dateToCalendarDay(activeSelection)
setDateSelected(selectedDate, true)
setCurrentDate(selectedDate, false)
}
}
activeSelection?.apply selectedDate@{
timePickerView?.apply {
hour = DateUtilsOffsetDate.getHourOfDay(this@selectedDate)
minute = DateUtilsOffsetDate.getMinuteOfHour(this@selectedDate)
}
}
syncPickerMode()
}
private fun checkIfCalendarNeedsSync(currentValue: OffsetDateTime?): Boolean {
val calendarValue = calendarView!!.selectedDate?.let {
calendarDayToDate(it, currentValue ?: DateUtilsOffsetDate.nowLocal())
}
if (currentValue == null && calendarValue == null) return false
if (currentValue == null || calendarValue == null) return true
return !DateUtilsOffsetDate.isDateEqual(currentValue, calendarValue)
}
@Override
override fun onSelectionChange(newSelection: OffsetDateTime?) {
setupHeader(newSelection)
if (!checkIfCalendarNeedsSync(newSelection)) return
calendarView?.apply {
if (newSelection == null) clearSelection()
else {
val selectedDate = dateToCalendarDay(newSelection)
setDateSelected(selectedDate, true)
setCurrentDate(selectedDate, false)
}
}
timePickerView?.apply {
if (newSelection == null) return@apply
hour = DateUtilsOffsetDate.getHourOfDay(newSelection)
minute = DateUtilsOffsetDate.getMinuteOfHour(newSelection)
}
}
@Override
override fun doOnViewStateRestored(savedInstanceState: Bundle?) {
super.doOnViewStateRestored(savedInstanceState)
calendarView!!.setOnDateChangedListener { _: MaterialCalendarView?, date: CalendarDay, _: Boolean ->
if (isDialogShown) {
val draftDate = dialogSelection.getDraftSelection()
val hour: Int
val minute: Int
val second = 0
if (draftDate != null) {
hour = DateUtilsOffsetDate.getHourOfDay(draftDate)
minute = DateUtilsOffsetDate.getMinuteOfHour(draftDate)
} else {
val now = DateUtilsOffsetDate.nowLocal()
hour = DateUtilsOffsetDate.getHourOfDay(now)
minute = DateUtilsOffsetDate.getMinuteOfHour(now)
}
dialogSelection.setDraftSelection(
DateUtilsOffsetDate.date(date.year, date.month, date.day, hour, minute, second, zoneOffset)
)
} else {
val currentDate = dialogSelection.getCurrentSelection()
val hour: Int
val minute: Int
val second = 0
if (currentDate != null) {
hour = DateUtilsOffsetDate.getHourOfDay(currentDate)
minute = DateUtilsOffsetDate.getMinuteOfHour(currentDate)
} else {
val now = DateUtilsOffsetDate.nowLocal()
hour = DateUtilsOffsetDate.getHourOfDay(now)
minute = DateUtilsOffsetDate.getMinuteOfHour(now)
}
dialogSelection.setCurrentSelection(
DateUtilsOffsetDate.date(date.year, date.month, date.day, hour, minute, second, zoneOffset)
)
}
}
timePickerView!!.setOnTimeChangedListener { _: TimePicker?, hourOfDay: Int, minute: Int ->
val date = DateUtilsOffsetDate.setTimeToDate(dialogSelection.getDraftSelection(), hourOfDay, minute, 0)
if (isDialogShown) dialogSelection.setDraftSelection(date) else dialogSelection.setCurrentSelection(date)
}
}
@Override
override fun setSelection(newSelection: OffsetDateTime?) {
super.setSelection(newSelection)
zoneOffset = newSelection?.offset ?: DEFAULT_OFFSET
}
fun setDialogDateFormat(dateFormat: String?) {
val activeSelection = dialogSelection.getActiveSelection()
dialogDateFormat = dateFormat ?: DEFAULT_DATE_FORMAT
setupHeader(activeSelection)
}
private fun selectViews(view: View) {
selectionTextValue = view.findViewById(R.id.dateSelectionValue)
timePickerView = view.findViewById(R.id.timePickerView)
modeChangeButton = view.findViewById(R.id.datePickerModeChangeButton)
calendarView = view.findViewById(R.id.dateCalendarView)
}
private fun setupHeader(selection: OffsetDateTime?) {
modeChangeButton?.apply {
visibility = if (selection == null) View.GONE else View.VISIBLE
}
selectionTextValue?.apply {
val dateString = DateUtilsOffsetDate.getDateString(dialogDateFormat, selection, Locale.getDefault())
val default = ResourceUtils.getPhrase(requireContext(), R.string.dialog_month_picker_empty_text)
text = if (dateString.isNullOrBlank()) default else dateString
}
}
private fun dateToCalendarDay(date: OffsetDateTime?): CalendarDay? {
if (date == null) return null
val year = DateUtilsOffsetDate.extractYearFromDate(date)
val month = DateUtilsOffsetDate.extractMonthOfYearFromDate(date)
val day = DateUtilsOffsetDate.extractDayOfMonthFromDate(date)
return CalendarDay.from(year, month, day)
}
private fun calendarDayToDate(
calendarDay: CalendarDay?,
currentSelection: OffsetDateTime,
): OffsetDateTime? {
if (calendarDay == null) return null
val hour = currentSelection.hour
val minute = currentSelection.minute
return DateUtilsOffsetDate.date(calendarDay.year, calendarDay.month, calendarDay.day, hour, minute, 0)
}
private fun syncPickerMode() {
val activeSelection = dialogSelection.getActiveSelection()
if (showingTimePicker && activeSelection == null) showingTimePicker = false
val modeIconRes = if (showingTimePicker) R.drawable.dialogs_ic_calendar else R.drawable.dialogs_ic_time
val modeIcon = ResourceUtils.getDrawable(modeChangeButton!!.context, modeIconRes).apply {
this!!.setTint(ResourceUtils.getColorByAttribute(modeChangeButton!!.context, R.attr.colorOnPrimary))
}
modeChangeButton!!.setImageDrawable(modeIcon)
if (showingTimePicker) {
timePickerView!!.visibility = View.VISIBLE
calendarView!!.visibility = View.GONE
} else {
timePickerView!!.visibility = View.GONE
calendarView!!.visibility = View.VISIBLE
}
measureDialogLayout()
}
}
| 1
|
Kotlin
|
1
| 2
|
9300a8921365dd92905ae172a7180ef0cb8f958a
| 11,269
|
lightbulb-dialogs
|
Apache License 2.0
|
lightbulb-dialogs/src/main/java/com/github/rooneyandshadows/lightbulb/dialogs/picker_dialog_datetime/DateTimePickerDialog.kt
|
RooneyAndShadows
| 417,583,232
| false
|
{"Kotlin": 402809}
|
package com.github.rooneyandshadows.lightbulb.dialogs.picker_dialog_datetime
import android.content.res.Configuration
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.TimePicker
import androidx.appcompat.widget.AppCompatImageButton
import androidx.appcompat.widget.AppCompatTextView
import com.github.rooneyandshadows.java.commons.date.DateUtilsOffsetDate
import com.github.rooneyandshadows.lightbulb.commons.utils.ResourceUtils
import com.github.rooneyandshadows.lightbulb.dialogs.R
import com.github.rooneyandshadows.lightbulb.dialogs.base.BasePickerDialogFragment
import com.github.rooneyandshadows.lightbulb.dialogs.base.constraints.regular.RegularDialogConstraints
import com.github.rooneyandshadows.lightbulb.dialogs.base.constraints.regular.RegularDialogConstraintsBuilder
import com.github.rooneyandshadows.lightbulb.dialogs.base.internal.DialogTypes
import com.prolificinteractive.materialcalendarview.CalendarDay
import com.prolificinteractive.materialcalendarview.MaterialCalendarView
import java.time.OffsetDateTime
import java.time.ZoneOffset
import java.util.*
@Suppress("UNUSED_PARAMETER")
class DateTimePickerDialog : BasePickerDialogFragment<OffsetDateTime>(DateTimeSelection(null, null)) {
private var showingTimePicker = false
private var calendarView: MaterialCalendarView? = null
private var timePickerView: TimePicker? = null
private var selectionTextValue: AppCompatTextView? = null
private var modeChangeButton: AppCompatImageButton? = null
private var zoneOffset = DEFAULT_OFFSET
var dialogDateFormat = DEFAULT_DATE_FORMAT
private set
override var dialogType: DialogTypes
get() = DialogTypes.NORMAL
set(value) {}
companion object {
private val DEFAULT_OFFSET = ZoneOffset.of(DateUtilsOffsetDate.getLocalTimeZone())
private const val DEFAULT_DATE_FORMAT = "dd MMM HH:mm, yyyy"
private const val SHOWING_TIME_PICKER_TAG = "SHOWING_TIME_PICKER_TAG"
private const val DATE_FORMAT_TAG = "DATE_FORMAT_TEXT"
private const val DATE_OFFSET_TAG = "DATE_OFFSET_TAG"
fun newInstance(): DateTimePickerDialog {
return DateTimePickerDialog()
}
}
@Override
override fun getRegularConstraints(): RegularDialogConstraints {
return RegularDialogConstraintsBuilder(this)
.default()
.withMaxHeightInPercents(90)
.build()
}
@Override
override fun doOnSaveDialogProperties(outState: Bundle) {
super.doOnSaveDialogProperties(outState)
outState.apply {
putString(DATE_OFFSET_TAG, zoneOffset.toString())
putBoolean(SHOWING_TIME_PICKER_TAG, showingTimePicker)
putString(DATE_FORMAT_TAG, dialogDateFormat)
}
}
@Override
override fun doOnRestoreDialogProperties(savedState: Bundle) {
super.doOnRestoreDialogProperties(savedState)
savedState.apply {
showingTimePicker = getBoolean(SHOWING_TIME_PICKER_TAG)
dialogDateFormat = getString(DATE_FORMAT_TAG, dialogDateFormat)
zoneOffset = ZoneOffset.of(getString(DATE_OFFSET_TAG))
}
}
@Override
override fun getDialogLayout(layoutInflater: LayoutInflater): View {
val orientation = resources.configuration.orientation
return if (orientation == Configuration.ORIENTATION_PORTRAIT)
layoutInflater.inflate(R.layout.dialog_picker_datetime_vertical, null)
else layoutInflater.inflate(R.layout.dialog_picker_datetime_horizontal, null)
}
@Override
override fun setupDialogContent(view: View, savedInstanceState: Bundle?) {
val activeSelection = dialogSelection.getActiveSelection()
selectViews(view)
setupHeader(activeSelection)
val context = requireContext()
modeChangeButton?.apply {
background = ResourceUtils.getDrawable(context, R.drawable.dialogs_bg_round_corners_transparent_ripple)
setOnClickListener {
showingTimePicker = !showingTimePicker
syncPickerMode()
}
}
calendarView?.apply {
leftArrow.setTint(ResourceUtils.getColorByAttribute(context, R.attr.colorAccent))
rightArrow.setTint(ResourceUtils.getColorByAttribute(context, R.attr.colorAccent))
if (activeSelection == null) clearSelection()
else {
val selectedDate = dateToCalendarDay(activeSelection)
setDateSelected(selectedDate, true)
setCurrentDate(selectedDate, false)
}
}
activeSelection?.apply selectedDate@{
timePickerView?.apply {
hour = DateUtilsOffsetDate.getHourOfDay(this@selectedDate)
minute = DateUtilsOffsetDate.getMinuteOfHour(this@selectedDate)
}
}
syncPickerMode()
}
private fun checkIfCalendarNeedsSync(currentValue: OffsetDateTime?): Boolean {
val calendarValue = calendarView!!.selectedDate?.let {
calendarDayToDate(it, currentValue ?: DateUtilsOffsetDate.nowLocal())
}
if (currentValue == null && calendarValue == null) return false
if (currentValue == null || calendarValue == null) return true
return !DateUtilsOffsetDate.isDateEqual(currentValue, calendarValue)
}
@Override
override fun onSelectionChange(newSelection: OffsetDateTime?) {
setupHeader(newSelection)
if (!checkIfCalendarNeedsSync(newSelection)) return
calendarView?.apply {
if (newSelection == null) clearSelection()
else {
val selectedDate = dateToCalendarDay(newSelection)
setDateSelected(selectedDate, true)
setCurrentDate(selectedDate, false)
}
}
timePickerView?.apply {
if (newSelection == null) return@apply
hour = DateUtilsOffsetDate.getHourOfDay(newSelection)
minute = DateUtilsOffsetDate.getMinuteOfHour(newSelection)
}
}
@Override
override fun doOnViewStateRestored(savedInstanceState: Bundle?) {
super.doOnViewStateRestored(savedInstanceState)
calendarView!!.setOnDateChangedListener { _: MaterialCalendarView?, date: CalendarDay, _: Boolean ->
if (isDialogShown) {
val draftDate = dialogSelection.getDraftSelection()
val hour: Int
val minute: Int
val second = 0
if (draftDate != null) {
hour = DateUtilsOffsetDate.getHourOfDay(draftDate)
minute = DateUtilsOffsetDate.getMinuteOfHour(draftDate)
} else {
val now = DateUtilsOffsetDate.nowLocal()
hour = DateUtilsOffsetDate.getHourOfDay(now)
minute = DateUtilsOffsetDate.getMinuteOfHour(now)
}
dialogSelection.setDraftSelection(
DateUtilsOffsetDate.date(date.year, date.month, date.day, hour, minute, second, zoneOffset)
)
} else {
val currentDate = dialogSelection.getCurrentSelection()
val hour: Int
val minute: Int
val second = 0
if (currentDate != null) {
hour = DateUtilsOffsetDate.getHourOfDay(currentDate)
minute = DateUtilsOffsetDate.getMinuteOfHour(currentDate)
} else {
val now = DateUtilsOffsetDate.nowLocal()
hour = DateUtilsOffsetDate.getHourOfDay(now)
minute = DateUtilsOffsetDate.getMinuteOfHour(now)
}
dialogSelection.setCurrentSelection(
DateUtilsOffsetDate.date(date.year, date.month, date.day, hour, minute, second, zoneOffset)
)
}
}
timePickerView!!.setOnTimeChangedListener { _: TimePicker?, hourOfDay: Int, minute: Int ->
val date = DateUtilsOffsetDate.setTimeToDate(dialogSelection.getDraftSelection(), hourOfDay, minute, 0)
if (isDialogShown) dialogSelection.setDraftSelection(date) else dialogSelection.setCurrentSelection(date)
}
}
@Override
override fun setSelection(newSelection: OffsetDateTime?) {
super.setSelection(newSelection)
zoneOffset = newSelection?.offset ?: DEFAULT_OFFSET
}
fun setDialogDateFormat(dateFormat: String?) {
val activeSelection = dialogSelection.getActiveSelection()
dialogDateFormat = dateFormat ?: DEFAULT_DATE_FORMAT
setupHeader(activeSelection)
}
private fun selectViews(view: View) {
selectionTextValue = view.findViewById(R.id.dateSelectionValue)
timePickerView = view.findViewById(R.id.timePickerView)
modeChangeButton = view.findViewById(R.id.datePickerModeChangeButton)
calendarView = view.findViewById(R.id.dateCalendarView)
}
private fun setupHeader(selection: OffsetDateTime?) {
modeChangeButton?.apply {
visibility = if (selection == null) View.GONE else View.VISIBLE
}
selectionTextValue?.apply {
val dateString = DateUtilsOffsetDate.getDateString(dialogDateFormat, selection, Locale.getDefault())
val default = ResourceUtils.getPhrase(requireContext(), R.string.dialog_month_picker_empty_text)
text = if (dateString.isNullOrBlank()) default else dateString
}
}
private fun dateToCalendarDay(date: OffsetDateTime?): CalendarDay? {
if (date == null) return null
val year = DateUtilsOffsetDate.extractYearFromDate(date)
val month = DateUtilsOffsetDate.extractMonthOfYearFromDate(date)
val day = DateUtilsOffsetDate.extractDayOfMonthFromDate(date)
return CalendarDay.from(year, month, day)
}
private fun calendarDayToDate(
calendarDay: CalendarDay?,
currentSelection: OffsetDateTime,
): OffsetDateTime? {
if (calendarDay == null) return null
val hour = currentSelection.hour
val minute = currentSelection.minute
return DateUtilsOffsetDate.date(calendarDay.year, calendarDay.month, calendarDay.day, hour, minute, 0)
}
private fun syncPickerMode() {
val activeSelection = dialogSelection.getActiveSelection()
if (showingTimePicker && activeSelection == null) showingTimePicker = false
val modeIconRes = if (showingTimePicker) R.drawable.dialogs_ic_calendar else R.drawable.dialogs_ic_time
val modeIcon = ResourceUtils.getDrawable(modeChangeButton!!.context, modeIconRes).apply {
this!!.setTint(ResourceUtils.getColorByAttribute(modeChangeButton!!.context, R.attr.colorOnPrimary))
}
modeChangeButton!!.setImageDrawable(modeIcon)
if (showingTimePicker) {
timePickerView!!.visibility = View.VISIBLE
calendarView!!.visibility = View.GONE
} else {
timePickerView!!.visibility = View.GONE
calendarView!!.visibility = View.VISIBLE
}
measureDialogLayout()
}
}
| 1
|
Kotlin
|
1
| 2
|
9300a8921365dd92905ae172a7180ef0cb8f958a
| 11,269
|
lightbulb-dialogs
|
Apache License 2.0
|
wishlist/src/main/java/com/karzek/wishlist/di/wishlistModule.kt
|
MarjanaKarzek
| 839,724,284
| false
|
{"Kotlin": 26622}
|
package com.karzek.wishlist.di
import androidx.datastore.core.DataStore
import com.karzek.domain.wishlist.WishlistRepository
import com.karzek.wishlist.data.WishlistData
import com.karzek.wishlist.data.WishlistRepositoryImpl
import com.karzek.wishlist.data.wishlistDataStore
import org.koin.android.ext.koin.androidContext
import org.koin.dsl.module
val wishlistDataModule = module {
single<WishlistRepository> {
WishlistRepositoryImpl(
storage = get(),
dispatcher = get(),
errorEntityFactory = get(),
)
}
single<DataStore<WishlistData>> { androidContext().wishlistDataStore }
}
| 0
|
Kotlin
|
0
| 0
|
212b25b9fdbc771d0e9bc37425d98c764e8229cd
| 615
|
android-venue-recommendations
|
Apache License 2.0
|
core/src/androidMain/kotlin/xyz/mcxross/zero/oauth/browser/BrowserSelector.kt
|
mcxross
| 703,434,925
| false
|
{"Kotlin": 237524}
|
/*
* Copyright 2016 McXross. 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 xyz.mcxross.zero.oauth.browser
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.content.pm.ResolveInfo
import android.net.Uri
import android.os.Build
import androidx.browser.customtabs.CustomTabsService
import xyz.mcxross.zero.oauth.DefaultAuthorizationService
/**
* Utility class to obtain the browser package name to be used for
* [DefaultAuthorizationService.performAuthorizationRequest] calls. It prioritizes browsers which
* support [custom tabs](https://developer.chrome.com/multidevice/android/customtabs). To mitigate
* man-in-the-middle attacks by malicious apps pretending to be browsers for the specific URI we
* query, only those which are registered as a handler for _all_ HTTP and HTTPS URIs will be used.
*/
actual object BrowserSelector {
private const val SCHEME_HTTP = "http"
private const val SCHEME_HTTPS = "https"
/** The service we expect to find on a web browser that indicates it supports custom tabs. */
val ACTION_CUSTOM_TABS_CONNECTION: String = CustomTabsService.ACTION_CUSTOM_TABS_CONNECTION
/**
* Intent for querying installed web browsers as seen at
* https://cs.android.com/android/platform/superproject/+/master:packages/modules/Permission/PermissionController/src/com/android/permissioncontroller/role/model/BrowserRoleBehavior.java
*/
val BROWSER_INTENT: Intent =
Intent()
.setAction(Intent.ACTION_VIEW)
.addCategory(Intent.CATEGORY_BROWSABLE)
.setData(Uri.fromParts("http", "", null))
/**
* Retrieves the full list of browsers installed on the device. Two entries will exist for each
* browser that supports custom tabs, with the [BrowserDescriptor.useCustomTab] flag set to `true`
* in one and `false` in the other. The list is in the order returned by the package manager, so
* indirectly reflects the user's preferences (i.e. their default browser, if set, should be the
* first entry in the list).
*/
@SuppressLint("PackageManagerGetSignatures")
fun getAllBrowsers(context: Context): List<BrowserDescriptor> {
val pm: PackageManager = context.packageManager
val browsers: MutableList<BrowserDescriptor> = ArrayList()
var defaultBrowserPackage: String? = null
var queryFlag: Int = PackageManager.GET_RESOLVED_FILTER
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
queryFlag = queryFlag or PackageManager.MATCH_ALL
}
// When requesting all matching activities for an intent from the package manager,
// the user's preferred browser is not guaranteed to be at the head of this list.
// Therefore, the preferred browser must be separately determined and the resultant
// list of browsers reordered to restore this desired property.
val resolvedDefaultActivity: ResolveInfo? = pm.resolveActivity(BROWSER_INTENT, 0)
if (resolvedDefaultActivity != null) {
defaultBrowserPackage = resolvedDefaultActivity.activityInfo.packageName
}
val resolvedActivityList: List<ResolveInfo> =
pm.queryIntentActivities(BROWSER_INTENT, queryFlag)
for (info in resolvedActivityList) {
// ignore handlers which are not browsers
if (!isFullBrowser(info)) {
continue
}
try {
var defaultBrowserIndex = 0
val packageInfo: PackageInfo =
pm.getPackageInfo(info.activityInfo.packageName, PackageManager.GET_SIGNATURES)
if (hasWarmupService(pm, info.activityInfo.packageName)) {
val customTabBrowserDescriptor = BrowserDescriptor(packageInfo, true)
if (info.activityInfo.packageName == defaultBrowserPackage) {
// If the default browser is having a WarmupService,
// will it be added to the beginning of the list.
browsers.add(defaultBrowserIndex, customTabBrowserDescriptor)
defaultBrowserIndex++
} else {
browsers.add(customTabBrowserDescriptor)
}
}
val fullBrowserDescriptor = BrowserDescriptor(packageInfo, false)
if (info.activityInfo.packageName == defaultBrowserPackage) {
// The default browser is added to the beginning of the list.
// If there is support for Custom Tabs, will the one disabling Custom Tabs
// be added as the second entry.
browsers.add(defaultBrowserIndex, fullBrowserDescriptor)
} else {
browsers.add(fullBrowserDescriptor)
}
} catch (e: PackageManager.NameNotFoundException) {
// a descriptor cannot be generated without the package info
}
}
return browsers
}
actual fun select(
browserMatcher: BrowserMatcher,
browsers: List<BrowserDescriptor>
): BrowserDescriptor? {
var bestMatch: BrowserDescriptor? = null
for (browser in browsers) {
if (!browserMatcher.matches(browser)) {
continue
}
if (browser.useCustomTab) {
// directly return the first custom tab supporting browser that is matched
return browser
}
if (bestMatch == null) {
// store this as the best match for use if we don't find any matching
// custom tab supporting browsers
bestMatch = browser
}
}
return bestMatch
}
/**
* Searches through all browsers for the best match based on the supplied browser matcher. Custom
* tab supporting browsers are preferred, if the matcher permits them, and browsers are evaluated
* in the order returned by the package manager, which should indirectly match the user's
* preferences.
*
* @param context [Context] to use for accessing [PackageManager].
* @return The package name recommended to use for connecting to custom tabs related components.
*/
@SuppressLint("PackageManagerGetSignatures")
fun select(context: Context, browserMatcher: BrowserMatcher): BrowserDescriptor? {
val allBrowsers = getAllBrowsers(context)
return select(browserMatcher, allBrowsers)
}
private fun hasWarmupService(pm: PackageManager, packageName: String): Boolean {
val serviceIntent = Intent()
serviceIntent.setAction(ACTION_CUSTOM_TABS_CONNECTION)
serviceIntent.setPackage(packageName)
return pm.resolveService(serviceIntent, 0) != null
}
private fun isFullBrowser(resolveInfo: ResolveInfo): Boolean {
// The filter must match ACTION_VIEW, CATEGORY_BROWSEABLE, and at least one scheme,
if (
resolveInfo.filter == null ||
!resolveInfo.filter.hasAction(Intent.ACTION_VIEW) ||
!resolveInfo.filter.hasCategory(Intent.CATEGORY_BROWSABLE) ||
resolveInfo.filter.schemesIterator() == null
) {
return false
}
// The filter must not be restricted to any particular set of authorities
if (resolveInfo.filter.authoritiesIterator() != null) {
return false
}
// The filter must support both HTTP and HTTPS.
var supportsHttp = false
var supportsHttps = false
val schemeIter: Iterator<String> = resolveInfo.filter.schemesIterator()
while (schemeIter.hasNext()) {
val scheme = schemeIter.next()
supportsHttp = supportsHttp or (SCHEME_HTTP == scheme)
supportsHttps = supportsHttps or (SCHEME_HTTPS == scheme)
if (supportsHttp && supportsHttps) {
return true
}
}
// at least one of HTTP or HTTPS is not supported
return false
}
}
| 0
|
Kotlin
|
0
| 6
|
70c511acad1fc9461b4ed9bf6caa73c7a8243cd9
| 8,056
|
zeroauth
|
Apache License 2.0
|
src/main/kotlin/day12.kt
|
p88h
| 317,362,882
| false
| null |
internal fun rotate(vec: Point, deg: Int): Point {
when (deg) {
90 -> return Point(-vec.y , vec.x)
180 -> return Point(-vec.x, -vec.y)
270 -> return Point(vec.y, -vec.x)
}
throw IllegalArgumentException()
}
internal fun move(vec: Point, dir: Point, num: Int): Point {
return Point(vec.x + dir.x * num, vec.y + dir.y * num)
}
internal data class Ship(var pos: Point, var dir: Point)
internal data class Instr(val op: Char, val num: Int);
fun main(args: Array<String>) {
val insns = allLines(args, "day12.in").map { Instr(it.get(0), it.substring(1).toInt()) }.toList()
var ship = Ship(Point(0, 0), Point(1, 0))
val dirs = mapOf('N' to Point(0, -1), 'S' to Point(0, 1), 'E' to Point(1, -0), 'W' to Point(-1, 0))
insns.forEach { when (it.op) {
'F' -> ship.pos = move(ship.pos, ship.dir, it.num)
'L', 'R' -> ship.dir = rotate(ship.dir, if (it.op == 'R') it.num else 360 - it.num)
'N', 'S', 'E', 'W' -> ship.pos = move(ship.pos, dirs[it.op]!!, it.num)
} }
println(Math.abs(ship.pos.x) + Math.abs(ship.pos.y))
// part 2
ship = Ship(Point(0, 0), Point(10, -1))
insns.forEach { when (it.op) {
'F' -> ship.pos = move(ship.pos, ship.dir, it.num)
'L', 'R' -> ship.dir = rotate(ship.dir, if (it.op == 'R') it.num else 360 - it.num)
'N', 'S', 'E', 'W' -> ship.dir = move(ship.dir, dirs[it.op]!!, it.num)
} }
println(Math.abs(ship.pos.x) + Math.abs(ship.pos.y))
}
| 0
|
Kotlin
|
0
| 5
|
846ad4a978823563b2910c743056d44552a4b172
| 1,483
|
aoc2020
|
The Unlicense
|
app/src/main/java/fr/skyle/scanny/enums/BarcodeFormat.kt
|
SkyleKayma
| 524,119,671
| false
|
{"Kotlin": 227075}
|
package fr.skyle.scanny.enums
enum class BarcodeFormat {
CODE_128,
CODE_39,
CODE_93,
BARCODE,
DATA_MATRIX,
EAN_13,
EAN_8,
ITF,
QR_CODE,
UPC_A,
UPC_E,
PDF417,
AZTEC;
companion object
}
| 0
|
Kotlin
|
0
| 0
|
00e0b86741a292e56529f34abdd0c6657c427f6e
| 241
|
Scanny
|
Apache License 2.0
|
app/src/main/java/com/touhidapps/modernApi/networkService/AllApi.kt
|
TouhidApps
| 371,456,422
| false
| null |
package com.touhidapps.modernApi.networkService
import com.touhidapps.modernApi.utils.toBase64Decode
object AllApi {
private external fun baseUrlFromJNI(): String
val BASE_URL = baseUrlFromJNI().toBase64Decode()
// api/demo/jsondemoapi.php?option=3
private const val V1 = "api/demo/"
const val WELCOME_MESSAGE = V1 + "jsondemoapi.php"
// https://touhidapps.com/api/demo/jsondemoapi.php?option=3
}
| 0
|
Kotlin
|
5
| 6
|
f50febe89d65dd503450493449aa3ad45fe5a9fb
| 424
|
Android-Modern-API-Call-Kotlin-MVVM
|
Apache License 2.0
|
app/src/main/java/com/touhidapps/modernApi/networkService/AllApi.kt
|
TouhidApps
| 371,456,422
| false
| null |
package com.touhidapps.modernApi.networkService
import com.touhidapps.modernApi.utils.toBase64Decode
object AllApi {
private external fun baseUrlFromJNI(): String
val BASE_URL = baseUrlFromJNI().toBase64Decode()
// api/demo/jsondemoapi.php?option=3
private const val V1 = "api/demo/"
const val WELCOME_MESSAGE = V1 + "jsondemoapi.php"
// https://touhidapps.com/api/demo/jsondemoapi.php?option=3
}
| 0
|
Kotlin
|
5
| 6
|
f50febe89d65dd503450493449aa3ad45fe5a9fb
| 424
|
Android-Modern-API-Call-Kotlin-MVVM
|
Apache License 2.0
|
app/src/main/java/me/rampoo/musicstream/data/retrofit/RetrofitClient.kt
|
Rampo0
| 246,787,148
| false
| null |
package me.rampoo.musicstream.data.retrofit
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object RetrofitClient {
private const val BASE_URL = "http://192.168.18.13:8000"
val instance : IApi by lazy {
val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
retrofit.create(IApi::class.java)
}
}
| 0
|
Kotlin
|
0
| 1
|
c88c947fb89b4926bd6a6711bbcff550e86ce24f
| 454
|
MVP-MusicStream
|
MIT License
|
android/app/src/main/kotlin/edu/hm/cs/tape/bbb_app/MainActivity.kt
|
bennyboer
| 306,332,971
| false
| null |
package edu.hm.cs.tape.bbb_app
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 28
|
Dart
|
46
| 83
|
19a2d45d3f5d03fa36c8092475e07da37b320a7d
| 127
|
bbb_app
|
MIT License
|
posts/src/main/java/com/sanogueralorenzo/posts/presentation/postlist/PostListAdapter.kt
|
Selidinok
| 150,962,368
| true
|
{"Kotlin": 69296}
|
package com.sanogueralorenzo.posts.presentation.postlist
import android.support.v7.widget.RecyclerView
import android.view.ViewGroup
import com.sanogueralorenzo.posts.R
import com.sanogueralorenzo.posts.presentation.loadAvatar
import com.sanogueralorenzo.posts.presentation.model.PostItem
import com.sanogueralorenzo.presentation.inflate
import kotlinx.android.synthetic.main.include_user_info.view.*
import kotlinx.android.synthetic.main.item_list_post.view.*
import java.util.ArrayList
class PostListAdapter constructor(private val itemClick: (PostItem) -> Unit) :
RecyclerView.Adapter<PostListAdapter.ViewHolder>() {
private val items = ArrayList<PostItem>()
override fun getItemCount(): Int = items.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder =
ViewHolder(parent)
override fun onBindViewHolder(holder: ViewHolder, position: Int) = holder.bind(items[position])
inner class ViewHolder(parent: ViewGroup) :
RecyclerView.ViewHolder(parent.inflate(R.layout.item_list_post)) {
fun bind(item: PostItem) {
itemView.userAvatar.loadAvatar(item.email)
itemView.userUsername.text = "@${item.username}"
itemView.userName.text = item.name
itemView.postTitle.text = item.title.capitalize()
itemView.postBody.text = item.body.capitalize()
itemView.setOnClickListener { itemClick.invoke(item) }
}
}
fun addItems(list: List<PostItem>) {
this.items.clear()
this.items.addAll(list)
notifyDataSetChanged()
}
}
| 0
|
Kotlin
|
0
| 0
|
f155f864e2b8b68687501e0ab6f0a51963531484
| 1,605
|
Android-Kotlin-Clean-Architecture
|
Apache License 2.0
|
LifeCanvas/app/src/main/java/com/example/lifecanvas/screen/note/NoteDetailScreen.kt
|
atakan-ozkan
| 738,927,867
| false
|
{"Kotlin": 148766}
|
package com.example.lifecanvas.screen.note
import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.MediaStore
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Create
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import com.example.lifecanvas.R
import com.example.lifecanvas.audio.AudioRecorder
import com.example.lifecanvas.helper.deleteBitmapFile
import com.example.lifecanvas.helper.loadImageBitmap
import com.example.lifecanvas.model.NoteModel
import com.example.lifecanvas.screen.filter.isValidTitle
import com.example.lifecanvas.viewModel.NoteViewModel
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.PermissionStatus
import com.google.accompanist.permissions.rememberMultiplePermissionsState
import com.google.accompanist.permissions.rememberPermissionState
import com.google.accompanist.permissions.shouldShowRationale
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File
import java.util.Date
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun NoteDetailScreen(noteViewModel: NoteViewModel, noteId: Int, navController: NavController,context: Context) {
val noteModel by noteViewModel.get(noteId).observeAsState()
var showEditNoteDialog by remember { mutableStateOf(false) }
if(noteModel == null){
Text(text = "Note Detail Not Found!")
return
}
noteModel?.let { note ->
Column(modifier = Modifier.fillMaxSize()) {
TopAppBar(
title = { Text("Note Detail") },
navigationIcon = {
IconButton(
onClick = {
navController.navigate("notesScreen")
}
) {
Icon(Icons.Filled.ArrowBack, contentDescription = "Back")
}
},
actions = {
IconButton(
onClick ={
showEditNoteDialog = true
}) {
Icon(Icons.Default.Create, contentDescription = "Edit Title")
}
IconButton(
onClick ={
if(note.type == "Image"){
note.filePath?.let { deleteBitmapFile(it) }
Toast.makeText(context, "Image note is deleted!", Toast.LENGTH_SHORT).show()
}
else if(note.type == "Voice"){
File(note.filePath).delete()
Toast.makeText(context, "Voice note is deleted!", Toast.LENGTH_SHORT).show()
}
else
{
Toast.makeText(context, "Text note is deleted!", Toast.LENGTH_SHORT).show()
}
noteViewModel.delete(note)
navController.navigate("notesScreen")
}) {
Icon(painter = painterResource(id = R.drawable.delete_icon), contentDescription = "Delete")
}
}
)
when (note.type) {
"Text" -> TextFieldNoteScreen(
noteContent = note.content,
onContentChange = { updatedContent ->
noteViewModel.update(note.copy(content = updatedContent))
}
)
"Voice" -> VoiceRecordNoteScreen(noteViewModel, note, navController)
"Image" -> ImageNoteScreen(noteViewModel, note)
else -> Text("Unknown note type, please go back!")
}
if (showEditNoteDialog) {
EditNoteDialog(
note = note,
noteViewModel =noteViewModel,
onDismiss = { showEditNoteDialog = false },
onNoteEdited = { editedNote ->
noteViewModel.update(editedNote)
showEditNoteDialog = false
Toast.makeText(context, "Note is modified!", Toast.LENGTH_SHORT).show()
}
)
}
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TextFieldNoteScreen(noteContent: String, onContentChange: (String) -> Unit) {
var text by remember { mutableStateOf(noteContent) }
Column(modifier = Modifier.imePadding()) {
OutlinedTextField(
value = text,
onValueChange = { updatedText ->
text = updatedText
onContentChange(updatedText)
},
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
.fillMaxSize(),
label = { Text("Note Content") }
)
}
}
@OptIn(ExperimentalPermissionsApi::class)
@Composable
fun VoiceRecordNoteScreen(noteViewModel: NoteViewModel, note: NoteModel, navController: NavController) {
val permissionsState = rememberMultiplePermissionsState(
permissions = listOf(
Manifest.permission.RECORD_AUDIO,
Manifest.permission.WRITE_EXTERNAL_STORAGE
)
)
val coroutineScope = rememberCoroutineScope()
when {
permissionsState.allPermissionsGranted -> {
VoiceRecorderUI(noteViewModel, note,navController)
}
permissionsState.shouldShowRationale || !permissionsState.allPermissionsGranted -> {
AlertDialog(
onDismissRequest = {},
title = { Text("Permission Required") },
text = { Text("This app needs access to your microphone and storage to record audio.") },
confirmButton = {
Button(onClick = {
coroutineScope.launch {
permissionsState.launchMultiplePermissionRequest()
}
}) {
Text("OK")
}
}
)
}
else -> {
Text("Permissions were not granted. You cannot record audio without permissions!")
}
}
}
@SuppressLint("CoroutineCreationDuringComposition")
@Composable
fun VoiceRecorderUI(noteViewModel: NoteViewModel, note: NoteModel, navController: NavController) {
val context = LocalContext.current
var isRecording by remember { mutableStateOf(false) }
var isPlaying by remember { mutableStateOf(false) }
var finishedRecord by remember {mutableStateOf(!note.filePath.isNullOrEmpty())}
var timerValue by remember { mutableIntStateOf(0) }
var playbackTimerValue by remember { mutableIntStateOf(0) }
val audioRecorder = remember { AudioRecorder(context, "NOTES_${note.id}.amr").apply {
setOnPlaybackCompleteListener {
isPlaying = false
}
} }
val coroutineScope = rememberCoroutineScope()
LaunchedEffect(key1 = isRecording) {
if (isRecording) {
timerValue = 0
while (isRecording) {
delay(1000)
timerValue++
}
}
}
LaunchedEffect(key1 = isPlaying) {
if (isPlaying) {
playbackTimerValue = 0
while (isPlaying) {
delay(1000)
playbackTimerValue++
}
}
}
DisposableEffect(key1 = navController) {
onDispose {
if (isPlaying) {
audioRecorder.stopPlaying()
isPlaying = false
}
}
}
Column(modifier = Modifier.fillMaxSize()) {
Row (
horizontalArrangement = Arrangement.SpaceEvenly,
modifier = Modifier.fillMaxWidth()
) {
Text(
text = if (isRecording) "${timerValue}s" else "${playbackTimerValue}s",
style = MaterialTheme.typography.headlineLarge
)
}
Spacer(modifier = Modifier.padding(16.dp))
Row (
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth()
){
Button(
onClick = {
if (isRecording) {
audioRecorder.stopRecording(noteViewModel, note)
isRecording = false
finishedRecord = true
} else {
audioRecorder.startRecording()
isRecording = true
}
}
,
enabled = !isPlaying && !finishedRecord
) {
Text(if (isRecording) "Stop" else "Start")
}
Button(
onClick = {
isPlaying = if (isPlaying) {
audioRecorder.stopPlaying()
false
} else {
audioRecorder.playRecording()
true
}
}
, enabled = !isRecording && finishedRecord
) {
Text(if (isPlaying) "Stop Playing" else "Play")
}
Button(
onClick = {
audioRecorder.deleteRecording()
isRecording = false
isPlaying = false
finishedRecord = false
timerValue = 0
val updatedNote = note.copy(filePath = null)
coroutineScope.launch {
noteViewModel.update(updatedNote)
}
}
, enabled = finishedRecord
) {
Text("Delete")
}
}
}
}
@Composable
fun ImageNoteScreen(noteViewModel: NoteViewModel, note: NoteModel) {
var imageBitmap by remember { mutableStateOf(loadImageBitmap(note.filePath)) }
val context = LocalContext.current
val selectImageLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.StartActivityForResult()
) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val imageUri: Uri? = result.data?.data
val imagePath = imageUri?.let { uriToFilePath(it, context) }
imagePath?.let {
noteViewModel.update(note.copy(filePath = it))
imageBitmap = loadImageBitmap(it)
}
}
}
Column(modifier = Modifier.fillMaxSize()) {
imageBitmap?.let { bitmap ->
Image(
bitmap = bitmap.asImageBitmap(),
contentDescription = "Note Image",
modifier = Modifier.fillMaxWidth()
)
}
if(imageBitmap == null){
ImageUploadSection(
onImageSelected = {
selectImageLauncher.launch(Intent(Intent.ACTION_PICK).apply { type = "image/*" })
}
)
}
Button(onClick = {
noteViewModel.update(note.copy(filePath = null))
imageBitmap = null
}) {
Text("Delete Image")
}
}
}
@OptIn(ExperimentalPermissionsApi::class)
@Composable
fun ImageUploadSection(onImageSelected: () -> Unit) {
val permissionsState = rememberPermissionState(Manifest.permission.READ_EXTERNAL_STORAGE)
val placeholder = painterResource(id = R.drawable.upload_icon)
val imageModifier = Modifier
.fillMaxWidth()
.height(200.dp)
.border(border = BorderStroke(1.dp, Color.Gray), shape = RoundedCornerShape(4.dp))
.clickable {
when (permissionsState.status) {
PermissionStatus.Granted -> {
onImageSelected()
}
else -> {
permissionsState.launchPermissionRequest()
}
}
}
Box(modifier = imageModifier, contentAlignment = Alignment.Center) {
Icon(painter = placeholder, contentDescription = "Upload Placeholder")
}
if (permissionsState.status.shouldShowRationale) {
AlertDialog(
onDismissRequest = {},
title = { Text("Permission Required") },
text = { Text("This action requires permission to access your device's storage. Please grant permission to continue.") },
confirmButton = {
Button(onClick = {
permissionsState.launchPermissionRequest()
}) {
Text("OK")
}
}
)
}
}
fun uriToFilePath(uri: Uri, context: Context): String? {
val cursor = context.contentResolver.query(uri, null, null, null, null)
cursor?.use {
if (it.moveToFirst()) {
val index = it.getColumnIndex(MediaStore.Images.Media.DATA)
return it.getString(index)
}
}
return null
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun EditNoteDialog(
note: NoteModel,
noteViewModel: NoteViewModel,
onDismiss: () -> Unit,
onNoteEdited: (NoteModel) -> Unit
) {
var title by remember { mutableStateOf(note.title) }
var isPublic by remember { mutableStateOf(note.isPublic) }
val currentDateTime = remember { Date() }
val isTitleValid = remember(title) { isValidTitle(title) }
val isTitleUsedLiveData = noteViewModel.isTitleUsed(title,note.id)
val isTitleUsed by isTitleUsedLiveData.observeAsState(initial = false)
val isEditButtonEnabled = isTitleValid && !isTitleUsed ||
(isTitleValid && isTitleUsed && title == note.title)
AlertDialog(
onDismissRequest = { onDismiss() },
title = { Text("Edit Note") },
text = {
Column {
OutlinedTextField(
value = title,
onValueChange = { title = it },
label = { Text("Title") },
isError = (!isTitleValid && title.isNotEmpty()) || (isTitleUsed && title != note.title)
)
if (!isTitleValid && title.isNotEmpty()) {
Text("Title must be at least 3 characters and start with a letter.", color = MaterialTheme.colorScheme.secondary)
} else if (isTitleUsed && title != note.title) {
Text("Title name is already used!", color = MaterialTheme.colorScheme.secondary)
}
if(isPublic){
Text("Current note visibility is public.", color = MaterialTheme.colorScheme.primary)
}
else{
Text("Current note visibility is private.", color = MaterialTheme.colorScheme.primary)
}
Row(verticalAlignment = Alignment.CenterVertically) {
Switch(
checked = isPublic,
onCheckedChange = { isPublic = it }
)
Text("Change visibility ")
}
}
},
confirmButton = {
Button(
onClick = {
onNoteEdited(
note.copy(
type = note.type,
title = title,
content = note.content,
isPublic = isPublic,
filePath = note.filePath,
createdDate = note.createdDate,
modifiedDate = currentDateTime
)
)
onDismiss()
},
enabled = isEditButtonEnabled
) {
Text("Save")
}
},
dismissButton = {
TextButton(onClick = { onDismiss() }) {
Text("Cancel")
}
}
)
}
| 0
|
Kotlin
|
0
| 0
|
b8f892c6857e5c15b1ed1d45c952d6694c9e0fbe
| 18,619
|
comp319a-2023f-final
|
MIT License
|
app/src/main/java/hu/mostoha/mobile/android/huki/model/domain/GpxWaypoint.kt
|
RolandMostoha
| 386,949,428
| false
| null |
package hu.mostoha.mobile.android.huki.model.domain
import io.ticofab.androidgpxparser.parser.domain.WayPoint
data class GpxWaypoint(
val location: Location,
val name: String? = null,
)
fun Location.toGpxWaypoint(): GpxWaypoint {
return GpxWaypoint(
name = null,
location = this,
)
}
fun List<Location>.toGpxWaypointsByLocations(): List<GpxWaypoint> {
return map { it.toGpxWaypoint() }
}
fun WayPoint.toGpxWaypoint(): GpxWaypoint {
return GpxWaypoint(
name = name,
location = Location(latitude, longitude, elevation),
)
}
fun List<WayPoint>.toGpxWaypoints(): List<GpxWaypoint> {
return map { it.toGpxWaypoint() }
}
| 0
|
Kotlin
|
1
| 5
|
45fc91f5c6d7c423397e706d6385d61874e21487
| 685
|
HuKi-Android
|
The Unlicense
|
app/src/main/java/hu/mostoha/mobile/android/huki/model/domain/GpxWaypoint.kt
|
RolandMostoha
| 386,949,428
| false
| null |
package hu.mostoha.mobile.android.huki.model.domain
import io.ticofab.androidgpxparser.parser.domain.WayPoint
data class GpxWaypoint(
val location: Location,
val name: String? = null,
)
fun Location.toGpxWaypoint(): GpxWaypoint {
return GpxWaypoint(
name = null,
location = this,
)
}
fun List<Location>.toGpxWaypointsByLocations(): List<GpxWaypoint> {
return map { it.toGpxWaypoint() }
}
fun WayPoint.toGpxWaypoint(): GpxWaypoint {
return GpxWaypoint(
name = name,
location = Location(latitude, longitude, elevation),
)
}
fun List<WayPoint>.toGpxWaypoints(): List<GpxWaypoint> {
return map { it.toGpxWaypoint() }
}
| 0
|
Kotlin
|
1
| 5
|
45fc91f5c6d7c423397e706d6385d61874e21487
| 685
|
HuKi-Android
|
The Unlicense
|
compiler/testData/codegen/boxInline/anonymousObject/nestedTypeRemapping.kt
|
JetBrains
| 3,432,266
| false
|
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
|
// TARGET_BACKEND: JVM
// FILE: 1.kt
inline fun f(crossinline block: () -> String): () -> String =
{
object : () -> String {
override fun invoke() = block()
}
}.let {
it()
}
// FILE: 2.kt
fun box(): String = f { "OK" }()
| 181
|
Kotlin
|
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 271
|
kotlin
|
Apache License 2.0
|
compiler/testData/codegen/boxInline/anonymousObject/nestedTypeRemapping.kt
|
JetBrains
| 3,432,266
| false
|
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
|
// TARGET_BACKEND: JVM
// FILE: 1.kt
inline fun f(crossinline block: () -> String): () -> String =
{
object : () -> String {
override fun invoke() = block()
}
}.let {
it()
}
// FILE: 2.kt
fun box(): String = f { "OK" }()
| 181
|
Kotlin
|
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 271
|
kotlin
|
Apache License 2.0
|
app/src/main/java/com/breezefsmhmhcorporation/features/leaveapplynew/ClickonStatus.kt
|
DebashisINT
| 654,125,604
| false
| null |
package com.breezefsmhmhcorporation.features.leaveapplynew
import com.breezefsmhmhcorporation.features.addAttendence.model.Leave_list_Response
interface ClickonStatus {
fun OnApprovedclick(obj: Leave_list_Response)
fun OnRejectclick(obj: Leave_list_Response)
}
| 0
|
Kotlin
|
0
| 0
|
855a26194f21b9b24780e0c3d26914bc1725bb60
| 271
|
HMHCorporation
|
Apache License 2.0
|
src/main/kotlin/com/github/pemistahl/lingua/api/LanguageDetector.kt
|
pemistahl
| 157,676,060
| false
| null |
/*
* Copyright © 2018-today Peter M. Stahl pemistahl@gmail.com
*
* 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 expressed or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.pemistahl.lingua.api
import com.github.pemistahl.lingua.api.Language.CHINESE
import com.github.pemistahl.lingua.api.Language.JAPANESE
import com.github.pemistahl.lingua.api.Language.UNKNOWN
import com.github.pemistahl.lingua.internal.Alphabet
import com.github.pemistahl.lingua.internal.Constant.CHARS_TO_LANGUAGES_MAPPING
import com.github.pemistahl.lingua.internal.Constant.MULTIPLE_WHITESPACE
import com.github.pemistahl.lingua.internal.Constant.NO_LETTER
import com.github.pemistahl.lingua.internal.Constant.NUMBERS
import com.github.pemistahl.lingua.internal.Constant.PUNCTUATION
import com.github.pemistahl.lingua.internal.Constant.isJapaneseAlphabet
import com.github.pemistahl.lingua.internal.Ngram
import com.github.pemistahl.lingua.internal.TestDataLanguageModel
import com.github.pemistahl.lingua.internal.TrainingDataLanguageModel
import com.github.pemistahl.lingua.internal.util.extension.containsAnyOf
import com.github.pemistahl.lingua.internal.util.extension.incrementCounter
import com.github.pemistahl.lingua.internal.util.extension.isLogogram
import java.util.SortedMap
import java.util.TreeMap
import java.util.concurrent.Callable
import java.util.concurrent.ExecutorService
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit
import kotlin.math.ln
private val UNIGRAM_MODELS = mutableMapOf<Language, TrainingDataLanguageModel>()
private val BIGRAM_MODELS = mutableMapOf<Language, TrainingDataLanguageModel>()
private val TRIGRAM_MODELS = mutableMapOf<Language, TrainingDataLanguageModel>()
private val QUADRIGRAM_MODELS = mutableMapOf<Language, TrainingDataLanguageModel>()
private val FIVEGRAM_MODELS = mutableMapOf<Language, TrainingDataLanguageModel>()
/**
* Detects the language of given input text.
*/
class LanguageDetector internal constructor(
internal val languages: MutableSet<Language>,
internal val minimumRelativeDistance: Double,
isEveryLanguageModelPreloaded: Boolean,
internal val numberOfLoadedLanguages: Int = languages.size,
internal val unigramLanguageModels: MutableMap<Language, TrainingDataLanguageModel> = UNIGRAM_MODELS,
internal val bigramLanguageModels: MutableMap<Language, TrainingDataLanguageModel> = BIGRAM_MODELS,
internal val trigramLanguageModels: MutableMap<Language, TrainingDataLanguageModel> = TRIGRAM_MODELS,
internal val quadrigramLanguageModels: MutableMap<Language, TrainingDataLanguageModel> = QUADRIGRAM_MODELS,
internal val fivegramLanguageModels: MutableMap<Language, TrainingDataLanguageModel> = FIVEGRAM_MODELS
) {
internal val threadPool = createThreadPool()
private val languagesWithUniqueCharacters = languages.filterNot { it.uniqueCharacters.isNullOrBlank() }.asSequence()
private val oneLanguageAlphabets = Alphabet.allSupportingExactlyOneLanguage().filterValues {
it in languages
}
init {
if (isEveryLanguageModelPreloaded) {
preloadLanguageModels()
}
}
/**
* Detects the language of given input text.
*
* @param text The input text to detect the language for.
* @return The identified language or [Language.UNKNOWN].
* @throws IllegalStateException If [destroy] has been invoked before on this instance of [LanguageDetector].
*/
fun detectLanguageOf(text: String): Language {
val confidenceValues = computeLanguageConfidenceValues(text)
if (confidenceValues.isEmpty()) return UNKNOWN
val mostLikelyLanguage = confidenceValues.firstKey()
if (confidenceValues.size == 1) return mostLikelyLanguage
val mostLikelyLanguageProbability = confidenceValues.getValue(mostLikelyLanguage)
val secondMostLikelyLanguageProbability = confidenceValues.values.elementAt(1)
return when {
mostLikelyLanguageProbability == secondMostLikelyLanguageProbability -> UNKNOWN
(mostLikelyLanguageProbability - secondMostLikelyLanguageProbability) < minimumRelativeDistance -> UNKNOWN
else -> mostLikelyLanguage
}
}
/**
* Computes confidence values for every language considered possible for the given input text.
*
* The values that this method computes are part of a **relative** confidence metric, not of an absolute one.
* Each value is a number between 0.0 and 1.0. The most likely language is always returned with value 1.0.
* All other languages get values assigned which are lower than 1.0, denoting how less likely those languages
* are in comparison to the most likely language.
*
* The map returned by this method does not necessarily contain all languages which the calling instance of
* [LanguageDetector] was built from. If the rule-based engine decides that a specific language is truly impossible,
* then it will not be part of the returned map. Likewise, if no ngram probabilities can be found within the
* detector's languages for the given input text, the returned map will be empty. The confidence value for
* each language not being part of the returned map is assumed to be 0.0.
*
* @param text The input text to detect the language for.
* @return A map of all possible languages, sorted by their confidence value in descending order.
* @throws IllegalStateException If [destroy] has been invoked before on this instance of [LanguageDetector].
*/
fun computeLanguageConfidenceValues(text: String): SortedMap<Language, Double> {
if (threadPool.isShutdown) {
throw IllegalStateException(
"This LanguageDetector instance has been destroyed and cannot be reused"
)
}
val values = TreeMap<Language, Double>()
val cleanedUpText = cleanUpInputText(text)
if (cleanedUpText.isEmpty() || NO_LETTER.matches(cleanedUpText)) return values
val words = splitTextIntoWords(cleanedUpText)
val languageDetectedByRules = detectLanguageWithRules(words)
if (languageDetectedByRules != UNKNOWN) {
values[languageDetectedByRules] = 1.0
return values
}
val filteredLanguages = filterLanguagesByRules(words)
if (filteredLanguages.size == 1) {
val filteredLanguage = filteredLanguages.iterator().next()
values[filteredLanguage] = 1.0
return values
}
val ngramSizeRange = if (cleanedUpText.length >= 120) (3..3) else (1..5)
val tasks = ngramSizeRange.filter { i -> cleanedUpText.length >= i }.map { i ->
Callable {
val testDataModel = TestDataLanguageModel.fromText(cleanedUpText, ngramLength = i)
val probabilities = computeLanguageProbabilities(testDataModel, filteredLanguages)
val unigramCounts = if (i == 1) {
val languages = probabilities.keys
val unigramFilteredLanguages =
if (languages.isNotEmpty()) filteredLanguages.asSequence()
.filter { languages.contains(it) }
.toSet()
else filteredLanguages
countUnigramsOfInputText(testDataModel, unigramFilteredLanguages)
} else {
null
}
Pair(probabilities, unigramCounts)
}
}
val allProbabilitiesAndUnigramCounts = threadPool.invokeAll(tasks).map { it.get() }
val allProbabilities = allProbabilitiesAndUnigramCounts.map { (probabilities, _) -> probabilities }
val unigramCounts = allProbabilitiesAndUnigramCounts[0].second ?: emptyMap()
val summedUpProbabilities = sumUpProbabilities(allProbabilities, unigramCounts, filteredLanguages)
val highestProbability = summedUpProbabilities.maxByOrNull { it.value }?.value ?: return sortedMapOf()
val confidenceValues = summedUpProbabilities.mapValues { highestProbability / it.value }
val sortedByConfidenceValue = compareByDescending<Language> { language -> confidenceValues[language] }
val sortedByConfidenceValueThenByLanguage = sortedByConfidenceValue.thenBy { language -> language }
return confidenceValues.toSortedMap(sortedByConfidenceValueThenByLanguage)
}
/**
* Destroys this [LanguageDetector] instance and frees associated resources.
*
* This will be useful if the library is used within a web application inside
* an application server. By calling this method prior to undeploying the
* web application, the language models are removed and memory is freed.
* The internal thread pool used for parallel processing is shut down as well.
* This prevents exceptions such as [OutOfMemoryError] when the web application
* is redeployed multiple times.
*/
fun destroy() {
threadPool.shutdown()
if (!threadPool.awaitTermination(10, TimeUnit.SECONDS)) {
threadPool.shutdownNow()
}
for (language in languages) {
unigramLanguageModels.remove(language)
bigramLanguageModels.remove(language)
trigramLanguageModels.remove(language)
quadrigramLanguageModels.remove(language)
fivegramLanguageModels.remove(language)
}
}
internal fun cleanUpInputText(text: String): String {
return text.trim().lowercase()
.replace(PUNCTUATION, "")
.replace(NUMBERS, "")
.replace(MULTIPLE_WHITESPACE, " ")
}
internal fun splitTextIntoWords(text: String): List<String> {
val words = mutableListOf<String>()
var nextWordStart = 0
for (i in text.indices) {
val char = text[i]
if (char == ' ') {
if (nextWordStart != i) {
words.add(text.substring(nextWordStart, i))
}
nextWordStart = i + 1
} else if (char.isLogogram()) {
if (nextWordStart != i) {
words.add(text.substring(nextWordStart, i))
}
words.add(text[i].toString())
nextWordStart = i + 1
}
}
if (nextWordStart != text.length) {
words.add(text.substring(nextWordStart, text.length))
}
return words
}
internal fun countUnigramsOfInputText(
unigramLanguageModel: TestDataLanguageModel,
filteredLanguages: Set<Language>
): Map<Language, Int> {
val unigramCounts = mutableMapOf<Language, Int>()
for (language in filteredLanguages) {
for (unigram in unigramLanguageModel.ngrams) {
val probability = lookUpNgramProbability(language, unigram)
if (probability > 0) {
unigramCounts.incrementCounter(language)
}
}
}
return unigramCounts
}
internal fun sumUpProbabilities(
probabilities: List<Map<Language, Double>>,
unigramCountsOfInputText: Map<Language, Int>,
filteredLanguages: Set<Language>
): Map<Language, Double> {
val summedUpProbabilities = mutableMapOf<Language, Double>()
for (language in filteredLanguages) {
summedUpProbabilities[language] = probabilities.sumOf { it[language] ?: 0.0 }
if (unigramCountsOfInputText.containsKey(language)) {
summedUpProbabilities[language] = summedUpProbabilities.getValue(language) /
unigramCountsOfInputText.getValue(language)
}
}
return summedUpProbabilities.filter { it.value != 0.0 }
}
internal fun detectLanguageWithRules(words: List<String>): Language {
val totalLanguageCounts = mutableMapOf<Language, Int>()
for (word in words) {
val wordLanguageCounts = mutableMapOf<Language, Int>()
for (character in word) {
var isMatch = false
for ((alphabet, language) in oneLanguageAlphabets) {
if (alphabet.matches(character)) {
wordLanguageCounts.incrementCounter(language)
isMatch = true
break
}
}
if (!isMatch) {
when {
Alphabet.HAN.matches(character) -> wordLanguageCounts.incrementCounter(CHINESE)
isJapaneseAlphabet(character) -> wordLanguageCounts.incrementCounter(JAPANESE)
Alphabet.LATIN.matches(character) ||
Alphabet.CYRILLIC.matches(character) ||
Alphabet.DEVANAGARI.matches(character) ->
languagesWithUniqueCharacters.filter {
it.uniqueCharacters?.contains(character) ?: false
}.forEach {
wordLanguageCounts.incrementCounter(it)
}
}
}
}
if (wordLanguageCounts.isEmpty()) {
totalLanguageCounts.incrementCounter(UNKNOWN)
} else if (wordLanguageCounts.size == 1) {
val language = wordLanguageCounts.keys.first()
if (language in languages) {
totalLanguageCounts.incrementCounter(language)
} else {
totalLanguageCounts.incrementCounter(UNKNOWN)
}
} else {
val sortedWordLanguageCounts = wordLanguageCounts.toList().sortedByDescending { it.second }
val (mostFrequentLanguage, firstCharCount) = sortedWordLanguageCounts[0]
val (_, secondCharCount) = sortedWordLanguageCounts[1]
if (firstCharCount > secondCharCount && mostFrequentLanguage in languages) {
totalLanguageCounts.incrementCounter(mostFrequentLanguage)
} else {
totalLanguageCounts.incrementCounter(UNKNOWN)
}
}
}
val unknownLanguageCount = totalLanguageCounts[UNKNOWN] ?: 0
if (unknownLanguageCount < (0.5 * words.size)) {
totalLanguageCounts.remove(UNKNOWN)
}
if (totalLanguageCounts.isEmpty()) {
return UNKNOWN
}
if (totalLanguageCounts.size == 1) {
return totalLanguageCounts.keys.first()
}
if (totalLanguageCounts.size == 2 &&
totalLanguageCounts.containsKey(CHINESE) &&
totalLanguageCounts.containsKey(JAPANESE)
) {
return JAPANESE
}
val sortedTotalLanguageCounts = totalLanguageCounts.toList().sortedByDescending { it.second }
val (mostFrequentLanguage, firstCharCount) = sortedTotalLanguageCounts[0]
val (_, secondCharCount) = sortedTotalLanguageCounts[1]
return when {
firstCharCount == secondCharCount -> UNKNOWN
else -> mostFrequentLanguage
}
}
internal fun filterLanguagesByRules(words: List<String>): Set<Language> {
val detectedAlphabets = mutableMapOf<Alphabet, Int>()
for (word in words) {
for (alphabet in Alphabet.values()) {
if (alphabet.matches(word)) {
detectedAlphabets.incrementCounter(alphabet)
break
}
}
}
if (detectedAlphabets.isEmpty()) {
return languages
}
if (detectedAlphabets.size > 1) {
val distinctAlphabets = mutableSetOf<Int>()
for (count in detectedAlphabets.values) {
distinctAlphabets.add(count)
}
if (distinctAlphabets.size == 1) {
return languages
}
}
val mostFrequentAlphabet = detectedAlphabets.entries.maxByOrNull { it.value }!!.key
val filteredLanguages = languages.filter { it.alphabets.contains(mostFrequentAlphabet) }
val languageCounts = mutableMapOf<Language, Int>()
for (word in words) {
for ((characters, languages) in CHARS_TO_LANGUAGES_MAPPING) {
if (word.containsAnyOf(characters)) {
for (language in languages) {
languageCounts.incrementCounter(language)
}
break
}
}
}
val languagesSubset = languageCounts.filterValues { it >= words.size / 2.0 }.keys
return if (languagesSubset.isNotEmpty()) {
filteredLanguages.filter { it in languagesSubset }.toSet()
} else {
filteredLanguages.toSet()
}
}
internal fun computeLanguageProbabilities(
testDataModel: TestDataLanguageModel,
filteredLanguages: Set<Language>
): Map<Language, Double> {
val probabilities = mutableMapOf<Language, Double>()
for (language in filteredLanguages) {
probabilities[language] = computeSumOfNgramProbabilities(language, testDataModel.ngrams)
}
return probabilities.filter { it.value < 0.0 }
}
internal fun computeSumOfNgramProbabilities(
language: Language,
ngrams: Set<Ngram>
): Double {
var probabilitiesSum = 0.0
for (ngram in ngrams) {
for (elem in ngram.rangeOfLowerOrderNgrams()) {
val probability = lookUpNgramProbability(language, elem)
if (probability > 0) {
probabilitiesSum += ln(probability)
break
}
}
}
return probabilitiesSum
}
internal fun lookUpNgramProbability(
language: Language,
ngram: Ngram
): Double {
val ngramLength = ngram.value.length
val languageModels = when (ngramLength) {
5 -> fivegramLanguageModels
4 -> quadrigramLanguageModels
3 -> trigramLanguageModels
2 -> bigramLanguageModels
1 -> unigramLanguageModels
0 -> throw IllegalArgumentException("Zerogram detected")
else -> throw IllegalArgumentException("unsupported ngram length detected: ${ngram.value.length}")
}
val model = loadLanguageModels(languageModels, language, ngramLength)
return model.getRelativeFrequency(ngram)
}
private fun loadLanguageModels(
languageModels: MutableMap<Language, TrainingDataLanguageModel>,
language: Language,
ngramLength: Int
): TrainingDataLanguageModel {
if (languageModels.containsKey(language)) {
return languageModels.getValue(language)
}
val model = loadLanguageModel(language, ngramLength)
languageModels[language] = model
return model
}
private fun loadLanguageModel(language: Language, ngramLength: Int): TrainingDataLanguageModel {
val fileName = "${Ngram.getNgramNameByLength(ngramLength)}s.json"
val filePath = "/language-models/${language.isoCode639_1}/$fileName"
val inputStream = Language::class.java.getResourceAsStream(filePath)
val jsonContent = inputStream.bufferedReader(Charsets.UTF_8).use { it.readText() }
return TrainingDataLanguageModel.fromJson(jsonContent)
}
private fun preloadLanguageModels() {
val tasks = mutableListOf<Callable<TrainingDataLanguageModel>>()
for (language in languages) {
tasks.add(Callable { loadLanguageModels(unigramLanguageModels, language, 1) })
tasks.add(Callable { loadLanguageModels(bigramLanguageModels, language, 2) })
tasks.add(Callable { loadLanguageModels(trigramLanguageModels, language, 3) })
tasks.add(Callable { loadLanguageModels(quadrigramLanguageModels, language, 4) })
tasks.add(Callable { loadLanguageModels(fivegramLanguageModels, language, 5) })
}
threadPool.invokeAll(tasks)
}
private fun createThreadPool(): ExecutorService {
val cpus = Runtime.getRuntime().availableProcessors()
val threadPool = ThreadPoolExecutor(cpus, cpus, 60L, TimeUnit.SECONDS, LinkedBlockingQueue())
threadPool.allowCoreThreadTimeOut(true)
return threadPool
}
override fun equals(other: Any?) = when {
this === other -> true
other !is LanguageDetector -> false
languages != other.languages -> false
minimumRelativeDistance != other.minimumRelativeDistance -> false
else -> true
}
override fun hashCode() = 31 * languages.hashCode() + minimumRelativeDistance.hashCode()
}
| 10
|
Kotlin
|
47
| 477
|
4ca58ead2d2ce6bad6d85574b7efd5b3ca29aa4b
| 21,461
|
lingua
|
Apache License 2.0
|
detekt-formatting/src/main/kotlin/io/gitlab/arturbosch/detekt/formatting/SpacingAroundOperator.kt
|
msteinbeck
| 85,065,932
| true
|
{"Kotlin": 169998, "Java": 153}
|
package io.gitlab.arturbosch.detekt.formatting
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.impl.source.tree.LeafPsiElement
import com.intellij.psi.impl.source.tree.PsiWhiteSpaceImpl
import com.intellij.psi.tree.TokenSet
import com.intellij.psi.util.PsiTreeUtil
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.TokenRule
import org.jetbrains.kotlin.lexer.KtTokens.ANDAND
import org.jetbrains.kotlin.lexer.KtTokens.ARROW
import org.jetbrains.kotlin.lexer.KtTokens.DIV
import org.jetbrains.kotlin.lexer.KtTokens.DIVEQ
import org.jetbrains.kotlin.lexer.KtTokens.ELVIS
import org.jetbrains.kotlin.lexer.KtTokens.EQ
import org.jetbrains.kotlin.lexer.KtTokens.EQEQ
import org.jetbrains.kotlin.lexer.KtTokens.EQEQEQ
import org.jetbrains.kotlin.lexer.KtTokens.EXCLEQ
import org.jetbrains.kotlin.lexer.KtTokens.EXCLEQEQEQ
import org.jetbrains.kotlin.lexer.KtTokens.GT
import org.jetbrains.kotlin.lexer.KtTokens.GTEQ
import org.jetbrains.kotlin.lexer.KtTokens.LT
import org.jetbrains.kotlin.lexer.KtTokens.LTEQ
import org.jetbrains.kotlin.lexer.KtTokens.MINUS
import org.jetbrains.kotlin.lexer.KtTokens.MINUSEQ
import org.jetbrains.kotlin.lexer.KtTokens.MUL
import org.jetbrains.kotlin.lexer.KtTokens.MULTEQ
import org.jetbrains.kotlin.lexer.KtTokens.OROR
import org.jetbrains.kotlin.lexer.KtTokens.PERC
import org.jetbrains.kotlin.lexer.KtTokens.PERCEQ
import org.jetbrains.kotlin.lexer.KtTokens.PLUS
import org.jetbrains.kotlin.lexer.KtTokens.PLUSEQ
import org.jetbrains.kotlin.psi.KtImportDirective
import org.jetbrains.kotlin.psi.KtPrefixExpression
import org.jetbrains.kotlin.psi.KtTypeArgumentList
import org.jetbrains.kotlin.psi.KtTypeParameterList
import org.jetbrains.kotlin.psi.KtValueArgument
/**
* Based on KtLint.
*
* @author Shyiko
*/
class SpacingAroundOperator(config: Config) : TokenRule("SpacingAroundOperator", Severity.Style, config) {
private val tokenSet = TokenSet.create(MUL, PLUS, MINUS, DIV, PERC, LT, GT, LTEQ, GTEQ, EQEQEQ, EXCLEQEQEQ, EQEQ,
EXCLEQ, ANDAND, OROR, ELVIS, EQ, MULTEQ, DIVEQ, PERCEQ, PLUSEQ, MINUSEQ, ARROW)
override fun procedure(node: ASTNode) {
if (tokenSet.contains(node.elementType) && node is LeafPsiElement &&
!node.isPartOf(KtPrefixExpression::class) && // not unary
!node.isPartOf(KtTypeParameterList::class) && // fun <T>fn(): T {}
!node.isPartOf(KtTypeArgumentList::class) && // C<T>
!node.isPartOf(KtValueArgument::class) && // fn(*array)
!node.isPartOf(KtImportDirective::class) // import *
) {
val spacingBefore = PsiTreeUtil.prevLeaf(node, true) is PsiWhiteSpace
val spacingAfter = PsiTreeUtil.nextLeaf(node, true) is PsiWhiteSpace
when {
!spacingBefore && !spacingAfter -> {
addFindings(CodeSmell(id, Entity.from(node), "Missing spacing around \":\""))
withAutoCorrect {
node.rawInsertBeforeMe(PsiWhiteSpaceImpl(" "))
node.rawInsertAfterMe(PsiWhiteSpaceImpl(" "))
}
}
!spacingBefore -> {
addFindings(CodeSmell(id, Entity.from(node), "Missing spacing before \":\""))
withAutoCorrect {
node.rawInsertBeforeMe(PsiWhiteSpaceImpl(" "))
}
}
!spacingAfter -> {
addFindings(CodeSmell(id, Entity.from(node, offset = 1), "Missing spacing after \":\""))
withAutoCorrect {
node.rawInsertAfterMe(PsiWhiteSpaceImpl(" "))
}
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
8e5b36489764018ca412e5f650096afb93cdb027
| 3,493
|
detekt
|
Apache License 2.0
|
app/src/main/java/com/example/tickerapp/feature_todo/presentation/util/isSameDay.kt
|
nicanor-jay
| 788,617,145
| false
|
{"Kotlin": 170474}
|
package com.example.tickerapp.feature_todo.presentation.util
import java.util.Calendar
import java.util.TimeZone
fun isSameDay(timestamp1: Long, timestamp2: Long): Boolean {
val calendar1 = Calendar.getInstance()
calendar1.timeZone = TimeZone.getDefault() // Set to user's timezone
calendar1.timeInMillis = timestamp1
val calendar2 = Calendar.getInstance()
calendar2.timeZone = TimeZone.getDefault() // Set to user's timezone
calendar2.timeInMillis = timestamp2
return (calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR) &&
calendar1.get(Calendar.DAY_OF_YEAR) == calendar2.get(Calendar.DAY_OF_YEAR))
}
| 0
|
Kotlin
|
0
| 1
|
0e53560bfa747980f1d9b358f9406242c4bc9c4b
| 655
|
Ticker
|
Apache License 2.0
|
straight/src/commonMain/kotlin/me/localx/icons/straight/filled/Referral.kt
|
localhostov
| 808,861,591
| false
|
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.straight.filled
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Filled.Referral: ImageVector
get() {
if (_referral != null) {
return _referral!!
}
_referral = Builder(name = "Referral", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(10.0f, 11.0f)
curveToRelative(0.0f, -1.654f, -1.346f, -3.0f, -3.0f, -3.0f)
lineTo(3.0f, 8.0f)
curveToRelative(-1.654f, 0.0f, -3.0f, 1.346f, -3.0f, 3.0f)
verticalLineToRelative(2.0f)
horizontalLineToRelative(10.0f)
verticalLineToRelative(-2.0f)
close()
moveTo(5.0f, 7.0f)
curveToRelative(1.93f, 0.0f, 3.5f, -1.57f, 3.5f, -3.5f)
reflectiveCurveTo(6.93f, 0.0f, 5.0f, 0.0f)
reflectiveCurveTo(1.5f, 1.57f, 1.5f, 3.5f)
reflectiveCurveToRelative(1.57f, 3.5f, 3.5f, 3.5f)
close()
moveTo(21.0f, 8.0f)
horizontalLineToRelative(-4.0f)
curveToRelative(-1.654f, 0.0f, -3.0f, 1.346f, -3.0f, 3.0f)
verticalLineToRelative(2.0f)
horizontalLineToRelative(10.0f)
verticalLineToRelative(-2.0f)
curveToRelative(0.0f, -1.654f, -1.346f, -3.0f, -3.0f, -3.0f)
close()
moveTo(19.0f, 7.0f)
curveToRelative(1.93f, 0.0f, 3.5f, -1.57f, 3.5f, -3.5f)
reflectiveCurveToRelative(-1.57f, -3.5f, -3.5f, -3.5f)
reflectiveCurveToRelative(-3.5f, 1.57f, -3.5f, 3.5f)
reflectiveCurveToRelative(1.57f, 3.5f, 3.5f, 3.5f)
close()
moveTo(20.351f, 15.548f)
lineToRelative(2.66f, 2.66f)
lineToRelative(-1.414f, 1.414f)
lineToRelative(-1.596f, -1.596f)
verticalLineToRelative(2.974f)
curveToRelative(0.0f, 1.654f, -1.346f, 3.0f, -3.0f, 3.0f)
lineTo(7.0f, 24.0f)
curveToRelative(-1.654f, 0.0f, -3.0f, -1.346f, -3.0f, -3.0f)
verticalLineToRelative(-6.0f)
horizontalLineToRelative(2.0f)
verticalLineToRelative(6.0f)
curveToRelative(0.0f, 0.552f, 0.449f, 1.0f, 1.0f, 1.0f)
horizontalLineToRelative(10.0f)
curveToRelative(0.551f, 0.0f, 1.0f, -0.448f, 1.0f, -1.0f)
verticalLineToRelative(-2.923f)
lineToRelative(-1.545f, 1.545f)
lineToRelative(-1.414f, -1.414f)
lineToRelative(2.659f, -2.659f)
curveToRelative(0.731f, -0.73f, 1.92f, -0.729f, 2.65f, 0.0f)
close()
}
}
.build()
return _referral!!
}
private var _referral: ImageVector? = null
| 1
|
Kotlin
|
0
| 5
|
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 3,700
|
icons
|
MIT License
|
advancedlocationlibrary/src/main/java/com/hms/advancedlocationlibrary/data/model/holders/Result.kt
|
Explore-In-HMS
| 516,013,569
| false
| null |
package com.hms.advancedlocationlibrary.data.model.holders
sealed class Result<T> {
data class Success<T>(var data: T) : Result<T>()
data class Failure<T>(var exception: Exception? = null) : Result<T>()
fun isSuccess(): Boolean {
return this is Success
}
val value: T get() = (this as Success).data
internal val reason: Exception? get() = (this as Failure).exception
}
| 0
|
Kotlin
|
0
| 2
|
3912ccd8f0c1161fb19e7878cd2312f8affd9c70
| 405
|
advanced-location
|
MIT License
|
app/src/main/kotlin/com/getstrm/pace/processing_platforms/h2/H2ViewGenerator.kt
|
getstrm
| 706,692,316
| false
|
{"Kotlin": 423141, "Shell": 8472, "Makefile": 8118, "Python": 794, "Dockerfile": 569}
|
package com.getstrm.pace.processing_platforms.h2
import build.buf.gen.getstrm.pace.api.entities.v1alpha.DataPolicy
import com.getstrm.pace.processing_platforms.ProcessingPlatformViewGenerator
import org.jooq.Condition
import org.jooq.conf.Settings
import org.jooq.impl.DSL
/**
* This in-memory view generator is only used to evaluate data policies on sample data without creating actual views.
* Instead, the corresponding select statements are executed directly on the sample data for the given principal.
* The source ref is overridden to point to the in-memory table.
*/
class H2ViewGenerator(
dataPolicy: DataPolicy,
private val principalToApply: DataPolicy.Principal?,
sourceRefOverride: String,
customJooqSettings: Settings.() -> Unit = {}
) : ProcessingPlatformViewGenerator(
dataPolicy.toBuilder().setSource(
dataPolicy.source.toBuilder().setRef(sourceRefOverride)
).build(),
customJooqSettings = customJooqSettings
) {
override fun toPrincipalCondition(principals: List<DataPolicy.Principal>): Condition? {
return if (principals.isEmpty()) {
null
} else {
if (principalToApply != null && principals.contains(principalToApply)) {
DSL.trueCondition()
} else {
DSL.falseCondition()
}
}
}
}
| 24
|
Kotlin
|
0
| 16
|
ed91fd3bd1825ef25a5d2a04b04de0947c1f880d
| 1,350
|
pace
|
Apache License 2.0
|
phone/src/main/java/app/pizzabutton/android/phone/viewmodels/UserViewModel.kt
|
tujson
| 298,683,923
| false
| null |
package app.pizzabutton.android.phone.viewmodels
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
import app.pizzabutton.android.common.models.User
import app.pizzabutton.android.phone.utils.FirebaseQueryLiveData
import com.google.firebase.database.ktx.database
import com.google.firebase.database.ktx.getValue
import com.google.firebase.ktx.Firebase
class UserViewModel(userId: String) : ViewModel() {
private val liveData = FirebaseQueryLiveData(
Firebase.database.reference.child(userId)
)
val userLiveData = Transformations.map(liveData) {
it.getValue<User>()!!
}
}
| 0
|
Kotlin
|
0
| 0
|
32e7e2597207bf503189c639cfaaa8ec874492ed
| 633
|
PizzaButton-App
|
MIT License
|
sculptor-shared/src/main/kotlin/io/papermc/sculptor/shared/MacheExtension.kt
|
PaperMC
| 776,033,668
| false
|
{"Kotlin": 89546}
|
package io.papermc.sculptor.shared
import io.papermc.sculptor.shared.util.MacheRepo
import org.gradle.api.NamedDomainObjectContainer
import org.gradle.api.model.ObjectFactory
import org.gradle.api.provider.ListProperty
import org.gradle.api.provider.Property
import org.gradle.kotlin.dsl.domainObjectContainer
import org.gradle.kotlin.dsl.listProperty
import org.gradle.kotlin.dsl.property
open class MacheExtension(objects: ObjectFactory) {
/**
* The version of Minecraft which will serve as the base.
*/
val minecraftVersion: Property<String> = objects.property()
/**
* Base arguments passed to the decompiler.
*/
val decompilerArgs: ListProperty<String> = objects.listProperty()
/**
* Arguments passed to the remapper. For the available placeholder see {@link io.papermc.sculptor.version.tasks.RemapJar}.
*/
val remapperArgs: ListProperty<String> = objects.listProperty()
/**
* Maven repositories needed to resolve the configurations necessary to run mache. The configurations are
* `codebook`, `paramMappings`, `constants`, `remapper`, and `decompiler`.
*
* These are defined in this way because we need this information for the metadata file we generate. Repositories
* defined in the normal Gradle style will not be reported in the metadata file.
*/
val repositories: NamedDomainObjectContainer<MacheRepo> = objects.domainObjectContainer(MacheRepo::class)
init {
decompilerArgs.convention(
listOf(
// Synthetic Not Set: Treat some known structures as synthetic even when not explicitly set
"-nns=true",
// Ternary Constant Simplification:
// Fold branches of ternary expressions that have boolean true and false constants
"-tcs=true",
// Override Annotation: Display override annotations for methods known to the decompiler
"-ovr=false",
// [Experimental] Verify Variable Merges:
// Double checks to make sure the validity of variable merges
"-vvm=true",
// Include Entire Classpath: Give the decompiler information about every jar on the classpath
"-iec=true",
// Include Java Runtime: Give the decompiler information about the Java runtime
"-jrt=current",
// Indent String
"-ind= ",
// JAD-Style Variable Naming: Use JAD-style variable naming for local variables
"-jvn=false",
// Decompile complex constant-dynamic expressions:
// Some constant-dynamic expressions can't be converted to a single Java expression with
// identical run-time behaviour. This decompiles them to a similar non-lazy expression,
// marked with a comment
"-dcc=true",
// Skip Extra Files: Skip copying non-class files from the input folder or file to the output
"-sef=true",
// New Line Seperator: Character that seperates lines in the decompiled output.
"-nls=1",
),
)
for (repo in DEFAULT_REPOS) {
repositories.register(repo.name) {
url.set(repo.url)
includeGroups.addAll(repo.includeGroups)
}
}
}
}
| 2
|
Kotlin
|
1
| 1
|
587470c158d1d3244f07918b917d840859ef6b07
| 3,439
|
sculptor
|
MIT License
|
domain/src/main/java/com/cerminnovations/domain/model/SpokenLanguage.kt
|
mbobiosio
| 324,425,383
| false
| null |
package com.cerminnovations.domain.model
/**
* @Author <NAME>
* https://linktr.ee/mbobiosio
*/
data class SpokenLanguage(
val name: String,
val englishName: String,
val iso6391: String
)
| 0
|
Kotlin
|
3
| 7
|
07270aa17f45edabfb6792fd529c212e1c585ce4
| 203
|
MoviesBoard
|
MIT License
|
app/src/main/java/de/htw_berlin/quiz_app/SessionsFragment.kt
|
ahak-Yem
| 749,561,027
| false
|
{"Kotlin": 64403}
|
package de.htw_berlin.quiz_app
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import de.htw_berlin.quiz_app.databinding.FragmentSessionsBinding
class SessionsFragment : Fragment() {
private lateinit var binding: FragmentSessionsBinding
private lateinit var sessionAdapter: SessionAdapter
private val viewModel: SessionsViewModel by viewModels()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentSessionsBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val sharedPreferences = requireContext().getSharedPreferences("LoginPrefs", Context.MODE_PRIVATE)
val spitzname = sharedPreferences.getString("spitzname", "") //Get userID from app preferences
if (spitzname != null) {
binding.username = spitzname
viewModel.getUserSessions(spitzname, onSuccess = {
binding.totalSessions = it.toString()
Toast.makeText(requireContext(), "Erfolgreich", Toast.LENGTH_SHORT).show()
}, onFailure = {
Toast.makeText(requireContext(),"Versuchen Sie später",Toast.LENGTH_SHORT).show()
})
}
setupRecyclerView()
}
private fun setupRecyclerView() {
sessionAdapter = SessionAdapter(emptyList()) // Pass an empty list initially
binding.sessionsRecyclerView.apply {
adapter = sessionAdapter
layoutManager = LinearLayoutManager(requireContext())
//setHasFixedSize(false)
}
observeViewModel()
}
private fun observeViewModel() {
viewModel.sessions.observe(viewLifecycleOwner) { sessions ->
sessionAdapter.updateSessions(sessions)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
24bb791cb14dffaf5680ff935e47dc4700f97d53
| 2,207
|
Quiz_App
|
MIT License
|
src/main/java/com/sayzen/campfiresdk/models/events/units/EventPollingChanged.kt
|
Daboo011
| 217,832,397
| false
|
{"Kotlin": 1107825}
|
package com.sayzen.campfiresdk.models.events.units
class EventPollingChanged(val pollingId:Long)
| 0
| null |
1
| 0
|
33c46da49d3758a1a006ac660dc823d35c66baea
| 97
|
CampfireSDK
|
Apache License 2.0
|
codebase/android/core/data/src/main/java/com/makeappssimple/abhimanyu/financemanager/android/core/data/model/DatabaseData.kt
|
Abhimanyu14
| 429,663,688
| false
| null |
package com.makeappssimple.abhimanyu.financemanager.android.core.data.model
import com.makeappssimple.abhimanyu.financemanager.android.core.model.Category
import com.makeappssimple.abhimanyu.financemanager.android.core.model.Emoji
import com.makeappssimple.abhimanyu.financemanager.android.core.model.Source
import com.makeappssimple.abhimanyu.financemanager.android.core.model.Transaction
import com.makeappssimple.abhimanyu.financemanager.android.core.model.TransactionFor
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class DatabaseData(
val categories: List<Category> = emptyList(),
val emojis: List<Emoji> = emptyList(),
val sources: List<Source> = emptyList(),
@SerialName(value = "transaction_for_values")
val transactionForValues: List<TransactionFor> = emptyList(),
val transactions: List<Transaction> = emptyList(),
)
| 0
|
Kotlin
|
0
| 0
|
5b24074ed66e6dadb8d64cf17b1240c4f0a6e0f0
| 913
|
finance-manager
|
Apache License 2.0
|
app/src/main/java/br/com/thedon/travellerapp/ui/components/RemoteImage.kt
|
thebergamo
| 668,639,027
| false
| null |
package br.com.thedon.travellerapp.ui.components
import android.annotation.SuppressLint
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import br.com.thedon.travellerapp.R
import br.com.thedon.travellerapp.ui.theme.compositedOnSurface
import coil.compose.AsyncImage
/**
* A wrapper around [AsyncImage], setting a default [contentScale] and showing
* content while loading.
*/
@SuppressLint("StateFlowValueCalledInComposition")
@Composable
fun RemoteImage(
url: String,
contentDescription: String?,
modifier: Modifier = Modifier,
contentScale: ContentScale = ContentScale.Crop,
placeholderColor: Color = MaterialTheme.colors.compositedOnSurface(0.2f)
) {
AsyncImage(
model = url,
contentDescription = contentDescription,
placeholder = painterResource(R.drawable.photo_placeholder),
modifier = modifier,
contentScale = contentScale
)
}
| 0
|
Kotlin
|
0
| 0
|
e34eface4b64fab53797425d80ddb9b3fad14fdc
| 1,120
|
pjatk-prm-traveller-app
|
MIT License
|
openai-core/src/commonMain/kotlin/com.aallam.openai.api/exception/OpenAIException.kt
|
aallam
| 345,180,734
| false
| null |
package com.aallam.openai.api.exception
/** OpenAI client exception */
public sealed class OpenAIException(
message: String? = null,
throwable: Throwable? = null
) : RuntimeException(message, throwable)
/** Runtime Http Client exception */
public class OpenAIHttpException(
throwable: Throwable? = null,
) : OpenAIException(throwable?.message, throwable)
/**
* An exception thrown when an error occurs while interacting with the OpenAI API.
*/
public class OpenAIAPIException(
/** Http status code **/
public val statusCode: Int,
/** Contains information about the error that occurred.*/
public val error: OpenAIError,
throwable: Throwable? = null,
) : OpenAIException(message = error.detail?.message, throwable = throwable)
/** An exception thrown in case a request times out. */
public class OpenAITimeoutException(
throwable: Throwable
) : OpenAIException(message = throwable.message, throwable = throwable)
/** An exception thrown in case of a server error */
public class OpenAIServerException(
throwable: Throwable? = null,
) : OpenAIException(message = throwable?.message, throwable = throwable)
| 6
|
Kotlin
|
51
| 459
|
4a8a5c66889a3aeb040b2444f8137f3ba5e668c0
| 1,150
|
openai-kotlin
|
MIT License
|
app/src/main/java/com/dansiapa/mvvmkotlin/view/RegisterActivity.kt
|
dansiapa
| 346,114,388
| false
| null |
package com.dansiapa.mvvmkotlin.view
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.dansiapa.mvvmkotlin.R
class RegisterActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_register)
}
}
| 0
|
Kotlin
|
0
| 1
|
fc45bf29f76e4590f86cd1c170a9f155dfece95f
| 351
|
Breaking-News_Intern
|
Apache License 2.0
|
library/core/src/main/java/com/michaelflisar/composepreferences/core/classes/PreferenceData.kt
|
MFlisar
| 705,594,559
| false
|
{"Kotlin": 131289}
|
package com.michaelflisar.composepreferences.core.classes
import androidx.compose.runtime.MutableState
/**
* helper class to be able to plug in KotPreferences separately as an optional module
* (or any other custom data class of course, if the user has one)
*
* @param value the value of the preference
* @param the update function to handle preference value changes
*/
data class PreferenceData<T>(
val value: T,
val onValueChange: (data: T) -> Unit = {}
) {
companion object
}
/**
* a convenient function to convert a [androidx.compose.runtime.State] into a [PreferenceData] object
*
* @return a [PreferenceData]
*/
fun <T> MutableState<T>.asPreferenceData(): PreferenceData<T> {
return PreferenceData(
value
) { value = it }
}
//@Composable
//fun <T> PreferenceData(setting: StorageSetting<T>): PreferenceData<T> {
// val scope = rememberCoroutineScope()
// val state = setting.collectSetting()
// return PreferenceData(state.value) {
// scope.launch(Dispatchers.IO) {
// setting.update(it)
// }
// }
//}
| 0
|
Kotlin
|
0
| 3
|
06bc9880b0434831fd0bd2a15bc8af507ade2a8a
| 1,086
|
ComposePreferences
|
Apache License 2.0
|
common/src/main/java/net/beholderface/oneironaut/casting/patterns/spells/idea/OpGetIdeaTimestamp.kt
|
ChuijkYahus
| 731,710,469
| false
|
{"Java Properties": 1, "Markdown": 4, "Shell": 2, "Python": 7, "Batchfile": 2, "Java": 99, "Kotlin": 49, "INI": 2}
|
package net.beholderface.oneironaut.casting.patterns.spells.idea
import at.petrak.hexcasting.api.misc.MediaConstants
import at.petrak.hexcasting.api.spell.ConstMediaAction
import at.petrak.hexcasting.api.spell.casting.CastingContext
import at.petrak.hexcasting.api.spell.getEntity
import at.petrak.hexcasting.api.spell.getPlayer
import at.petrak.hexcasting.api.spell.getVec3
import at.petrak.hexcasting.api.spell.iota.EntityIota
import at.petrak.hexcasting.api.spell.iota.GarbageIota
import at.petrak.hexcasting.api.spell.iota.Iota
import at.petrak.hexcasting.api.spell.iota.Vec3Iota
import at.petrak.hexcasting.api.spell.mishaps.MishapBadEntity
import at.petrak.hexcasting.api.spell.mishaps.MishapInvalidIota
import net.minecraft.entity.Entity
import net.minecraft.entity.EntityType
import net.minecraft.text.Text
import net.minecraft.util.math.BlockPos
import net.beholderface.oneironaut.casting.IdeaInscriptionManager
import net.beholderface.oneironaut.getSoulprint
import net.beholderface.oneironaut.registry.SoulprintIota
class OpGetIdeaTimestamp : ConstMediaAction {
override val argc = 1
override val mediaCost = MediaConstants.DUST_UNIT / 10
override fun execute(args: List<Iota>, ctx: CastingContext): List<Iota> {
var output : Iota = GarbageIota()
val rawKeyIota = args[0]
val keyEntity : Entity
val keyPos : BlockPos
if (rawKeyIota.type == EntityIota.TYPE){
keyEntity = args.getEntity(0, argc)
ctx.assertEntityInRange(keyEntity)
if (keyEntity.isPlayer || keyEntity.type.equals(EntityType.VILLAGER)){
output = IdeaInscriptionManager.getIotaTimestamp(keyEntity.uuid, ctx.world)
} else {
throw MishapBadEntity(keyEntity, Text.translatable("oneironaut.mishap.badentitykey"))
}
} else if (rawKeyIota.type == Vec3Iota.TYPE){
keyPos = BlockPos(args.getVec3(0, argc))
output = IdeaInscriptionManager.getIotaTimestamp(keyPos, ctx.world)
} else if (rawKeyIota.type == SoulprintIota.TYPE){
val keySoulprint = args.getSoulprint(0, argc).toString() + "soul"
output = IdeaInscriptionManager.getIotaTimestamp(keySoulprint, ctx.world)
} else {
throw MishapInvalidIota(rawKeyIota, 0, Text.translatable("oneironaut.mishap.invalidideakey"));
}
return listOf(output)
}
}
| 1
| null |
1
| 1
|
5e8d7a59e9c05d250da3b506349d5d64168ddd4a
| 2,411
|
oneironaut
|
MIT License
|
app/src/main/java/com/hopovo/mobile/android/prepexam/app/common/util/BitmapUtils.kt
|
MilanZk
| 276,394,492
| false
|
{"Kotlin": 192502, "Shell": 1098}
|
package com.hopovo.mobile.android.prepexam.app.common.util
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.util.Base64
import androidx.annotation.IntRange
import java.io.ByteArrayOutputStream
/**
* [Bitmap] utility methods to resize images and serialize/deserialize them into [String].
*/
object BitmapUtils {
/**
* Converts a [Bitmap] image into a [String] encoded in Base64 using as [android.graphics.Bitmap.CompressFormat] JPEG.
*/
@JvmStatic
fun fromBitmapToString(bitmap: Bitmap, compression: Int): String {
return fromBitmapToString(bitmap, Bitmap.CompressFormat.JPEG, compression)
}
/**
* Converts a [Bitmap] image into a [String] encoded in Base64.
*/
@JvmStatic
fun fromBitmapToString(bitmap: Bitmap, compressFormat: Bitmap.CompressFormat, compression: Int): String {
// Convert the bitmap to a byte array
val byteArrayOutputStream = ByteArrayOutputStream()
bitmap.compress(compressFormat, compression, byteArrayOutputStream)
val byteArray = byteArrayOutputStream.toByteArray()
// Convert byte array to string
return Base64.encodeToString(byteArray, Base64.DEFAULT)
}
/**
* Converts an [String] representing an image encoded in Base64 into a [Bitmap] image.
*/
@JvmStatic
fun fromStringToBitmap(encodedBitmap: String): Bitmap {
val decodedString = Base64.decode(encodedBitmap, Base64.DEFAULT)
return BitmapFactory.decodeByteArray(decodedString, 0, decodedString.size)
}
/**
* Resizes a [Bitmap] image using a matrix, which seems to produce better results than
* other methods. There is only one restriction for sizes, they must be greater than zero.
* Therefore, aspect ratio is not warranted to be preserved.
* IMPORTANT: This function returns a new bitmap, so the input bitmap can be safely
* [Bitmap.recycle]d. However, note that this approach may increase memory usage.
*/
@JvmStatic
fun getResizedBitmap(bitmap: Bitmap, @IntRange(from = 1) newWidth: Int, @IntRange(from = 1) newHeight: Int, copy: Boolean): Bitmap {
val width = bitmap.width
val height = bitmap.height
val scaleWidth = newWidth.toFloat() / width
val scaleHeight = newHeight.toFloat() / height
if (newHeight > 0 && newWidth > 0) {
// Create matrix for the manipulation
val matrix = Matrix()
// Add resize to the matrix
matrix.postScale(scaleWidth, scaleHeight)
// Resize the bitmap
val resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, false)
return if (copy) {
// resizedBitmap is a bitmap pointing to the same image buffer of input "bitmap" but with a
// new configuration. Therefore, it is a must to create a copy.
resizedBitmap.copy(resizedBitmap.config, false)
} else {
resizedBitmap
}
} else {
throw IllegalArgumentException("New dimensions contain sizes with zero or negative values. Height: $newHeight width: $newWidth")
}
}
@JvmStatic
fun getScaleFactor(photoPath: String, targetSize: Int): Float {
var scaleFactor = 1.0f
BitmapFactory.Options().apply {
// Get the dimensions of the bitmap
inJustDecodeBounds = true
BitmapFactory.decodeFile(photoPath, this)
val photoW: Int = outWidth
val photoH: Int = outHeight
// Determine how much to scale down the image
scaleFactor = Math.min(1.0f, targetSize.toFloat() / Math.min(photoW, photoH).toFloat())
}
return scaleFactor
}
}
| 0
|
Kotlin
|
0
| 1
|
24c7634eb76e720e45025e7142886b6834cbfb1d
| 3,829
|
chillupbox
|
MIT License
|
notes-mappers-v1/src/main/kotlin/org/avr/notes/mappers/RequestUtils.kt
|
alex-avr
| 589,281,806
| false
| null |
package org.avr.notes.mappers
import kotlinx.datetime.Instant
import org.avr.notes.api.v1.models.*
import org.avr.notes.common.NONE
import org.avr.notes.common.models.NotesRequestId
import org.avr.notes.common.models.NotesWorkMode
import org.avr.notes.common.models.folder.FolderId
import org.avr.notes.common.models.note.NoteId
import org.avr.notes.common.stubs.NotesStubs
fun getRequestId(request: IFolderRequest): NotesRequestId {
return request.requestId?.let { NotesRequestId(it) } ?: NotesRequestId.NONE
}
fun getRequestId(request: INoteRequest): NotesRequestId {
return request.requestId?.let { NotesRequestId(it) } ?: NotesRequestId.NONE
}
fun getFolderId(id: String?): FolderId {
return id?.let { FolderId(it) } ?: FolderId.NONE
}
fun getNoteId(id: String?): NoteId {
return id?.let { NoteId(it) } ?: NoteId.NONE
}
fun instantFromString(str: String?): Instant = when (str) {
null -> Instant.NONE
else -> Instant.parse(str)
}
fun DebugSettings?.transportToWorkMode() = when (this?.mode) {
RequestDebugMode.PROD -> NotesWorkMode.PROD
RequestDebugMode.TEST -> NotesWorkMode.TEST
RequestDebugMode.STUB -> NotesWorkMode.STUB
null -> NotesWorkMode.PROD
}
fun DebugSettings?.transportToStubCase() = when (this?.stub) {
RequestDebugStubs.NONE -> NotesStubs.NONE
RequestDebugStubs.SUCCESS -> NotesStubs.SUCCESS
RequestDebugStubs.NOT_FOUND -> NotesStubs.NOT_FOUND
RequestDebugStubs.BAD_ID -> NotesStubs.BAD_ID
RequestDebugStubs.BAD_NOTE_TITLE -> NotesStubs.BAD_NOTE_TITLE
RequestDebugStubs.BAD_NOTE_BODY -> NotesStubs.BAD_NOTE_BODY
RequestDebugStubs.BAD_FOLDER_NAME -> NotesStubs.BAD_FOLDER_NAME
RequestDebugStubs.CANNOT_DELETE -> NotesStubs.CANNOT_DELETE
RequestDebugStubs.BAD_SEARCH_STRING -> NotesStubs.BAD_SEARCH_STRING
null -> NotesStubs.NONE
}
fun noteSearchFilterFromTransport(searchFilter: NoteSearchFilter?): org.avr.notes.common.models.note.NoteSearchFilter =
searchFilter?.searchString?.let { org.avr.notes.common.models.note.NoteSearchFilter(it) }
?: org.avr.notes.common.models.note.NoteSearchFilter.NONE
| 0
|
Kotlin
|
0
| 0
|
4ddf9f0039bc2ac0bb239a1bb2f21ea141abbf42
| 2,117
|
notes
|
Apache License 2.0
|
certificatetransparency/src/main/kotlin/com/appmattus/certificatetransparency/internal/verifier/CertificateTransparencyTrustManager.kt
|
morristech
| 418,269,661
| true
|
{"Kotlin": 482406, "Java": 17861}
|
/*
* Copyright 2021 Appmattus Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.appmattus.certificatetransparency.internal.verifier
import com.appmattus.certificatetransparency.CTLogger
import com.appmattus.certificatetransparency.CTPolicy
import com.appmattus.certificatetransparency.VerificationResult
import com.appmattus.certificatetransparency.cache.DiskCache
import com.appmattus.certificatetransparency.chaincleaner.CertificateChainCleanerFactory
import com.appmattus.certificatetransparency.datasource.DataSource
import com.appmattus.certificatetransparency.internal.verifier.model.Host
import com.appmattus.certificatetransparency.loglist.LogListResult
import com.appmattus.certificatetransparency.loglist.LogListService
import org.bouncycastle.asn1.x500.X500Name
import org.bouncycastle.asn1.x500.style.BCStyle
import java.security.cert.X509Certificate
import javax.net.ssl.SSLPeerUnverifiedException
import javax.net.ssl.X509TrustManager
@Suppress("LongParameterList", "CustomX509TrustManager")
internal class CertificateTransparencyTrustManager(
private val delegate: X509TrustManager,
includeHosts: Set<Host>,
excludeHosts: Set<Host>,
certificateChainCleanerFactory: CertificateChainCleanerFactory?,
logListService: LogListService?,
logListDataSource: DataSource<LogListResult>?,
policy: CTPolicy?,
diskCache: DiskCache?,
private val failOnError: Boolean = true,
private val logger: CTLogger? = null
) : CertificateTransparencyBase(
includeHosts,
excludeHosts,
certificateChainCleanerFactory,
delegate,
logListService,
logListDataSource,
policy,
diskCache
), X509TrustManager {
override fun checkClientTrusted(chain: Array<out X509Certificate>, authType: String) = delegate.checkClientTrusted(chain, authType)
override fun checkServerTrusted(chain: Array<out X509Certificate>, authType: String) {
delegate.checkServerTrusted(chain, authType)
val leafCertificate = chain.first()
val commonName = X500Name(leafCertificate.subjectX500Principal.name).getRDNs(BCStyle.CN)[0].first.value.toString()
// val subjectAlternativeNames = leafCertificate.subjectAlternativeNames.filter { it[0] == 2 }.map { it[1].toString() }
// val dnsNames = listOf(cn) + subjectAlternativeNames
// val host = dnsNames.firstOrNull { enabledForCertificateTransparency(it) } ?: cn
val result = verifyCertificateTransparency(commonName, chain.toList())
logger?.log(commonName, result)
if (result is VerificationResult.Failure && failOnError) {
throw SSLPeerUnverifiedException("Certificate transparency failed")
}
}
override fun getAcceptedIssuers(): Array<X509Certificate> = delegate.acceptedIssuers
}
| 0
| null |
0
| 0
|
df5cd5de8abf90a916be0c6f657ee1b8212bf8a4
| 3,307
|
certificatetransparency
|
Apache License 2.0
|
ktor-client/ktor-client-core/src/io/ktor/client/call/TypeInfo.kt
|
sillerud
| 137,465,837
| true
|
{"Kotlin": 1751604, "Java": 62081, "Lua": 280, "HTML": 35}
|
package io.ktor.client.call
import java.lang.reflect.*
import kotlin.reflect.*
class TypeInfo(val type: KClass<*>, val reifiedType: Type)
@PublishedApi()
internal open class TypeBase<T>
inline fun <reified T> typeInfo(): TypeInfo {
val base = object : TypeBase<T>() {}
val superType = base::class.java.genericSuperclass!!
val reifiedType = (superType as ParameterizedType).actualTypeArguments.first()!!
return TypeInfo(T::class, reifiedType)
}
| 0
|
Kotlin
|
0
| 0
|
f51c77cbc9298b600968ca7c28b355242d764e52
| 465
|
ktor
|
Apache License 2.0
|
library/src/test/kotlin/me/proxer/library/api/ucp/DeleteSubscriptionEndpointTest.kt
|
proxer
| 43,981,937
| false
|
{"Kotlin": 492172}
|
package me.proxer.library.api.ucp
import me.proxer.library.ProxerTest
import me.proxer.library.runRequest
import org.amshove.kluent.shouldBeEqualTo
import org.amshove.kluent.shouldBeNull
import org.junit.jupiter.api.Test
/**
* @author <NAME>
*/
class DeleteSubscriptionEndpointTest : ProxerTest() {
@Test
fun testDefault() {
val (result, _) = server.runRequest("empty.json") {
api.ucp
.deleteSubscription("456")
.build()
.execute()
}
result.shouldBeNull()
}
@Test
fun testPath() {
val (_, request) = server.runRequest("empty.json") {
api.ucp.deleteSubscription("654")
.build()
.execute()
}
request.path shouldBeEqualTo "/api/v1/ucp/deletesubscription"
}
@Test
fun testParameter() {
val (_, request) = server.runRequest("empty.json") {
api.ucp.deleteSubscription("654")
.build()
.execute()
}
request.body.readUtf8() shouldBeEqualTo "id=654"
}
}
| 0
|
Kotlin
|
2
| 13
|
8e7d70afc0882fb41581d56308e12ad4c701832d
| 1,110
|
ProxerLibJava
|
MIT License
|
domain/src/main/java/pl/org/seva/victorweather/domain/repository/WeatherRepository.kt
|
syrop
| 855,980,365
| false
|
{"Kotlin": 73110}
|
package pl.org.seva.victorweather.domain.repository
import pl.org.seva.victorweather.domain.model.WeatherDomainModel
interface WeatherRepository {
suspend fun fetchWeather(lat: Double, lon: Double): WeatherDomainModel
suspend fun fetchWeatherHistory(city: String): WeatherDomainModel
suspend fun save(weather: WeatherDomainModel)
}
| 0
|
Kotlin
|
0
| 0
|
78d5876a29e7900acb31dee6baa3f5116d0fd509
| 350
|
Victor-Weather
|
MIT License
|
src/main/kotlin/me/fzzyhmstrs/amethyst_imbuement/registry/RegisterEnchantment.kt
|
fzzyhmstrs
| 461,338,617
| false
| null |
@file:Suppress("unused")
package me.fzzyhmstrs.amethyst_imbuement.registry
import me.fzzyhmstrs.amethyst_imbuement.AI
import me.fzzyhmstrs.amethyst_imbuement.LOGGER
import me.fzzyhmstrs.amethyst_imbuement.augment.*
import me.fzzyhmstrs.amethyst_imbuement.enchantment.*
import me.fzzyhmstrs.amethyst_imbuement.spells.*
import me.fzzyhmstrs.amethyst_imbuement.spells.pieces.effects.ModifiableEffects
import me.fzzyhmstrs.fzzy_core.coding_util.AbstractConfigDisableEnchantment
import net.minecraft.enchantment.DamageEnchantment
import net.minecraft.enchantment.Enchantment
import net.minecraft.entity.EquipmentSlot
import net.minecraft.registry.Registries
import net.minecraft.registry.Registry
object RegisterEnchantment {
private fun <T: Enchantment> register(e: T, name: String): T{
val id = AI.identity(name)
val e1 = Registry.register(Registries.ENCHANTMENT,id, e)
if (e1 is AbstractConfigDisableEnchantment){
if (!e1.isEnabled()){
LOGGER.info("Augment $id is set as disabled in the configs!")
}
}
println(e1)
return e
}
//vanilla style enchantments
val HEROIC = register(DamageEnchantment(Enchantment.Rarity.UNCOMMON, 3, EquipmentSlot.MAINHAND),"heroic")
val WASTING = register(WastingEnchantment(Enchantment.Rarity.RARE, EquipmentSlot.MAINHAND),"wasting")
val DEADLY_SHOT = register(DeadlyShotEnchantment(Enchantment.Rarity.COMMON, EquipmentSlot.MAINHAND),"deadly_shot")
val PUNCTURING = register(PuncturingEnchantment(Enchantment.Rarity.RARE, EquipmentSlot.MAINHAND),"puncturing")
val INSIGHT = register(InsightEnchantment(Enchantment.Rarity.COMMON, EquipmentSlot.MAINHAND),"insight")
val LIFESTEAL = register(LifestealEnchantment(Enchantment.Rarity.RARE, EquipmentSlot.MAINHAND),"lifesteal")
val DECAYED = register(DecayedEnchantment(Enchantment.Rarity.VERY_RARE, EquipmentSlot.MAINHAND),"decayed")
val CONTAMINATED = register(ContaminatedEnchantment(Enchantment.Rarity.VERY_RARE, EquipmentSlot.MAINHAND),"contaminated")
val CLEAVING = register(CleavingEnchantment(Enchantment.Rarity.COMMON, EquipmentSlot.MAINHAND),"cleaving")
val MULTI_JUMP = register(MultiJumpEnchantment(Enchantment.Rarity.RARE,EquipmentSlot.FEET),"multi_jump")
val NIGHT_VISION = register(NightVisionEnchantment(Enchantment.Rarity.RARE,1, EquipmentSlot.HEAD),"night_vision")
val STEADFAST = register(SteadfastEnchantment(Enchantment.Rarity.UNCOMMON, *AI.slots),"steadfast")
val RAIN_OF_THORNS = register(RainOfThornsEnchantment(Enchantment.Rarity.RARE, EquipmentSlot.MAINHAND),"rain_of_thorns")
val VEIN_MINER = register(VeinMinerEnchantment(Enchantment.Rarity.RARE,EquipmentSlot.MAINHAND, EquipmentSlot.OFFHAND),"vein_miner")
//augments for imbuing
val ACCURSED = register(AccursedAugment(Enchantment.Rarity.VERY_RARE,3, EquipmentSlot.OFFHAND),"accursed")
val ANGELIC = register(AngelicAugment(Enchantment.Rarity.VERY_RARE,1, EquipmentSlot.MAINHAND),"angelic")
val BEAST_MASTER = register(BeastMasterAugment(Enchantment.Rarity.VERY_RARE,3, EquipmentSlot.OFFHAND),"beast_master")
val BULWARK = register(BulwarkAugment(Enchantment.Rarity.VERY_RARE,1, EquipmentSlot.MAINHAND),"bulwark")
val CONSECRATED = register(ConsecratedAugment(Enchantment.Rarity.VERY_RARE,2, EquipmentSlot.OFFHAND),"consecrated")
val CRYSTALLINE = register(CrystallineAugment(Enchantment.Rarity.VERY_RARE,6, EquipmentSlot.OFFHAND),"crystalline")
val DRACONIC_VISION = register(DraconicVisionAugment(Enchantment.Rarity.VERY_RARE,1, EquipmentSlot.OFFHAND),"draconic_vision")
val ESCAPE = register(EscapeAugment(Enchantment.Rarity.VERY_RARE,1, EquipmentSlot.OFFHAND),"escape")
val FELINE = register(FelineAugment(Enchantment.Rarity.VERY_RARE,1, EquipmentSlot.OFFHAND),"feline")
val FRIENDLY = register(FriendlyAugment(Enchantment.Rarity.VERY_RARE,1, EquipmentSlot.OFFHAND),"friendly")
val GUARDIAN = register(GuardianAugment(Enchantment.Rarity.VERY_RARE,1, EquipmentSlot.OFFHAND),"guardian")
val HASTING = register(HastingAugment(Enchantment.Rarity.VERY_RARE,2, EquipmentSlot.MAINHAND),"hasting")
val HEADHUNTER = register(HeadhunterAugment(Enchantment.Rarity.VERY_RARE,1, EquipmentSlot.MAINHAND),"headhunter")
val HEALTHY = register(HealthyAugment(Enchantment.Rarity.VERY_RARE,1, EquipmentSlot.OFFHAND),"healthy")
val ILLUMINATING = register(IlluminatingAugment(Enchantment.Rarity.VERY_RARE,1, EquipmentSlot.OFFHAND),"illuminating")
val IMMUNITY = register(ImmunityAugment(Enchantment.Rarity.VERY_RARE,1, EquipmentSlot.OFFHAND),"immunity")
val INFLAMMABLE = register(InflammableAugment(Enchantment.Rarity.VERY_RARE,1, EquipmentSlot.OFFHAND),"inflammable")
val INVISIBILITY = register(InvisibilityAugment(Enchantment.Rarity.VERY_RARE,1, *AI.slots),"invisibility")
val LEAPING = register(LeapingAugment(Enchantment.Rarity.VERY_RARE,2, EquipmentSlot.LEGS),"leaping")
val LIGHTFOOTED = register(LightfootedAugment(Enchantment.Rarity.VERY_RARE,1, EquipmentSlot.FEET),"lightfooted")
val LUCKY = register(LuckyAugment(Enchantment.Rarity.VERY_RARE,1, EquipmentSlot.OFFHAND),"lucky")
val MOONLIT = register(MoonlitAugment(Enchantment.Rarity.VERY_RARE,2, *AI.slots),"moonlit")
val RESILIENCE = register(ResilienceAugment(Enchantment.Rarity.VERY_RARE,2, *AI.slots),"resilience")
val SHIELDING = register(ShieldingAugment(Enchantment.Rarity.VERY_RARE,3, EquipmentSlot.OFFHAND),"shielding")
val SLIMY = register(SlimyAugment(Enchantment.Rarity.VERY_RARE,1, EquipmentSlot.FEET),"slimy")
val SOULBINDING = register(SoulbindingAugment(Enchantment.Rarity.VERY_RARE,1, EquipmentSlot.OFFHAND),"soulbinding")
val SOUL_OF_THE_CONDUIT = register(SoulOfTheConduitAugment(Enchantment.Rarity.VERY_RARE,1 , EquipmentSlot.OFFHAND),"soul_of_the_conduit")
val SPECTRAL_VISION = register(SpectralVisionAugment(Enchantment.Rarity.VERY_RARE,1 , EquipmentSlot.HEAD),"spectral_vision")
val SPIKED = register(SpikedAugment(Enchantment.Rarity.VERY_RARE,3, EquipmentSlot.OFFHAND),"spiked")
val STRENGTH = register(StrengthAugment(Enchantment.Rarity.VERY_RARE,2, EquipmentSlot.MAINHAND),"strength")
val STRIDING = register(StridingAugment(Enchantment.Rarity.VERY_RARE,1, EquipmentSlot.FEET),"striding")
val SUNTOUCHED = register(SuntouchedAugment(Enchantment.Rarity.VERY_RARE,2, EquipmentSlot.OFFHAND),"suntouched")
val SWIFTNESS = register(SwiftnessAugment(Enchantment.Rarity.VERY_RARE,2, EquipmentSlot.LEGS),"swiftness")
val UNDYING = register(UndyingAugment(Enchantment.Rarity.VERY_RARE,1, EquipmentSlot.OFFHAND),"undying")
//Scepter Spells
val MAGIC_MISSILE = register(MagicMissileAugment(),"magic_missile")
val ABUNDANCE = register(AbundanceAugment(),"abundance")
val ANIMAL_HUSBANDRY = register(AnimalHusbandryAugment(),"animal_husbandry")
val BALL_LIGHTNING = register(BallLightningAugment(),"ball_lightning")
val BARRIER = register(BarrierAugment(),"barrier")
val BEDAZZLE = register(BedazzleAugment(),"bedazzle")
val BODY_SWAP = register(BodySwapAugment(),"body_swap")
val CHICKENFORM = register(ChickenformAugment(),"chickenform")
val CLEANSE = register(CleanseAugment(),"cleanse")
val COMET_STORM = register(CometStormAugment(),"comet_storm")
val CREATE_HARD_LIGHT = register(CreateHardLightAugment(),"create_hard_light")
val CREATE_LAVA = register(CreateLavaAugment(),"create_lava")
val CREATE_SPONGE = register(CreateSpongeAugment(),"create_sponge")
val CREATE_WATER = register(CreateWaterAugment(),"create_water")
val CRIPPLE = register(CrippleAugment(),"cripple")
val CURSE = register(CurseAugment(),"curse")
val DASH = register(DashAugment(),"dash")
val EMPOWERED_SLASH = register(EmpoweredSlashAugment(),"empowered_slash")
val EXCAVATE = register(ExcavateAugment(),"excavate")
val EXHAUST = register(ExhaustAugment(),"exhaust")
val FANG_BARRAGE = register(FangBarrageAugment(),"fang_barrage")
val FANGS = register(FangsAugment(),"fangs")
val FIREBALL = register(FireballAugment(),"fireball")
val FLAMEBOLT = register(FlameboltAugment(),"flamebolt")
val FLAMEWAVE = register(FlamewaveAugment(),"flamewave")
val FLARE = register(FlareAugment(),"flare")
val FORCE_FIELD = register(ForcefieldAugment(),"forcefield")
val FORTIFY = register(FortifyAugment(),"fortify")
val FROSTBOLT = register(FrostboltAugment(),"freezing")
val GUSTING = register(GustingAugment(),"gusting")
val HAMPTERTIME = register(HamptertimeAugment(),"hamptertime")
val HARD_LIGHT_BRIDGE = register(HardLightBridgeAugment(),"hard_light_bridge")
val HEALING_WIND = register(HealingWindAugment(),"healing_wind")
val ICE_SHARD = register(IceShardAugment(),"ice_shard")
val ICE_SPIKES = register(IceSpikesAugment(),"ice_spikes")
val INSPIRING_SONG = register(InspiringSongAugment(),"inspiring_song")
val LEVITATING_BULLET = register(LevitatingBulletAugment(),"levitating_bullet")
val LIGHTNING_BOLT = register(LightningBoltAugment(),"lightning_bolt")
val LIGHTNING_STORM = register(LightningStormAugment(),"lightning_storm")
val MAGNETIC_AURA = register(MagneticAuraAugment(),"magnetic_aura")
val MASS_CLEANSE = register(MassCleanseAugment(),"mass_cleanse")
val MASS_EXHAUST = register(MassExhaustAugment(),"mass_exhaust")
val MASS_FORTIFY = register(MassFortifyAugment(),"mass_fortify")
val MASS_HEAL = register(MassHealAugment(),"mass_heal")
val MASS_REVIVIFY = register(MassRevivifyAugment(),"mass_revivify")
val MEND_EQUIPMENT = register(MendEquipmentAugment(),"mend_equipment")
val MENTAL_CLARITY = register(MentalClarityAugment(),"mental_clarity")
val MINOR_HEAL = register(MinorHealAugment(),"minor_heal")
val PERSUADE = register(PersuadeAugment(),"persuade")
val POULTRYMORPH = register(PoultrymorphAugment(),"poultrymorph")
val RECALL = register(RecallAugment(),"recall")
val REGENERATE = register(RegenerateAugment(),"regenerate")
val RESONATE = register(ResonateAugment(),"resonate")
val SHINE = register(ShineAugment(),"shine")
val SMITING_BLOW = register(SmitingBlowAugment(),"smiting_blow")
val SOUL_MISSILE = register(SoulMissileAugment(),"soul_missile")
val SPECTRAL_SLASH = register(SpectralSlashAugment(),"spectral_slash")
val SUMMON_SEAHORSE = register(SummonSeahorseAugment(),"summon_seahorse")
val SUMMON_BONESTORM = register(SummonBonestormAugment(),"summon_bonestorm")
val SUMMON_CHICKEN = register(SummonChickenAugment(),"summon_chicken")
val SUMMON_FURY_TOTEM = register(SummonFuryTotemAugment(),"summon_fury_totem")
val SUMMON_GOLEM = register(SummonGolemAugment(),"summon_golem")
val SUMMON_GRACE_TOTEM = register(SummonGraceTotemAugment(),"summon_grace_totem")
val SUMMON_HAMSTER = register(SummonHamsterAugment(),"summon_hamster")
val SUMMON_ZOMBIE = register(SummonZombieAugment(),"summon_zombie")
val SURVEY = register(SurveyAugment(),"survey")
val TELEPORT = register(TeleportAugment(),"teleport")
val TORRENT_OF_BEAKS = register(TorrentOfBeaksAugment(),"torrent_of_beaks")
val WEIGHTLESSNESS = register(WeightlessnessAugment(),"weightlessness")
val WINTERS_GRASP = register(WintersGraspAugment(),"winters_grasp") //id kept as hail storm to maintain compat
val WITHERING_BOLT = register(WitheringBoltAugment(),"withering_bolt")
val ZAP = register(ZapAugment(),"zap")
val DEBUG = register(DebugAugment(),"debug")
fun registerAll(){
ModifiableEffects.init()
}
}
| 16
|
Kotlin
|
7
| 3
|
9971606dfafa9422e9558238c7783f8e27bd34a3
| 11,602
|
ai
|
MIT License
|
app/src/main/java/me/whirledsol/jsoncrypt/JsonCryptActivity.kt
|
whirledsol
| 430,240,780
| false
|
{"Kotlin": 30488, "Java": 906}
|
package me.whirledsol.jsoncrypt
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.CountDownTimer
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.WindowManager
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.tabs.TabLayout
abstract class JsonCryptActivity : AppCompatActivity(){
private var TIMEOUT_DURATION : Long = 10*60*1000 //10 min
private var TIMEOUT_WARNING_DURATION: Long = 1*60*1000 //1 min
private lateinit var _timer : CountDownTimer
private lateinit var _text_title: TextView
private lateinit var _text_version : TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//setup timeout
_timer = object : CountDownTimer(TIMEOUT_DURATION, 1000) {
override fun onTick(millisUntilFinished: Long) {
if(millisUntilFinished == TIMEOUT_DURATION - TIMEOUT_WARNING_DURATION){
Toast.makeText(this@JsonCryptActivity,"You will be logged out in ${TIMEOUT_WARNING_DURATION/1000} seconds.",
Toast.LENGTH_SHORT)
}
}
override fun onFinish() {
onClose()
}
}
//prevent screenshot
window.setFlags(WindowManager.LayoutParams.FLAG_SECURE,WindowManager.LayoutParams.FLAG_SECURE);
}
fun onCreateActionBar(showTabs: Boolean = false){
//setup elements in action bar
setSupportActionBar(findViewById(R.id.toolbar))
//title
_text_title = findViewById<TextView>(R.id.toolbar_text_title)
_text_title.setOnClickListener { view ->
onClickTitle()
}
//version
_text_version = findViewById<TextView>(R.id.toolbar_text_version)
_text_version.text = BuildConfig.VERSION_NAME
val tabLayout = findViewById<TabLayout>(R.id.tabs)
if(showTabs){
tabLayout.visibility = View.VISIBLE
}
}
fun openUrl(url: String){
//open the supplied link the browser
val i = Intent(Intent.ACTION_VIEW)
i.data = Uri.parse(url)
startActivity(i)
}
private fun onClickTitle(){
//title is clicked, so go back no matter where you are
var i = Intent(applicationContext,MainActivity::class.java)
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
startActivity(i)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return when (item.itemId) {
R.id.action_about -> {onAbout(); return true}
R.id.action_close -> {onClose(); return true}
else -> super.onOptionsItemSelected(item)
}
}
private fun onAbout(){
var i = Intent(applicationContext,AboutActivity::class.java)
startActivity(i)
}
fun onClose() {
ExitActivity.exitApplication(this@JsonCryptActivity);
}
override fun onPause() {
super.onPause()
_timer.start()
}
override fun onStop() {
super.onStop()
_timer.start()
}
override fun onResume() {
super.onResume()
_timer.cancel()
}
}
| 0
|
Kotlin
|
0
| 4
|
71e4062214c8d9a469f7ef34f62d31bf050044f8
| 3,763
|
JsonCryptApp
|
Apache License 2.0
|
app/src/main/java/com/metropolia/eatthefrog/ui/theme/Color.kt
|
metropolia-mobile-project
| 558,353,904
| false
|
{"Kotlin": 267772}
|
package com.metropolia.eatthefrog.ui.theme
import androidx.compose.ui.graphics.Color
/**
* Default Color objects used as the application's theme.
*/
val YaleBlue = Color(0xFF124191)
val YaleBlueLight = Color(0xFF6070FD)
val GreyBlue = Color(0xFF9FABC0)
val LightGray = Color(0xFFF3F3F3)
val DarkGray = Color(0xFF212121)
| 4
|
Kotlin
|
2
| 1
|
2ae0deeb9527471bd63871a5c166b155b5147f38
| 323
|
EatTheFrog
|
MIT License
|
domain/src/commonMain/kotlin/nay/kirill/healthcare/domain/useCases/ClearParamsUseCase.kt
|
kirillNay
| 695,954,274
| false
|
{"Kotlin": 69782, "HTML": 393}
|
package nay.kirill.healthcare.domain.useCases
import nay.kirill.healthcare.domain.repositories.HealthParamsRepository
class ClearParamsUseCase(
private val repository: HealthParamsRepository
) {
suspend operator fun invoke() = repository.clearParams()
}
| 0
|
Kotlin
|
0
| 0
|
b412d0013d20b3d054b20e275d2516d37927ea7a
| 265
|
GlassOfWater-client
|
MIT License
|
feature/home/src/main/kotlin/team/duckie/app/android/feature/home/viewmodel/mypage/MyPageState.kt
|
duckie-team
| 503,869,663
| false
| null |
/*
* Designed and developed by Duckie Team, 2022
*
* Licensed under the MIT.
* Please see full license: https://github.com/duckie-team/duckie-android/blob/develop/LICENSE
*/
package team.duckie.app.android.feature.home.viewmodel.mypage
import team.duckie.app.android.domain.user.model.User
import team.duckie.app.android.domain.user.model.UserProfile
import team.duckie.app.android.feature.profile.dummy.skeletonUserProfile
internal data class MyPageState(
val isLoading: Boolean = true,
val isError: Boolean = false,
val userProfile: UserProfile = skeletonUserProfile(),
val me: User? = null,
)
| 19
|
Kotlin
|
2
| 34
|
4fa7edae1fd24811ec278b0e24236c247f98dff0
| 620
|
duckie-android
|
MIT License
|
maps-api/src/main/java/com/omh/android/maps/api/presentation/interfaces/maps/OmhMap.kt
|
openmobilehub
| 602,788,589
| false
| null |
/*
* Copyright 2023 Open Mobile Hub
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.omh.android.maps.api.presentation.interfaces.maps
import android.Manifest.permission.ACCESS_COARSE_LOCATION
import android.Manifest.permission.ACCESS_FINE_LOCATION
import androidx.annotation.RequiresPermission
import com.omh.android.maps.api.presentation.models.OmhCoordinate
import com.omh.android.maps.api.presentation.models.OmhMarkerOptions
/**
* Abstraction to provide access to the OmhMap. This is the main class of OMH Maps SDK
* for Android and is the entry point for all methods related to the map.
* You cannot instantiate a GoogleMap object directly, rather,
* you must obtain one from the getMapAsync() method on a OmhMapView that you have added to your application.
*/
interface OmhMap {
/**
* Adds a marker to this map. The marker's icon is rendered on the map at the position.
*
* @param options a marker options object that defines how to render the marker.
* @return [OmhMarker] that was added to the map.
*/
fun addMarker(options: OmhMarkerOptions): OmhMarker?
/**
* Gets the camera's position.
*
* @return the position's coordinate.
*/
fun getCameraPositionCoordinate(): OmhCoordinate
/**
* Moves the camera's position to a specific position.
*
* @param coordinate the position's coordinate that the camera will be moved
* @param zoomLevel is the resolution of the current view. Zoom levels are between 0 and 18,
* But some tiles might go beyond that.
*/
fun moveCamera(coordinate: OmhCoordinate, zoomLevel: Float)
/**
* Enables or disables the zoom gestures in the map.
*
* @param enableZoomGestures true enables zoom gestures, false disables zoom gestures.
*/
fun setZoomGesturesEnabled(enableZoomGestures: Boolean)
/**
* Enables or disables the my location layer.
*
* @param enable true enables the my location layer, false disables the my location layer.
*/
@RequiresPermission(anyOf = [ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION])
fun setMyLocationEnabled(enable: Boolean)
/**
* Gets the status of the my-location layer.
*
* @return true if the my-location layer is enabled; false otherwise.
*/
fun isMyLocationEnabled(): Boolean
/**
* Sets a callback that's invoked when the my location button is clicked.
*
* @param omhOnMyLocationButtonClickListener Callback interface for when the My Location button is clicked.
*/
fun setMyLocationButtonClickListener(omhOnMyLocationButtonClickListener: OmhOnMyLocationButtonClickListener)
/**
* Sets the callback that's invoked when the camera starts moving or the reason for camera motion has changed.
*
* @param listener Callback interface for when the camera motion starts.
*/
fun setOnCameraMoveStartedListener(listener: OmhOnCameraMoveStartedListener)
/**
* Sets the callback that is invoked when the camera movement has ended.
*
* @param listener Callback interface for when camera movement has ended.
*/
fun setOnCameraIdleListener(listener: OmhOnCameraIdleListener)
}
| 4
|
Kotlin
|
0
| 0
|
2b099dc112e2d235696219ce9bf8626d6b901014
| 3,742
|
omh-maps
|
Apache License 2.0
|
src/main/kotlin/org/kirinhorse/kbt/expression/ExpError.kt
|
KirinHorse
| 674,049,029
| false
| null |
package com.xqkj.app.bigclicker.btree.expression
import org.kirinhorse.kbt.Error
import org.kirinhorse.kbt.expression.ExpOperator
import org.kirinhorse.kbt.expression.Expression
abstract class ExpError(val exp: Expression) : Error()
class ExpErrorOperator(private val opt: ExpOperator) : ExpError(opt.exp) {
override val msg get() = "表达式错误:${exp.expText}中的${opt.keyWord}: 第${opt.position}"
}
class ExpErrorUnknownSymbol(exp: Expression) : ExpError(exp) {
override val msg get() = "表达式错误:无法识别${exp.expText}"
}
| 0
|
Kotlin
|
0
| 0
|
8129e6c493b045737c3f37077279c92013d06d44
| 520
|
KotlinBehaviors
|
MIT License
|
presentation/src/main/java/com/mota/presentation/ui/screens/setting/SettingItem.kt
|
htJason98
| 421,515,876
| false
| null |
package com.mota.presentation.ui.screens.setting
import com.mota.presentation.R
sealed class SettingItem(val icon: Int, val itemName: String) {
object Groups : SettingItem(R.drawable.ic_settings_groups, "Device Groups")
object Subscription : SettingItem(R.drawable.ic_subscription, "Subscriptions")
object VoiceAssistant : SettingItem(R.drawable.ic_voice, "Voice Assistant")
object Help : SettingItem(R.drawable.ic_help, "Help")
object Shop : SettingItem(R.drawable.ic_shop, "Shop Pebblebee")
object SendLog : SettingItem(R.drawable.ic_send_log, "Send Support Data")
object PhoneSetting : SettingItem(R.drawable.ic_global, "Phone Global Setting")
}
| 0
|
Kotlin
|
0
| 0
|
94648db449f64f4ca781566cb1ea6dcce837baf5
| 679
|
jetpack-compose-map-app
|
MIT License
|
app/src/main/java/com/mobilicos/smotrofon/data/formstate/UpdateUserPasswordFormState.kt
|
Globalrunet
| 578,572,630
| false
| null |
package com.mobilicos.smotrofon.data.formstate
import com.mobilicos.smotrofon.model.Error
import com.mobilicos.smotrofon.model.Result
/**
* Data validation state of the login form.
*/
data class UpdateUserPasswordFormState(
val password: String = "",
val isDataValid: Boolean = false,
val passwordError: Int? = null
)
| 0
|
Kotlin
|
0
| 0
|
33d720706ce1a464e46c87d61c680c03e0202757
| 335
|
smotrofon
|
Apache License 2.0
|
fyno-kotlin-sdk/src/main/java/io/fyno/kotlin_sdk/FynoSdk.kt
|
fynoio
| 574,803,067
| false
|
{"Kotlin": 126915, "Java": 36422}
|
package io.fyno.kotlin_sdk
import android.content.Context
import io.fyno.callback.FynoCallback
import io.fyno.callback.models.MessageStatus
import io.fyno.core.FynoCore
import io.fyno.core.utils.LogLevel
import io.fyno.pushlibrary.FynoPush
import io.fyno.pushlibrary.models.PushRegion
//import io.sentry.Sentry
//import io.sentry.protocol.User
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
public object FynoSdk {
fun initialize(
context: Context,
workspaceId: String,
token: String,
userId: String? = null,
version: String = "live"
) {
runBlocking {
CoroutineScope(Dispatchers.IO).launch {
FynoCore.initialize(context, workspaceId, token, version)
userId?.let {
FynoCore.identify(uniqueId = it, update = true)
// Sentry.configureScope {
// val user = User()
// user.id = userId
// it.user = user
// }
}
}
}
}
fun updateStatus(context: Context, callback_url: String, status: MessageStatus) {
FynoCallback().updateStatus(context,callback_url,status)
}
fun registerPush(
xiaomiApplicationId: String? = "",
xiaomiApplicationKey: String? = "",
pushRegion: PushRegion? = PushRegion.INDIA,
integrationId: String = ""
) {
FynoPush().registerPush(
xiaomiApplicationId,
xiaomiApplicationKey,
pushRegion,
integrationId
)
}
fun identify(uniqueId: String, userName: String? = null) {
runBlocking {
CoroutineScope(Dispatchers.IO).launch {
FynoCore.identify(uniqueId, userName, true)
}
}
}
fun resetUser() {
runBlocking {
CoroutineScope(Dispatchers.IO).launch {
FynoCore.resetUser()
}
}
}
fun resetConfig() {
FynoCore.resetConfig()
}
fun saveConfig(wsId: String, apiKey: String, fcmIntegration: String, miIntegration: String) {
FynoCore.saveConfig(wsId, apiKey, fcmIntegration, miIntegration)
}
fun setLogLevel(level: LogLevel) {
FynoCore.setLogLevel(level)
}
fun mergeProfile(oldDistinctId: String, newDistinctId: String) {
runBlocking {
CoroutineScope(Dispatchers.IO).launch {
FynoCore.mergeProfile(oldDistinctId, newDistinctId)
}
}
}
}
| 0
|
Kotlin
|
0
| 1
|
25640964c2aff113318d0e138dd10924e5d688fa
| 2,676
|
kotlin-sdk
|
MIT License
|
app/src/main/java/com/rushadvisualexpressions/sudokuyoutube/view/PlaySudokuActivity.kt
|
rupeshbhurke
| 246,276,076
| false
| null |
package com.rushadvisualexpressions.sudokuyoutube.view
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import com.rushadvisualexpressions.sudokuyoutube.R
import com.rushadvisualexpressions.sudokuyoutube.game.Cell
import com.rushadvisualexpressions.sudokuyoutube.view.custom.SudokuBoardView.OnTouchListener
import com.rushadvisualexpressions.sudokuyoutube.viewmodel.PlaySudokuViewModel
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.activity_main.view.*
class PlaySudokuActivity : AppCompatActivity(), OnTouchListener {
private lateinit var viewModel : PlaySudokuViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
sudokuBoardView.registerListener(this)
viewModel = ViewModelProviders.of(this).get(PlaySudokuViewModel::class.java)
viewModel.sudokuGame.selectedCellLiveData.observe( this, Observer { updateSelectedCellUI(it) })
viewModel.sudokuGame.cellLiveData.observe( this, Observer { updateCells(it) })
val buttons = listOf( oneButton, twoButton, threeButton, fourButton, fiveButton,
sixButton, sevenButton, eightButton, nineButton)
buttons.forEachIndexed { index, button ->
button.setOnClickListener {viewModel.sudokuGame.handleInput(index + 1) }
}
}
private fun updateCells(cells: List<Cell>?) = cells?.let{
sudokuBoardView.updateCells(cells)
}
private fun updateSelectedCellUI(cell: Pair<Int, Int>?) = cell?.let {
sudokuBoardView.updateSelectedCellUI( cell.first, cell.second)
}
override fun onCellTouched(row: Int, col: Int) {
viewModel.sudokuGame.updateSelectedCell(row, col)
}
}
| 0
|
Kotlin
|
0
| 0
|
b3cc3ef62f2c008a29ba7ea11eb9d71f207cfbdf
| 1,926
|
SudokuYoutube
|
MIT License
|
app/src/main/java/com/example/climby/data/model/message/MessageModel.kt
|
JavierGF1991
| 431,588,749
| false
| null |
package com.example.climby.data.model.message
import android.os.Parcel
import android.os.Parcelable
import com.example.climby.data.model.user.UserModel
import com.google.gson.annotations.SerializedName
data class MessageModel(
@SerializedName("read") val read: Boolean?,
@SerializedName("text") val text: String?
) : Parcelable {
constructor(parcel: Parcel) : this(
parcel.readValue(Boolean::class.java.classLoader) as? Boolean,
parcel.readString(),
)
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeValue(read)
parcel.writeString(text)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<MessageModel> {
override fun createFromParcel(parcel: Parcel): MessageModel {
return MessageModel(parcel)
}
override fun newArray(size: Int): Array<MessageModel?> {
return arrayOfNulls(size)
}
}
}
| 0
|
Kotlin
|
0
| 1
|
53c65467ed8e8eb3d798ab657d8881ac2ab3a130
| 997
|
climby_app
|
RSA Message-Digest License
|
src/main/kotlin/pullrequest/checker/MergedPullRequestChecker.kt
|
clemens-code
| 385,173,945
| false
| null |
package io.github.clemenscode.bitbucketwatcher.pullrequest.checker
import feign.FeignException
import io.github.clemenscode.bitbucketwatcher.branches.BranchDeleter
import io.github.clemenscode.bitbucketwatcher.client.builder.PullRequestMessages
import io.github.clemenscode.bitbucketwatcher.logger.getLogger
import io.github.clemenscode.bitbucketwatcher.model.PullRequest
import io.github.clemenscode.bitbucketwatcher.notificator.PullRequestNotificator
import org.springframework.stereotype.Component
@Component
internal class MergedPullRequestChecker(
private val pullRequestMessages: PullRequestMessages,
private val deleter: BranchDeleter,
private val notificator: PullRequestNotificator
) {
private val logger = getLogger(MergedPullRequestChecker::class.java)
fun publishMergedPullRequests(
publishedPRs: MutableMap<String, PullRequest>,
mergedPullRequests: List<PullRequest>
): MutableMap<String, PullRequest> {
mergedPullRequests
.forEach {
if (publishedPRs[it.id] != null) {
logger.info("Merged ${it.title} sending it to teams")
try {
deleter.deleteBranch(it.branchId)
} catch (e: FeignException) {
logger.warn("Could not delete Branch of merged PR ${it.title}", e)
}
notificator.publish(pullRequestMessages.mergedPRMessage(it))
publishedPRs.remove(it.id)
}
}
return publishedPRs
}
}
| 2
|
Kotlin
|
0
| 4
|
b0a6105d173dee549235691fb71f7faef2acc130
| 1,578
|
bitbucketwatcher
|
MIT License
|
src/main/kotlin/io/github/kryszak/gwatlin/api/characters/model/character/CharacterCore.kt
|
Kryszak
| 214,791,260
| false
|
{"Kotlin": 443350, "Shell": 654}
|
package io.github.kryszak.gwatlin.api.characters.model.character
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
/**
* Data model for core character infos
*/
@Serializable
data class CharacterCore(
val name: String,
val race: String,
val gender: String,
val profession: String,
val level: Int,
val guild: String,
val age: Int,
val created: String,
@SerialName("last_modified")
val lastModified: String,
val deaths: Int,
val title: Int
)
| 1
|
Kotlin
|
1
| 6
|
e2a2047e9644a7d27183a98cd28a96844b338232
| 523
|
gwatlin
|
MIT License
|
networking/src/main/java/com/mobile_pablo/networking/interceptor/RequestInterceptor.kt
|
mobile-pablo
| 669,791,669
| false
| null |
package com.mobile_pablo.networking.interceptor
import com.mobile_pablo.core.util.EMPTY_STRING
import okhttp3.Interceptor
import okhttp3.Protocol
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody
import java.net.HttpURLConnection
import java.net.SocketTimeoutException
import java.net.UnknownHostException
class RequestInterceptor : Interceptor {
companion object {
private const val USER_AGENT = "User-Agent"
private const val ANDROID = "Android"
}
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
return try {
val requestBuilder = request.newBuilder()
.addHeader(USER_AGENT, ANDROID)
chain.proceed(requestBuilder.build())
} catch (timeout: SocketTimeoutException) {
Response.Builder()
.request(request)
.protocol(Protocol.HTTP_2)
.code(HttpURLConnection.HTTP_CLIENT_TIMEOUT)
.body(EMPTY_STRING.toResponseBody())
.message("SocketTimeout ${timeout.message}")
.build()
} catch (unknown: UnknownHostException) {
Response.Builder()
.request(request)
.protocol(Protocol.HTTP_2)
.code(HttpURLConnection.HTTP_UNAVAILABLE)
.body(EMPTY_STRING.toResponseBody())
.message("Unknown ${unknown.message}")
.build()
} catch (ex: Exception) {
Response.Builder()
.request(request)
.protocol(Protocol.HTTP_2)
.code(HttpURLConnection.HTTP_INTERNAL_ERROR)
.body(EMPTY_STRING.toResponseBody())
.message("Exception ${ex.message}")
.build()
}
}
}
| 0
|
Kotlin
|
0
| 0
|
eb649bf0b7cc5f0dd420a933a9a36c0b4f95913a
| 1,842
|
Youtube_-_TV
|
MIT License
|
networking/src/main/java/com/mobile_pablo/networking/interceptor/RequestInterceptor.kt
|
mobile-pablo
| 669,791,669
| false
| null |
package com.mobile_pablo.networking.interceptor
import com.mobile_pablo.core.util.EMPTY_STRING
import okhttp3.Interceptor
import okhttp3.Protocol
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody
import java.net.HttpURLConnection
import java.net.SocketTimeoutException
import java.net.UnknownHostException
class RequestInterceptor : Interceptor {
companion object {
private const val USER_AGENT = "User-Agent"
private const val ANDROID = "Android"
}
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
return try {
val requestBuilder = request.newBuilder()
.addHeader(USER_AGENT, ANDROID)
chain.proceed(requestBuilder.build())
} catch (timeout: SocketTimeoutException) {
Response.Builder()
.request(request)
.protocol(Protocol.HTTP_2)
.code(HttpURLConnection.HTTP_CLIENT_TIMEOUT)
.body(EMPTY_STRING.toResponseBody())
.message("SocketTimeout ${timeout.message}")
.build()
} catch (unknown: UnknownHostException) {
Response.Builder()
.request(request)
.protocol(Protocol.HTTP_2)
.code(HttpURLConnection.HTTP_UNAVAILABLE)
.body(EMPTY_STRING.toResponseBody())
.message("Unknown ${unknown.message}")
.build()
} catch (ex: Exception) {
Response.Builder()
.request(request)
.protocol(Protocol.HTTP_2)
.code(HttpURLConnection.HTTP_INTERNAL_ERROR)
.body(EMPTY_STRING.toResponseBody())
.message("Exception ${ex.message}")
.build()
}
}
}
| 0
|
Kotlin
|
0
| 0
|
eb649bf0b7cc5f0dd420a933a9a36c0b4f95913a
| 1,842
|
Youtube_-_TV
|
MIT License
|
app/src/main/java/com/bluewhaleyt/whaleutils/activity/ChatActivity.kt
|
BlueWhaleYT
| 665,099,127
| false
| null |
package com.bluewhaleyt.whaleutils.activity
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.bluewhaleyt.design.widget.recyclerview.adapter.AdapterCallback
import com.bluewhaleyt.design.widget.recyclerview.adapter.CustomAdapter
import com.bluewhaleyt.whaleutils.R
import com.bluewhaleyt.whaleutils.databinding.ActivityChatBinding
import java.util.Date
data class Message(val message: String, val sender: String)
data class Timestamp(val time: Long)
object ViewType {
const val MESSAGE: Int = 0
const val TIMESTAMP: Int = 1
}
class ChatActivity : AppCompatActivity() {
private lateinit var binding: ActivityChatBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityChatBinding.inflate(layoutInflater)
setContentView(binding.root)
val adapter = CustomAdapter<Any>(this)
adapter.addViewType(ViewType.MESSAGE, R.layout.layout_list_item_1)
adapter.addViewType(ViewType.TIMESTAMP, R.layout.layout_chat_timestamp)
adapter.setCallback(object : AdapterCallback<Any> {
override fun getItemViewType(data: Any, itemIndex: Int): Int {
return when (data) {
is Message -> ViewType.MESSAGE
is Timestamp -> ViewType.TIMESTAMP
else -> throw IllegalArgumentException("Invalid item type")
}
}
override fun onCreateView(itemView: View, data: Any, itemIndex: Int) {
when (data) {
is Message -> {
val tvSender = itemView.findViewById<TextView>(R.id.tv_text_1)
val tvMessage = itemView.findViewById<TextView>(R.id.tv_text_2)
tvSender.text = data.sender
tvMessage.text = data.message
}
is Timestamp -> {
val tvTime = itemView.findViewById<TextView>(R.id.tv_timestamp)
tvTime.apply {
val stamp = Timestamp(data.time)
val date = Date(stamp.time)
text = date.toString()
setTextColor(Color.GRAY)
}
}
}
}
})
val chatItems: List<Any> = listOf(
Timestamp(1085347200L),
Message("Hello", "John"),
Timestamp(1685347200L),
Message("How are you?", "John"),
Message("I'm good. Thanks!", "Alice"),
)
binding.rvChat.setAdapter(adapter, chatItems)
}
}
| 0
|
Kotlin
|
0
| 1
|
24cad14d625908cb4d22a73e9ce07db40327d346
| 2,804
|
WhaleUtils
|
MIT License
|
src/main/kotlin/me/alejandrorm/klosure/sparql/algebra/filters/operators/LiteralExpression.kt
|
alejandrorm
| 512,041,126
| false
|
{"Kotlin": 196720, "Ruby": 28544, "HTML": 25737}
|
package me.alejandrorm.klosure.sparql.algebra.filters.operators
import me.alejandrorm.klosure.model.Graph
import me.alejandrorm.klosure.model.Graphs
import me.alejandrorm.klosure.model.NodeId
import me.alejandrorm.klosure.sparql.SolutionMapping
import me.alejandrorm.klosure.sparql.algebra.aggregates.NonAggregateExpression
class LiteralExpression(val id: NodeId) : NonAggregateExpression {
override fun eval(solution: SolutionMapping, activeGraph: Graph, graphs: Graphs): NodeId {
return id
}
override fun toString(): String {
return id.toString()
}
}
| 0
|
Kotlin
|
0
| 0
|
14abf426f3cad162c021ffae750038e25b8cb271
| 588
|
klosure
|
Apache License 2.0
|
core/src/main/kotlin/com/wafflestudio/snuttev/core/domain/lecture/dto/LectureResponse.kt
|
wafflestudio
| 379,143,639
| false
|
{"Kotlin": 172741, "Dockerfile": 229}
|
package com.wafflestudio.snuttev.core.domain.lecture.dto
import com.wafflestudio.snuttev.core.common.type.LectureClassification
import com.wafflestudio.snuttev.core.domain.evaluation.dto.SemesterLectureDto
data class LectureDto(
val id: Long,
val title: String?,
val instructor: String?,
val department: String?,
val courseNumber: String?,
val credit: Int?,
val academicYear: String?,
val category: String?,
val classification: LectureClassification?,
val evaluation: LectureEvaluationSimpleSummary,
)
data class LectureEvaluationSimpleSummary(
val avgRating: Double?,
)
data class LectureAndSemesterLecturesResponse(
val id: Long,
val title: String?,
val instructor: String?,
val department: String?,
val courseNumber: String?,
val credit: Int?,
val academicYear: String?,
val category: String?,
val classification: LectureClassification?,
val semesterLectures: List<SemesterLectureDto>,
)
data class LectureIdResponse(
// FIXME: evLectureId로 대체되므로 삭제 (evLectureId 생성: 2024-04-14)
val id: Long,
val snuttId: String? = null,
val evLectureId: Long = id,
)
data class LectureTakenByUserResponse(
val id: Long,
val title: String?,
val instructor: String?,
val department: String?,
val courseNumber: String?,
val credit: Int?,
val academicYear: String?,
val category: String?,
val classification: LectureClassification?,
val takenYear: Int,
val takenSemester: Int,
)
data class EvLectureSummaryForSnutt(
val snuttId: String,
val evLectureId: Long,
val avgRating: Double?,
)
| 0
|
Kotlin
|
2
| 4
|
255c6dea41eb3d1d49ff2b9dfaabec082f0ca66f
| 1,633
|
snutt-ev
|
MIT License
|
examples/networking/impl/src/main/java/com/squareup/invert/examples/LiveNetworkUserRepo.kt
|
square
| 789,061,154
| false
|
{"Kotlin": 369133, "JavaScript": 4120, "HTML": 1882, "CSS": 1113, "Shell": 878}
|
package com.squareup.invert.examples
import com.squareup.invert.examples.models.LoginRequest
import com.squareup.invert.examples.models.NetworkConfig
import com.squareup.invert.examples.models.User
import com.squareup.invert.examples.network.Response
import com.squareup.invert.examples.repository.UserRepo
import com.squareup.anvil.annotations.ContributesBinding
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.request.*
import io.ktor.http.*
import com.squareup.invert.examples.scopes.AppScope
import javax.inject.Inject
@ContributesBinding(AppScope::class)
class LiveNetworkUserRepo @Inject constructor(
private val networkConfig: NetworkConfig,
private val ktorClient: HttpClient,
) : UserRepo {
override suspend fun login(loginRequest: LoginRequest): Response<User> {
val response = ktorClient.request("${networkConfig.fullUrl}login") {
method = HttpMethod.Post
contentType(ContentType.Application.Json)
accept(ContentType.Application.Json)
setBody(loginRequest)
}
if (response.status == HttpStatusCode.OK) {
val user = response.body<User>()
return Response.Success(user)
}
return Response.Failure()
}
}
| 4
|
Kotlin
|
0
| 82
|
31b1859a5b9b49553068a4da6ada5de2fe9d82ac
| 1,269
|
invert
|
Apache License 2.0
|
android-sdk/src/main/java/webtrekk/android/sdk/module/DependencyModule.kt
|
acamarinkovic
| 198,233,644
| true
|
{"Kotlin": 209891, "Java": 7560}
|
/*
* MIT License
*
* Copyright (c) 2019 Webtrekk GmbH
*
* 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 NON INFRINGEMENT. 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 webtrekk.android.sdk.module
import org.koin.dsl.module.module
import webtrekk.android.sdk.core.Scheduler
import webtrekk.android.sdk.core.Sessions
import webtrekk.android.sdk.api.datasource.SyncRequestsDataSource
import webtrekk.android.sdk.api.datasource.SyncRequestsDataSourceImpl
import webtrekk.android.sdk.data.entity.DataTrack
import webtrekk.android.sdk.data.repository.CustomParamRepository
import webtrekk.android.sdk.data.repository.CustomParamRepositoryImpl
import webtrekk.android.sdk.data.repository.TrackRequestRepository
import webtrekk.android.sdk.data.repository.TrackRequestRepositoryImpl
import webtrekk.android.sdk.core.SchedulerImpl
import webtrekk.android.sdk.core.SessionsImpl
import webtrekk.android.sdk.domain.internal.CacheTrackRequestWithCustomParams
import webtrekk.android.sdk.domain.internal.CacheTrackRequest
import webtrekk.android.sdk.domain.internal.ExecuteRequest
import webtrekk.android.sdk.domain.internal.GetCachedDataTracks
import webtrekk.android.sdk.domain.internal.ClearTrackRequests
internal val dataModule = module {
single<TrackRequestRepository> {
TrackRequestRepositoryImpl(
get()
)
}
single<CustomParamRepository> {
CustomParamRepositoryImpl(
get()
)
}
single<SyncRequestsDataSource<DataTrack>> {
SyncRequestsDataSourceImpl(
get()
)
}
}
internal val internalInteractorsModule = module {
single<Sessions> { SessionsImpl(get()) }
single<Scheduler> { SchedulerImpl(get()) }
factory { CacheTrackRequest(get()) }
factory { GetCachedDataTracks(get()) }
factory { CacheTrackRequestWithCustomParams(get(), get()) }
factory { ExecuteRequest(get(), get()) }
factory { ClearTrackRequests(get()) }
}
| 0
|
Kotlin
|
0
| 0
|
ec8c385b329921d9f027545f405da86ef3346e84
| 2,942
|
webtrekk-android-sdk-BETA
|
MIT License
|
androidApp/src/main/java/com/jetbrains/kmm/androidApp/main/MainActivity.kt
|
MarcFelip
| 606,124,769
| false
| null |
package com.jetbrains.kmm.androidApp.main
import android.annotation.SuppressLint
import kotlinx.coroutines.*
import android.content.Intent
import android.graphics.Bitmap
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.ImageButton
import android.widget.ImageView
import androidx.compose.runtime.Composable
import androidx.compose.runtime.livedata.observeAsState
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.jetbrains.androidApp.R
import com.jetbrains.kmm.androidApp.addProject.AddProjectActivity
import com.jetbrains.kmm.androidApp.main.adapter.ProjectAdapter
import com.jetbrains.kmm.androidApp.profile.ProfileActivity
import com.jetbrains.kmm.androidApp.project.ProjectActivity
import com.jetbrains.kmm.shared.Models
class MainActivity : AppCompatActivity(), ProjectAdapter.onClickListener {
private val CAMERA_REQUEST_CODE = 1
private lateinit var image_view: ImageView
private var image: Bitmap? = null
private lateinit var final_image: Bitmap
private lateinit var viewModel: MainViewModel
private lateinit var projectsAdapter: ProjectAdapter
private var loadedProjects: List<Models.Projects> = emptyList()
@SuppressLint("MissingInflatedId")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val user_button: ImageButton = findViewById(R.id.btn_profile)
val new_project_button: Button = findViewById(R.id.btn_new_project)
viewModel = ViewModelProvider(this).get(MainViewModel::class.java)
user_button.setOnClickListener{
val intent = Intent(this@MainActivity, ProfileActivity::class.java)
startActivity(intent)
}
new_project_button.setOnClickListener{
val intent = Intent(this@MainActivity, AddProjectActivity::class.java)
startActivity(intent)
}
lifecycleScope.launch{
initRecyclerView()
}
}
private suspend fun initRecyclerView(){
loadedProjects = viewModel.loadProjects()
val listProjects = loadedProjects.map { project ->
Projects(
name = project.name ?: "",
data = project.data ?: ""
)
}
val recyclerView = findViewById<RecyclerView>(R.id.projets_recyclerView)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = ProjectAdapter(listProjects, this@MainActivity)
}
override fun onClick(position: Int) {
val project_show = loadedProjects[position]
val intent = Intent(this@MainActivity, ProjectActivity::class.java)
val bundle = Bundle().apply {
//putString("projectId", project_show._id.toString())
putString("projectId", project_show.projectId.toString())
putString("name", project_show.name.toString())
putString("data", project_show.data.toString())
putString("userId", project_show.userId.toString())
putString("location", project_show.location.toString())
putString("variety", project_show.variety.toString())
}
intent.putExtras(bundle)
startActivity(intent)
}
}
| 0
|
Kotlin
|
1
| 0
|
0430abd3abf9939636aa8aa47c250ac98b06ce97
| 3,506
|
TFM-MarcFelip
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.