path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
src/main/kotlin/lmr/rcd/models/entity/Entity.kt
halgorithm
256,116,377
false
null
package lmr.rcd.models.entity abstract class Entity constructor(override var data: RcdObjectData) : EntityInterface { override val _id = generateId() // REVIEW: does this id get cached? override var parent: Any? = null override val typeId get() = data.typeId override val params get() = data.params override val tests get() = data.tests override val updates get() = data.updates override fun _attachTo(obj: Any) { parent = obj } override fun _detach() { parent = null } private companion object { private var nextId = 0; fun generateId(): Int = nextId++ } }
0
Kotlin
0
0
195af71e8794a0867598675dbacb39eae7f20bc5
621
lmr-rcd-kt
Boost Software License 1.0
buildSrc/src/main/java/Accompanist.kt
VictorHVS
463,924,761
false
{"Kotlin": 76744}
object Accompanist { private const val accompanistVersion = "0.23.0" const val animations = "com.google.accompanist:accompanist-navigation-animation:$accompanistVersion" const val pager = "com.google.accompanist:accompanist-pager:$accompanistVersion" const val pagerIndicators = "com.google.accompanist:accompanist-pager-indicators:$accompanistVersion" const val swipeRefresh = "com.google.accompanist:accompanist-swiperefresh:$accompanistVersion" const val systemUIController = "com.google.accompanist:accompanist-systemuicontroller:$accompanistVersion" }
0
Kotlin
0
4
813760b9186a59431ba757a0d20f572a9892c0ae
581
rat-cinema
Apache License 2.0
haze/src/androidMain/kotlin/dev/chrisbanes/haze/Platform.kt
chrisbanes
710,434,447
false
{"Kotlin": 74749, "Shell": 1077}
// Copyright 2023, Christopher Banes and the Haze project contributors // SPDX-License-Identifier: Apache-2.0 package dev.chrisbanes.haze import androidx.compose.ui.geometry.Offset import androidx.compose.ui.node.CompositionLocalConsumerModifierNode import androidx.compose.ui.node.currentValueOf import androidx.compose.ui.platform.LocalView import kotlin.concurrent.getOrSet internal actual fun createHazeNode( state: HazeState, style: HazeStyle, ): HazeNode = AndroidHazeNode(state, style) internal actual fun CompositionLocalConsumerModifierNode.calculateWindowOffset(): Offset { val view = currentValueOf(LocalView) val loc = tmpArray.getOrSet { IntArray(2) } view.getLocationOnScreen(loc) return Offset(loc[0].toFloat(), loc[1].toFloat()) } private val tmpArray = ThreadLocal<IntArray>()
6
Kotlin
23
842
bf015a42d3572d47391af819aac07894ffc4b63f
811
haze
Apache License 2.0
domain/src/main/java/app/cookery/domain/observers/ObserveAreas.kt
skorudzhiev
356,818,469
false
null
package app.cookery.domain.observers import app.cookery.data.entities.categories.Area import app.cookery.domain.SubjectInteractor import app.cookery.repositories.categories.CategoriesRepository import kotlinx.coroutines.flow.Flow import javax.inject.Inject class ObserveAreas @Inject constructor( private val repository: CategoriesRepository ) : SubjectInteractor<ObserveAreas.Params, List<Area>>() { override fun createObservable(params: Params): Flow<List<Area>> { return repository.observeAreaMeals() } data class Params(val area: String? = null) }
3
Kotlin
0
2
1c8b3bdf78be34fab2b2e79d293e8993c98b898c
580
Cookery
Apache License 2.0
straight/src/commonMain/kotlin/me/localx/icons/straight/bold/EyeDropperHalf.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.bold 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.Bold.EyeDropperHalf: ImageVector get() { if (_eyeDropperHalf != null) { return _eyeDropperHalf!! } _eyeDropperHalf = Builder(name = "EyeDropperHalf", 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(22.902f, 1.099f) curveToRelative(-1.417f, -1.419f, -3.887f, -1.415f, -5.303f, 0.0f) lineToRelative(-2.486f, 2.486f) curveToRelative(-1.338f, 1.338f, -3.462f, 1.366f, -4.837f, 0.07f) lineToRelative(-2.09f, 2.151f) lineToRelative(2.175f, 2.175f) lineTo(2.172f, 16.172f) curveToRelative(-1.185f, 1.185f, -1.469f, 2.933f, -0.854f, 4.389f) lineToRelative(-1.318f, 1.318f) lineToRelative(2.121f, 2.121f) lineToRelative(1.316f, -1.316f) curveToRelative(0.488f, 0.207f, 1.017f, 0.316f, 1.563f, 0.316f) curveToRelative(1.068f, 0.0f, 2.073f, -0.416f, 2.828f, -1.172f) lineToRelative(8.189f, -8.189f) lineToRelative(2.175f, 2.176f) lineToRelative(2.152f, -2.09f) curveToRelative(-1.297f, -1.375f, -1.266f, -3.501f, 0.071f, -4.838f) lineToRelative(2.486f, -2.486f) curveToRelative(0.708f, -0.708f, 1.098f, -1.649f, 1.098f, -2.651f) reflectiveCurveToRelative(-0.39f, -1.942f, -1.098f, -2.65f) close() moveTo(10.414f, 15.0f) horizontalLineToRelative(-2.828f) lineToRelative(4.896f, -4.897f) lineToRelative(1.414f, 1.414f) lineToRelative(-3.483f, 3.482f) close() moveTo(20.781f, 4.279f) lineToRelative(-2.487f, 2.486f) curveToRelative(-0.904f, 0.905f, -1.488f, 2.003f, -1.749f, 3.158f) lineToRelative(-2.468f, -2.468f) curveToRelative(1.154f, -0.262f, 2.252f, -0.846f, 3.157f, -1.75f) lineToRelative(2.487f, -2.486f) curveToRelative(0.191f, -0.191f, 0.414f, -0.22f, 0.53f, -0.22f) reflectiveCurveToRelative(0.339f, 0.028f, 0.53f, 0.22f) curveToRelative(0.191f, 0.191f, 0.219f, 0.414f, 0.219f, 0.529f) curveToRelative(0.0f, 0.116f, -0.028f, 0.339f, -0.219f, 0.53f) close() } } .build() return _eyeDropperHalf!! } private var _eyeDropperHalf: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,426
icons
MIT License
app/src/main/java/com/tec/mvvm_notesapp/models/Notes.kt
aniketsen123
598,490,439
false
null
package com.tec.mvvm_notesapp.models import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import java.io.Serializable @Entity(tableName = "notes_table") data class Notes( @PrimaryKey(autoGenerate = true) val id: Int?, @ColumnInfo(name = "title") val title: String?, @ColumnInfo(name = "subtitle") val subtitle: String?, @ColumnInfo(name = "note") val note: String?, @ColumnInfo(name = "date") val date: String? ) : Serializable { }
9
Kotlin
16
0
b8bab2ed163788a426fcccc154f6971c7c29973e
493
MVVM_notesapp
MIT License
sharedUi/src/main/java/com/example/sharedui/x/Shared.kt
Bit-Camp-IO
643,303,285
false
null
package com.example.sharedui.x 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.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.GenericShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Divider import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import androidx.navigation.NavController import com.example.sharedui.R import com.example.sharedui.colors.BlackTransparent37 import com.example.sharedui.colors.PineGreenLight import com.example.sharedui.colors.WhiteTransparent60 fun mainShape(cornerRadiusDegree: Float = 60f, slopeLength: Float = 50f) = GenericShape { size, _ -> fun getSlopeDistance(y: Float): Float { val transitionUnit = slopeLength / size.height return transitionUnit * y } moveTo(slopeLength + cornerRadiusDegree, 0f) lineTo(size.width - cornerRadiusDegree, 0f) quadraticBezierTo( size.width, 0f, size.width - getSlopeDistance(cornerRadiusDegree), cornerRadiusDegree ) lineTo( size.width - getSlopeDistance(size.height - cornerRadiusDegree), size.height - cornerRadiusDegree ) quadraticBezierTo( size.width - slopeLength, size.height, size.width - getSlopeDistance(size.height) - cornerRadiusDegree, size.height ) lineTo(cornerRadiusDegree, size.height) quadraticBezierTo( 0f, size.height, getSlopeDistance(cornerRadiusDegree), size.height - cornerRadiusDegree ) lineTo(getSlopeDistance(size.height - cornerRadiusDegree), cornerRadiusDegree) quadraticBezierTo( slopeLength, 0f, cornerRadiusDegree + getSlopeDistance(size.height), 0f ) close() } @Composable fun AppToolBar( modifier: Modifier = Modifier, title: String="", navController: NavController, suffixIcon: @Composable () -> Unit ) { Row( modifier = modifier .fillMaxWidth() .padding(horizontal = 24.dp, vertical = 24.dp), horizontalArrangement = Arrangement.SpaceBetween ) { Row(verticalAlignment = Alignment.CenterVertically) { IconButton( modifier = Modifier .background(color = BlackTransparent37, shape = RoundedCornerShape(8.dp)) .size(40.dp, 40.dp), onClick = {navController.popBackStack() }, content = { Icon( painter = painterResource(id = R.drawable.ic_arrow_back), contentDescription = "Back Button", tint = WhiteTransparent60 ) }) Spacer(modifier = Modifier.width(16.dp)) Text(text = title, style = MaterialTheme.typography.titleLarge) } suffixIcon() } } @Composable fun BackGround() { Box( modifier = Modifier.background(Color.Red) ) { Image( painter = painterResource(id = R.drawable.back_ground), alignment = Alignment.TopStart, contentDescription = null, contentScale = ContentScale.FillWidth, modifier = Modifier .fillMaxSize() ) } } @Composable fun DividerTitle(title:String){ Row(Modifier.padding(bottom = 16.dp)) { Spacer(modifier = Modifier.width(24.dp)) Divider(Modifier.size(5.dp, 20.dp), color = PineGreenLight) Spacer(modifier = Modifier.width(8.dp)) Text(text = title) } }
0
Kotlin
1
2
82141ba5d053fe9c3112d1150b226aceb6125a48
4,500
TMDA-Android
Apache License 2.0
src/main/kotlin/dataModels/UnknownEntity.kt
kirilenkobm
668,817,148
false
null
package dataModels class UnknownEntity(override val path: String): FileSystemEntity
0
Kotlin
0
0
f12dc4ad0a0f3783b86b3e5b27020eb9abc2206b
85
DirExplorer
Apache License 2.0
src/test/kotlin/com/github/hanseter/json/editor/base/TestUtils.kt
Hanseter
265,563,400
false
null
package com.github.hanseter.json.editor.base import com.sun.javafx.robot.FXRobot import javafx.scene.input.KeyCode import org.controlsfx.control.SearchableComboBox import org.json.JSONObject import org.json.JSONTokener import java.nio.file.Files import java.nio.file.Paths import java.util.stream.Collectors object TestUtils { fun loadSchema(schemaName: String) = JSONObject(JSONTokener(this::class.java.classLoader.getResourceAsStream(schemaName))) fun getAllSchemas(): List<String> { val basePath = Paths.get(this::class.java.classLoader.getResource("")!!.toURI()) ?: return emptyList() return Files.walk(basePath) .filter { Files.isRegularFile(it) && it.toFile().extension == "json" } .map { basePath.relativize(it).toString() }.collect(Collectors.toList()) } fun createSchemaComboBox() = SearchableComboBox<String>().apply { items.addAll(getAllSchemas()) } }
1
Kotlin
2
2
7b17ae30c87fbf03d8a6b3e28eb5a504299df8da
953
JSONPropertyEditorFx
MIT License
feature-staking-impl/src/main/java/jp/co/soramitsu/staking/impl/presentation/staking/rebond/confirm/ConfirmRebondPayload.kt
soramitsu
278,060,397
false
null
package jp.co.soramitsu.staking.impl.presentation.staking.rebond.confirm import android.os.Parcelable import kotlinx.parcelize.Parcelize import java.math.BigDecimal @Parcelize class ConfirmRebondPayload( val amount: BigDecimal, val collatorAddress: String? ) : Parcelable
15
null
30
89
812c6ed5465d19a0616865cbba3e946d046720a1
282
fearless-Android
Apache License 2.0
kotlin/app/src/main/java/com/huawei/iap/adapters/ProductsListAdapter.kt
huaweicodelabs
276,520,763
false
null
/** * Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.huawei.iap.adapters import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.ViewHolder import com.huawei.iap.R import com.huawei.iap.adapters.ProductsListAdapter.MyViewHolder import com.huawei.iap.callbacks.ProductItemClick import com.huawei.iap.models.ProductsListModel import kotlinx.android.synthetic.main.item_productslist.view.* class ProductsListAdapter(var names: List<ProductsListModel>,private val productItemClick: ProductItemClick) : RecyclerView.Adapter<MyViewHolder>() { override fun getItemViewType(position: Int): Int { return position } override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): MyViewHolder { val itemView = LayoutInflater.from(viewGroup.context) .inflate(R.layout.item_productslist, viewGroup, false) return MyViewHolder(itemView) } override fun onBindViewHolder(myViewHolder: MyViewHolder, i: Int) { myViewHolder.bindItems(names[i]) } override fun getItemCount(): Int { return if (names == null) 0 else names.size } override fun getItemId(position: Int): Long { return position.toLong() } inner class MyViewHolder(itemView: View) : ViewHolder(itemView) { fun bindItems(productModel: ProductsListModel){ productModel?.let { productDetails ->{ itemView.item_name.text = productModel.name itemView.item_price.text = productModel.price itemView.item_image.setImageResource(productModel.image) } } itemView.setOnClickListener { productItemClick.onClick(productModel) } } } }
2
null
5
7
a9cd7994c1ec51f0788e5f4b335ce797e9815861
2,542
IAP
Apache License 2.0
src/main/kotlin/io/testaxis/backend/models/Build.kt
testaxis
301,692,798
false
null
package io.testaxis.backend.models import com.fasterxml.jackson.annotation.JsonIgnore import org.springframework.data.annotation.CreatedDate import org.springframework.data.annotation.LastModifiedDate import java.util.Date import javax.persistence.CascadeType import javax.persistence.Entity import javax.persistence.FetchType import javax.persistence.JoinColumn import javax.persistence.ManyToOne import javax.persistence.OneToMany @Entity class Build( @ManyToOne @JoinColumn(name = "project_id", nullable = false) var project: Project, var visible: Boolean = true, var status: BuildStatus = BuildStatus.UNKNOWN, var branch: String, var commit: String, var slug: String, var tag: String? = null, var pr: String? = null, var service: String? = null, var serviceBuild: String? = null, var serviceBuildUrl: String? = null, var serviceJob: String? = null, @JsonIgnore @OneToMany(fetch = FetchType.LAZY, cascade = [CascadeType.ALL]) @JoinColumn(name = "build_id") var testCaseExecutions: MutableList<TestCaseExecution> = mutableListOf(), @CreatedDate var createdAt: Date = Date(), @Suppress("ForbiddenComment") // TODO: Fix @CreatedDate and @LastModifiedDate annotations @LastModifiedDate var updatedAt: Date = Date(), ) : AbstractJpaPersistable<Long>() enum class BuildStatus { SUCCESS, BUILD_FAILED, TESTS_FAILED, UNKNOWN }
0
Kotlin
0
0
17494eee5c2c39bea5b32d7adc8567fddb2036be
1,409
testaxis-backend
MIT License
projects/core/src/main/kotlin/site/siredvin/peripheralworks/data/ModLootTableProvider.kt
SirEdvin
489,471,520
false
null
package site.siredvin.peripheralworks.data import net.minecraft.data.loot.LootTableProvider import net.minecraft.data.loot.LootTableSubProvider import net.minecraft.resources.ResourceLocation import net.minecraft.world.level.storage.loot.LootTable import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets import site.siredvin.peripheralium.data.blocks.LootTableHelper import site.siredvin.peripheralworks.common.setup.Blocks import java.util.function.BiConsumer object ModLootTableProvider { fun getTables(): List<LootTableProvider.SubProviderEntry> { return listOf( LootTableProvider.SubProviderEntry({ LootTableSubProvider { registerBlocks(it) } }, LootContextParamSets.BLOCK), ) } fun registerBlocks(consumer: BiConsumer<ResourceLocation, LootTable.Builder>) { LootTableHelper.dropSelf(consumer, Blocks.ULTIMATE_SENSOR) LootTableHelper.dropSelf(consumer, Blocks.UNIVERSAL_SCANNER) LootTableHelper.dropSelf(consumer, Blocks.PERIPHERAL_CASING) LootTableHelper.dropSelf(consumer, Blocks.ITEM_PEDESTAL) LootTableHelper.dropSelf(consumer, Blocks.MAP_PEDESTAL) LootTableHelper.dropSelf(consumer, Blocks.DISPLAY_PEDESTAL) } }
3
Kotlin
2
6
68c7053de2f755e24c207c6357aef4a58426d690
1,302
UnlimitedPeripheralWorks
MIT License
app/src/main/java/com/oguzdogdu/wallieshd/presentation/favorites/FavoritesListAdapter.kt
oguzsout
616,912,430
false
{"Kotlin": 381609}
package com.oguzdogdu.wallieshd.presentation.favorites import android.annotation.SuppressLint import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.oguzdogdu.domain.model.favorites.FavoriteImages import com.oguzdogdu.wallieshd.R import com.oguzdogdu.wallieshd.databinding.ItemMainImageBinding import com.oguzdogdu.wallieshd.util.itemLoading import com.oguzdogdu.wallieshd.util.loadImage class FavoritesListAdapter : ListAdapter<FavoriteImages, FavoritesListAdapter.FavoritesViewHolder>( DIFF_CALLBACK ) { private var onItemClickListener: ((FavoriteImages?) -> Unit)? = null fun setOnItemClickListener(listener: (FavoriteImages?) -> Unit) { onItemClickListener = listener } inner class FavoritesViewHolder(private val binding: ItemMainImageBinding) : RecyclerView.ViewHolder(binding.root) { @SuppressLint("ResourceAsColor") fun bind(wallpaper: FavoriteImages) { binding.apply { imageViewItemWallpaper.loadImage( wallpaper.url, placeholder = this.root.context.itemLoading( R.color.purple_03 ) ) binding.root.setOnClickListener { onItemClickListener?.let { it(wallpaper) } } } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FavoritesViewHolder { return FavoritesViewHolder( ItemMainImageBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) } override fun onBindViewHolder(holder: FavoritesViewHolder, position: Int) { getItem(position)?.let { holder.bind(it) } } companion object { val DIFF_CALLBACK: DiffUtil.ItemCallback<FavoriteImages> = object : DiffUtil.ItemCallback<FavoriteImages>() { override fun areItemsTheSame( oldItem: FavoriteImages, newItem: FavoriteImages ) = oldItem.id == newItem.id override fun areContentsTheSame( oldItem: FavoriteImages, newItem: FavoriteImages ) = oldItem == newItem } } }
0
Kotlin
0
8
f4dfeea21aabb253dd4aff4001c91138d5af88e4
2,540
Wallies
MIT License
app/src/main/java/cn/settile/fanboxviewer/Adapters/RecyclerView/Supporting/SupportingRecycleViewAdapter.kt
709924470
190,781,467
false
null
package cn.settile.fanboxviewer.Adapters.RecyclerView.Supporting import android.content.res.ColorStateList import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import cn.settile.fanboxviewer.Network.Bean.SupportingItem import cn.settile.fanboxviewer.R import com.makeramen.roundedimageview.RoundedImageView import com.squareup.picasso.Picasso class SupportingRecycleViewAdapter(private val dataSet:Array<SupportingItem>) : RecyclerView.Adapter<SupportingRecycleViewAdapter.SupportingViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SupportingViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.component_item_supporting, parent, false) return SupportingViewHolder(view) } override fun onBindViewHolder(holder: SupportingViewHolder, position: Int) { holder.creatorName.text = dataSet[position].creator holder.title.text = dataSet[position].title holder.fee.text = dataSet[position].plan holder.desc.text = dataSet[position].desc holder.cover.setVisibility(View.VISIBLE) Picasso.get().load(dataSet[position].coverImgURL).into(holder.cover) } override fun getItemCount(): Int { return dataSet.size } class SupportingViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val creatorName : TextView val title : TextView val fee: TextView val desc: TextView val cover: ImageView init { creatorName = itemView.findViewById(R.id.creatorName) title = itemView.findViewById(R.id.supporting_title) fee = itemView.findViewById(R.id.supporting_fee) desc = itemView.findViewById(R.id.supporting_description) cover = itemView.findViewById(R.id.supporting_coverImg) } } }
2
null
5
56
b5e38903497947ca1b199edab3aeb73b1ebf10d0
2,002
FanboxViewer
MIT License
3_semester/coursework/mobile_app/app/src/main/java/coursework/mobile_app/App.kt
danilbushkov
315,379,979
false
{"Pascal": 301812, "C++": 237500, "Rust": 155300, "Kotlin": 86563, "Python": 52552, "Java": 36617, "Go": 18404, "Assembly": 9374, "PLpgSQL": 8293, "Makefile": 7264, "C": 6011, "QMake": 1043, "CMake": 468, "Shell": 305, "Dockerfile": 172, "Batchfile": 92}
package coursework.mobile_app import android.app.Application import android.content.Intent import android.content.SharedPreferences import coursework.mobile_app.model.HttpClientService import coursework.mobile_app.model.HttpSettings import coursework.mobile_app.model.TasksService class App:Application() { val httpClientService:HttpClientService = HttpClientService(HttpSettings()) var auth: Boolean = false set(value){ if (!value){ // val intent = Intent(this,AuthActivity::class.java) // intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) // startActivity(intent) } field = value } val tasksService = TasksService() var storage: SharedPreferences? = null set(value){ field=value httpClientService.httpSettings.host= field!!.getString("host",HttpSettings.DEFAULT_HOST).toString() httpClientService.httpSettings.port= field!!.getString("port",HttpSettings.DEFAULT_PORT).toString() httpClientService.updatePath() httpClientService.token=field!!.getString("token","").toString() } companion object{ val NAME_STORAGE="storage" } }
0
Pascal
0
0
f2b3f8898300697f59afe2e1ba3eb1489cff76d4
1,236
vyatsu
MIT License
app/src/main/java/com/draw2form/ai/presentation/screens/LoginScreen.kt
laurenthat-metropolia
711,905,629
false
{"Kotlin": 359447}
package com.draw2form.ai.presentation.screens import android.content.Intent import android.net.Uri 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.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.selection.toggleable import androidx.compose.material3.Checkbox import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext 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.airbnb.lottie.compose.LottieAnimation import com.airbnb.lottie.compose.LottieCompositionSpec import com.airbnb.lottie.compose.LottieConstants import com.airbnb.lottie.compose.rememberLottieComposition import com.draw2form.ai.R import com.draw2form.ai.presentation.components.SignInGoogleButton import com.draw2form.ai.presentation.ui.theme.LinkUpTheme @Composable fun LoginScreen() { val context = LocalContext.current val intent = remember { Intent( Intent.ACTION_VIEW, Uri.parse("https://draw2form.ericaskari.com/api/auth/google") ) } val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.login_lottie)) val (checkedState, onStateChange) = remember { mutableStateOf(false) } LazyColumn() { item { Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .fillMaxWidth() .padding(5.dp) ) { LottieAnimation( modifier = Modifier .size(width = 350.dp, height = 350.dp), composition = composition, iterations = LottieConstants.IterateForever, ) Spacer(modifier = Modifier.height(50.dp)) Text( text = "AI FORM BUILDER", fontWeight = FontWeight.Bold, style = MaterialTheme.typography.headlineLarge, textAlign = TextAlign.Center, ) Spacer(modifier = Modifier.height(100.dp)) Row( Modifier .fillMaxWidth() .height(56.dp) .toggleable( value = checkedState, onValueChange = { onStateChange(!checkedState) }, ) .padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center, ) { Checkbox( checked = checkedState, onCheckedChange = null ) Text( text = "I accept the terms and conditions", style = MaterialTheme.typography.bodyLarge, modifier = Modifier.padding(start = 16.dp) ) } Spacer(modifier = Modifier.height(80.dp)) Text( text = stringResource(R.string.login), style = MaterialTheme.typography.bodyLarge, modifier = Modifier.padding(start = 16.dp) ) Spacer(modifier = Modifier.height(10.dp)) Column( modifier = Modifier .padding(top = 20.dp) ) { SignInGoogleButton(enabled = checkedState) { context.startActivity(intent) } } } } } } @Preview(showBackground = true) @Composable fun LoginScreenPreview() { LinkUpTheme { Surface { LoginScreen() } } }
0
Kotlin
1
2
4146ad646571093e459a726c8f7456c495951410
4,726
AI-Form-Builder
MIT License
JOOX_SDK_Demo_Android/app/src/main/java/com/tencent/joox/sdk/utils/ui/ResourceUtil.kt
TencentCloud
386,706,230
false
{"Kotlin": 243250, "Java": 61143, "Shell": 454}
package com.tencent.joox.sdk.utils.ui import android.content.ContentResolver import android.content.Context import android.content.res.Resources import android.net.Uri object ResourceUtil { fun resIdToUrl(context: Context, resId: Int): String { val resources = context.resources return try { Uri.parse( ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + resources.getResourcePackageName(resId) + '/' + resources.getResourceTypeName(resId) + '/' + resources.getResourceEntryName(resId) ).toString() } catch (e: Resources.NotFoundException) { "" } } }
0
Kotlin
1
9
530745eeb83c331c549994b60ee223b464ece8be
715
joox-sdk-android
Apache License 2.0
infra/nats/src/main/kotlin/io/bluetape4k/nats/service/Service.kt
debop
625,161,599
false
{"Kotlin": 7504333, "HTML": 502995, "Java": 2273, "JavaScript": 1351, "Shell": 1301, "CSS": 444, "Dockerfile": 121, "Mustache": 82}
package io.bluetape4k.nats.service import io.nats.client.Connection import io.nats.service.Service import io.nats.service.ServiceBuilder import io.nats.service.ServiceEndpoint inline fun natsService(initializer: ServiceBuilder.() -> Unit): Service { return ServiceBuilder().apply(initializer).build() } fun natsServiceOf( nc: Connection, name: String, version: String, vararg serviceEndpoints: ServiceEndpoint, ): Service = natsService { connection(nc) name(name) version(version) serviceEndpoints.forEach { serviceEndpoint -> addServiceEndpoint(serviceEndpoint) } }
0
Kotlin
0
1
ce3da5b6bddadd29271303840d334b71db7766d2
618
bluetape4k
MIT License
app/src/main/java/app/eluvio/wallet/network/converters/RedeemedOfferConverter.kt
eluv-io
719,801,077
false
{"Kotlin": 842368, "Java": 29738}
package app.eluvio.wallet.network.converters import app.eluvio.wallet.data.entities.RedeemStateEntity import app.eluvio.wallet.network.api.authd.RedeemableOffersApi import app.eluvio.wallet.network.dto.NftInfoDto import app.eluvio.wallet.network.dto.NftRedeemableOfferDto import app.eluvio.wallet.network.dto.RedemptionStatusDto import app.eluvio.wallet.util.logging.Log import app.eluvio.wallet.util.realm.toRealmInstant fun NftInfoDto.toRedeemStateEntities( statuses: List<RedemptionStatusDto>, currentUserAddress: String? ): List<RedeemStateEntity> { val contract = contract_addr.removePrefix("0x") val relevantStatuses = statuses.filter { it.operation == RedeemableOffersApi.REDEEM_OPERATION && it.contract == contract && it.tokenId == token_id_str } return offers?.map { offer -> offer.toEntity(relevantStatuses, currentUserAddress) } ?: emptyList() } /** *[statuses] should be pre-filtered to only include relevant statuses */ private fun NftRedeemableOfferDto.toEntity( statuses: List<RedemptionStatusDto>, currentUserAddress: String? ): RedeemStateEntity { val dto = this val statusDto = statuses.firstOrNull { it.offerId == dto.id } return RedeemStateEntity().apply { offerId = dto.id active = dto.active redeemer = dto.redeemer redeemed = dto.redeemed?.toRealmInstant() transaction = dto.transaction status = parseRedemptionStatus(redeemer, currentUserAddress, statusDto) } } private fun parseRedemptionStatus( redeemer: String?, currentUserAddress: String?, statusDto: RedemptionStatusDto? ): RedeemStateEntity.RedeemStatus { val statusStr = statusDto?.status return when { redeemer != null -> { if (isOwnedByAnotherUser(redeemer, currentUserAddress)) { RedeemStateEntity.RedeemStatus.REDEEMED_BY_ANOTHER_USER } else { RedeemStateEntity.RedeemStatus.REDEEMED_BY_CURRENT_USER } } statusDto == null -> { // Unless redemption has occurred in the last 24h, it won't be found in the statuses. // This is normal and expected for most Offers. RedeemStateEntity.RedeemStatus.UNREDEEMED } // TODO: we are assuming that when status=complete but no [redeemer], the current user is the owner. is this assumptions true? statusStr == "complete" -> RedeemStateEntity.RedeemStatus.REDEEMED_BY_CURRENT_USER statusStr == "failed" -> RedeemStateEntity.RedeemStatus.REDEEM_FAILED statusStr == "" || statusStr == null -> { // The BE sends "" to signal that the redemption is in progress. Don't ask me why. // catching nulls just in case the BE starts omitting "" from its responses, resulting in [null] in our DTO. RedeemStateEntity.RedeemStatus.REDEEMING } else -> { // There *is* a redemption status, but it's not one we recognize. Log.w("Unknown redemption status: ${statusDto.status}. Defaulting to UNREDEEMED") RedeemStateEntity.RedeemStatus.REDEEMING } } } private fun isOwnedByAnotherUser(redeemer: String?, currentUser: String?): Boolean { val redeemerAddress = redeemer?.removePrefix("0x")?.lowercase() ?: return false val currentAddress = currentUser?.removePrefix("0x")?.lowercase() ?: return false return redeemerAddress.isNotEmpty() && redeemerAddress != currentAddress }
8
Kotlin
1
0
d8493e512ff9e20239e387ae7449e3a857813eb1
3,530
elv-wallet-android
MIT License
js/js.translator/testData/box/expression/cast/safeCastToGenericTypeWithUpperBound.kt
JakeWharton
99,388,807
false
null
package foo open class A class B : A() class C fun <T : A> notNullToNullableT(a: Any): T? = a as? T? fun <T : A> nullableToNullableT(a: Any?): T? = a as? T? fun box(): String { val a = A() val b = B() val c = C() success("notNullToNullableT<A>(a)") { assertEquals(a, notNullToNullableT<A>(a)) } success("notNullToNullableT<A>(b)") { assertEquals(b, notNullToNullableT<A>(b)) } success("notNullToNullableT<A>(c)") { assertEquals(null, notNullToNullableT<A>(c)) } success("nullableToNullableT<A>(a)") { assertEquals(a, nullableToNullableT<A>(a)) } success("nullableToNullableT<A>(b)") { assertEquals(b, nullableToNullableT<A>(b)) } success("nullableToNullableT<A>(null)") { assertEquals(null, nullableToNullableT<A>(null)) } success("nullableToNullableT<A>(c)") { assertEquals(null, nullableToNullableT<A>(c)) } return "OK" }
184
null
5691
83
4383335168338df9bbbe2a63cb213a68d0858104
875
kotlin
Apache License 2.0
uvmprimer/00-common/src/main/kotlin/dut/three_cycle.kt
frwang96
416,809,961
false
null
/* * SPDX-License-Identifier: Apache-2.0 */ @file:Verik @file:Suppress("ClassName") package dut import io.verik.core.* class three_cycle( @In var A: Ubit<`8`>, @In var B: Ubit<`8`>, @In var clk: Boolean, @In var reset_n: Boolean, @In var start: Boolean, @Out var done_mult: Boolean, @Out var result_mult: Ubit<`16`> ) : Module() { var a_int: Ubit<`8`> = nc() var b_int: Ubit<`8`> = nc() var mult1: Ubit<`16`> = nc() var mult2: Ubit<`16`> = nc() var done3: Boolean = nc() var done2: Boolean = nc() var done1: Boolean = nc() var done_mult_int: Boolean = nc() @Seq fun mult() { on(posedge(clk), negedge(reset_n)) { if (!reset_n) { done_mult_int = false done3 = false done2 = false done1 = false a_int = u0() b_int = u0() mult1 = u0() mult2 = u0() result_mult = u0() } else { a_int = A b_int = B mult1 = a_int mul b_int mult2 = mult1 result_mult = mult2 done3 = start && !done_mult_int done2 = done3 && !done_mult_int done1 = done2 && !done_mult_int done_mult_int = done1 && !done_mult_int } } } @Com fun set_done_mult() { done_mult = done_mult_int } }
0
Kotlin
1
5
9a0f5f79b824e69a33dc4f9717d3b9e3ed103180
1,491
verik-examples
Apache License 2.0
app/src/main/java/org/redbyte/animatron/pascal/PascalActivity.kt
i-redbyte
229,621,861
false
{"Kotlin": 94268}
package org.redbyte.animatron.pascal import android.content.Context import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import org.redbyte.animatron.R class PascalActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_pascal) val pascal = findViewById<PascalTriangleView>(R.id.triangle) pascal.rotationDegrees = 180f pascal.itemClick = { Toast.makeText(this, "Select value: $it", Toast.LENGTH_SHORT).show() } } companion object { fun newInstance(context: Context): Intent = Intent(context, PascalActivity::class.java) } }
0
Kotlin
0
8
d3749bcbf9579280b4c61b877a1675645431b32f
786
Animatron
MIT License
composeApp/src/desktopMain/kotlin/io/github/snd_r/komelia/settings/FilesystemSettingsRepository.kt
Snd-R
775,064,249
false
{"Kotlin": 1370443, "C": 37132, "CMake": 17841, "Shell": 2152, "Dockerfile": 1673, "JavaScript": 695, "HTML": 447}
package io.github.snd_r.komelia.settings import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import io.github.snd_r.komelia.platform.DownscaleOption import io.github.snd_r.komelia.platform.PlatformDecoderSettings import io.github.snd_r.komelia.platform.UpscaleOption import io.github.snd_r.komelia.ui.series.BooksLayout import io.github.snd_r.komelia.updates.AppVersion import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import kotlinx.datetime.Instant class FilesystemSettingsRepository( private val actor: FileSystemSettingsActor, ) : SettingsRepository { override fun getServerUrl(): Flow<String> { return actor.getState().map { it.server.url } } override suspend fun putServerUrl(url: String) { actor.transform { settings -> settings.copy(server = settings.server.copy(url = url)) } } override fun getCardWidth(): Flow<Dp> { return actor.getState().map { it.appearance.cardWidth.dp } } override suspend fun putCardWidth(cardWidth: Dp) { actor.transform { settings -> settings.copy(appearance = settings.appearance.copy(cardWidth = cardWidth.value.toInt())) } } override fun getCurrentUser(): Flow<String> { return actor.getState().map { it.user.username } } override suspend fun putCurrentUser(username: String) { actor.transform { settings -> settings.copy(user = settings.user.copy(username = username)) } } override fun getDecoderType(): Flow<PlatformDecoderSettings> { return actor.getState().map { val decoderSettings = it.decoder PlatformDecoderSettings( platformType = decoderSettings.decoder, upscaleOption = UpscaleOption(decoderSettings.upscaleOption), downscaleOption = DownscaleOption(decoderSettings.downscaleOption) ) } } override suspend fun putDecoderType(decoder: PlatformDecoderSettings) { actor.transform { settings -> settings.copy( decoder = settings.decoder.copy( decoder = decoder.platformType, upscaleOption = decoder.upscaleOption.value, downscaleOption = decoder.downscaleOption.value ) ) } } override fun getSeriesPageLoadSize(): Flow<Int> { return actor.getState().map { it.appearance.seriesPageLoadSize } } override suspend fun putSeriesPageLoadSize(size: Int) { actor.transform { settings -> settings.copy(appearance = settings.appearance.copy(seriesPageLoadSize = size)) } } override fun getBookPageLoadSize(): Flow<Int> { return actor.getState().map { it.appearance.bookPageLoadSize } } override suspend fun putBookPageLoadSize(size: Int) { actor.transform { settings -> settings.copy(appearance = settings.appearance.copy(bookPageLoadSize = size)) } } override fun getBookListLayout(): Flow<BooksLayout> { return actor.getState().map { it.appearance.bookListLayout } } override suspend fun putBookListLayout(layout: BooksLayout) { actor.transform { settings -> settings.copy(appearance = settings.appearance.copy(bookListLayout = layout)) } } override fun getCheckForUpdatesOnStartup(): Flow<Boolean> { return actor.getState().map { it.updates.checkForUpdatesOnStartup } } override suspend fun putCheckForUpdatesOnStartup(check: Boolean) { actor.transform { settings -> settings.copy(updates = settings.updates.copy(checkForUpdatesOnStartup = check)) } } override fun getLastUpdateCheckTimestamp(): Flow<Instant?> { return actor.getState().map { it.updates.lastUpdateCheckTimestamp } } override suspend fun putLastUpdateCheckTimestamp(timestamp: Instant) { actor.transform { settings -> settings.copy(updates = settings.updates.copy(lastUpdateCheckTimestamp = timestamp)) } } override fun getLastCheckedReleaseVersion(): Flow<AppVersion?> { return actor.getState().map { it.updates.lastCheckedReleaseVersion } } override suspend fun putLastCheckedReleaseVersion(version: AppVersion) { actor.transform { settings -> settings.copy(updates = settings.updates.copy(lastCheckedReleaseVersion = version)) } } override fun getDismissedVersion(): Flow<AppVersion?> { return actor.getState().map { it.updates.dismissedVersion } } override suspend fun putDismissedVersion(version: AppVersion) { actor.transform { settings -> settings.copy(updates = settings.updates.copy(dismissedVersion = version)) } } fun getOnnxModelsPath(): Flow<String> { return actor.getState().map { it.decoder.onnxModelsPath } } suspend fun putOnnxModelsPath(path: String) { actor.transform { settings -> settings.copy(decoder = settings.decoder.copy(onnxModelsPath = path)) } } }
1
Kotlin
0
9
5a16d84ed86321e4c7efa96daea9dd7dbfc2308b
4,951
Komelia
Apache License 2.0
composeApp/src/desktopMain/kotlin/io/github/snd_r/komelia/settings/FilesystemSettingsRepository.kt
Snd-R
775,064,249
false
{"Kotlin": 1370443, "C": 37132, "CMake": 17841, "Shell": 2152, "Dockerfile": 1673, "JavaScript": 695, "HTML": 447}
package io.github.snd_r.komelia.settings import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import io.github.snd_r.komelia.platform.DownscaleOption import io.github.snd_r.komelia.platform.PlatformDecoderSettings import io.github.snd_r.komelia.platform.UpscaleOption import io.github.snd_r.komelia.ui.series.BooksLayout import io.github.snd_r.komelia.updates.AppVersion import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import kotlinx.datetime.Instant class FilesystemSettingsRepository( private val actor: FileSystemSettingsActor, ) : SettingsRepository { override fun getServerUrl(): Flow<String> { return actor.getState().map { it.server.url } } override suspend fun putServerUrl(url: String) { actor.transform { settings -> settings.copy(server = settings.server.copy(url = url)) } } override fun getCardWidth(): Flow<Dp> { return actor.getState().map { it.appearance.cardWidth.dp } } override suspend fun putCardWidth(cardWidth: Dp) { actor.transform { settings -> settings.copy(appearance = settings.appearance.copy(cardWidth = cardWidth.value.toInt())) } } override fun getCurrentUser(): Flow<String> { return actor.getState().map { it.user.username } } override suspend fun putCurrentUser(username: String) { actor.transform { settings -> settings.copy(user = settings.user.copy(username = username)) } } override fun getDecoderType(): Flow<PlatformDecoderSettings> { return actor.getState().map { val decoderSettings = it.decoder PlatformDecoderSettings( platformType = decoderSettings.decoder, upscaleOption = UpscaleOption(decoderSettings.upscaleOption), downscaleOption = DownscaleOption(decoderSettings.downscaleOption) ) } } override suspend fun putDecoderType(decoder: PlatformDecoderSettings) { actor.transform { settings -> settings.copy( decoder = settings.decoder.copy( decoder = decoder.platformType, upscaleOption = decoder.upscaleOption.value, downscaleOption = decoder.downscaleOption.value ) ) } } override fun getSeriesPageLoadSize(): Flow<Int> { return actor.getState().map { it.appearance.seriesPageLoadSize } } override suspend fun putSeriesPageLoadSize(size: Int) { actor.transform { settings -> settings.copy(appearance = settings.appearance.copy(seriesPageLoadSize = size)) } } override fun getBookPageLoadSize(): Flow<Int> { return actor.getState().map { it.appearance.bookPageLoadSize } } override suspend fun putBookPageLoadSize(size: Int) { actor.transform { settings -> settings.copy(appearance = settings.appearance.copy(bookPageLoadSize = size)) } } override fun getBookListLayout(): Flow<BooksLayout> { return actor.getState().map { it.appearance.bookListLayout } } override suspend fun putBookListLayout(layout: BooksLayout) { actor.transform { settings -> settings.copy(appearance = settings.appearance.copy(bookListLayout = layout)) } } override fun getCheckForUpdatesOnStartup(): Flow<Boolean> { return actor.getState().map { it.updates.checkForUpdatesOnStartup } } override suspend fun putCheckForUpdatesOnStartup(check: Boolean) { actor.transform { settings -> settings.copy(updates = settings.updates.copy(checkForUpdatesOnStartup = check)) } } override fun getLastUpdateCheckTimestamp(): Flow<Instant?> { return actor.getState().map { it.updates.lastUpdateCheckTimestamp } } override suspend fun putLastUpdateCheckTimestamp(timestamp: Instant) { actor.transform { settings -> settings.copy(updates = settings.updates.copy(lastUpdateCheckTimestamp = timestamp)) } } override fun getLastCheckedReleaseVersion(): Flow<AppVersion?> { return actor.getState().map { it.updates.lastCheckedReleaseVersion } } override suspend fun putLastCheckedReleaseVersion(version: AppVersion) { actor.transform { settings -> settings.copy(updates = settings.updates.copy(lastCheckedReleaseVersion = version)) } } override fun getDismissedVersion(): Flow<AppVersion?> { return actor.getState().map { it.updates.dismissedVersion } } override suspend fun putDismissedVersion(version: AppVersion) { actor.transform { settings -> settings.copy(updates = settings.updates.copy(dismissedVersion = version)) } } fun getOnnxModelsPath(): Flow<String> { return actor.getState().map { it.decoder.onnxModelsPath } } suspend fun putOnnxModelsPath(path: String) { actor.transform { settings -> settings.copy(decoder = settings.decoder.copy(onnxModelsPath = path)) } } }
1
Kotlin
0
9
5a16d84ed86321e4c7efa96daea9dd7dbfc2308b
4,951
Komelia
Apache License 2.0
performance-tests/test/org/jetbrains/kotlin/idea/perf/whole/HighlightWholeProjectPerformanceTest.kt
JetBrains
278,369,660
false
null
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.perf import com.intellij.codeInsight.daemon.impl.HighlightInfo import com.intellij.openapi.module.impl.ProjectLoadingErrorsHeadlessNotifier import com.intellij.testFramework.UsefulTestCase import org.jetbrains.kotlin.idea.perf.util.* import org.jetbrains.kotlin.idea.testFramework.ProjectOpenAction import org.jetbrains.kotlin.test.JUnit3RunnerWithInners import org.junit.runner.RunWith import java.io.File @RunWith(JUnit3RunnerWithInners::class) class HighlightWholeProjectPerformanceTest : UsefulTestCase() { override fun setUp() { val allowedErrorDescription = setOf( "Unknown artifact type: war", "Unknown artifact type: exploded-war" ) ProjectLoadingErrorsHeadlessNotifier.setErrorHandler( { errorDescription -> val description = errorDescription.description if (description !in allowedErrorDescription) { throw RuntimeException(description) } else { logMessage { "project loading error: '$description' at '${errorDescription.elementName}'" } } }, testRootDisposable ) } fun testHighlightAllKtFilesInProject() { val emptyProfile = System.getProperty("emptyProfile", "false").toBoolean() val projectSpecs = projectSpecs() suite(suiteName = "allKtFilesInProject") { app { warmUpProject() with(config) { warmup = 1 iterations = 3 } for (projectSpec in projectSpecs) { val projectName = projectSpec.name val projectPath = projectSpec.path try { project(ExternalProject(projectPath, ProjectOpenAction.GRADLE_PROJECT), refresh = true) { profile(if (emptyProfile) EmptyProfile else DefaultProfile) val projectDir = File(projectPath) val ktFiles = projectDir.allFilesWithExtension("kt").toList() logStatValue("number of kt files", ktFiles.size) val topMidLastFiles = limitedFiles(ktFiles, 10) .map { val path = it.path it to path.substring(path.indexOf(projectPath) + projectPath.length + 1) } logStatValue("limited number of kt files", topMidLastFiles.size) topMidLastFiles.forEach { logMessage { "${it.second} fileSize: ${it.first.length()}" } } topMidLastFiles.forEachIndexed { idx, pair -> val file = pair.first val fileName = pair.second logMessage { "$idx / ${topMidLastFiles.size} : $fileName fileSize: ${file.length()}" } try { fixture(fileName).use { measure<List<HighlightInfo>>(fileName) { test = { highlight(it) } } } } catch (e: Exception) { // nothing as it is already caught by perfTest } } } } catch (e: Exception) { // nothing as it is already caught by perfTest } } } } } private fun limitedFiles(ktFiles: List<File>, partPercent: Int): Collection<File> { val sortedBySize = ktFiles .filter { it.length() > 0 } .map { it to it.length() }.sortedByDescending { it.second } val percentOfFiles = (sortedBySize.size * partPercent) / 100 val topFiles = sortedBySize.take(percentOfFiles).map { it.first } val midFiles = sortedBySize.take(sortedBySize.size / 2 + percentOfFiles / 2).takeLast(percentOfFiles).map { it.first } val lastFiles = sortedBySize.takeLast(percentOfFiles).map { it.first } return LinkedHashSet(topFiles + midFiles + lastFiles) } private fun projectSpecs(): List<ProjectSpec> { val projects = System.getProperty("performanceProjects") ?: return emptyList() return projects.split(",").map { val idx = it.indexOf("=") if (idx <= 0) ProjectSpec(it, "../$it") else ProjectSpec(it.substring(0, idx), it.substring(idx + 1)) }.filter { val path = File(it.path) path.exists() && path.isDirectory } } private data class ProjectSpec(val name: String, val path: String) }
1
null
37
82
cc81d7505bc3e9ad503d706998ae8026c067e838
5,411
intellij-kotlin
Apache License 2.0
src/plugin-saxon/main/uk/co/reecedunn/intellij/plugin/saxon/query/s9api/binding/trans/XPathException.kt
rhdunn
62,201,764
false
{"Kotlin": 8262637, "XQuery": 996770, "HTML": 39377, "XSLT": 6853}
/* * Copyright (C) 2019, 2021 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.saxon.query.s9api.binding.trans import uk.co.reecedunn.intellij.plugin.saxon.query.s9api.binding.QName import uk.co.reecedunn.intellij.plugin.saxon.query.s9api.binding.om.StructuredQName import javax.xml.transform.SourceLocator import javax.xml.transform.TransformerException class XPathException(private val `object`: TransformerException, private val `class`: Class<*>) : TransformerException(`object`.message) { override fun getLocator(): SourceLocator? = `object`.locator override fun getException(): Throwable? = cause override val cause: Throwable? = `object`.cause fun getErrorCodeQName(): QName? { if (`class`.isInstance(`object`)) { return `class`.getMethod("getErrorCodeQName").invoke(`object`)?.let { StructuredQName(it, `class`.classLoader.loadClass("net.sf.saxon.om.StructuredQName")) } } return null } } fun Throwable.toXPathException(classLoader: ClassLoader): XPathException? { val xpathExceptionClass = classLoader.loadClass("net.sf.saxon.trans.XPathException") return when { this is TransformerException -> XPathException(this, xpathExceptionClass) cause is TransformerException -> XPathException(cause as TransformerException, xpathExceptionClass) else -> null } }
49
Kotlin
9
25
d8d460d31334e8b2376a22f3832a20b2845bacab
1,958
xquery-intellij-plugin
Apache License 2.0
app/src/main/java/com/mikhailgrigorev/quickpass/NewPasswordActivity.kt
grigorevmp
268,231,866
false
null
package com.mikhailgrigorev.quickpass import android.Manifest import android.annotation.SuppressLint import android.app.Activity import android.content.* import android.content.pm.PackageManager import android.content.res.Configuration import android.database.Cursor import android.graphics.Point import android.net.Uri import android.os.Build import android.os.Bundle import android.os.Handler import android.provider.DocumentsContract import android.provider.MediaStore import android.text.Editable import android.text.TextWatcher import android.util.Log import android.util.TypedValue import android.view.KeyEvent import android.view.MotionEvent import android.view.View import android.view.animation.AccelerateDecelerateInterpolator import android.widget.SeekBar import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatDelegate import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import com.google.android.material.chip.Chip import com.mikhailgrigorev.quickpass.databinding.ActivityNewPasswordBinding import com.mikhailgrigorev.quickpass.dbhelpers.DataBaseHelper import com.mikhailgrigorev.quickpass.dbhelpers.PasswordsDataBaseHelper import java.io.File import java.io.FileInputStream import java.io.FileOutputStream import java.io.IOException import java.nio.channels.FileChannel import java.text.SimpleDateFormat import java.util.* import kotlin.random.Random class NewPasswordActivity : AppCompatActivity() { private var isImage = false private val _keyTheme = "themePreference" private val _preferenceFile = "quickPassPreference" private var length = 20 private var useSymbols = false private var useUC = false private var useLetters = false private var useNumbers = false private var imageName: String = "" private lateinit var login: String private lateinit var binding: ActivityNewPasswordBinding @SuppressLint( "Recycle", "ClickableViewAccessibility", "ResourceAsColor", "RestrictedApi", "SetTextI18n" ) override fun onCreate(savedInstanceState: Bundle?) { val pref = getSharedPreferences(_preferenceFile, Context.MODE_PRIVATE) when(pref.getString(_keyTheme, "none")){ "yes" -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) "no" -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) "none", "default" -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM) "battery" -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY) } when(pref.getString("themeAccentPreference", "none")){ "Red" -> setTheme(R.style.AppThemeRed) "Pink" -> setTheme(R.style.AppThemePink) "Purple" -> setTheme(R.style.AppThemePurple) "Violet" -> setTheme(R.style.AppThemeViolet) "DViolet" -> setTheme(R.style.AppThemeDarkViolet) "Blue" -> setTheme(R.style.AppThemeBlue) "Cyan" -> setTheme(R.style.AppThemeCyan) "Teal" -> setTheme(R.style.AppThemeTeal) "Green" -> setTheme(R.style.AppThemeGreen) "LGreen" -> setTheme(R.style.AppThemeLightGreen) else -> setTheme(R.style.AppTheme) } super.onCreate(savedInstanceState) when (resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) { Configuration.UI_MODE_NIGHT_NO -> window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR } val handler = Handler() val r = Runnable { if(condition) { condition=false val intent = Intent(this, LoginAfterSplashActivity::class.java) startActivity(intent) finish() } } val time: Long = 100000 val sharedPref = getSharedPreferences(_preferenceFile, Context.MODE_PRIVATE) val lockTime = sharedPref.getString("appLockTime", "6") if(lockTime != null) { if (lockTime != "0") handler.postDelayed(r, time * lockTime.toLong()) } else handler.postDelayed(r, time * 6L) binding = ActivityNewPasswordBinding.inflate(layoutInflater) setContentView(binding.root) val cardRadius = sharedPref.getString("cardRadius", "none") if(cardRadius != null) if(cardRadius != "none") { binding.infoCard.radius = TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, cardRadius.toFloat(), resources.displayMetrics ) } val args: Bundle? = intent.extras login = args?.get("login").toString() val dbHelper = DataBaseHelper(this) val database = dbHelper.writableDatabase val cursor: Cursor = database.query( dbHelper.TABLE_USERS, arrayOf(dbHelper.KEY_IMAGE), "NAME = ?", arrayOf(login), null, null, null ) if (cursor.moveToFirst()) { val imageIndex: Int = cursor.getColumnIndex(dbHelper.KEY_IMAGE) do { when(cursor.getString(imageIndex).toString()){ "ic_account" -> binding.accountAvatar.backgroundTintList = ContextCompat.getColorStateList( this, R.color.ic_account ) "ic_account_Pink" -> binding.accountAvatar.backgroundTintList = ContextCompat.getColorStateList( this, R.color.ic_account_Pink ) "ic_account_Red" -> binding.accountAvatar.backgroundTintList = ContextCompat.getColorStateList( this, R.color.ic_account_Red ) "ic_account_Purple" -> binding.accountAvatar.backgroundTintList = ContextCompat.getColorStateList( this, R.color.ic_account_Purple ) "ic_account_Violet" -> binding.accountAvatar.backgroundTintList = ContextCompat.getColorStateList( this, R.color.ic_account_Violet ) "ic_account_Dark_Violet" -> binding.accountAvatar.backgroundTintList = ContextCompat.getColorStateList( this, R.color.ic_account_Dark_Violet ) "ic_account_Blue" -> binding.accountAvatar.backgroundTintList = ContextCompat.getColorStateList( this, R.color.ic_account_Blue ) "ic_account_Cyan" -> binding.accountAvatar.backgroundTintList = ContextCompat.getColorStateList( this, R.color.ic_account_Cyan ) "ic_account_Teal" -> binding.accountAvatar.backgroundTintList = ContextCompat.getColorStateList( this, R.color.ic_account_Teal ) "ic_account_Green" -> binding.accountAvatar.backgroundTintList = ContextCompat.getColorStateList( this, R.color.ic_account_Green ) "ic_account_lightGreen" -> binding.accountAvatar.backgroundTintList = ContextCompat.getColorStateList( this, R.color.ic_account_lightGreen ) else -> binding.accountAvatar.backgroundTintList = ContextCompat.getColorStateList( this, R.color.ic_account ) } binding.accountAvatarText.text = login[0].toString() } while (cursor.moveToNext()) } val list = mutableListOf<String>() val pass: String = args?.get("pass").toString() binding.genPasswordIdField.setText(pass) if(pass!="") { val myPasswordManager = PasswordManager() var evaluation: String = myPasswordManager.evaluatePasswordString(binding.genPasswordIdField.text.toString()) if (myPasswordManager.popularPasswords(binding.genPasswordIdField.text.toString())){ evaluation = "low" } if (binding.genPasswordIdField.text.toString().length == 4) if (myPasswordManager.popularPin(binding.genPasswordIdField.text.toString())) evaluation = "low" binding.passQuality.text = evaluation when (evaluation) { "low" -> binding.passQuality.text = getString(R.string.low) "high" -> binding.passQuality.text = getString(R.string.high) else -> binding.passQuality.text = getString(R.string.medium) } when (evaluation) { "low" -> binding.passQuality.setTextColor( ContextCompat.getColor( applicationContext, R.color.negative ) ) "high" -> binding.passQuality.setTextColor( ContextCompat.getColor( applicationContext, R.color.positive ) ) else -> binding.passQuality.setTextColor( ContextCompat.getColor( applicationContext, R.color.fixable ) ) } } useLetters = args?.get("useLetters") as Boolean if(useLetters){ binding.lettersToggle.isChecked = true list.add(binding.lettersToggle.text.toString()) } useUC = args.get("useUC") as Boolean if(useUC){ binding.upperCaseToggle.isChecked = true list.add(binding.upperCaseToggle.text.toString()) } useNumbers = args.get("useNumbers") as Boolean if(useNumbers){ binding.numbersToggle.isChecked = true list.add(binding.numbersToggle.text.toString()) } useSymbols = args.get("useSymbols") as Boolean if(useSymbols){ binding.symToggles.isChecked = true list.add(binding.symToggles.text.toString()) } length = args.get("length") as Int binding.lengthToggle.text = getString(R.string.length) + ": " + length binding.getInfo.setOnClickListener { if(binding.infoCard.visibility == View.GONE){ binding.infoCard.visibility = View.VISIBLE } else{ binding.infoCard.visibility = View.GONE } } binding.lengthToggle.setOnClickListener { if(binding.seekBar.visibility == View.GONE){ binding.seekBar.visibility = View.VISIBLE } else{ binding.seekBar.visibility = View.GONE } } // Set a SeekBar change listener binding.seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) { // Display the current progress of SeekBar length = i binding.lengthToggle.text = getString(R.string.length) + ": " + length } override fun onStartTrackingTouch(seekBar: SeekBar) { // Do something } override fun onStopTrackingTouch(seekBar: SeekBar) { // Do something } }) // Loop through the chips for (index in 0 until binding.passSettings.childCount) { val chip: Chip = binding.passSettings.getChildAt(index) as Chip // Set the chip checked change listener chip.setOnCheckedChangeListener{ view, isChecked -> val deg = binding.generatePassword.rotation + 30f binding.generatePassword.animate().rotation(deg).interpolator = AccelerateDecelerateInterpolator() if (isChecked){ if (view.id == R.id.lettersToggle) useLetters = true if (view.id == R.id.symToggles) useSymbols = true if (view.id == R.id.numbersToggle) useNumbers = true if (view.id == R.id.upperCaseToggle) useUC = true list.add(view.text.toString()) }else{ if (view.id == R.id.lettersToggle) useLetters = false if (view.id == R.id.symToggles) useSymbols = false if (view.id == R.id.numbersToggle) useNumbers = false if (view.id == R.id.upperCaseToggle) useUC = false list.remove(view.text.toString()) } } } binding.genPasswordIdField.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) { if (binding.genPasswordIdField.hasFocus()) { length = s.toString().length binding.lengthToggle.text = getString(R.string.length) + ": " + length binding.seekBar.progress = length val deg = binding.generatePassword.rotation + 10f binding.generatePassword.animate().rotation(deg).interpolator = AccelerateDecelerateInterpolator() val myPasswordManager = PasswordManager() binding.lettersToggle.isChecked = myPasswordManager.isLetters(binding.genPasswordIdField.text.toString()) binding.upperCaseToggle.isChecked = myPasswordManager.isUpperCase(binding.genPasswordIdField.text.toString()) binding.numbersToggle.isChecked = myPasswordManager.isNumbers(binding.genPasswordIdField.text.toString()) binding.symToggles.isChecked = myPasswordManager.isSymbols(binding.genPasswordIdField.text.toString()) var evaluation: String = myPasswordManager.evaluatePasswordString(binding.genPasswordIdField.text.toString()) if (myPasswordManager.popularPasswords(binding.genPasswordIdField.text.toString())) { evaluation = "low" } if (binding.genPasswordIdField.text.toString().length == 4) if (myPasswordManager.popularPin(binding.genPasswordIdField.text.toString())) evaluation = "low" when (evaluation) { "low" -> binding.passQuality.text = getString(R.string.low) "high" -> binding.passQuality.text = getString(R.string.high) else -> binding.passQuality.text = getString(R.string.medium) } when (evaluation) { "low" -> binding.passQuality.setTextColor( ContextCompat.getColor( applicationContext, R.color.negative ) ) "high" -> binding.passQuality.setTextColor( ContextCompat.getColor( applicationContext, R.color.positive ) ) else -> binding.passQuality.setTextColor( ContextCompat.getColor( applicationContext, R.color.fixable ) ) } } } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { } }) binding.generatePassword.setOnClickListener { binding.genPasswordIdField.clearFocus() val deg = 0f binding.generatePassword.animate().rotation(deg).interpolator = AccelerateDecelerateInterpolator() val myPasswordManager = PasswordManager() //Create a password with letters, uppercase letters, numbers but not special chars with 17 chars if(list.size == 0 || (list.size == 1 && binding.lengthToggle.isChecked)|| (list.size == 1 && list[0].contains( getString( R.string.length ) ))){ binding.genPasswordId.error = getString(R.string.noRules) } else { binding.genPasswordId.error = null val newPassword: String = myPasswordManager.generatePassword( useLetters, useUC, useNumbers, useSymbols, length ) binding.genPasswordIdField.setText(newPassword) var evaluation: String = myPasswordManager.evaluatePasswordString(binding.genPasswordIdField.text.toString()) if (myPasswordManager.popularPasswords(binding.genPasswordIdField.text.toString())){ evaluation = "low" } if (binding.genPasswordIdField.text.toString().length == 4) if (myPasswordManager.popularPin(binding.genPasswordIdField.text.toString())) evaluation = "low" binding.passQuality.text = evaluation when (evaluation) { "low" -> binding.passQuality.text = getString(R.string.low) "high" -> binding.passQuality.text = getString(R.string.high) else -> binding.passQuality.text = getString(R.string.medium) } when (evaluation) { "low" -> binding.passQuality.setTextColor( ContextCompat.getColor( applicationContext, R.color.negative ) ) "high" -> binding.passQuality.setTextColor( ContextCompat.getColor( applicationContext, R.color.positive ) ) else -> binding.passQuality.setTextColor( ContextCompat.getColor( applicationContext, R.color.fixable ) ) } } } binding.generatePassword.setOnTouchListener { v, event -> when (event.action) { MotionEvent.ACTION_DOWN -> { binding.cardPass.elevation = 50F binding.generatePassword.background = ContextCompat.getDrawable(this, R.color.grey) v.invalidate() } MotionEvent.ACTION_UP -> { binding.generatePassword.background = ContextCompat.getDrawable(this, R.color.white) binding.cardPass.elevation = 10F v.invalidate() } } false } binding.genPasswordId.setOnClickListener { if(binding.genPasswordIdField.text.toString() != ""){ val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager val clip = ClipData.newPlainText("Password", binding.genPasswordIdField.text.toString()) clipboard.setPrimaryClip(clip) toast(getString(R.string.passCopied)) } } binding.genPasswordIdField.setOnClickListener { if(binding.genPasswordIdField.text.toString() != ""){ val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager val clip = ClipData.newPlainText("Password", binding.genPasswordIdField.text.toString()) clipboard.setPrimaryClip(clip) toast(getString(R.string.passCopied)) } } binding.emailSwitch.setOnClickListener { if (binding.emailSwitch.isChecked) binding.email.visibility = View.VISIBLE else binding.email.visibility = View.GONE } binding.back.setOnClickListener { val intent = Intent() intent.putExtra("login", login) setResult(1, intent) finish() } binding.savePass.setOnClickListener { val pdbHelper = PasswordsDataBaseHelper(this, login) val passDataBase = pdbHelper.writableDatabase val contentValues = ContentValues() val newCursor: Cursor = passDataBase.query( pdbHelper.TABLE_USERS, arrayOf(pdbHelper.KEY_NAME), "NAME = ?", arrayOf(binding.newNameField.text.toString()), null, null, null ) val login2 = binding.newNameField.text if (newCursor.moveToFirst()) { binding.newName.error = getString(R.string.exists) } else if (login2 != null) { if (login2.isEmpty() || login2.length < 2) { binding.newName.error = getString(R.string.errNumOfText) } else if (binding.genPasswordIdField.text.toString() == "" || binding.genPasswordIdField.text.toString().length < 4) { binding.genPasswordId.error = getString(R.string.errPass) } else { contentValues.put(pdbHelper.KEY_ID, Random.nextInt(0, 10000)) contentValues.put(pdbHelper.KEY_NAME, binding.newNameField.text.toString()) val pm = PasswordManager() if (binding.cryptToggle.isChecked) { val dc = pm.encrypt(binding.genPasswordIdField.text.toString()) contentValues.put( pdbHelper.KEY_PASS, dc ) contentValues.put(pdbHelper.KEY_CIPHER, "crypted") } else{ contentValues.put(pdbHelper.KEY_PASS, binding.genPasswordIdField.text.toString()) contentValues.put(pdbHelper.KEY_CIPHER, "none") } contentValues.put(pdbHelper.KEY_TAGS, binding.keyWordsField.text.toString()) contentValues.put(pdbHelper.KEY_LOGIN, binding.emailField.text.toString()) var keyFA = "0" if (binding.authToggle.isChecked) keyFA = "1" var keyTimeLimit = "0" if (binding.timeLimit.isChecked) keyTimeLimit = "1" contentValues.put(pdbHelper.KEY_2FA, keyFA) contentValues.put(pdbHelper.KEY_USE_TIME, keyTimeLimit) contentValues.put(pdbHelper.KEY_TIME, getDateTime()) contentValues.put(pdbHelper.KEY_DESC, binding.noteField.text.toString()) passDataBase.insert(pdbHelper.TABLE_USERS, null, contentValues) val intent = Intent() intent.putExtra("login", login) pdbHelper.close() setResult(1, intent) val mediaStorageDir = File( applicationContext.getExternalFilesDir("QuickPassPhotos")!!.absolutePath ) if (!mediaStorageDir.exists()) { mediaStorageDir.mkdirs() Toast.makeText(applicationContext, "Directory Created", Toast.LENGTH_LONG).show() } if (!mediaStorageDir.exists()) { if (!mediaStorageDir.mkdirs()) { Log.d("App", "failed to create directory") } } if (mediaStorageDir.exists()) { if(imageName != "") { val from = File(mediaStorageDir, "$imageName.jpg") val to = File(mediaStorageDir, "${binding.newNameField.text}.jpg") if (from.exists()) from.renameTo(to) } } finish() } } } binding.upload.setOnClickListener{ checkPermissionForImage() } } private val PERMISSION_CODE_READ = 1001 private val PERMISSION_CODE_WRITE = 1002 private val IMAGE_PICK_CODE = 1000 private fun checkPermissionForImage() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if ((checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) && (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) ) { val permission = arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE) val permissionCoarse = arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE) requestPermissions(permission, PERMISSION_CODE_READ) // GIVE AN INTEGER VALUE FOR PERMISSION_CODE_READ LIKE 1001 requestPermissions(permissionCoarse, PERMISSION_CODE_WRITE) // GIVE AN INTEGER VALUE FOR PERMISSION_CODE_WRITE LIKE 1002 } else { pickImageFromGallery() } } } private fun pickImageFromGallery() { val intent = Intent(Intent.ACTION_PICK) intent.type = "image/*" startActivityForResult(intent, IMAGE_PICK_CODE) // GIVE AN INTEGER VALUE FOR IMAGE_PICK_CODE LIKE 1000 } @Throws(IOException::class) private fun copyFile(sourceFile: File, destFile: File) { if (!sourceFile.exists()) { return } val source: FileChannel? = FileInputStream(sourceFile).channel val destination: FileChannel? = FileOutputStream(destFile).channel if (destination != null && source != null) { destination.transferFrom(source, 0, source.size()) } source?.close() destination?.close() } private fun getImagePath(context: Context, uri: Uri): String? { var filePath = "" try { if (DocumentsContract.isDocumentUri(context, uri)) { if (isExternalStorageDocument(uri)) { val docId = DocumentsContract.getDocumentId(uri) val split = docId.split(":").toTypedArray() val type = split[0] if ("primary".equals(type, ignoreCase = true)) { return context.getExternalFilesDir(null).toString() + "/" + split[1] } } else if (isDownloadsDocument(uri)) { val id = DocumentsContract.getDocumentId(uri) val contentUri = ContentUris.withAppendedId( Uri.parse("content://downloads/public_downloads"), java.lang.Long.valueOf(id) ) return getDataColumn(context, contentUri, null, null) } else if (isMediaDocument(uri)) { val docId = DocumentsContract.getDocumentId(uri) val split = docId.split(":").toTypedArray() val type = split[0] var contentUri: Uri? = null when (type) { "image" -> { contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI } "video" -> { contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI } "audio" -> { contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI } } val selection = "_id=?" val selectionArgs = arrayOf<String?>( split[1] ) return getDataColumn(context, contentUri, selection, selectionArgs) } } else if ("content".equals(uri.scheme, ignoreCase = true)) { // Return the remote address return if (isGooglePhotosUri(uri)) uri.lastPathSegment else getDataColumn( context, uri, null, null ) } else if ("file".equals(uri.scheme, ignoreCase = true)) { return uri.path } } catch (e: java.lang.Exception) { filePath = "" } return filePath } private fun getDataColumn( context: Context, uri: Uri?, selection: String?, selectionArgs: Array<String?>? ): String? { var cursor: Cursor? = null val column = "_data" val projection = arrayOf( column ) try { cursor = context.contentResolver.query( uri!!, projection, selection, selectionArgs, null ) if (cursor != null && cursor.moveToFirst()) { val index = cursor.getColumnIndexOrThrow(column) return cursor.getString(index) } } finally { cursor?.close() } return null } private fun isExternalStorageDocument(uri: Uri): Boolean { return "com.android.externalstorage.documents" == uri.authority } private fun isDownloadsDocument(uri: Uri): Boolean { return "com.android.providers.downloads.documents" == uri.authority } private fun isMediaDocument(uri: Uri): Boolean { return "com.android.providers.media.documents" == uri.authority } private fun isGooglePhotosUri(uri: Uri): Boolean { return "com.google.android.apps.photos.content" == uri.authority } override fun onKeyUp(keyCode: Int, msg: KeyEvent?): Boolean { when (keyCode) { KeyEvent.KEYCODE_BACK -> { val intent = Intent() intent.putExtra("login", login) setResult(1, intent) finish() } } return false } private fun getDateTime(): String? { val dateFormat = SimpleDateFormat( "yyyy-MM-dd HH:mm:ss", Locale.getDefault() ) val date = Date() return dateFormat.format(date) } private fun Context.toast(message: String)= Toast.makeText(this, message, Toast.LENGTH_SHORT).show() @SuppressLint("SdCardPath") override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == 1) { if (resultCode == 1) { recreate() } } if (resultCode == Activity.RESULT_OK && requestCode == IMAGE_PICK_CODE) { // I'M GETTING THE URI OF THE IMAGE AS DATA AND SETTING IT TO THE IMAGEVIEW binding.attachedImage.setImageURI(data?.data) val display = windowManager.defaultDisplay val size = Point() display.getSize(size) val widthMax: Int = size.x val width = (widthMax/1.3).toInt() val height = binding.attachedImage.drawable.minimumHeight * width / binding.attachedImage.drawable.minimumWidth binding.attachedImage.layoutParams.height = height binding.attachedImage.layoutParams.width = width binding.attachedImage.layoutParams.height = height binding.attachedImage.layoutParams.width = width if (ContextCompat.checkSelfPermission( this, Manifest.permission.WRITE_EXTERNAL_STORAGE ) != PackageManager.PERMISSION_GRANTED ) { ActivityCompat.requestPermissions( this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), PackageManager.PERMISSION_GRANTED ) } val selectedImageURI: Uri = data?.data!! val mediaStorageDir = File( applicationContext.getExternalFilesDir("QuickPassPhotos")!!.absolutePath ) if (!mediaStorageDir.exists()) { mediaStorageDir.mkdirs() Toast.makeText(applicationContext, "Directory Created", Toast.LENGTH_LONG).show() } if (!mediaStorageDir.exists()) { if (!mediaStorageDir.mkdirs()) { Log.d("App", "failed to create directory") } } imageName = if(binding.newNameField.text.toString() == ""){ "000000001tmp000000001" } else binding.newNameField.text.toString() val file = File(mediaStorageDir, "${imageName}.jpg") val resultURI = getImagePath(this, selectedImageURI) if (resultURI != null){ copyFile(File(resultURI), file) } isImage = true } } }
1
Kotlin
0
5
d02277bd3b294cd8d40678d12a7ca5e81d931ec2
35,166
QuickPass-Mobile-Password-manager
MIT License
javatests/com/google/android/libraries/pcc/chronicle/codegen/processor/testdata/annotatedtypes/ExampleKotlinTypeReader.kt
google
564,990,777
false
{"Kotlin": 1440403, "Starlark": 163311, "Java": 10061, "AIDL": 5852, "Python": 4367, "Dockerfile": 2035, "Shell": 1301}
/* * Copyright 2022 Google LLC * * 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.google.android.libraries.pcc.chronicle.codegen.processor.testdata.annotatedtypes import com.google.android.libraries.pcc.chronicle.annotation.ChronicleConnection import com.google.android.libraries.pcc.chronicle.api.ReadConnection @ChronicleConnection(dataClass = ExampleKotlinType::class) interface ExampleKotlinTypeReader : ReadConnection { fun getExampleKotlinType(): ExampleKotlinType }
0
Kotlin
7
29
aa89a5c470f5fbb5d00496f8d4da488d9f771f67
1,003
private-compute-libraries
Apache License 2.0
src/main/kotlin/io/unthrottled/amii/core/personality/emotions/EmotionEvents.kt
ani-memes
303,354,188
false
null
package io.unthrottled.amii.core.personality.emotions import com.intellij.openapi.project.Project import com.intellij.util.messages.Topic interface MoodListener { fun onDerivedMood(currentMood: Mood) {} fun onRequestMood() {} } val EMOTION_TOPIC = Topic( "Current Mood", MoodListener::class.java ) enum class EmotionalMutationType { COOL_DOWN, RESET } enum class MoodCategory { POSITIVE, NEGATIVE, NEUTRAL } data class EmotionalMutationAction( val type: EmotionalMutationType, val moodCategory: MoodCategory, val project: Project? = null ) interface EmotionalMutationActionListener { fun onAction(emotionalMutationAction: EmotionalMutationAction) } val EMOTIONAL_MUTATION_TOPIC = Topic( "Mood Mutation", EmotionalMutationActionListener::class.java )
7
null
14
257
c9a4ef10f6e1a5ce68dc3a007b45cadbc33deed0
779
AMII
Apache License 2.0
app/src/main/java/com/boosters/promise/data/user/source/remote/UserRemoteDataSourceImpl.kt
boostcampwm-2022
562,936,971
false
{"Kotlin": 196544}
package com.boosters.promise.data.user.source.remote import com.boosters.promise.util.NetworkConnectionUtil import com.boosters.promise.data.user.di.UserModule import com.google.firebase.firestore.CollectionReference import com.google.firebase.firestore.ktx.snapshots import com.google.firebase.messaging.FirebaseMessaging import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.mapNotNull import kotlinx.coroutines.tasks.await import javax.inject.Inject import javax.inject.Singleton @Singleton class UserRemoteDataSourceImpl @Inject constructor( @UserModule.UserCollectionReference private val userCollectionReference: CollectionReference, private val networkConnectionUtil: NetworkConnectionUtil ) : UserRemoteDataSource { override suspend fun requestSignUp(userName: String): Result<UserBody> = runCatching { networkConnectionUtil.checkNetworkOnline() val userCode = userCollectionReference.document().id.take(USER_CODE_LENGTH) val token = FirebaseMessaging.getInstance().token.await() val userBody = UserBody( userCode = userCode, userName = userName, geoLocation = null, token = token ) userCollectionReference.document(userCode).set( userBody ).await() userBody } override fun getUser(userCode: String): Flow<UserBody> = userCollectionReference.document(userCode).snapshots().mapNotNull { it.toObject(UserBody::class.java) } override suspend fun getUserList(userCodeList: List<String>): Flow<List<UserBody>> = userCollectionReference.whereIn(USER_CODE_KEY, userCodeList).snapshots().mapNotNull { it.toObjects(UserBody::class.java) } override fun getUserByName(userName: String): Flow<List<UserBody>> = userCollectionReference.whereEqualTo(USER_NAME_KEY, userName).snapshots().mapNotNull { it.toObjects(UserBody::class.java) } companion object { private const val USER_CODE_LENGTH = 6 private const val USER_CODE_KEY = "userCode" private const val USER_NAME_KEY = "userName" } }
3
Kotlin
5
23
126598bc7a703001ce699d8e3772386d9ffab86a
2,173
android03-Promise
MIT License
app/src/main/java/com/example/compasswithangelinkotlin/MainActivity.kt
Scorpionorange
248,510,801
false
null
package com.example.compasswithangelinkotlin import android.animation.ObjectAnimator import android.content.Context import android.hardware.* import android.os.Build import android.os.Bundle import androidx.annotation.RequiresApi import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_main.* import kotlin.math.roundToInt import kotlin.math.roundToLong class MainActivity : AppCompatActivity(), Runnable{ private var currentDirection: Int = 0 private var mTargetDirection: Int = 0 private var accelerometerValues = FloatArray(3) private var magneticFieldValues = FloatArray(3) private lateinit var mSensorManager: SensorManager private lateinit var mOrientationSensor: Sensor private lateinit var mMagneticSensor: Sensor private lateinit var mOrientationListener: MySensorEventListener private lateinit var mMagneticListener: MySensorEventListener override fun run() { calculateOrientation() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) initServices() } @RequiresApi(Build.VERSION_CODES.KITKAT) override fun onResume(){ super.onResume() mOrientationListener = MySensorEventListener() mMagneticListener = MySensorEventListener() mSensorManager.registerListener(mOrientationListener, mOrientationSensor, Sensor.TYPE_ACCELEROMETER) mSensorManager.registerListener(mMagneticListener, mMagneticSensor, Sensor.TYPE_MAGNETIC_FIELD) } override fun onPause() { //取消注册 mSensorManager.unregisterListener(mOrientationListener) mSensorManager.unregisterListener(mMagneticListener) super.onPause() } override fun onStop() { //取消注册 mSensorManager.unregisterListener(mOrientationListener) mSensorManager.unregisterListener(mMagneticListener) super.onStop() } @RequiresApi(Build.VERSION_CODES.KITKAT) inner class MySensorEventListener : SensorEventListener2 { override fun onSensorChanged(event: SensorEvent) { if (event.sensor.type == Sensor.TYPE_ACCELEROMETER) { accelerometerValues = event.values } if (event.sensor.type == Sensor.TYPE_MAGNETIC_FIELD) { magneticFieldValues = event.values } calculateOrientation() imageRotation() currentDirection = mTargetDirection angle.text = currentDirection.toString()+"°" } override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {} override fun onFlushCompleted(sensor: Sensor?) {} } fun initServices() { mSensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager mOrientationSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) //加速度传感器 mMagneticSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD) //地磁场传感器 } fun calculateOrientation() { val values = FloatArray(3) val RValues = FloatArray(9) // 更新旋转矩阵. // 参数1: // 参数2:将磁场数据转换进实际的重力坐标中,一般默认情况下可以设置为null // 参数3:加速度 // 参数4:地磁 SensorManager.getRotationMatrix(RValues, null, accelerometerValues, magneticFieldValues) //根据旋转矩阵计算设备的方向 //参数1:旋转矩阵 //参数2:模拟方向传感器的数据 SensorManager.getOrientation(RValues, values) values[0] = Math.toDegrees(values[0].toDouble()).toFloat() //mTargetDirection = (-values[0]).roundToLong().toFloat() mTargetDirection = -values[0].roundToInt() } fun imageRotation(){ //顺时针转动为正,故手机顺时针转动时,图片得逆时针转动 //让图片相对自身中心点转动,开始角度默认为0;此后开始角度等于上一次结束角度 val animator = ObjectAnimator.ofFloat( compassImage, "rotation", currentDirection.toFloat(), mTargetDirection.toFloat()) animator.duration = 100 animator.start() } }
0
Kotlin
0
0
51e2e679ad44b80d03c129e0bb537e4185a367cb
4,004
CompassWithAngelInKotlin
Apache License 2.0
AOS/app/src/main/java/com/example/eeos/consts/Consts.kt
JNU-econovation
696,705,501
false
null
package com.example.eeos.consts val programCategory = listOf("all", "weekly", "presidentTeam", "eventTeam", "etc") val programStatus = listOf("active", "end") val categoryChips: List<String> = listOf( "전체", "주간 발표", "회장단", "행사부", "기타 행사" ) val programStatusChips: List<String> = listOf( "진행 중", "완료" ) object ProgramType { const val demand = " demand" const val notification = "notification" } object AttendStatus { const val attend = "attend" const val absent = "absent" const val late = "late" const val nonResponse = "nonResponse" const val nonRelated = "nonRelated" } val attendStatusMap = mapOf( "attend" to "참석", "absent" to "불참", "late" to "지각", "nonResponse" to "미정" ) object MemberStatus { const val AM = "AM" const val RM = "RM" const val CM = "CM" const val OB = "OB" } val memberStatusMap = mapOf( "AM" to "am", "RM" to "rm", "CM" to "cm", "OB" to "ob" ) object SnackBarMessage { const val onActiveStatusChanged = "회원 상태가 변경 되었습니다." const val onAttendStatusChanged = "참석 상태가 변경 되었습니다." const val onLogout = "성공적으로 로그아웃 되었습니다." } object ProgramStatus { const val active = "active" const val end = "end" }
3
null
7
6
4d58bddd313e94e38586ff3dcd23784e167274e6
1,249
EEOS
MIT License
Corona-Warn-App/src/test/java/testhelpers/extensions/TimeExtensions.kt
corona-warn-app
268,027,139
false
null
package testhelpers.extensions import java.time.Instant import java.time.ZonedDateTime fun String.toInstant(): Instant = ZonedDateTime.parse(this).toInstant()
6
Kotlin
504
2,486
7b0eee8d53a090ee0ca585c6a90c4cec570e51d6
161
cwa-app-android
Apache License 2.0
tilbakekreving/infrastructure/src/test/kotlin/infrastructure/repo/OpprettTilbakekrevingsbehandlingRepoTest.kt
navikt
227,366,088
false
{"Kotlin": 8994200, "Shell": 4369, "TSQL": 1233, "Dockerfile": 800}
package infrastructure.repo import io.kotest.matchers.shouldBe import no.nav.su.se.bakover.common.extensions.februar import no.nav.su.se.bakover.test.TikkendeKlokke import no.nav.su.se.bakover.test.fixedClock import no.nav.su.se.bakover.test.fixedClockAt import no.nav.su.se.bakover.test.persistence.TestDataHelper import no.nav.su.se.bakover.test.persistence.withMigratedDb import org.junit.jupiter.api.Test import tilbakekreving.domain.TilbakekrevingsbehandlingHendelser /** * Disse testene dekker også hentForSak og hent(hendelseId) */ class OpprettTilbakekrevingsbehandlingRepoTest { @Test fun `kan opprette og hente tilbakekrevingsbehandling`() { val clock = TikkendeKlokke(fixedClockAt(1.februar(2021))) withMigratedDb { dataSource -> val testDataHelper = TestDataHelper(dataSource = dataSource, clock = clock) val (sak, _, _, _, _, _, hendelse, oppgaveHendelse) = testDataHelper.persisterOpprettetTilbakekrevingsbehandlingHendelse() val actual = testDataHelper.tilbakekrevingHendelseRepo.hentForSak(sak.id) val actualKravgrunnlag = testDataHelper.kravgrunnlagPostgresRepo.hentKravgrunnlagPåSakHendelser(sak.id).also { it.size shouldBe 1 it.detaljerSortert.first().kravgrunnlag shouldBe sak.uteståendeKravgrunnlag } actual shouldBe TilbakekrevingsbehandlingHendelser.create( sakId = sak.id, clock = fixedClock, hendelser = listOf(hendelse), kravgrunnlagPåSak = actualKravgrunnlag, oppgaveHendelser = listOf(oppgaveHendelse), dokumentHendelser = listOf(), ) } } }
1
Kotlin
1
1
82897d6bc412e9a086063aece4d1a54822ad2c82
1,752
su-se-bakover
MIT License
intellij.tools.ide.starter/src/com/intellij/ide/starter/utils/utils.kt
JetBrains
499,194,001
false
null
package com.intellij.ide.starter.utils import com.intellij.ide.starter.di.di import com.intellij.ide.starter.ide.IDETestContext import com.intellij.ide.starter.path.GlobalPaths import com.intellij.ide.starter.process.exec.ExecOutputRedirect import com.intellij.ide.starter.process.exec.ProcessExecutor import com.intellij.ide.starter.system.SystemInfo import org.kodein.di.direct import org.kodein.di.instance import java.io.* import java.lang.Long.numberOfLeadingZeros import java.nio.charset.Charset import java.nio.file.FileStore import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import java.time.LocalDateTime import java.time.format.DateTimeFormatter import kotlin.io.path.* import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.seconds fun formatArtifactName(artifactType: String, testName: String): String { val testNameFormatted = testName.replace("/", "-").replace(" ", "") val time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) return "$artifactType-$testNameFormatted-$time" } fun getThrowableText(t: Throwable): String { val writer = StringWriter() t.printStackTrace(PrintWriter(writer)) return writer.buffer.toString() } /** * In case of success - return T * In case of error - print error to stderr and return null */ inline fun <T> catchAll(action: () -> T): T? { try { return action() } catch (t: Throwable) { logError("CatchAll swallowed error: ${t.message}") logError(getThrowableText(t)) return null } } fun FileStore.getDiskInfo(): String = buildString { appendLine("Disk info of ${name()}") appendLine(" Total space: " + totalSpace.formatSize()) appendLine(" Unallocated space: " + unallocatedSpace.formatSize()) appendLine(" Usable space: " + usableSpace.formatSize()) } fun Runtime.getRuntimeInfo(): String = buildString { appendLine("Memory info") appendLine(" Total memory: " + totalMemory().formatSize()) appendLine(" Free memory: " + freeMemory().formatSize()) appendLine(" Max memory: " + maxMemory().formatSize()) } /** * Invoke cmd: java [arg1 arg2 ... argN] */ fun execJavaCmd(javaHome: Path, args: Iterable<String> = listOf()): List<String> { val ext = if (SystemInfo.isWindows) ".exe" else "" val realJavaHomePath = if (javaHome.isSymbolicLink()) javaHome.readSymbolicLink() else javaHome val java = realJavaHomePath.toAbsolutePath().resolve("bin/java$ext") require(java.isRegularFile()) { "Java is not found under $java" } val prefix = "exec-java-cmd" val stdout = ExecOutputRedirect.ToString() val stderr = ExecOutputRedirect.ToString() val processArguments = listOf(java.toString()).plus(args) ProcessExecutor( presentableName = prefix, workDir = javaHome, timeout = 1.minutes, args = processArguments, stdoutRedirect = stdout, stderrRedirect = stderr ).start() val mergedOutput = listOf(stdout, stderr) .flatMap { it.read().split(System.lineSeparator()) } .map { it.trim() } .filter { it.isNotBlank() } logOutput( """ Result of calling $processArguments: ${mergedOutput.joinToString(System.lineSeparator())} """) return mergedOutput } /** * Invoke java -version * * @return * openjdk version "17.0.1" 2021-10-19 LTS * OpenJDK Runtime Environment Corretto-17.0.1.12.1 (build 17.0.1+12-LTS) * OpenJDK 64-Bit Server VM Corretto-17.0.1.12.1 (build 17.0.1+12-LTS, mixed mode, sharing) */ fun callJavaVersion(javaHome: Path): String = execJavaCmd(javaHome, listOf("-version")).joinToString(System.lineSeparator()) fun isX64Jdk(javaHome: Path): Boolean { val archProperty = execJavaCmd(javaHome, listOf("-XshowSettings:all", "-version")).firstOrNull { it.startsWith("sun.arch.data.model") } if (archProperty.isNullOrBlank()) throw IllegalAccessException("Couldn't get architecture property sun.arch.data.model value from JDK") return archProperty.trim().endsWith("64") } fun resolveInstalledJdk11(): Path { val jdkEnv = listOf("JDK_11_X64", "JAVA_HOME").firstNotNullOfOrNull { System.getenv(it) } ?: System.getProperty("java.home") val javaHome = jdkEnv?.let { val path = Path(it) if (path.isSymbolicLink()) path.readSymbolicLink() else path } if (javaHome == null || !javaHome.exists()) throw IllegalArgumentException("Java Home $javaHome is null, empty or doesn't exist. Specify JAVA_HOME to point to JDK 11 x64") require(javaHome.isDirectory() && Files.walk(javaHome) .use { it.count() } > 10) { "Java Home $javaHome is not found or empty!" } require(isX64Jdk(javaHome)) { "JDK at path $javaHome should support x64 architecture" } return javaHome } fun String.withIndent(indent: String = " "): String = lineSequence().map { "$indent$it" }.joinToString(System.lineSeparator()) private fun quoteArg(arg: String): String { val specials = " #'\"\n\r\t\u000c" if (!specials.any { arg.contains(it) }) { return arg } val sb = StringBuilder(arg.length * 2) for (element in arg) { when (element) { ' ', '#', '\'' -> sb.append('"').append(element).append('"') '"' -> sb.append("\"\\\"\"") '\n' -> sb.append("\"\\n\"") '\r' -> sb.append("\"\\r\"") '\t' -> sb.append("\"\\t\"") else -> sb.append(element) } } return sb.toString() } /** * Writes list of Java arguments to the Java Command-Line Argument File * See https://docs.oracle.com/javase/9/tools/java.htm, section "java Command-Line Argument Files" **/ fun writeJvmArgsFile(argFile: File, args: List<String>, lineSeparator: String = System.lineSeparator(), charset: Charset = Charsets.UTF_8) { BufferedWriter(OutputStreamWriter(FileOutputStream(argFile), charset)).use { writer -> for (arg in args) { writer.write(quoteArg(arg)) writer.write(lineSeparator) } } } fun takeScreenshot(logsDir: Path) { val toolsDir = di.direct.instance<GlobalPaths>().getCacheDirectoryFor("tools") val toolName = "TakeScreenshot" val screenshotTool = toolsDir / toolName if (!File(screenshotTool.toString()).exists()) { val archivePath = toolsDir / "$toolName.zip" HttpClient.download("https://repo.labs.intellij.net/phpstorm/tools/TakeScreenshot-1.02.zip", archivePath) FileSystem.unpack(archivePath, screenshotTool) } val screenshotFile = logsDir.resolve("screenshot_beforeKill.jpg") val toolPath = screenshotTool.resolve("$toolName.jar") val javaPath = ProcessHandle.current().info().command().orElseThrow().toString() ProcessExecutor( presentableName = "take-screenshot", workDir = toolsDir, timeout = 15.seconds, args = mutableListOf(javaPath, "-jar", toolPath.absolutePathString(), screenshotFile.toString()), environmentVariables = mapOf("DISPLAY" to ":88"), onlyEnrichExistedEnvVariables = true ).start() if (screenshotFile.exists()) { logOutput("Screenshot saved in $screenshotFile") } else { error("Couldn't take screenshot") } } fun collectJBRDiagnosticFilesIfExist(context: IDETestContext) { val userHome = System.getProperty("user.home") val pathUserHome = Paths.get(userHome) val listOfJavaErrorFiles = pathUserHome.toFile().listFiles().filter { it.nameWithoutExtension.startsWith("java_error_in_idea_") && it.extension == "log" } if(listOfJavaErrorFiles.isNotEmpty()) { listOfJavaErrorFiles.forEach { if (!context.paths.jbrDiagnostic.resolve(it.name).toFile().exists()) it.copyTo(context.paths.jbrDiagnostic.resolve(it.name).toFile()) } context.publishArtifact(context.paths.jbrDiagnostic) } } fun startProfileNativeThreads(pid: String) { if (!SystemInfo.isWindows) { val toolsDir = di.direct.instance<GlobalPaths>().getCacheDirectoryFor("tools") val toolName = when { SystemInfo.isMac -> "async-profiler-2.7-macos" SystemInfo.isLinux -> "async-profiler-2.7-linux-x64" else -> error("Not supported OS") } val profiler = toolsDir / toolName downloadAsyncProfilerIfNeeded(profiler, toolsDir) givePermissionsToExecutables(profiler) ProcessExecutor( presentableName = "start-profile", workDir = profiler, timeout = 15.seconds, args = mutableListOf("./profiler.sh", "start", pid) ).start() } } private fun givePermissionsToExecutables(profiler: Path) { ProcessExecutor( presentableName = "give-permissions-to-jattach", workDir = profiler.resolve("build"), timeout = 10.seconds, args = mutableListOf("chmod", "+x", "jattach") ).start() ProcessExecutor( presentableName = "give-permissions-to-profiler", workDir = profiler, timeout = 10.seconds, args = mutableListOf("chmod", "+x", "profiler.sh") ).start() } fun stopProfileNativeThreads(pid: String, fileToStoreInfo: String) { if (!SystemInfo.isWindows) { val toolsDir = di.direct.instance<GlobalPaths>().getCacheDirectoryFor("tools") val toolName = "async-profiler-2.7-macos" val profiler = toolsDir / toolName ProcessExecutor( presentableName = "stop-profile", workDir = profiler, timeout = 15.seconds, args = mutableListOf("./profiler.sh", "stop", pid, "-f", fileToStoreInfo) ).start() } } private fun downloadAsyncProfilerIfNeeded(profiler: Path, toolsDir: Path) { if (!File(profiler.toString()).exists()) { val profilerFileName = when { SystemInfo.isMac -> "async-profiler-2.7-macos.zip" SystemInfo.isLinux -> "async-profiler-2.7-linux-x64.tar.gz" else -> error("Current OS is not supported") } val archivePath = toolsDir / profilerFileName HttpClient.download("https://github.com/jvm-profiling-tools/async-profiler/releases/download/v2.7/$profilerFileName", archivePath) FileSystem.unpack(archivePath, toolsDir) } } fun Long.formatSize(): String { if (this < 1024) return "$this B" val z = (63 - numberOfLeadingZeros(this)) / 10 return String.format("%.1f %sB", this.toDouble() / (1L shl z * 10), " KMGTPE"[z]) } fun pathInsideJarFile( jarFile: Path, pathInsideJar: String ): String = jarFile.toAbsolutePath().toString().trimEnd('/') + "!/" + pathInsideJar data class FindUsagesCallParameters(val pathToFile: String, val offset: String, val element: String) { override fun toString() = "$pathToFile $element, $offset)" }
1
null
2
8
ffff397bd7f4cbfbaf135eeaadc6f5e4ed85a84b
10,372
intellij-ide-starter
Apache License 2.0
plugin-unity-agent/src/main/kotlin/jetbrains/buildServer/unity/messages/BuildProblem.kt
JetBrains
159,985,216
false
{"Kotlin": 258801, "ANTLR": 53548, "Java": 30081, "C#": 4690, "Shell": 3230, "Batchfile": 1180}
/* * Copyright 2000-2023 JetBrains s.r.o. * * 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 jetbrains.buildServer.unity.messages import jetbrains.buildServer.messages.serviceMessages.MessageWithAttributes import jetbrains.buildServer.messages.serviceMessages.ServiceMessageTypes class BuildProblem : MessageWithAttributes { private constructor(attributes: Map<String, String>) : super(ServiceMessageTypes.BUILD_PORBLEM, attributes) constructor(description: String) : this(mapOf("description" to description)) }
41
Kotlin
40
73
9f7fbb31a25be1abafcd8d77fd62d369598cd47b
1,039
teamcity-unity-plugin
Apache License 2.0
src/main/kotlin/character/ActiveClassJob.kt
drakon64
622,012,311
false
{"Kotlin": 174367}
package cloud.drakon.ktlodestone.character /** A Character's active [ClassJob]. */ data class ActiveClassJob( val classJob: ClassJob, val level: Byte, val discipline: Discipline, )
1
Kotlin
0
1
deed0581e6f8485769afb622fd4d18571edab287
194
KtLodestone
MIT License
src/test/kotlin/lambdada/parsec/parser/T08_JSonParser.kt
d-plaindoux
117,681,573
false
null
package lambdada.parsec.parser import lambdada.parsec.examples.json.* import lambdada.parsec.io.Reader import org.junit.Assert.assertEquals import org.junit.Test class T08_JSonParser { @Test fun shouldJSonParserReturnInteger() { val parser = JSonParser.JSON assertEquals(parser.invoke(Reader.string("42")).fold({ it.value == JSonNumber(42F) }, { false }), true) } @Test fun shouldJSonParserReturnNull() { val parser = JSonParser.JSON assertEquals(parser.invoke(Reader.string("null")).fold({ it.value == JSonNull }, { false }), true) } @Test fun shouldJSonParserReturnTrue() { val parser = JSonParser.JSON assertEquals(parser.invoke(Reader.string("true")).fold({ it.value == JSonBoolean(true) }, { false }), true) } @Test fun shouldJSonParserReturnFalse() { val parser = JSonParser.JSON assertEquals(parser.invoke(Reader.string("false")).fold({ it.value == JSonBoolean(false) }, { false }), true) } @Test fun shouldJSonParserReturnString() { val parser = JSonParser.JSON assertEquals(parser.invoke(Reader.string("\"42\"")).fold({ it.value == JSonString("42") }, { false }), true) } @Test fun shouldJSonParserReturnEmptyArray() { val parser = JSonParser.JSON assertEquals(parser.invoke(Reader.string("[]")).fold({ it.value == JSonArray(listOf()) }, { false }), true) } @Test fun shouldJSonParserReturnEmptyObject() { val parser = JSonParser.JSON assertEquals(parser.invoke(Reader.string("{}")).fold({ it.value == JSonObject(mapOf()) }, { false }), true) } @Test fun shouldJSonParserReturnSingletonObject() { val parser = JSonParser.JSON assertEquals(parser.invoke(Reader.string("{\"a\":42}")).fold({ it.value == JSonObject(mapOf("a" to JSonNumber(42F))) }, { false }), true) } @Test fun shouldJSonParserReturnSingletonArray() { val parser = JSonParser.JSON assertEquals(parser.invoke(Reader.string("[42]")).fold({ it.value == JSonArray(listOf(JSonNumber(42F))) }, { false }), true) } @Test fun shouldJSonParserReturnArray() { val parser = JSonParser.JSON assertEquals(parser.invoke(Reader.string("[42,43]")).fold({ it.value == JSonArray(listOf(JSonNumber(42F), JSonNumber(43F))) }, { false }), true) } @Test fun shouldParseJSon1k() { val parser = JSonParser.JSON val url = T08_JSonParser::class.java.getResource("/1k.json") val reader = JSonParser.reader(Reader.url(url)) assertEquals(parser.invoke(reader).fold({ true }, { false }), true) } }
0
Kotlin
5
12
24146ec4e28304bc9234e970ab571a3af9ddf23a
2,690
parsec.kotlin
Apache License 2.0
data/src/main/java/com/semicolon/data/remote/request/exercise/FinishMeasureExerciseRequest.kt
Walkhub
443,006,389
false
null
package com.semicolon.data.remote.request.exercise import com.google.gson.annotations.SerializedName data class FinishMeasureExerciseRequest( @SerializedName("walk_count") val walkCount: Int, @SerializedName("distance") val distanceAsCentimeter: Int, @SerializedName("calorie") val kilocalorie: Int, @SerializedName("image_url") val imageUrl: String, @SerializedName("paused_time") val pausedTime: Long )
5
Kotlin
1
29
5070c2c33365f2db6f57975078e1ecd7594f66fa
426
walkhub_android
MIT License
app/src/main/kotlin/ru/subtlefox/mvi/cookbook/screens/sample2/mvi/entitiy/DynamicCurrencyAction.kt
Subtle-fox
518,114,574
false
{"Kotlin": 96952, "Java": 47}
package ru.subtlefox.mvi.cookbook.screens.sample2.mvi.entitiy sealed class DynamicCurrencyAction { object ChangeCurrency : DynamicCurrencyAction() { override fun toString() = "ChangeCurrency" } }
0
Kotlin
0
4
cbd0d60a002b72688647345c3415b06c5bb39fac
213
MVI-on-Flow
Apache License 2.0
build-logic/src/main/kotlin/plugin/compose/ComposeMultiplatformPlugin.kt
taetae98coding
704,079,988
false
{"Kotlin": 118985, "Swift": 451, "Ruby": 107}
package plugin.compose import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.plugins.PluginManager internal class ComposeMultiplatformPlugin : Plugin<Project> { private val composeAndroidPlugin = ComposeAndroidPlugin() override fun apply(target: Project) { applyPlugin(target.pluginManager) composeAndroidPlugin.apply(target) } private fun applyPlugin(manager: PluginManager) = with(manager) { apply("org.jetbrains.compose") } }
0
Kotlin
0
0
f6c9c29c09072f173845ccbd96161676e85e8ebb
503
CodeLab
Apache License 2.0
kotlin-project/rekindle-book-store-aqa/domain/core/src/main/kotlin/com/rekindle/book/store/domain/configuration/endpoint/CustomersEndpoint.kt
amfibolos
845,646,691
false
{"Kotlin": 69165, "C#": 51552, "TypeScript": 47535, "JavaScript": 574}
package com.rekindle.book.store.domain.configuration.endpoint import org.aeonbits.owner.Config import org.aeonbits.owner.Config.Key import org.aeonbits.owner.Config.Sources @Sources(value = ["classpath:endpoints/customers-endpoints.properties"]) interface CustomersEndpoint : Config { @Key("customers") fun customers(): String @Key("customer.by.id") fun customerById(): String }
0
Kotlin
0
0
d33eada0e214304ae083bb840b3877ca41a171c9
399
rekindle-aqa
Apache License 2.0
app/src/main/java/com/example/myapplication/data/repository/TopHeadlinesRepository.kt
DeMoss15
222,141,463
false
null
package com.example.myapplication.data.repository import com.example.myapplication.domain.model.Article import io.reactivex.Single interface TopHeadlinesRepository { fun getTopHeadlines( page: Int, query: String? = null, sources: String? = null, category: String? = null, country: String? = null ): Single<List<Article>> }
0
Kotlin
0
0
bc9dd558000f8fbe996cca82477bea98dd2a5c31
372
PaginatorRenderKit
Apache License 2.0
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/workspacesweb/CfnNetworkSettingsProps.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 142794926}
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package io.cloudshiftdev.awscdk.services.workspacesweb import io.cloudshiftdev.awscdk.CfnTag import io.cloudshiftdev.awscdk.common.CdkDslMarker import io.cloudshiftdev.awscdk.common.CdkObject import io.cloudshiftdev.awscdk.common.CdkObjectWrappers import kotlin.String import kotlin.Unit import kotlin.collections.List /** * Properties for defining a `CfnNetworkSettings`. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import io.cloudshiftdev.awscdk.services.workspacesweb.*; * CfnNetworkSettingsProps cfnNetworkSettingsProps = CfnNetworkSettingsProps.builder() * .securityGroupIds(List.of("securityGroupIds")) * .subnetIds(List.of("subnetIds")) * .vpcId("vpcId") * // the properties below are optional * .tags(List.of(CfnTag.builder() * .key("key") * .value("value") * .build())) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-workspacesweb-networksettings.html) */ public interface CfnNetworkSettingsProps { /** * One or more security groups used to control access from streaming instances to your VPC. * * *Pattern* : `^[\w+\-]+$` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-workspacesweb-networksettings.html#cfn-workspacesweb-networksettings-securitygroupids) */ public fun securityGroupIds(): List<String> /** * The subnets in which network interfaces are created to connect streaming instances to your VPC. * * At least two of these subnets must be in different availability zones. * * *Pattern* : `^subnet-([0-9a-f]{8}|[0-9a-f]{17})$` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-workspacesweb-networksettings.html#cfn-workspacesweb-networksettings-subnetids) */ public fun subnetIds(): List<String> /** * The tags to add to the network settings resource. * * A tag is a key-value pair. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-workspacesweb-networksettings.html#cfn-workspacesweb-networksettings-tags) */ public fun tags(): List<CfnTag> = unwrap(this).getTags()?.map(CfnTag::wrap) ?: emptyList() /** * The VPC that streaming instances will connect to. * * *Pattern* : `^vpc-[0-9a-z]*$` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-workspacesweb-networksettings.html#cfn-workspacesweb-networksettings-vpcid) */ public fun vpcId(): String /** * A builder for [CfnNetworkSettingsProps] */ @CdkDslMarker public interface Builder { /** * @param securityGroupIds One or more security groups used to control access from streaming * instances to your VPC. * *Pattern* : `^[\w+\-]+$` */ public fun securityGroupIds(securityGroupIds: List<String>) /** * @param securityGroupIds One or more security groups used to control access from streaming * instances to your VPC. * *Pattern* : `^[\w+\-]+$` */ public fun securityGroupIds(vararg securityGroupIds: String) /** * @param subnetIds The subnets in which network interfaces are created to connect streaming * instances to your VPC. * At least two of these subnets must be in different availability zones. * * *Pattern* : `^subnet-([0-9a-f]{8}|[0-9a-f]{17})$` */ public fun subnetIds(subnetIds: List<String>) /** * @param subnetIds The subnets in which network interfaces are created to connect streaming * instances to your VPC. * At least two of these subnets must be in different availability zones. * * *Pattern* : `^subnet-([0-9a-f]{8}|[0-9a-f]{17})$` */ public fun subnetIds(vararg subnetIds: String) /** * @param tags The tags to add to the network settings resource. * A tag is a key-value pair. */ public fun tags(tags: List<CfnTag>) /** * @param tags The tags to add to the network settings resource. * A tag is a key-value pair. */ public fun tags(vararg tags: CfnTag) /** * @param vpcId The VPC that streaming instances will connect to. * *Pattern* : `^vpc-[0-9a-z]*$` */ public fun vpcId(vpcId: String) } private class BuilderImpl : Builder { private val cdkBuilder: software.amazon.awscdk.services.workspacesweb.CfnNetworkSettingsProps.Builder = software.amazon.awscdk.services.workspacesweb.CfnNetworkSettingsProps.builder() /** * @param securityGroupIds One or more security groups used to control access from streaming * instances to your VPC. * *Pattern* : `^[\w+\-]+$` */ override fun securityGroupIds(securityGroupIds: List<String>) { cdkBuilder.securityGroupIds(securityGroupIds) } /** * @param securityGroupIds One or more security groups used to control access from streaming * instances to your VPC. * *Pattern* : `^[\w+\-]+$` */ override fun securityGroupIds(vararg securityGroupIds: String): Unit = securityGroupIds(securityGroupIds.toList()) /** * @param subnetIds The subnets in which network interfaces are created to connect streaming * instances to your VPC. * At least two of these subnets must be in different availability zones. * * *Pattern* : `^subnet-([0-9a-f]{8}|[0-9a-f]{17})$` */ override fun subnetIds(subnetIds: List<String>) { cdkBuilder.subnetIds(subnetIds) } /** * @param subnetIds The subnets in which network interfaces are created to connect streaming * instances to your VPC. * At least two of these subnets must be in different availability zones. * * *Pattern* : `^subnet-([0-9a-f]{8}|[0-9a-f]{17})$` */ override fun subnetIds(vararg subnetIds: String): Unit = subnetIds(subnetIds.toList()) /** * @param tags The tags to add to the network settings resource. * A tag is a key-value pair. */ override fun tags(tags: List<CfnTag>) { cdkBuilder.tags(tags.map(CfnTag::unwrap)) } /** * @param tags The tags to add to the network settings resource. * A tag is a key-value pair. */ override fun tags(vararg tags: CfnTag): Unit = tags(tags.toList()) /** * @param vpcId The VPC that streaming instances will connect to. * *Pattern* : `^vpc-[0-9a-z]*$` */ override fun vpcId(vpcId: String) { cdkBuilder.vpcId(vpcId) } public fun build(): software.amazon.awscdk.services.workspacesweb.CfnNetworkSettingsProps = cdkBuilder.build() } private class Wrapper( cdkObject: software.amazon.awscdk.services.workspacesweb.CfnNetworkSettingsProps, ) : CdkObject(cdkObject), CfnNetworkSettingsProps { /** * One or more security groups used to control access from streaming instances to your VPC. * * *Pattern* : `^[\w+\-]+$` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-workspacesweb-networksettings.html#cfn-workspacesweb-networksettings-securitygroupids) */ override fun securityGroupIds(): List<String> = unwrap(this).getSecurityGroupIds() /** * The subnets in which network interfaces are created to connect streaming instances to your * VPC. * * At least two of these subnets must be in different availability zones. * * *Pattern* : `^subnet-([0-9a-f]{8}|[0-9a-f]{17})$` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-workspacesweb-networksettings.html#cfn-workspacesweb-networksettings-subnetids) */ override fun subnetIds(): List<String> = unwrap(this).getSubnetIds() /** * The tags to add to the network settings resource. * * A tag is a key-value pair. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-workspacesweb-networksettings.html#cfn-workspacesweb-networksettings-tags) */ override fun tags(): List<CfnTag> = unwrap(this).getTags()?.map(CfnTag::wrap) ?: emptyList() /** * The VPC that streaming instances will connect to. * * *Pattern* : `^vpc-[0-9a-z]*$` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-workspacesweb-networksettings.html#cfn-workspacesweb-networksettings-vpcid) */ override fun vpcId(): String = unwrap(this).getVpcId() } public companion object { public operator fun invoke(block: Builder.() -> Unit = {}): CfnNetworkSettingsProps { val builderImpl = BuilderImpl() return Wrapper(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.workspacesweb.CfnNetworkSettingsProps): CfnNetworkSettingsProps = CdkObjectWrappers.wrap(cdkObject) as? CfnNetworkSettingsProps ?: Wrapper(cdkObject) internal fun unwrap(wrapped: CfnNetworkSettingsProps): software.amazon.awscdk.services.workspacesweb.CfnNetworkSettingsProps = (wrapped as CdkObject).cdkObject as software.amazon.awscdk.services.workspacesweb.CfnNetworkSettingsProps } }
1
Kotlin
0
4
a18731816a3ec710bc89fb8767d2ab71cec558a6
9,523
kotlin-cdk-wrapper
Apache License 2.0
app/src/main/java/com/suihan74/satena/scenes/authentication/MastodonAuthenticationActivity.kt
suihan74
207,459,108
false
{"Kotlin": 1729040, "Java": 10330}
package com.suihan74.satena.scenes.authentication import android.content.Intent import android.net.Uri import android.os.Bundle import android.util.Log import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.browser.customtabs.CustomTabColorSchemeParams import androidx.browser.customtabs.CustomTabsIntent import androidx.core.content.ContextCompat import androidx.lifecycle.lifecycleScope import com.google.gson.Gson import com.suihan74.satena.R import com.suihan74.satena.SatenaApplication import com.suihan74.satena.databinding.ActivityMastodonAuthenticationBinding import com.suihan74.utilities.extensions.ContextExtensions.showToast import com.sys1yagi.mastodon4j.MastodonClient import com.sys1yagi.mastodon4j.api.Scope import com.sys1yagi.mastodon4j.api.entity.auth.AppRegistration import com.sys1yagi.mastodon4j.api.method.Apps import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import okhttp3.OkHttpClient import org.chromium.customtabsclient.shared.CustomTabsHelper class MastodonAuthenticationActivity : AppCompatActivity() { private lateinit var binding : ActivityMastodonAuthenticationBinding // ------ // override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMastodonAuthenticationBinding.inflate(layoutInflater) setContentView(binding.root) binding.authButton.setOnClickListener { showProgressBar() lifecycleScope.launch(Dispatchers.Main) { try { startAuthorizeMastodon(binding.instanceName.text.toString()) } catch (e: Throwable) { Log.w("FailedToSignIn", e) showToast("インスタンスが見つかりません") } finally { hideProgressBar() } } } } override fun onResume() { super.onResume() if (Intent.ACTION_VIEW == intent.action) { val uri = intent.data if (uri?.scheme == "satena-mastodon") { lifecycleScope.launch(Dispatchers.Main) { showProgressBar() try { val instance = uri.host!! val authCode = uri.getQueryParameter("code") ?: throw Exception("invalid code") continueAuthorizeMastodon(instance, authCode) showToast("$instance にログイン完了") // 前の画面に戻る finish() } catch (e: Throwable) { Log.e("FailedToSignIn", e.message ?: "") showToast("ログイン失敗") } finally { hideProgressBar() } } } } } // ------ // /** Mastodonインスタンスへのアプリの登録情報を端末に保存する */ private fun writeAppRegistration(instance: String, appRegistration: AppRegistration) { val filename = "mstdn_app_reg_$instance" openFileOutput(filename, MODE_PRIVATE).use { val json = Gson().toJson(appRegistration) it.write(json.toByteArray()) } } /** 既に端末に保存されているMastodonインスタンスへのアプリの登録情報を取得する */ private fun readAppRegistration(instance: String) : AppRegistration? { val filename = "mstdn_app_reg_$instance" val result = runCatching { openFileInput(filename).bufferedReader().useLines { lines -> val json = lines.fold("") { some, text -> "$some\n$text" } Gson().fromJson(json, AppRegistration::class.java) } } return result.getOrNull() } // ------ // private suspend fun startAuthorizeMastodon(instance: String) = withContext(Dispatchers.IO) { val client = MastodonClient.Builder( instance, OkHttpClient.Builder(), Gson() ).build() val apps = Apps(client) val appRegistration = readAppRegistration(instance) ?: apps.createApp( "Satena for Android", "satena-mastodon://$instance/callback", Scope(Scope.Name.ALL), getString(R.string.developer_website) ).execute() .also { writeAppRegistration(instance, it) } val url = apps.getOAuthUrl( clientId = appRegistration.clientId, scope = Scope(Scope.Name.ALL), redirectUri = "satena-mastodon://$instance/callback" ) withContext(Dispatchers.Main) { val context = this@MastodonAuthenticationActivity val intent = CustomTabsIntent.Builder() .setShowTitle(true) .setUrlBarHidingEnabled(true) .setDefaultColorSchemeParams(CustomTabColorSchemeParams.Builder() .setToolbarColor(ContextCompat.getColor(context, R.color.colorPrimary)) .build() ) .build() .apply { val packageName = CustomTabsHelper.getPackageNameToUse(context) intent.setPackage(packageName) } intent.launchUrl(context, Uri.parse(url)) } } private suspend fun continueAuthorizeMastodon(instanceName: String, code: String) = withContext(Dispatchers.IO) { val client = MastodonClient.Builder( instanceName, OkHttpClient.Builder(), Gson() ).build() val apps = Apps(client) val appRegistration = readAppRegistration(instanceName)!! val clientId = appRegistration.clientId val clientSecret = appRegistration.clientSecret val redirectUri = appRegistration.redirectUri val accessToken = apps.getAccessToken( clientId, clientSecret, redirectUri, code, "authorization_code" ).execute() // make a MastodonClient // persist AccessToken SatenaApplication.instance.accountLoader .signInMastodon(instanceName, accessToken.accessToken) } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) setIntent(intent) } // ------ // private fun showProgressBar() { binding.clickGuard.visibility = View.VISIBLE binding.progressBar.visibility = View.VISIBLE } private fun hideProgressBar() { binding.clickGuard.visibility = View.GONE binding.progressBar.visibility = View.GONE } }
34
Kotlin
1
7
ee29a0ed1d60c9ee35bb03f128d0e39c58e3a4c4
6,857
Satena
MIT License
app/src/main/java/com/simbiri/equityjamii/ui/main_activity/my_profile/NetworkFragment.kt
SimbaSimbiri
706,250,529
false
{"Kotlin": 196968}
package com.simbiri.equityjamii.ui.main_activity.my_profile import android.app.Dialog import android.content.Context import androidx.fragment.app.viewModels import android.os.Bundle import android.util.DisplayMetrics import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.WindowManager import androidx.viewpager2.adapter.FragmentStateAdapter import com.google.android.material.bottomsheet.BottomSheetBehavior import com.google.android.material.bottomsheet.BottomSheetDialog import com.google.android.material.bottomsheet.BottomSheetDialogFragment import com.google.android.material.tabs.TabLayoutMediator import com.simbiri.equityjamii.R import com.simbiri.equityjamii.data.model.Network import com.simbiri.equityjamii.databinding.DialogNetworkBinding class NetworkFragment : BottomSheetDialogFragment() { companion object { private const val ARGS_NETWORK = "NETWORK_INFO" fun newInstance(myNetwork: Network?): NetworkFragment{ val fragReturn = NetworkFragment() val networkBundle = Bundle() networkBundle.putParcelable(ARGS_NETWORK, myNetwork) fragReturn.arguments = networkBundle return fragReturn } } private lateinit var binding: DialogNetworkBinding private val viewModel: NetworkViewModel by viewModels() private var networkParced : Network? = Network() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = DialogNetworkBinding.inflate(layoutInflater) val view = binding.root networkParced = arguments?.getParcelable<Network>(ARGS_NETWORK) networkParced.let { viewModel.setNetwork(networkParced!!) } setupViewPagerAndTabs() return view } private fun setupViewPagerAndTabs() { val pagerAdapter = NetworkPagerAdapter(this) binding.viewPagerNetwork.apply { adapter = pagerAdapter isUserInputEnabled = false } TabLayoutMediator(binding.tabLayoutNetwork, binding.viewPagerNetwork) { tab, position -> tab.text = when (position) { 0 -> "Following ${networkParced?.followingList?.size}" 1 -> "Followers ${networkParced?.followerList?.size}" 2 -> "Recommended" else -> "" } }.attach() } class NetworkPagerAdapter(fragment: Fragment) : FragmentStateAdapter(fragment) { override fun getItemCount(): Int = 3 override fun createFragment(position: Int): Fragment { return when (position) { 2 -> RecommendedFragment() 0 -> FollowingFragment() 1 -> FollowersFragment() else -> Fragment() } } } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dialog = super.onCreateDialog(savedInstanceState) dialog.setContentView(R.layout.dialog_network) dialog.setCanceledOnTouchOutside(true) val displayMetrics = DisplayMetrics() val windowManager = requireActivity().getSystemService(Context.WINDOW_SERVICE) as WindowManager windowManager.defaultDisplay.getMetrics(displayMetrics) dialog.setOnShowListener { dialogInterface -> val bottomSheetDialog = dialogInterface as BottomSheetDialog val bottomSheet = bottomSheetDialog.findViewById<View>(com.google.android.material.R.id.design_bottom_sheet) bottomSheet?.let { val behavior = BottomSheetBehavior.from(bottomSheet) behavior.isDraggable = true behavior.isHideable = true behavior.state = BottomSheetBehavior.STATE_EXPANDED } } return dialog } }
0
Kotlin
0
0
afe8f3958915c21d6db20701addaa3c2e63f68fc
3,980
EquiJamii
Apache License 2.0
app/src/main/java/ru/awawa/clockutils/MainActivity.kt
0awawa0
361,454,558
false
null
package ru.awawa.clockutils import android.os.Bundle import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material.* import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import com.google.accompanist.systemuicontroller.rememberSystemUiController import ru.awawa.clockutils.ui.theme.ClockUtilsTheme import ru.awawa.clockutils.ui.theme.Grey700 import ru.awawa.clockutils.ui.views.* class MainActivity : ComponentActivity() { companion object { const val EXTRA_TYPE = "TYPE" const val TYPE_STOPWATCH = "Stopwatch" const val TYPE_TIMER = "Timer" } private val tag = "MainActivity" private val viewModel by viewModels<MainViewModel>() private var selectedItem by mutableStateOf(0) private val navigationItems = listOf(NavigationItem.Stopwatch, NavigationItem.Timer, NavigationItem.Metronome) private val currentNavItem: NavigationItem get() = navigationItems[selectedItem] override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) when (intent.getStringExtra(EXTRA_TYPE)) { TYPE_STOPWATCH -> selectedItem = 0 TYPE_TIMER -> selectedItem = 1 } setContent { val navController = rememberNavController() val systemUiController = rememberSystemUiController() ClockUtilsTheme { systemUiController.setSystemBarsColor( color = Grey700, darkIcons = false ) Scaffold( bottomBar = { BottomBar( items = navigationItems, currentItem = currentNavItem, onItemSelected = { if (selectedItem != it) { selectedItem = it navController.navigate(currentNavItem.route) } } ) }, content = { paddings -> val currentStopwatchTime: Long by viewModel.currentStopwatchTime.collectAsState() val isStopwatchRunning: Boolean by viewModel.isStopwatchRunning.collectAsState() val currentTimerTime: Long by viewModel.currentTimerTime.collectAsState() val totalTimerTime: Long by viewModel.totalTimerTime.collectAsState() val isTimerRunning: Boolean by viewModel.isTimerRunning.collectAsState() val bitsPerMinute: Float by viewModel.bitsPerMinute.collectAsState() NavHost( navController = navController, startDestination = currentNavItem.route, modifier = Modifier .padding(paddings) .fillMaxSize() ) { val childModifier = Modifier.fillMaxSize() for (item in navigationItems) { composable(item.route) { when (item.route) { NavigationItem.Stopwatch.route -> StopwatchView( modifier = childModifier, currentTime = currentStopwatchTime, isRunning = isStopwatchRunning, viewModel.checkPoints.value, onSwitchStopwatch = viewModel::onSwitchStopwatch, onResetStopwatch = viewModel::onResetStopwatch, onAddCheckPoint = viewModel::onAddCheckPoint ) NavigationItem.Timer.route -> TimerView( label = "", currentTime = currentTimerTime, totalTime = totalTimerTime, isRunning = isTimerRunning, onSetTime = viewModel::onSetTimerTime, onStartTimer = { viewModel.onStartTimer(applicationContext) }, onPauseTimer = viewModel::onPauseTimer, onStopTimer = viewModel::onStopTimer ) NavigationItem.Metronome.route -> RoundRangePickView( modifier = childModifier.padding(16.dp), skipAngle = 45f, minValue = 10f, maxValue = 300f, startValue = 60f, onValueChanged = { viewModel.onBpmChanged(bitsPerMinute) }, textFormatter = { String.format("%02d", (290 * it + 10).toInt()) }, onButtonClick = { viewModel.onBpmChanged(bitsPerMinute - 2) } ) } } } } }, ) } } } override fun onPause() { super.onPause() } override fun onResume() { super.onResume() Log.w(tag, "onResume()") } }
0
Kotlin
0
0
fa93828a240efd6b7044792da4b00c6b45a9ffb6
6,230
ClockUtils
MIT License
src/main/kotlin/club/anifox/backend/domain/mappers/anime/detail/AnimeDetail.kt
DeNyWho
649,026,698
false
{"Kotlin": 264633}
package club.anifox.backend.domain.mappers.anime.detail import club.anifox.backend.domain.mappers.anime.toAnimeTranslation import club.anifox.backend.domain.mappers.anime.toGenre import club.anifox.backend.domain.mappers.anime.toStudio import club.anifox.backend.domain.model.anime.AnimeImagesTypes import club.anifox.backend.domain.model.anime.detail.AnimeDetail import club.anifox.backend.jpa.entity.anime.AnimeTable fun AnimeTable.toAnimeDetail(): AnimeDetail { return AnimeDetail( url = url, title = title, image = AnimeImagesTypes(large = images.large, medium = images.medium, cover = images.cover), studio = studios.toList().map { it.toStudio() }, season = season, description = description, titleOther = titleOther, titleEnglish = titleEn.toList(), titleJapan = titleJapan.toList(), synonyms = synonyms, nextEpisode = nextEpisode, year = year, releasedOn = releasedOn, airedOn = airedOn, type = type, rating = totalRating, shikimoriRating = shikimoriRating, episodes = episodesCount, episodesAired = episodesAired, playerLink = playerLink, genres = genres.toList().map { it.toGenre() }, status = status, ratingMpa = ratingMpa, minimalAge = minimalAge, translations = translations.toList().map { it.toAnimeTranslation() }, ) }
0
Kotlin
0
0
146c70e8b2aa22911e66ff6459b90960be8ea851
1,443
Anifox_Backend
Apache License 2.0
src/main/kotlin/club/anifox/backend/domain/mappers/anime/detail/AnimeDetail.kt
DeNyWho
649,026,698
false
{"Kotlin": 264633}
package club.anifox.backend.domain.mappers.anime.detail import club.anifox.backend.domain.mappers.anime.toAnimeTranslation import club.anifox.backend.domain.mappers.anime.toGenre import club.anifox.backend.domain.mappers.anime.toStudio import club.anifox.backend.domain.model.anime.AnimeImagesTypes import club.anifox.backend.domain.model.anime.detail.AnimeDetail import club.anifox.backend.jpa.entity.anime.AnimeTable fun AnimeTable.toAnimeDetail(): AnimeDetail { return AnimeDetail( url = url, title = title, image = AnimeImagesTypes(large = images.large, medium = images.medium, cover = images.cover), studio = studios.toList().map { it.toStudio() }, season = season, description = description, titleOther = titleOther, titleEnglish = titleEn.toList(), titleJapan = titleJapan.toList(), synonyms = synonyms, nextEpisode = nextEpisode, year = year, releasedOn = releasedOn, airedOn = airedOn, type = type, rating = totalRating, shikimoriRating = shikimoriRating, episodes = episodesCount, episodesAired = episodesAired, playerLink = playerLink, genres = genres.toList().map { it.toGenre() }, status = status, ratingMpa = ratingMpa, minimalAge = minimalAge, translations = translations.toList().map { it.toAnimeTranslation() }, ) }
0
Kotlin
0
0
146c70e8b2aa22911e66ff6459b90960be8ea851
1,443
Anifox_Backend
Apache License 2.0
auth-center/auth-center-infra/src/main/kotlin/com/jmsoftware/maf/authcenter/role/persistence/Role.kt
johnnymillergh
240,563,247
false
null
package com.jmsoftware.maf.authcenter.role.persistence import com.baomidou.mybatisplus.annotation.TableField import com.baomidou.mybatisplus.annotation.TableName import com.jmsoftware.maf.springcloudstarter.database.BasePersistenceEntity /** * # Role * * Role Persistence object class * * @author <NAME> (锺俊), e-mail: <EMAIL>, date: 4/10/22 7:15 PM * @see <a href='https://dev.mysql.com/doc/refman/8.0/en/keywords.html'>MySQL Keywords and Reserved Words</a> */ @TableName(value = Role.TABLE_NAME) class Role : BasePersistenceEntity() { companion object { const val TABLE_NAME = "role" const val COL_NAME = "`name`" const val COL_DESCRIPTION = "`description`" } /** * Role name */ @TableField(value = COL_NAME) lateinit var name: String /** * Role description */ @TableField(value = COL_DESCRIPTION) lateinit var description: String }
1
null
4
11
67917520e69c3f2a47fdd06817e9421cd4d82159
921
muscle-and-fitness-server
Apache License 2.0
app/src/main/java/com/vicent/composeapplication/math/LevelMath.kt
Vicent9920
438,942,802
false
null
package com.vicent.composeapplication.math import com.vicent.composeapplication.model.GridUnit import kotlin.random.Random /** * <pre> * author: Vincent * date : 2021/11/30 19:03 * desc : 级别算法 * </pre> */ object LevelMath { private val levelList = mutableListOf(16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38) fun getLevelName(name:Int):Int{ return levelList.size+1-name } /** * 设置关卡数据,并返回可输入单元格数量 */ fun setLevelData(level:Int, source:MutableList<GridUnit>):Int{ // 确定每行镂空数量 val emptyBlank = createNineRandomArray(81-levelList[level-1],81) // 将每行指定元素镂空 emptyBlank.forEach { source[it].value = 0 source[it].onlyRead = false } return emptyBlank.size } /** * 生成指定大小且内容为1-9不重复的随机数组 * @param size 数组大小 */ private fun createNineRandomArray(size:Int,max: Int):IntArray{ val result = IntArray(size) for (i in 0 until size){ while (true){ val code = Random.nextInt(1,max) if(!result.contains(code)){ result[i] = code break } } } return result } }
0
Kotlin
0
1
7a05c18cb4ed8fae33402e127c6d64a4098b3e4a
1,294
ComposeApplication
Apache License 2.0
scoping/src/main/java/com/dropbox/kaiken/scoping/AuthAwareScopeOwnerActivity.kt
dropbox
299,992,268
false
null
package com.dropbox.kaiken.scoping import androidx.activity.ComponentActivity import androidx.lifecycle.ViewModelStoreOwner import com.dropbox.kaiken.scoping.internal.AuthHelper import com.dropbox.kaiken.scoping.internal.locateAuthHelperStore /** * An activity that is authentication aware (i.e. the activity is running under a specific user * scope which is indicated by its associated viewing user selector). * * This interface relies on the implementor extending from [androidx.fragment.app.FragmentActivity]. */ interface AuthAwareScopeOwnerActivity : DependencyProviderResolver, ViewModelStoreOwner { val authRequired: Boolean @JvmDefault fun getViewingUserSelector(): ViewingUserSelector? = locateAuthHelper().viewingUserSelector /** * Resolves the dependencies for the given type. * * [finishIfInvalidAuth] must be called before calling this method. */ @JvmDefault override fun <T> resolveDependencyProvider(): T = locateAuthHelper().resolveDependencyProvider() /** * Finishes the activity if the current authentication state is invalid (e.g. a current * viewing user id is presents but it's user services are not available), otherwise it noops. * * This should be the first method that is called `onCreate()` after the `super.onCreate()` * call. * * This method must be called before any calls to [resolveDependencyProvider]. * * @return whether or not the activity has been finished. */ @JvmDefault override fun finishIfInvalidAuth(): Boolean { val activity = (this as ComponentActivity) val authHelper = locateAuthHelper() if (!authHelper.validateAuth()) { activity.finish() return true } return false } private fun locateAuthHelper(): AuthHelper = locateAuthHelperStore().authHelper }
8
Kotlin
10
75
cb68ee0f54588f8f8150ac357fb74df29bb3a5bd
1,912
kaiken
Apache License 2.0
howto-dapp/src/main/java/de/timolia/howto/database/SQLApi.kt
TimoliaDE
579,343,701
false
{"Kotlin": 45480, "Dockerfile": 956}
package de.timolia.howto.conversion import java.sql.SQLException import java.util.* import kotlin.jvm.Volatile object SQLApi { @Volatile private var connection: SqlUserConnection? = null @Volatile private var triedConnect = false private fun establishConnection(): SqlUserConnection { if (!triedConnect) { synchronized(SQLApi::class.java) { if (!triedConnect) { tryGuardedConnect() } } } return connection ?: throw RuntimeException("Earlier attempt connecting to sql failed") } private fun tryGuardedConnect() { try { connection = SqlUserConnection.connect() } catch (exception: SQLException) { throw RuntimeException("Unable to establish sql connection", exception) } finally { triedConnect = true } } fun getUuid(name: String?): UUID? { return try { establishConnection().getUuid(name) } catch (exception: RuntimeException) { exception.printStackTrace() throw exception } } fun getName(uuid: UUID?): String? { return getName(uuid, null) } fun getName(uuid: UUID?, fallback: String?): String? { val connection: SqlUserConnection = try { establishConnection() } catch (exception: RuntimeException) { if (fallback != null && SqlUserConnection.isDevEnv()) { System.err.println("Unable to establish sql connection for $uuid fallback to $fallback") exception.printStackTrace() return fallback } throw RuntimeException("Unable to establish sql connection", exception) } return connection.getName(uuid, fallback) } }
9
Kotlin
7
0
c070fadf97c85b5fa496cda556dea5ecd8ccc710
1,839
HowTo
MIT License
src/main/kotlin/br/com/zupacademy/giovanna/conta/ContaEntity.kt
giovanna-bernardi
383,793,280
true
{"Kotlin": 112775, "Smarty": 1902, "Dockerfile": 154}
package br.com.zupacademy.giovanna.conta import br.com.zupacademy.giovanna.compartilhado.SensitiveDataCPFConverter import javax.persistence.Column import javax.persistence.Convert import javax.persistence.Embeddable import javax.validation.constraints.NotBlank import javax.validation.constraints.Size @Embeddable class ContaEntity( @field:NotBlank @Column(name = "conta_instituicao", nullable = false) val nomeInstituicao: String, @field:NotBlank @Column(name = "conta_titular_nome", nullable = false) val nomeTitular: String, @field:NotBlank @Convert(converter = SensitiveDataCPFConverter::class) @Column(name = "conta_titular_cpf", nullable = false) val cpfTitular: String, @field:NotBlank @field:Size(max = 4) @Column(name = "conta_agencia", length = 4, nullable = false) val agencia: String, @field:NotBlank @field:Size(max = 6) @Column(name = "conta_numero", length = 6, nullable = false) val numeroConta: String ) { companion object { public val ITAU_UNIBANCO_ISPB: String = "60701190" } }
0
Kotlin
0
0
646992b7e3bf4c27fd8989ce5d9e85909511a167
1,083
orange-talents-05-template-pix-keymanager-grpc
Apache License 2.0
src/main/kotlin/org/snd/metadata/MetadataProvider.kt
Snd-R
463,859,568
false
null
package org.snd.metadata import org.snd.metadata.model.MatchQuery import org.snd.metadata.model.Provider import org.snd.metadata.model.SeriesSearchResult import org.snd.metadata.model.metadata.ProviderBookId import org.snd.metadata.model.metadata.ProviderBookMetadata import org.snd.metadata.model.metadata.ProviderSeriesId import org.snd.metadata.model.metadata.ProviderSeriesMetadata interface MetadataProvider { fun providerName(): Provider fun getSeriesMetadata(seriesId: ProviderSeriesId): ProviderSeriesMetadata fun getBookMetadata(seriesId: ProviderSeriesId, bookId: ProviderBookId): ProviderBookMetadata fun searchSeries(seriesName: String, limit: Int = 5): Collection<SeriesSearchResult> fun matchSeriesMetadata(matchQuery: MatchQuery): ProviderSeriesMetadata? }
11
Kotlin
9
99
0584078f460c5d8c7b740bbe77905fab1c0ad105
799
komf
MIT License
libs/etterlatte-database/src/main/kotlin/JdbcUtils.kt
navikt
417,041,535
false
null
package no.nav.etterlatte.libs.database import no.nav.etterlatte.libs.common.objectMapper import org.postgresql.util.PGobject import java.sql.PreparedStatement import java.sql.ResultSet fun <T> ResultSet.singleOrNull(block: ResultSet.() -> T): T? { return if (next()) { block().also { require(!next()) { "Skal være unik" } } } else { null } } fun <T> ResultSet.single(block: ResultSet.() -> T): T { require(next()) { "Skal ha en verdi" } return block().also { require(!next()) { "Skal være unik" } } } fun <T> ResultSet.firstOrNull(block: ResultSet.() -> T): T? { return if (next()) { block() } else { null } } fun <T> ResultSet.toList(block: ResultSet.() -> T): List<T> { val list = ArrayList<T>() while (next()) { list.add(block()) } return list } inline fun <reified T : Any> PreparedStatement.setJsonb( parameterIndex: Int, jsonb: T?, ): PreparedStatement { if (jsonb == null) { this.setNull(parameterIndex, java.sql.Types.NULL) } val jsonObject = PGobject() jsonObject.type = "json" jsonObject.value = objectMapper.writeValueAsString(jsonb) this.setObject(parameterIndex, jsonObject) return this }
19
null
0
6
abd4600c70b4188d7d6272ea2d650421ffdfcfb6
1,285
pensjon-etterlatte-saksbehandling
MIT License
src/test/kotlin/com/funivan/idea/phpClean/inspections/toStringCall/ToStringCallInspectionTest.kt
funivan
144,475,458
false
null
package com.funivan.idea.phpClean.inspections.toStringCall import com.funivan.idea.phpClean.BaseInspectionTest class ToStringCallInspectionTest : BaseInspectionTest() { fun testMethodCall() { assert( ToStringCallInspection(), """ <?php class Hello { public function randomize(): self { /* .. */return ${'$'}this; } public function __toString(){ return 'Hi'; } } echo <warning descr="Deprecated __toString call">(new Hello())->randomize()</warning>; """, """ <?php class Hello { public function randomize(): self { /* .. */return ${'$'}this; } public function __toString(){ return 'Hi'; } } echo (new Hello())->randomize()->__toString(); """ ) } fun testConcatenation() { assert( ToStringCallInspection(), """ <?php class Hello { public function randomize(): self { /* .. */return ${'$'}this; } public function __toString(){ echo 'Hi'; } } ${'$'}phrase = 'Hi ' . <warning descr="Deprecated __toString call">(new Hello())->randomize()</warning>; """ , """ <?php class Hello { public function randomize(): self { /* .. */return ${'$'}this; } public function __toString(){ echo 'Hi'; } } ${'$'}phrase = 'Hi ' . (new Hello())->randomize()->__toString(); """ ) } fun testManualTypeCasting() { assert( ToStringCallInspection(), """ <?php class Hello { public function randomize(): self { /* .. */return ${'$'}this; } public function __toString(){ echo 'Hi'; } } echo (new Hello())->randomize()->__toString(); 'Who say ' . (new Hello())->randomize()->__toString() . '?'; """ ) } fun testNullableString() { assert( ToStringCallInspection(), """ <?php class A{ function test(): ?string{ return null; } } echo (new A())->test(); """ ) } fun testNewObject() { assert( ToStringCallInspection(), """ <?php class Hello { public function __toString(){ echo 'Hi'; } } echo <warning descr="Deprecated __toString call">new Hello()</warning>; ${'$'}phrase = <warning descr="Deprecated __toString call">new Hello()</warning> . ' there'; """, """ <?php class Hello { public function __toString(){ echo 'Hi'; } } echo (new Hello())->__toString(); ${'$'}phrase = (new Hello())->__toString() . ' there'; """ ) } fun testMethodStringReturned() { assert( ToStringCallInspection(), """ <?php class Hello { public function str():string{ return 'Hi'; } /** * @return string|int|boolean */ public function s(){ echo 'Hi'; } } echo (new Hello())->str(); ${'$'}hi = new Hello(); echo ${'$'}hi->str(); ${'$'}message = ${'$'}hi->str() . 'msg'; echo (new Hello())->s(); """ ) } fun testStaticMethod() { assert( ToStringCallInspection(), """ <?php class someClass { public function __toString(){ } public static function create() : self{ } } echo <warning descr="Deprecated __toString call">SomeClass::create()</warning>; """, """ <?php class someClass { public function __toString(){ } public static function create() : self{ } } echo SomeClass::create()->__toString(); """ ) } }
6
null
6
86
103124c4a270989bd24e59151358acbb80407ffd
5,136
PhpClean
MIT License
Widget/app/src/main/java/com/microsoft/device/display/samples/widget/feed/RssSimpleApi.kt
mattaeus-isenberg
293,419,966
true
{"Kotlin": 203418, "HTML": 1541}
/* * * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. * */ package com.microsoft.device.display.samples.widget.feed import retrofit2.Call import retrofit2.http.GET interface RssSimpleApi { @get:GET(".") val rssFeed: Call<String> }
0
null
0
0
1912950691e1b6187cfb2b41aeee22b0251a1f3b
292
surface-duo-app-samples
MIT License
app/src/main/java/com/rifqimfahmi/foorballapps/util/Ext.kt
rifqimfahmi
161,456,967
false
null
package com.rifqimfahmi.foorballapps.util import android.content.Context import com.rifqimfahmi.foorballapps.R /* * Created by Rifqi Mulya Fahmi on 29/11/18. */ fun Context.getLeaguesName(position: Int) : String { return resources.getStringArray(R.array.leagues)[position] } fun Context.getLeaguesId(position: Int) : String { return resources.getStringArray(R.array.leagues_id)[position] }
4
Kotlin
39
138
96aa72a2dbda49a5653ccf27088fa66b898500dd
404
android-mvvm-coroutine
MIT License
codebase/android/feature/home/src/test/java/com/makeappssimple/abhimanyu/financemanager/android/feature/home/viewmodel/HomeScreenViewModelTest.kt
Abhimanyu14
429,663,688
false
{"Kotlin": 1908017}
package com.makeappssimple.abhimanyu.financemanager.android.feature.home.viewmodel import org.junit.Assert import org.junit.Test internal class HomeScreenViewModelTest { @Test fun sampleText() { Assert.assertEquals(4, 2 + 2) } }
11
Kotlin
0
3
a9e7570d854c7738d0ad5bcf139fa9874fa83b21
252
finance-manager
Apache License 2.0
projects/core/src/main/kotlin/site/siredvin/peripheralworks/data/ModLanguageProvider.kt
SirEdvin
489,471,520
false
null
package site.siredvin.peripheralworks.data import net.minecraft.data.PackOutput import site.siredvin.peripheralium.data.language.LanguageProvider import site.siredvin.peripheralworks.PeripheralWorksCore import site.siredvin.peripheralworks.xplat.PeripheralWorksPlatform import java.util.stream.Stream abstract class ModLanguageProvider(output: PackOutput, locale: String) : LanguageProvider( output, PeripheralWorksCore.MOD_ID, locale, PeripheralWorksPlatform.holder, *ModText.values(), *ModTooltip.values(), ) { companion object { private val extraExpectedKeys: MutableList<String> = mutableListOf() fun addExpectedKey(key: String) { extraExpectedKeys.add(key) } } override fun getExpectedKeys(): Stream<String> { return Stream.concat(super.getExpectedKeys(), extraExpectedKeys.stream()) } }
3
Kotlin
2
6
4261ad04499375f16704c8df3f3faeb0e314ac54
882
UnlimitedPeripheralWorks
MIT License
app/src/main/java/com/example/zmci/SplashFragment.kt
cpe-pd
543,865,380
false
null
package com.example.zmci import android.content.Intent import android.os.Bundle import android.os.Handler import androidx.appcompat.app.AppCompatActivity class SplashFragment : AppCompatActivity() { /* SplashFragment Methods: - onCreate (savedInstanceState: Bundle?) */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.fragment_splash) supportActionBar?.hide() Handler().postDelayed({ val intent = Intent(this@SplashFragment,LoginFragment::class.java) startActivity(intent) finish() },3000) } }
0
Kotlin
0
4
d234920683722f9e0c71c9a2c48565400f8761c0
681
ppe-for-construction-android-app
MIT License
src/test/kotlin/uk/gov/justice/digital/hmpps/pollpush/HouseKeepingIntegrationTest.kt
ministryofjustice
86,676,196
false
null
package uk.gov.justice.digital.hmpps.pollpush import com.github.tomakehurst.wiremock.client.WireMock import com.github.tomakehurst.wiremock.client.WireMock.get import com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor import com.github.tomakehurst.wiremock.client.WireMock.put import com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor import com.github.tomakehurst.wiremock.client.WireMock.urlMatching import org.assertj.core.api.Assertions.assertThat import org.awaitility.kotlin.await import org.awaitility.kotlin.matches import org.awaitility.kotlin.untilCallTo import org.junit.jupiter.api.Test import org.springframework.http.MediaType import uk.gov.justice.digital.hmpps.pollpush.services.CaseNotesExtension.Companion.caseNotesApi import uk.gov.justice.digital.hmpps.pollpush.services.CommunityApiExtension.Companion.communityApi import wiremock.org.apache.http.protocol.HTTP class HouseKeepingIntegrationTest : QueueIntegrationTest() { @Test fun `will purge any messages on the dlq`() { awsSqsDlqClient.sendMessage(dlqUrl, "{}") await untilCallTo { getNumberOfMessagesCurrentlyOnDlq() } matches { it == 1 } webTestClient.put() .uri("/queue-admin/purge-queue/$dlqName") .headers(setAuthorisation(roles = listOf("ROLE_CASE_NOTE_QUEUE_ADMIN"))) .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isOk await untilCallTo { getNumberOfMessagesCurrentlyOnDlq() } matches { it == 0 } assertThat(getNumberOfMessagesCurrentlyOnQueue()).isEqualTo(0) // Nothing to process caseNotesApi.verify(0, WireMock.anyRequestedFor(WireMock.anyUrl())) communityApi.verify(0, WireMock.anyRequestedFor(WireMock.anyUrl())) } @Test fun `housekeeping will consume a message on the dlq and return to main queue`() { stubApiCalls() awsSqsDlqClient.sendMessage(dlqUrl, caseNoteEvent()) webTestClient.put() .uri("/queue-admin/retry-all-dlqs") .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isOk await untilCallTo { getNumberOfMessagesCurrentlyOnQueue() } matches { it == 0 } await untilCallTo { getNumberOfMessagesCurrentlyOnDlq() } matches { it == 0 } caseNotesApi.verify(1, getRequestedFor(urlMatching("/case-notes/G4803UT/1234"))) communityApi.verify(1, putRequestedFor(urlMatching("/secure/nomisCaseNotes/G4803UT/-25"))) } @Test fun `will consume a message on the dlq and return to main queue`() { stubApiCalls() awsSqsDlqClient.sendMessage(dlqUrl, caseNoteEvent()) webTestClient.put() .uri("/queue-admin/retry-dlq/$dlqName") .headers(setAuthorisation(roles = listOf("ROLE_CASE_NOTE_QUEUE_ADMIN"))) .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isOk await untilCallTo { getNumberOfMessagesCurrentlyOnDlq() } matches { it == 0 } await untilCallTo { getNumberOfMessagesCurrentlyOnQueue() } matches { it == 0 } caseNotesApi.verify(1, getRequestedFor(urlMatching("/case-notes/G4803UT/1234"))) communityApi.verify(1, putRequestedFor(urlMatching("/secure/nomisCaseNotes/G4803UT/-25"))) } } private fun stubApiCalls() { // stub calls caseNotesApi.stubFor( get(urlMatching("/case-notes/G4803UT/1234")) .willReturn( WireMock.aResponse().withStatus(200).withHeader(HTTP.CONTENT_TYPE, "application/json") .withBody(caseNote()) ) ) communityApi.stubFor( put(urlMatching("/secure/nomisCaseNotes/G4803UT/-25")) .willReturn(WireMock.aResponse().withStatus(200)) ) } private fun caseNoteEvent(offenderIdDisplay: String = "G4803UT", eventType: String = "KA-KE") = """{ "MessageId": "ae06c49e-1f41-4b9f-b2f2-dcca610d02cd", "Type": "Notification", "Timestamp": "2019-10-21T14:01:18.500Z", "Message": "{\"eventId\":\"5958295\",\"eventType\":\"$eventType\",\"eventDatetime\":\"2019-10-21T15:00:25.489964\", \"rootOffenderId\":2419065,\"offenderIdDisplay\":\"$offenderIdDisplay\",\"agencyLocationId\":\"MDI\", \"caseNoteId\": 1234}", "TopicArn": "arn:aws:sns:eu-west-1:000000000000:offender_events", "MessageAttributes": {"eventType": {"Type": "String", "Value": "KA-KE"}, "id": {"Type": "String", "Value": "8b07cbd9-0820-0a0f-c32f-a9429b618e0b"}, "contentType": {"Type": "String", "Value": "text/plain;charset=UTF-8"}, "timestamp": {"Type": "Number.java.lang.Long", "Value": "1571666478344"}}} """.trimIndent() private fun caseNote(offenderIdentifier: String = "G4803UT", eventType: String = "KA-KE", agency: String = "MDI") = """ { "caseNoteId": "1234", "eventId": "-25", "offenderIdentifier": "$offenderIdentifier", "type": "${eventType.substringBefore("-")}", "typeDescription": "POM Notes", "subType": "${eventType.substringAfter("-")}", "subTypeDescription": "General POM Note", "authorUserId": "SECURE_CASENOTE_USER_ID", "authorName": "<NAME>", "text": "This is a case note", "locationId": "$agency", "amendments": [], "creationDateTime": "2019-03-23T11:22", "occurrenceDateTime": "2019-03-23T11:22" } """.trimIndent()
9
Kotlin
4
3
4b870f70d360dc67c73ba09b14fc6255bab0d0f8
5,199
case-notes-to-probation
MIT License
app/src/main/java/cz/nestresuju/model/repositories/ProgramRepository.kt
johnondrej
371,166,772
false
null
package cz.nestresuju.model.repositories import kotlinx.coroutines.flow.Flow import org.threeten.bp.ZonedDateTime /** * Common interface for all program repositories. */ interface ProgramRepository<T> { suspend fun fetchProgramResults() suspend fun getProgramResults(): T suspend fun observeProgramResults(): Flow<T> suspend fun updateProgramResults(updater: (T) -> T) suspend fun submitResults(programCompletedDate: ZonedDateTime) }
0
Kotlin
0
0
8d7c54c00c865a370ed24a356abd2bfeeef4ed4b
462
nestresuju-android
Apache License 2.0
app/src/main/java/com/gals/prayertimes/utils/Helpers.kt
AbdullahAlSamman
796,622,066
false
{"Kotlin": 111719, "HTML": 7648}
package com.gals.prayertimes.utils import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.sp import com.gals.prayertimes.R import com.gals.prayertimes.model.NotificationType import com.gals.prayertimes.repository.remote.model.PrayerName import com.gals.prayertimes.repository.remote.model.SinglePrayer import com.gals.prayertimes.ui.theme.colorBackgroundAsr import com.gals.prayertimes.ui.theme.colorBackgroundDuhr import com.gals.prayertimes.ui.theme.colorBackgroundFajer import com.gals.prayertimes.ui.theme.colorBackgroundIsha import com.gals.prayertimes.ui.theme.colorBackgroundMaghrib import com.gals.prayertimes.ui.theme.colorBackgroundSunrise val Int.nonScaledSp @Composable get() = (this / LocalDensity.current.fontScale).sp @Composable fun prayerColorMapper(prayer: PrayerName): Color = when (prayer) { PrayerName.FAJER -> colorBackgroundFajer PrayerName.SUNRISE -> colorBackgroundSunrise PrayerName.DUHR -> colorBackgroundDuhr PrayerName.ASR -> colorBackgroundAsr PrayerName.MAGHRIB -> colorBackgroundMaghrib PrayerName.ISHA -> colorBackgroundIsha PrayerName.UNKNOWN -> colorBackgroundFajer } @Composable fun prayerNameMapper(prayerName: PrayerName): String = when (prayerName) { PrayerName.FAJER -> stringResource(id = R.string.text_prayer_fajer) PrayerName.SUNRISE -> stringResource(id = R.string.text_prayer_sunrise) PrayerName.DUHR -> stringResource(id = R.string.text_prayer_duhr) PrayerName.ASR -> stringResource(id = R.string.text_prayer_asr) PrayerName.MAGHRIB -> stringResource(id = R.string.text_prayer_maghrib) PrayerName.ISHA -> stringResource(id = R.string.text_prayer_isha) PrayerName.UNKNOWN -> stringResource(id = R.string.text_prayer_isha) } @Composable fun getStatusBarColors(): Pair<Color, Boolean> { val color = if (isSystemInDarkTheme()) { colorResource(id = R.color.background_color_time_isha) } else { colorResource(id = R.color.background_color_time_fajer) } return (color to isSystemInDarkTheme()) } @Composable fun getNotificationTypeText(notificationType: NotificationType): String = when (notificationType) { NotificationType.SILENT -> stringResource(id = R.string.text_alarm_silent) NotificationType.TONE -> stringResource(id = R.string.text_alarm_tone) NotificationType.HALF -> stringResource(id = R.string.text_alarm_half_athan) NotificationType.FULL -> stringResource(id = R.string.text_alarm_full_athan) }
0
Kotlin
0
0
0004b0b814acac11c856d2eaeec5c33eb9974082
2,819
PrayerTimes
Apache License 2.0
content-types/content-types-core-model/src/main/kotlin/org/orkg/contenttypes/domain/RosettaStoneTemplate.kt
TIBHannover
197,416,205
false
{"Kotlin": 5888031, "Cypher": 219508, "Python": 4881, "Shell": 2767, "Groovy": 1936, "HTML": 240, "Batchfile": 82}
package org.orkg.contenttypes.domain import java.time.OffsetDateTime import org.orkg.common.ContributorId import org.orkg.common.ObservatoryId import org.orkg.common.OrganizationId import org.orkg.common.ThingId import org.orkg.graph.domain.Classes import org.orkg.graph.domain.FormattedLabel import org.orkg.graph.domain.GeneralStatement import org.orkg.graph.domain.Predicates import org.orkg.graph.domain.Resource import org.orkg.graph.domain.Visibility data class RosettaStoneTemplate( val id: ThingId, val label: String, val description: String?, val formattedLabel: FormattedLabel, val targetClass: ThingId, val exampleUsage: String?, val properties: List<TemplateProperty>, val createdBy: ContributorId, val createdAt: OffsetDateTime, val observatories: List<ObservatoryId>, val organizations: List<OrganizationId>, val visibility: Visibility, val unlistedBy: ContributorId? = null ) { companion object { fun from(resource: Resource, statements: Map<ThingId, List<GeneralStatement>>): RosettaStoneTemplate { val directStatements = statements[resource.id]!! return RosettaStoneTemplate( id = resource.id, label = resource.label, description = directStatements .wherePredicate(Predicates.description) .singleOrNull()?.`object`?.label, formattedLabel = directStatements .wherePredicate(Predicates.templateLabelFormat) .single() .let { FormattedLabel.of(it.`object`.label) }, targetClass = directStatements .wherePredicate(Predicates.shTargetClass) .single() .`object`.id, exampleUsage = directStatements .wherePredicate(Predicates.shTargetClass) .single().`object`.id .let { statements[it].orEmpty() } .wherePredicate(Predicates.exampleOfUsage) .singleOrNull()?.`object`?.label, properties = directStatements .wherePredicate(Predicates.shProperty) .filter { it.`object` is Resource && Classes.propertyShape in (it.`object` as Resource).classes } .mapNotNull { TemplateProperty.from(it.`object` as Resource, statements[it.`object`.id].orEmpty()) } .sortedBy { it.order }, createdAt = resource.createdAt, createdBy = resource.createdBy, organizations = listOf(resource.organizationId), observatories = listOf(resource.observatoryId), visibility = resource.visibility, unlistedBy = resource.unlistedBy ) } } }
0
Kotlin
0
4
ee884fb0b87c20e18b6e1ee81379f9d2ab17c8f3
2,873
orkg-backend
MIT License
lib/src/test/kotlin/io/wavebeans/lib/io/ByteArrayLittleEndianInputOutputSpec.kt
WaveBeans
174,378,458
false
{"Kotlin": 1263856, "Shell": 6924, "Dockerfile": 408}
package io.wavebeans.lib.io import assertk.assertThat import assertk.assertions.isEqualTo import io.wavebeans.lib.* import io.wavebeans.lib.stream.FiniteStream import io.wavebeans.lib.stream.rangeProjection import io.wavebeans.lib.stream.trim import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import java.io.File import java.lang.Thread.sleep import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit.MILLISECONDS private class ByteArrayFileOutputMock( val stream: FiniteStream<Sample>, val bitDepth: BitDepth ) : StreamOutput<Sample> { private val file = File.createTempFile("test", ".tmp").also { it.deleteOnExit() } override val input: Bean<Sample> get() = throw UnsupportedOperationException() override val parameters: BeanParams get() = throw UnsupportedOperationException() override fun writer(sampleRate: Float): Writer { return object : AbstractWriter<Sample>(stream, sampleRate, FileWriterDelegate({ file.toURI() }), ByteArrayFileOutputMock::class) { override fun header(): ByteArray? = null override fun footer(): ByteArray? = null override fun serialize(element: Sample): ByteArray { val buf = ByteArray(bitDepth.bytesPerSample) buf.encodeSampleLEBytes(0, element, bitDepth) return buf } } } fun readBytes(sampleRate: Float): List<Byte> { val writer = writer(sampleRate) while (writer.write()) { sleep(0) } writer.close() return file.readBytes().toList() } } object ByteArrayLittleEndianInputOutputSpec : Spek({ val sampleRate = 50.0f val buffer = ByteArray(100) { (it and 0xFF).toByte() } describe("Wav LE input, sample rate = 50.0Hz, bit depth = 8, mono") { val input = buffer.asInput(sampleRate) describe("samples are with values 0..100") { val samples = (0 until 100).map { sampleOf(it.toByte().asUnsignedByte().toByte()) } it("should be the same") { assertThat(input.asSequence(sampleRate).toList()).isEqualTo(samples) } } describe("output based on that input") { val output = ByteArrayFileOutputMock( input, BitDepth.BIT_8 ) it("should return byte array as input stream the same as initial buffer") { assertThat(output.readBytes(sampleRate).map { it.toInt() }).isEqualTo(buffer.map { it.toInt() and 0xFF }) } } describe("Projected range 0.0s..1.0s") { val projection = input.rangeProjection(0, 1000, MILLISECONDS) itShouldHave("number of samples 50") { assertThat(projection.samplesCount(sampleRate)).isEqualTo(50L) } itShouldHave("Length should be 1000ms for sample rate 50Hz") { assertThat(projection.length(sampleRate, MILLISECONDS)).isEqualTo(1000L) } itShouldHave("Samples should be [0,50)") { assertThat(projection.listOfBytesAsInts(sampleRate, 50)).isEqualTo( (0 until 50).toList() ) } } describe("Projected range 0.5s..1.0s") { val projection = input.rangeProjection(500, 1000, MILLISECONDS) itShouldHave("number of samples 25") { assertThat(projection.samplesCount(sampleRate)).isEqualTo(25L) } itShouldHave("length 500ms for sample rate 50Hz") { assertThat(projection.length(sampleRate, MILLISECONDS)).isEqualTo(500L) } itShouldHave("samples with values [25,50)") { assertThat(projection.listOfBytesAsInts(sampleRate)).isEqualTo( (25 until 50).toList() ) } } describe("Projected range 0.1s..0.2s") { val projection = input.rangeProjection(100, 200, MILLISECONDS) itShouldHave("number of samples 5") { assertThat(projection.samplesCount(sampleRate)).isEqualTo(5L) } itShouldHave("length 100ms for sample rate 50Hz") { assertThat(projection.length(sampleRate, MILLISECONDS)).isEqualTo(100L) } itShouldHave("samples with values [5,10)") { assertThat(projection.listOfBytesAsInts(sampleRate)).isEqualTo( (5 until 10).toList() ) } } describe("Projected range 1.5s..2.5s") { val projection = input.rangeProjection(1500, 2500, MILLISECONDS) itShouldHave("number of samples 25") { assertThat(projection.samplesCount(sampleRate)).isEqualTo(25L) } itShouldHave("length 500ms for sample rate 50Hz") { assertThat(projection.length(sampleRate, MILLISECONDS)).isEqualTo(500L) } itShouldHave("samples with values [75,100)") { assertThat(projection.listOfBytesAsInts(sampleRate)).isEqualTo( (75 until 100).toList() ) } } describe("Projected range -1.5s..2.5s") { val projection = input.rangeProjection(-1500, 2500, MILLISECONDS) itShouldHave("number of samples 100") { assertThat(projection.samplesCount(sampleRate)).isEqualTo(100L) } itShouldHave("length 2000ms for sample rate 50Hz") { assertThat(projection.length(sampleRate, MILLISECONDS)).isEqualTo(2000L) } itShouldHave("samples with values [0,100)") { assertThat(projection.listOfBytesAsInts(sampleRate)).isEqualTo( (0 until 100).toList() ) } } } describe("Wav LE input, sample rate = 50.0Hz, bit depth = 16, mono") { val buffer16 = ByteArray(200) { (it and 0xFF).toByte() } val input = buffer16.asInput(sampleRate, BitDepth.BIT_16) itShouldHave("number of samples 100") { assertThat(input.samplesCount()).isEqualTo(100L) } itShouldHave("length 2000ms") { assertThat(input.length(MILLISECONDS)).isEqualTo(2000L) } describe("samples with samples made of byte range [0,200)") { val samples = (0 until 200 step 2) .map { sampleOf((it + 1 and 0xFF shl 8 or (it and 0xFF)).toShort()) } it("should be the same") { assertThat(input.asSequence(sampleRate).toList()).isEqualTo(samples) } } describe("output based on that input") { val output = ByteArrayFileOutputMock( input, BitDepth.BIT_16 ) it("should return byte array as input stream the same as initial buffer") { assertThat(output.readBytes(sampleRate).toByteArray()).isEqualTo(buffer16) } } describe("Projected range 1.0s..2.0s") { val projection = input.rangeProjection(1000, 2000, MILLISECONDS) itShouldHave("number of samples 25") { assertThat(projection.samplesCount(sampleRate)).isEqualTo(50L) } itShouldHave("length 1000ms for sample rate 50Hz") { assertThat(projection.length(sampleRate, MILLISECONDS)).isEqualTo(1000L) } itShouldHave("samples with samples made of byte range [100,200)") { assertThat(projection.listOfShortsAsInts(sampleRate).map { it and 0xFFFF }).isEqualTo( (100 until 200) .windowed(2, 2) .map { it[0] or (it[1] shl 8) } .toList() ) } } } describe("Output of ByteArray LE, sequence of -100:100, encoding to 8 bit ") { // no need to test that case, 8 bit can't keep such signal as it is unsigned } describe("Output of ByteArray LE, sequence of -100:100, encoding to 16 bit ") { val signal = (-100 until 100).toList() val output = ByteArrayFileOutputMock( object : FiniteStream<Sample> { override val parameters: BeanParams get() = throw UnsupportedOperationException() override fun length(timeUnit: TimeUnit): Long = Long.MAX_VALUE override fun samplesCount(): Long = throw UnsupportedOperationException() override fun asSequence(sampleRate: Float): Sequence<Sample> = signal.asSequence().map { el -> sampleOf(el.toShort()) } override val desiredSampleRate: Float? = null override fun inputs(): List<AnyBean> = throw UnsupportedOperationException() }, BitDepth.BIT_16) it("output should be equal to 16 byte array 0-0x0F") { assertThat(output.readBytes(sampleRate).map { it.toInt() and 0xFF }) .isEqualTo(signal.map { listOf(it and 0xFF, it and 0xFF00 shr 8) }.flatten()) } } describe("Output of ByteArray LE, sequence of -100:100, encoding to 24 bit ") { val signal = (-100 until 100).toList() val output = ByteArrayFileOutputMock( object : FiniteStream<Sample> { override val parameters: BeanParams get() = throw UnsupportedOperationException() override fun length(timeUnit: TimeUnit): Long = Long.MAX_VALUE override fun samplesCount(): Long = throw UnsupportedOperationException() override fun asSequence(sampleRate: Float): Sequence<Sample> = signal.asSequence() .map { el -> sampleOf(el, true) } override val desiredSampleRate: Float? = null override fun inputs(): List<AnyBean> = throw UnsupportedOperationException() }, BitDepth.BIT_24) it("output should correspond to input signal") { assertThat(output.readBytes(sampleRate).map { it.toInt() and 0xFF }) .isEqualTo(signal .map { listOf(it and 0xFF, it and 0xFF00 shr 8, it and 0xFF0000 shr 16) } .flatten() ) } } describe("Output of ByteArray LE, sine 32 hz, encoding to 8 bit ") { val signal = 32.sine(.01, 0.5).trim(1000) val output = ByteArrayFileOutputMock(signal, BitDepth.BIT_8) it("output should be correspond to input signal") { assertThat(output.readBytes(44100.0f).map { it.asUnsignedByte() }) .isEqualTo( signal.asSequence(44100.0f).map { it.asByte().toInt() and 0xFF }.toList() ) } } })
26
Kotlin
0
21
2a0eb6b481f0f848a7e66f7cb4c395ddb47952d1
10,785
wavebeans
Apache License 2.0
app/src/main/java/com/example/movie_world_kotlin_best_practices/ui/component/SearchUI.kt
mudasir3
639,374,641
false
null
package com.example.movie_world_kotlin_best_practices.ui.component import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import com.example.movie_world_kotlin_best_practices.R import androidx.compose.ui.draw.clip import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavController import com.example.movie_world_kotlin_best_practices.data.datasource.remote.ApiURL import com.example.movie_world_kotlin_best_practices.data.model.BaseModel import com.example.movie_world_kotlin_best_practices.navigation.Screen import com.example.movie_world_kotlin_best_practices.ui.theme.DefaultBackgroundColor import com.example.movie_world_kotlin_best_practices.ui.theme.FontColor import com.example.movie_world_kotlin_best_practices.ui.theme.SecondaryFontColor import com.example.movie_world_kotlin_best_practices.ui.theme.cornerRadius import com.example.movie_world_kotlin_best_practices.utils.network.DataState import com.example.movie_world_kotlin_best_practices.utils.roundTo import com.skydoves.landscapist.ImageOptions import com.skydoves.landscapist.animation.circular.CircularRevealPlugin import com.skydoves.landscapist.coil.CoilImage import com.skydoves.landscapist.components.rememberImageComponent @Composable fun SearchUI(navController:NavController, searchData: MutableState<DataState<BaseModel>?>, itemClick:()->Unit) { LazyColumn( modifier = Modifier .fillMaxWidth() .heightIn(0.dp, 350.dp) // define max height .clip(RoundedCornerShape(bottomStart = 15.dp, bottomEnd = 15.dp)) .background(color = DefaultBackgroundColor) .padding(top = 8.dp) ) { searchData.value?.let { if (it is DataState.Success<BaseModel>) { items(items = it.data.results, itemContent = { item -> Row(modifier = Modifier .padding(bottom = 8.dp, start = 8.dp , end = 8.dp) .clickable { itemClick.invoke() navController.navigate( Screen.MovieDetail.route.plus( "/${item.id}" ) ) }) { CoilImage( modifier = Modifier .height(100.dp) .width(80.dp).cornerRadius(8), imageModel = { ApiURL.IMAGE_URL.plus(item.backdropPath) }, imageOptions = ImageOptions( contentScale = ContentScale.Crop, alignment = Alignment.Center, contentDescription = "search item", colorFilter = null, ), component = rememberImageComponent { +CircularRevealPlugin( duration = 800 ) }, ) Column { Text( text = item.title, modifier = Modifier.padding( start = 8.dp, top = 4.dp ), fontWeight = FontWeight.SemiBold ) Text( text = item.releaseDate, color = FontColor, fontSize = 16.sp, modifier = Modifier.padding(start = 8.dp) ) Text( text = "${stringResource(R.string.rating_search)} ${item.voteAverage.roundTo(1)}", color = SecondaryFontColor, fontSize = 12.sp, modifier = Modifier.padding(start = 8.dp) ) } } }) } } } }
0
Kotlin
0
0
83158eb30072d6ca2cbc0009eea0ef47bd3e625d
4,911
Movie-World-Kotln-Best-Practices
Apache License 2.0
viewlegacy/src/androidMain/kotlin/tech/skot/core/components/presented/SKAlertView.kt
skot-framework
235,318,194
false
null
package tech.skot.core.components.presented import android.content.DialogInterface import android.text.Editable import android.text.TextWatcher import android.widget.EditText import androidx.appcompat.app.AlertDialog import androidx.fragment.app.Fragment import tech.skot.core.components.SKActivity import tech.skot.core.components.SKComponentView import tech.skot.viewlegacy.databinding.SkAlertInputBinding class SKAlertView(override val proxy: SKAlertViewProxy, activity: SKActivity, fragment: Fragment?) : SKComponentView<Unit>(proxy, activity, fragment, Unit) { data class State(val state: SKAlertVC.Shown, val alert: AlertDialog) private var current: State? = null private var editText: EditText? = null private var firstInputChangeDoneFor = false fun onState(state: SKAlertVC.Shown?) { if (state != current?.state) { if (state != null) { AlertDialog.Builder(context) .setTitle(state.title) .setMessage(state.message) .setOnDismissListener { if (proxy.state == state) { proxy.state = null } } .setCancelable(state.cancelable) .apply { if (state.withInput) { val inputView = SkAlertInputBinding.inflate( this@SKAlertView.activity.layoutInflater, null, false ) editText = inputView.et.apply { setText(proxy.inputText) addTextChangedListener(object : TextWatcher { override fun beforeTextChanged( p0: CharSequence?, p1: Int, p2: Int, p3: Int ) { //na } override fun onTextChanged( p0: CharSequence?, p1: Int, p2: Int, p3: Int ) { val newText = p0?.toString() if (firstInputChangeDoneFor || !newText.isNullOrBlank()) { proxy.inputText = p0?.toString() } firstInputChangeDoneFor = true } override fun afterTextChanged(p0: Editable?) { //na } }) } setView(inputView.root) } setPositiveButton( state.mainButton.label, state.mainButton.action?.let { action -> DialogInterface.OnClickListener { p0, p1 -> action() } }) state.secondaryButton?.let { button -> setNegativeButton(button.label, button.action?.let { action -> DialogInterface.OnClickListener { p0, p1 -> action() } }) } state.neutralButton?.let { button -> setNeutralButton(button.label, button.action?.let { action -> DialogInterface.OnClickListener { p0, p1 -> action() } }) } } .create() .let { current = State(state, it) it.show() } } else { current?.alert?.dismiss() current = null } } } fun onInputText(inputText: String?) { if (editText?.text?.toString() != inputText) { editText?.setText(inputText) } } }
1
null
4
6
8fcff82c719c9775e63da9c3808817704068cbba
4,791
skot
Apache License 2.0
app/src/main/java/com/lambdaschool/hackathon_portal/ui/fragments/detail/DescriptionFragment.kt
BloomTech-Labs
227,462,757
false
{"Kotlin": 158652}
package com.lambdaschool.hackathon_portal.ui.fragments.detail import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import com.lambdaschool.hackathon_portal.R import com.lambdaschool.hackathon_portal.ui.fragments.BaseFragment import kotlinx.android.synthetic.main.fragment_description.* class DescriptionFragment : BaseFragment() { private lateinit var detailViewModel: DetailViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) detailViewModel = ViewModelProvider(this, viewModelProviderFactory) .get(DetailViewModel::class.java) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_description, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) detailViewModel.currentHackathon.observe(this, Observer { hackathon -> hackathon?.let { fragment_description_text_view_description.text = it.description } }) } }
4
Kotlin
0
0
d8bca01bfd6453f623b807c58f57b89c8bc9ca86
1,292
hackathon-portal-android
MIT License
app/src/main/java/cash/z/ecc/android/ui/setup/BackupFragment.kt
zcash-hackworks
272,508,715
true
{"Kotlin": 249480}
package cash.z.ecc.android.ui.setup import android.content.Context import android.os.Bundle import android.text.SpannableString import android.text.Spanned import android.view.LayoutInflater import android.view.View import android.widget.TextView import android.widget.Toast import androidx.activity.addCallback import androidx.lifecycle.lifecycleScope import cash.z.ecc.android.ZcashWalletApp import cash.z.ecc.android.databinding.FragmentBackupBinding import cash.z.ecc.android.di.viewmodel.activityViewModel import cash.z.ecc.android.feedback.Report import cash.z.ecc.android.feedback.Report.MetricType.SEED_PHRASE_LOADED import cash.z.ecc.android.feedback.Report.Tap.BACKUP_DONE import cash.z.ecc.android.feedback.Report.Tap.BACKUP_VERIFY import cash.z.ecc.android.feedback.measure import cash.z.ecc.android.lockbox.LockBox import cash.z.ecc.android.ui.base.BaseFragment import cash.z.ecc.android.ui.setup.WalletSetupViewModel.LockBoxKey import cash.z.ecc.android.ui.setup.WalletSetupViewModel.WalletSetupState.SEED_WITH_BACKUP import cash.z.ecc.android.ui.util.AddressPartNumberSpan import cash.z.ecc.kotlin.mnemonic.Mnemonics import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class BackupFragment : BaseFragment<FragmentBackupBinding>() { override val screen = Report.Screen.BACKUP val walletSetup: WalletSetupViewModel by activityViewModel(false) private var hasBackUp: Boolean = true //TODO: implement backup and then check for it here-ish override fun inflate(inflater: LayoutInflater): FragmentBackupBinding = FragmentBackupBinding.inflate(inflater) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) with(binding) { applySpan( textAddressPart1, textAddressPart2, textAddressPart3, textAddressPart4, textAddressPart5, textAddressPart6, textAddressPart7, textAddressPart8, textAddressPart9, textAddressPart10, textAddressPart11, textAddressPart12, textAddressPart13, textAddressPart14, textAddressPart15, textAddressPart16, textAddressPart17, textAddressPart18, textAddressPart19, textAddressPart20, textAddressPart21, textAddressPart22, textAddressPart23, textAddressPart24 ) } binding.buttonPositive.setOnClickListener { onEnterWallet().also { if (hasBackUp) tapped(BACKUP_DONE) else tapped(BACKUP_VERIFY) } } if (hasBackUp) { binding.buttonPositive.text = "Done" } } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) mainActivity?.onBackPressedDispatcher?.addCallback(this) { onEnterWallet(false) } } override fun onAttach(context: Context) { super.onAttach(context) walletSetup.checkSeed().onEach { when(it) { SEED_WITH_BACKUP -> { hasBackUp = true } } }.launchIn(lifecycleScope) } override fun onResume() { super.onResume() resumedScope.launch { binding.textBirtdate.text = "Birthday Height: %,d".format(walletSetup.loadBirthdayHeight()) } } private fun onEnterWallet(showMessage: Boolean = !this.hasBackUp) { if (showMessage) { Toast.makeText(activity, "Backup verification coming soon!", Toast.LENGTH_LONG).show() } mainActivity?.navController?.popBackStack() } private fun applySpan(vararg textViews: TextView) = lifecycleScope.launch { val words = loadSeedWords() val thinSpace = "\u2005" // 0.25 em space textViews.forEachIndexed { index, textView -> val numLength = "$index".length val word = words[index] // TODO: work with a charsequence here, rather than constructing a String textView.text = SpannableString("${index + 1}$thinSpace${String(word)}").apply { setSpan(AddressPartNumberSpan(), 0, 1 + numLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) } } } private suspend fun loadSeedWords(): List<CharArray> = withContext(Dispatchers.IO) { mainActivity!!.feedback.measure(SEED_PHRASE_LOADED) { val lockBox = LockBox(ZcashWalletApp.instance) val mnemonics = Mnemonics() val seedPhrase = lockBox.getCharsUtf8(LockBoxKey.SEED_PHRASE)!! val result = mnemonics.toWordList(seedPhrase) result } } }
0
Kotlin
1
2
baf3522e8905d541e6539f1278a082abd5cc28fd
4,783
zircles-android
Apache License 2.0
app-tracking-protection/vpn-impl/src/main/java/com/duckduckgo/mobile/android/vpn/ui/newtab/AppTrackingProtectionNewTabSettingView.kt
hojat72elect
822,396,044
false
{"Kotlin": 11626231, "HTML": 65873, "Ruby": 16984, "C++": 10312, "JavaScript": 5520, "CMake": 1992, "C": 1076, "Shell": 784}
package com.duckduckgo.mobile.android.vpn.ui.newtab import android.annotation.SuppressLint import android.content.Context import android.util.AttributeSet import android.view.View import android.widget.LinearLayout import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.findViewTreeLifecycleOwner import androidx.lifecycle.findViewTreeViewModelStoreOwner import com.duckduckgo.anvil.annotations.ContributesRemoteFeature import com.duckduckgo.anvil.annotations.InjectWith import com.duckduckgo.anvil.annotations.PriorityKey import com.duckduckgo.common.ui.viewbinding.viewBinding import com.duckduckgo.common.utils.ViewViewModelFactory import com.duckduckgo.di.scopes.ActivityScope import com.duckduckgo.di.scopes.AppScope import com.duckduckgo.di.scopes.ViewScope import com.duckduckgo.feature.toggles.api.Toggle import com.duckduckgo.mobile.android.vpn.databinding.ViewApptpSettingsItemBinding import com.duckduckgo.mobile.android.vpn.feature.removal.VpnFeatureRemover import com.duckduckgo.mobile.android.vpn.ui.newtab.AppTrackingProtectionNewTabSettingsViewModel.ViewState import com.duckduckgo.mobile.android.vpn.ui.onboarding.VpnStore import com.duckduckgo.newtabpage.api.NewTabPageSection import com.duckduckgo.newtabpage.api.NewTabPageSectionSettingsPlugin import com.squareup.anvil.annotations.ContributesMultibinding import dagger.android.support.AndroidSupportInjection import javax.inject.Inject import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach @InjectWith(ViewScope::class) class AppTrackingProtectionNewTabSettingView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyle: Int = 0, ) : LinearLayout(context, attrs, defStyle) { @Inject lateinit var viewModelFactory: ViewViewModelFactory private val binding: ViewApptpSettingsItemBinding by viewBinding() private var coroutineScope: CoroutineScope? = null private val viewModel: AppTrackingProtectionNewTabSettingsViewModel by lazy { ViewModelProvider( findViewTreeViewModelStoreOwner()!!, viewModelFactory )[AppTrackingProtectionNewTabSettingsViewModel::class.java] } override fun onAttachedToWindow() { AndroidSupportInjection.inject(this) super.onAttachedToWindow() findViewTreeLifecycleOwner()?.lifecycle?.addObserver(viewModel) @SuppressLint("NoHardcodedCoroutineDispatcher") coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Main) viewModel.viewState .onEach { render(it) } .launchIn(coroutineScope!!) } private fun render(viewState: ViewState) { binding.root.quietlySetIsChecked(viewState.enabled) { _, enabled -> viewModel.onSettingEnabled(enabled) } } } @ContributesMultibinding(scope = ActivityScope::class) @PriorityKey(NewTabPageSectionSettingsPlugin.APP_TRACKING_PROTECTION) class AppTrackingProtectionNewTabSettingViewPlugin @Inject constructor( private val vpnStore: VpnStore, private val vpnFeatureRemover: VpnFeatureRemover, ) : NewTabPageSectionSettingsPlugin { override val name = NewTabPageSection.APP_TRACKING_PROTECTION.name override fun getView(context: Context): View { return AppTrackingProtectionNewTabSettingView(context) } override suspend fun isActive(): Boolean { if (vpnFeatureRemover.isFeatureRemoved()) { return false } return vpnStore.didShowOnboarding() } } /** * Local feature/settings - they will never be in remote config */ @ContributesRemoteFeature( scope = AppScope::class, featureName = "newTabAppTPSectionSetting", ) interface NewTabAppTrackingProtectionSectionSetting { @Toggle.DefaultValue(true) fun self(): Toggle }
0
Kotlin
0
0
b89591136b60933d6a03fac43a38ee183116b7f8
3,924
DuckDuckGo
Apache License 2.0
app/src/main/java/br/com/montecardo/finanseer/persistence/VolatileMemoryDao.kt
MonteCardo
55,604,939
false
{"Kotlin": 32126, "Java": 19966}
package br.com.montecardo.finanseer.persistence import br.com.montecardo.finanseer.investment.data.Investment import br.com.montecardo.finanseer.investment.data.Movement /** * DAO implementation in memory. * * Created by gabryel on 20/09/17. */ class VolatileMemoryDao : FinanceDAO { private val investments: MutableMap<String, Investment> = mutableMapOf() private val movements: MutableMap<String, Movement> = mutableMapOf() override fun persist(inv: Investment) { investments[inv.id] = inv } override fun persist(mov: Movement) { movements[mov.id] = mov } override fun getInvestment(id: String) = investments[id] override fun getAllInvestments() = investments.values.toList() override fun getMovementsByInvestment(invId: String) = movements.values.filter { it.investmentId == invId } }
0
Kotlin
0
2
e9e2add4f59067fd0992358d30111786e0db3e38
864
FinanceApp
MIT License
src/shmp/lang/language/syntax/clause/realization/SyntaxClause.kt
ShMPMat
240,860,070
false
null
package shmp.lang.language.syntax.clause.realization import shmp.lang.language.category.value.CategoryValues import shmp.lang.language.Language import shmp.lang.language.lexis.Word import shmp.lang.language.syntax.SyntaxRelation import shmp.lang.language.syntax.clause.translation.SentenceNode import shmp.lang.language.syntax.sequence.WordSequence import shmp.lang.language.syntax.arranger.Arranger import shmp.lang.language.syntax.arranger.PassingArranger import kotlin.random.Random interface SyntaxClause { fun toNode(language: Language, random: Random): SentenceNode } interface UnfoldableClause: SyntaxClause { fun unfold(language: Language, random: Random): WordSequence } internal fun Word.wordToNode( generalType: SyntaxRelation, arranger: Arranger = PassingArranger, presetCategories: CategoryValues = categoryValues.map { it.categoryValue } ) = SentenceNode(this, presetCategories.toMutableList(), arranger, generalType)
0
Kotlin
0
1
1096dfa274f72282ff7286e2421ab5f43ac99147
958
LanguageGenerator
MIT License
test-models/src/main/kotlin/com/github/dimsuz/modelgenerator/LceState.kt
dimsuz
173,502,815
false
null
package com.github.dimsuz.modelgenerator data class LceState<C>( val isLoading: Boolean, val content: C?, val error: Throwable? ) { companion object { @Suppress("FunctionName", "FunctionNaming") // constructor function, caps ok fun <C> Loading(content: C? = null): LceState<C> { return LceState(isLoading = true, content = content, error = null) } @Suppress("FunctionName", "FunctionNaming") // constructor function, caps ok fun <C> Content(content: C): LceState<C> { return LceState(isLoading = false, content = content, error = null) } @Suppress("FunctionName", "FunctionNaming") // constructor function, caps ok fun <C> Error(error: Throwable, content: C? = null): LceState<C> { return LceState(isLoading = false, content = content, error = error) } } }
1
Kotlin
0
4
c1f28e476b330773880396f82f0c6790ad590a51
824
etg-model-generator
Apache License 2.0
base/src/main/java/cn/neday/base/config/LogConfig.kt
nEdAy
199,621,863
false
null
package cn.neday.base.config import com.blankj.utilcode.util.AppUtils import com.blankj.utilcode.util.LogUtils object LogConfig { fun init() { LogUtils.getConfig().isLogSwitch = AppUtils.isAppDebug() } }
1
null
3
11
584bc01304ba9faf03b341fb0d6590830118f572
222
Sheep
MIT License
core/src/main/kotlin/assignment/AssignmentFilter.kt
amplitude
519,022,661
false
null
package com.amplitude.assignment import com.amplitude.util.Cache interface AssignmentFilter { suspend fun shouldTrack(assignment: Assignment): Boolean } class InMemoryAssignmentFilter(size: Int) : AssignmentFilter { // Cache of canonical assignment to the last sent timestamp. private val cache = Cache<String, Unit>(size, DAY_MILLIS) override suspend fun shouldTrack(assignment: Assignment): Boolean { val canonicalAssignment = assignment.canonicalize() val track = cache.get(canonicalAssignment) == null if (track) { cache.set(canonicalAssignment, Unit) } return track } }
0
Kotlin
1
0
5fc1b86922ad2f381b39ce89d094bd25051db62a
652
evaluation-proxy
MIT License
app/src/main/kotlin/com/blacksquircle/ui/application/viewmodel/MainViewModel.kt
massivemadness
100,590,072
false
null
/* * Copyright 2021 Squircle IDE contributors. * * 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.blacksquircle.ui.application.viewmodel import android.content.Intent import android.net.Uri import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.blacksquircle.ui.R import com.blacksquircle.ui.core.lifecycle.SingleLiveEvent import com.blacksquircle.ui.data.converter.DocumentConverter import com.blacksquircle.ui.data.storage.keyvalue.SettingsManager import com.blacksquircle.ui.domain.repository.documents.DocumentRepository import com.blacksquircle.ui.filesystem.base.model.FileModel import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class MainViewModel @Inject constructor( private val settingsManager: SettingsManager, private val documentRepository: DocumentRepository ) : ViewModel() { companion object { private const val TAG = "MainViewModel" } val toastEvent = SingleLiveEvent<Int>() val fullScreenMode: Boolean get() = settingsManager.fullScreenMode val confirmExit: Boolean get() = settingsManager.confirmExit fun handleIntent(intent: Intent, onSuccess: () -> Unit) { viewModelScope.launch { try { var path = intent.data?.path.toString() Log.d(TAG, "Handle external file path = $path") if (path.contains('%')) { // probably encoded path = Uri.decode(path) Log.d(TAG, "Decoded path = $path") } if (path.startsWith("/external_files/")) { path = path.replaceFirst( oldValue = "/external_files/", newValue = "/storage/emulated/0/" ) } val index = path.indexOf("/storage/emulated/0/") if (index > -1) { val fileModel = FileModel(path.substring(index, path.length)) val documentModel = DocumentConverter.toModel(fileModel) documentRepository.updateDocument(documentModel) onSuccess() } else { toastEvent.value = R.string.message_file_not_found } } catch (e: Exception) { Log.e(TAG, e.message, e) toastEvent.value = R.string.message_unknown_exception } } } }
45
null
5
358
f02741bc1dd92a9f44f23f55a4dac0a00c237eac
3,059
ModPE-IDE
Apache License 2.0
module/src/main/java/com/ke/hs_tracker/module/entity/FormatType.kt
keluokeda
469,693,055
false
{"Kotlin": 372770}
package com.ke.hs_tracker.module.entity import androidx.annotation.StringRes import com.ke.hs_tracker.module.R enum class FormatType(@StringRes val title: Int) { Unknown(R.string.module_unknown), /** * 标准 */ Standard(R.string.module_standard), /** * 狂野 */ Wild(R.string.module_wild), /** * 经典 */ Classic(R.string.module_classic) } val String.toFormatType: FormatType get() = FormatType.values().find { this.contains(it.name, true) } ?: FormatType.Unknown
8
Kotlin
31
216
b4c42c2ecf385f0f9b18bf5656f1ede42795ef20
534
hs_tracker
MIT License
src/main/kotlin/org/swineproject/warthog/Menu.kt
SwineEngine
147,653,583
false
null
package org.swineproject.warthog import jep.Jep import jep.JepConfig import jep.python.PyObject import org.eclipse.swt.SWT import org.eclipse.swt.widgets.* import org.eclipse.swt.widgets.Menu import org.swineproject.warthog.filetypes.ProjectFile import java.io.File class Menu(decorations: Decorations) { val menuBar = Menu(decorations, SWT.BAR) val fileMenu = MenuItem(menuBar, SWT.CASCADE).apply { text = "File" this.menu = Menu(this).apply { MenuItem(this, SWT.PUSH).apply { text = "New Project" addListener(SWT.Selection) { val directoryDialog = DirectoryDialog(decorations as Shell) directoryDialog.filterPath = Globals.workingDirectory val directory = directoryDialog.open() if (directory != null) { ProjectFile.new(directory) // TODO: Use a templating engine instead like Velocity or StringTemplate val game = this::class.java.getResource("/scripts/game.py").readText() .replace(">title", "\"Title\"") .replace(">size", "(800, 600)") .replace(">vsync", "True") val scene = this::class.java.getResource("/scripts/scene.py").readText() File("$directory/game.py").apply { writeText(game) } File("$directory/assets/scenes/").mkdirs() File("$directory/assets/scenes/main_scene.py").apply { writeText(scene) } File("$directory/assets/scripts").mkdirs() File("$directory/assets/sprites").mkdirs() Globals.workingDirectory = directory Globals.project!!.refreshFiles() if (Globals.python != null) { Globals.python!!.close() } Globals.python = Jep() Globals.python!!.runScript("$directory/assets/scenes/main_scene.py") Globals.hierarchy!!.list.removeAll() Globals.syncAllObjects() // TODO: Check if the object doesn't have a parent, if it does, append it as a child item Globals.objectList.forEach { Globals.hierarchy!!.list.add(Globals.python!!.getValue("$it.name").toString()) } } } } // MenuItem(this, SWT.PUSH).apply { text = "Open Project" } } } }
0
Kotlin
0
0
2a7648773e6ce13f1f4df72227f8fd1cb9d1e11b
2,766
Warthog
MIT License
src/main/kotlin/mara/server/domain/board/BoardController.kt
DDD-Community
728,030,267
false
{"Kotlin": 75860, "Shell": 1330}
package mara.server.domain.board import mara.server.common.CommonResponse import mara.server.common.success import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController @RestController @RequestMapping("/boards") class BoardController(private val boardService: BoardService) { @PostMapping fun createBoard(@RequestBody boardRequest: BoardRequest,): CommonResponse<Long> { return success(boardService.createBoard(boardRequest)) } @GetMapping("/{id}") fun getBoard(@PathVariable(name = "id") id: Long): CommonResponse<BoardResponse> { return success(boardService.getBoard(id)) } }
2
Kotlin
3
6
4e84ea9b88593549efaf9141d7144f1329f00554
921
fridge-link-server
MIT License
src/main/kotlin/space/kscience/gradle/KScienceJSPlugin.kt
SciProgCentre
194,256,204
false
null
package space.kscience.gradle import org.gradle.api.Plugin import org.gradle.api.Project public open class KScienceJSPlugin : Plugin<Project> { override fun apply(project: Project): Unit = project.run { if (!plugins.hasPlugin("org.jetbrains.kotlin.js")) { plugins.apply("org.jetbrains.kotlin.js") } else { logger.info("Kotlin JS plugin is already present") } project.configureKScience() } }
0
null
3
8
c9440e7fc939f2bad609a59326410402e78c3668
457
gradle-tools
Apache License 2.0
sdk/sdk-metrics/src/commonMain/kotlin/io/opentelemetry/kotlin/sdk/metrics/data/DoubleSumData.kt
dcxp
450,518,130
false
{"Kotlin": 1483649}
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ package io.opentelemetry.kotlin.sdk.metrics.data /** [SumData] recorded uses `double`s. */ interface DoubleSumData : SumData<DoublePointData> { companion object { val EMPTY = create(false, AggregationTemporality.CUMULATIVE, emptyList()) fun create( isMonotonic: Boolean, temporality: AggregationTemporality, points: Collection<DoublePointData> ): DoubleSumData { return Implementation(points, isMonotonic, temporality) } data class Implementation( override val points: Collection<DoublePointData>, override val isMonotonic: Boolean, override val aggregationTemporality: AggregationTemporality ) : DoubleSumData } }
10
Kotlin
2
29
9c3186e26bd3ac78b650163be2c8f569096aaeec
843
opentelemetry-kotlin
Apache License 2.0
platform/src/main/kotlin/researchstack/backend/adapter/outgoing/mongo/entity/education/EducationalContentEntity.kt
S-ResearchStack
520,365,362
false
{"Kotlin": 1297740, "Dockerfile": 202, "Shell": 59}
package researchstack.backend.adapter.outgoing.mongo.entity.education import org.springframework.data.annotation.Id import org.springframework.data.mongodb.core.mapping.Document import researchstack.backend.enums.EducationalContentStatus import researchstack.backend.enums.EducationalContentType import researchstack.backend.enums.ScratchContentBlockType import java.time.LocalDateTime @Document("educationalContent") data class EducationalContentEntity( @Id val id: String? = null, val title: String, val type: EducationalContentType, val status: EducationalContentStatus, val category: String, val creatorId: String, val publisherId: String? = null, val modifierId: String? = null, val modifiedAt: LocalDateTime? = null, val publishedAt: LocalDateTime? = null, val content: Content ) { sealed interface Content data class PdfContent( val url: String, val description: String ) : Content data class VideoContent( val url: String, val description: String ) : Content data class ScratchContent( val coverImage: String, val description: String, val blocks: List<Block> ) : Content { interface Block { val id: String val type: ScratchContentBlockType val sequence: Int } data class TextBlock( override val id: String, override val type: ScratchContentBlockType, override val sequence: Int, val text: String ) : Block data class VideoBlock( override val id: String, override val type: ScratchContentBlockType, override val sequence: Int, val url: String, val text: String ) : Block data class ImageBlock( override val id: String, override val type: ScratchContentBlockType, override val sequence: Int, val images: List<Image> ) : Block data class Image( val id: String, val url: String, val caption: String ) } }
1
Kotlin
9
29
edd76f219cdb10c8151b8ac14175b1e818a6036a
2,162
backend-system
Apache License 2.0
services/blueprint-service/src/main/kotlin/org/katan/service/blueprint/http/dto/BlueprintResponse.kt
KatanPanel
182,468,654
false
null
package org.katan.service.blueprint.http.dto import kotlinx.datetime.Instant import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import org.katan.model.blueprint.Blueprint @Serializable internal data class BlueprintResponse( val id: String, val name: String, val version: String, @SerialName("image-id") val imageId: String, @SerialName("created-at") val createdAt: Instant, @SerialName("updated-at") val updatedAt: Instant? ) { constructor(blueprint: Blueprint) : this( id = blueprint.id.value.toString(), name = blueprint.name, version = blueprint.version, imageId = blueprint.imageId, createdAt = blueprint.createdAt, updatedAt = blueprint.updatedAt ) }
0
null
5
55
8e2f39310ec87bf19eed5a8a73b105518cabe7d9
770
Katan
Apache License 2.0
spring-boot-kotlin/src/test/kotlin/com/example/api/integration/EmployeeWebApplicationTest.kt
anirban99
302,595,489
false
null
package com.example.api.integration import com.example.api.service.EmployeeService import com.example.api.utils.faker.EmployeeFaker import com.fasterxml.jackson.databind.ObjectMapper import com.nhaarman.mockitokotlin2.doReturn import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance import org.mockito.Mockito import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.boot.test.mock.mockito.MockBean import org.springframework.http.MediaType import org.springframework.test.context.ActiveProfiles import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.request.MockMvcRequestBuilders import org.springframework.test.web.servlet.result.MockMvcResultMatchers @ActiveProfiles(value= ["test"]) @AutoConfigureMockMvc(addFilters = false) @TestInstance(TestInstance.Lifecycle.PER_CLASS) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class EmployeeWebApplicationTest { @Autowired private lateinit var mockMvc: MockMvc @Autowired private lateinit var objectMapper: ObjectMapper @MockBean private lateinit var employeeService: EmployeeService private val id = Math.random().toLong() @Test fun `Given valid url, when GET employee list is called, then returns 200 `() { val employeeList = listOf( EmployeeFaker.fakeEmployee(), EmployeeFaker.fakeEmployee(), EmployeeFaker.fakeEmployee(), EmployeeFaker.fakeEmployee() ) Mockito.`when`(employeeService.getAllEmployees()).doReturn(employeeList) mockMvc.perform(MockMvcRequestBuilders.get("/employees") .contentType(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().isOk) .andExpect(MockMvcResultMatchers.jsonPath("$").exists()) .andExpect(MockMvcResultMatchers.jsonPath("$.[*].id").isNotEmpty) } @Test fun `Given valid url, when GET employee by id is called, then returns 200 `() { val employee = EmployeeFaker.fakeEmployee().copy(id = id) Mockito.`when`(employeeService.getEmployeesById(id)).doReturn(employee) mockMvc.perform(MockMvcRequestBuilders.get("/employees/{id}", id) .contentType(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().isOk) .andExpect(MockMvcResultMatchers.jsonPath("$.id").value(id)) } @Test fun `Given valid url, when POST employee is called, then returns 200 `() { val employee = EmployeeFaker.fakeEmployee().copy(id = id) Mockito.`when`(employeeService.createEmployee(employee)).doReturn(employee) mockMvc.perform(MockMvcRequestBuilders.post("/employees") .content(objectMapper.writeValueAsString(employee)) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().isOk) .andExpect(MockMvcResultMatchers.jsonPath("$.id").value(id)) .andExpect(MockMvcResultMatchers.jsonPath("$.firstName").value(employee.firstName)) } @Test fun `Given valid url, when PUT employee is called, then returns 200 `() { val employee = EmployeeFaker.fakeUpdatedEmployee().copy(id = id) Mockito.`when`(employeeService.updateEmployeeById(id, employee)).doReturn(employee) mockMvc.perform(MockMvcRequestBuilders.put("/employees/{id}", id) .content(objectMapper.writeValueAsString(employee)) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().isOk) .andExpect(MockMvcResultMatchers.jsonPath("$.id").value(id)) .andExpect(MockMvcResultMatchers.jsonPath("$.firstName").value(employee.firstName)) .andExpect(MockMvcResultMatchers.jsonPath("$.emailId").value(employee.emailId)) } @Test fun `Given valid url, when DELETE employee by id is called, then returns 200 `() { val employee = EmployeeFaker.fakeEmployee().copy(id = id) Mockito.`when`(employeeService.deleteEmployeesById(id)).doReturn(employee) mockMvc.perform(MockMvcRequestBuilders.delete("/employees/{id}", id) .contentType(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().isOk) .andExpect(MockMvcResultMatchers.jsonPath("$.id").value(id)) } }
0
Kotlin
7
9
f55de288208ac061559b79062bf8f2d8dacf69b3
4,761
spring-boot-examples
Apache License 2.0
step5skie/shared/src/commonMain/kotlin/RocketLaunch.kt
kotlin-hands-on
665,019,040
false
null
package com.muheng.kotlinmultiplatformsandbox import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class RocketLaunch( @SerialName("flight_number") val flightNumber: Int, @SerialName("name") val missionName: String, @SerialName("date_utc") val launchDateUTC: String, @SerialName("success") val launchSuccess: Boolean? )
1
null
7
6
316d97f250f288acd7b9f709463f64e207e4c42f
402
get-started-with-kmp
Apache License 2.0
flutterapp/android/app/src/main/kotlin/de/kneke/flutterapp/MainActivity.kt
Kneke
175,188,803
false
{"Kotlin": 89367, "Swift": 13981, "Dart": 10584, "JavaScript": 7751, "HTML": 3824, "Ruby": 3260, "Dockerfile": 511, "SCSS": 466, "Shell": 224, "Objective-C": 38}
package de.kneke.flutterapp import android.util.Log import androidx.annotation.NonNull import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.engine.FlutterEngine import io.flutter.plugins.GeneratedPluginRegistrant import de.kneke.flutterapp.channel.config.QuoteViewModelChannel import de.kneke.flutterapp.channel.config.LegalResourceChannel class MainActivity : FlutterActivity() { override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) { GeneratedPluginRegistrant.registerWith(flutterEngine); // Register channels QuoteViewModelChannel(flutterEngine); LegalResourceChannel(flutterEngine); } }
22
Kotlin
0
2
35b0d4447ab42dedaed54509e73a1ae794199d3c
684
kotlin_multiplatform_quotes
Apache License 2.0
humingbirdgraphlib/src/main/java/com/humingbirdgraphlib/bargraph/VerticalValueIndicatorAdapter.kt
sujeet-kumar-mehta
166,382,339
false
{"Gradle": 4, "XML": 50, "Java Properties": 3, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Java": 2, "Kotlin": 12, "INI": 2}
package com.butterflybarchart import android.app.Activity import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.humingbirdgraphlib.R /** * Created by aurigait on 17/1/17. */ class VerticalValueIndicatorAdapter : RecyclerView.Adapter<VerticalValueIndicatorAdapter.ViewHolder> { private var mActivity: Activity? = null private var statesList = listOf<String>("More than 75% users", "More than 50% users", "Less than 50% users", "Less than 25% users") private var colorList = listOf<Int>(R.color.graph_green, R.color.graph_yellow, R.color.graph_orange, R.color.graph_red) constructor(mActivity: Activity) { this.mActivity = mActivity } override fun onCreateViewHolder(parent: ViewGroup, i: Int): VerticalValueIndicatorAdapter.ViewHolder { var viewHolder: VerticalValueIndicatorAdapter.ViewHolder? = null val inflater = LayoutInflater.from(parent.context) val viewItem = inflater.inflate(R.layout.item_text_view_bar_color, parent, false) viewHolder = ViewHolder(viewItem) return viewHolder } override fun onBindViewHolder(holder: VerticalValueIndicatorAdapter.ViewHolder, i: Int) { holder.textView.text = statesList[i] mActivity?.resources?.getColor(colorList[i])?.let { holder.verticalBarIndicator.setBackgroundColor(it) } } override fun getItemCount(): Int { return statesList!!.size } inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { val textView: TextView val verticalBarIndicator: View init { textView = view.findViewById(R.id.tv) verticalBarIndicator = view.findViewById(R.id.vertical_bar_color_indicator) } } }
0
Kotlin
0
6
c218a5af78a30be1b6cdc6584a8c299d5072ee28
1,866
HummingbirdGraphLibrary
MIT License
src/test/kotlin/com/fwdekker/randomness/PersistentSettingsTest.kt
FWDekker
96,791,256
false
{"Kotlin": 577836, "HTML": 2713, "Java": 1024}
package com.fwdekker.randomness import com.fwdekker.randomness.testhelpers.beforeNonContainer import com.intellij.openapi.util.JDOMUtil import io.kotest.assertions.throwables.shouldThrow import io.kotest.core.spec.style.FunSpec import io.kotest.matchers.nulls.beNull import io.kotest.matchers.should import io.kotest.matchers.shouldNot import java.net.URL /** * Unit tests for [PersistentSettings]. */ object PersistentSettingsTest : FunSpec({ lateinit var settings: PersistentSettings fun getTestConfig(path: String): URL = javaClass.getResource(path)!! beforeNonContainer { settings = PersistentSettings() } context("version upgrades") { test("fails for versions below v3.0.0") { val xml = JDOMUtil.load("""<component><option name="version" value="2.0.0"/></component>""") shouldThrow<IllegalStateException> { settings.loadState(xml) } } context("v3.1.0 to v3.2.0") { test("replaces `type` with `version` in all `UuidScheme`s") { val xml = JDOMUtil.load(getTestConfig("/settings-upgrades/v3.1.0-v3.2.0.xml")) xml.getSchemes().single().run { getProperty("type") shouldNot beNull() getProperty("version") should beNull() } settings.loadState(xml) settings.state.getSchemes().single().run { getProperty("type") should beNull() getProperty("version") shouldNot beNull() } } } } })
8
Kotlin
7
45
f5c0e51db2fec993d0dcf274ad32f732a8bb152c
1,581
intellij-randomness
MIT License
app/src/main/java/org/p2p/wallet/common/feature_toggles/toggles/remote/NetworkObservationFeatureToggle.kt
p2p-org
306,035,988
false
{"Kotlin": 4545395, "HTML": 3064848, "Java": 296567, "Groovy": 1601, "Shell": 1252}
package org.p2p.wallet.common.feature_toggles.toggles.remote import org.p2p.wallet.common.feature_toggles.remote_config.RemoteConfigValuesProvider class NetworkObservationFeatureToggle( valuesProvider: RemoteConfigValuesProvider ) : BooleanFeatureToggle(valuesProvider) { override val featureKey: String = "solana_negative_status_enabled" override val featureDescription: String = "Enable Solana network negative status observation feature" override val defaultValue: Boolean = false }
8
Kotlin
18
34
d091e18b7d88c936b7c6c627f4fec96bcf4a0356
504
key-app-android
MIT License
src/fundamentos/pacoteB/Matematica.kt
ravi2612
327,423,746
false
null
package fundamentos.pacoteB fun soma(a: Int, b:Int): Int{ return a + b } fun subtracao(a: Int, b:Int): Int { return a - b }
0
Kotlin
0
0
10bcb2e03dc1074a92b7914c9d157f2246dd8f78
131
Kotlin
MIT License
domain/domain-usecase/src/main/java/com/odogwudev/example/domain_usecase/helper/tvSeries/discover/DiscoverTvSeriesUseCase.kt
odogwudev
592,877,753
false
null
package com.odogwudev.example.domain_usecase.helper.tvSeries.discover import com.odogwudev.example.domain_util.FilterType import com.odogwudev.example.domain_util.result.wrapToResult import com.odogwudev.example.explore_api.ExploreService import com.odogwudev.example.pagination_api.RefreshType class DiscoverTvSeriesUseCase(private val exploreService: ExploreService) { suspend operator fun invoke( region: List<String> = emptyList(), withGenres: List<Int> = emptyList(), sortBy: List<String> = listOf(FilterType.DEFAULT.value), refreshType: RefreshType ) = wrapToResult { exploreService.getTvSeries( region = region, withGenres = withGenres, sortBy = sortBy, refreshType = refreshType ) } }
0
Kotlin
0
4
82791abdcf1554d2a2cd498a19cd93952f90e53e
803
CinephilesCompanion
MIT License
PagingArchitectureRetrofit/data/src/main/java/dev/seabat/android/pagingarchitectureretrofit/data/datasource/github/model/Owner.kt
seabat
636,759,391
false
{"Kotlin": 83756}
package dev.seabat.android.pagingarchitectureretrofit.data.datasource.github.model import com.squareup.moshi.Json data class Owner( @Json(name = "avatar_url") val avatarUrl: String? )
0
Kotlin
0
0
f8b7521282ed6a54415ecfef5a79dc41a350d047
189
hello-architecture-retrofit
Apache License 2.0
src/main/java/dev/blachut/svelte/lang/SvelteFileViewProvider.kt
convincely
248,160,749
false
{"Gradle": 2, "Markdown": 2, "Shell": 1, "Text": 10, "Ignore List": 1, "Batchfile": 1, "EditorConfig": 1, "Java Properties": 1, "Kotlin": 66, "Svelte": 22, "Java": 70, "JFlex": 2, "SVG": 2, "XML": 1, "HTML": 1, "YAML": 2}
package dev.blachut.svelte.lang import com.intellij.lang.Language import com.intellij.lang.LanguageParserDefinitions import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.MultiplePsiFilesPerDocumentFileViewProvider import com.intellij.psi.PsiFile import com.intellij.psi.PsiManager import com.intellij.psi.impl.source.PsiFileImpl import com.intellij.psi.templateLanguages.TemplateLanguageFileViewProvider import dev.blachut.svelte.lang.psi.SvelteTemplateElementTypes class SvelteFileViewProvider(virtualFile: VirtualFile, psiManager: PsiManager, eventSystemEnabled: Boolean) : MultiplePsiFilesPerDocumentFileViewProvider(psiManager, virtualFile, eventSystemEnabled), TemplateLanguageFileViewProvider { private val htmlLanguage = SvelteHTMLLanguage.INSTANCE override fun getBaseLanguage(): Language { return SvelteLanguage.INSTANCE } override fun getTemplateDataLanguage(): Language { return htmlLanguage } override fun getLanguages(): Set<Language> { return setOf(SvelteLanguage.INSTANCE, htmlLanguage) } override fun cloneInner(virtualFile: VirtualFile): MultiplePsiFilesPerDocumentFileViewProvider { return SvelteFileViewProvider(virtualFile, manager, false) } override fun createFile(lang: Language): PsiFile? { return when { lang === htmlLanguage -> { val file = LanguageParserDefinitions.INSTANCE.forLanguage(lang).createFile(this) as PsiFileImpl file.contentElementType = SvelteTemplateElementTypes.SVELTE_HTML_TEMPLATE_DATA file } lang === SvelteLanguage.INSTANCE -> LanguageParserDefinitions.INSTANCE.forLanguage(lang).createFile(this) else -> null } } }
1
null
1
1
f8906d30b8c175d578b40b81f65d53e4eeaad310
1,772
svelte-intellij
MIT License
android/app/src/main/java/app/covidshield/receiver/worker/NotificationWorker.kt
cds-snc
268,543,048
false
null
package app.covidshield.receiver.worker import android.annotation.TargetApi import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.os.Build import android.text.Html import android.text.Html.FROM_HTML_MODE_LEGACY import android.text.Spanned import androidx.core.app.NotificationCompat import androidx.work.CoroutineWorker import androidx.work.ForegroundInfo import androidx.work.WorkerParameters import app.covidshield.MainActivity import app.covidshield.R import kotlinx.coroutines.delay private const val CHANNEL_ID = "1" private const val CHANNEL_NAME = "COVID Alert" class NotificationWorker(private val context: Context, parameters: WorkerParameters) : CoroutineWorker(context, parameters) { private val notificationManager: NotificationManager = context.applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager override suspend fun doWork(): Result { val intent = Intent(context, MainActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK } val pendingIntent = PendingIntent.getActivity(context, 0, intent, 0) val notification = NotificationCompat.Builder(context, "1") .setSmallIcon(inputData.getInt("smallIcon", R.drawable.ic_notification_icon)) .setContentTitle(inputData.getString("title")) .setContentText(inputData.getString("body")) .setPriority(inputData.getInt("priority", NotificationCompat.PRIORITY_MAX)) .setContentIntent(pendingIntent) .setOngoing(true) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { createNotificationChannel(CHANNEL_ID, CHANNEL_NAME, inputData.getBoolean("disableSound", false)) notification.setChannelId(CHANNEL_ID) } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { val styledText: Spanned = Html.fromHtml(inputData.getString("body"), FROM_HTML_MODE_LEGACY) notification.setStyle(NotificationCompat.BigTextStyle().bigText(styledText)) } val foregroundInfo = ForegroundInfo(1, notification.build()) setForeground(foregroundInfo) // TODO: How long should the notification appear? delay(5000) return Result.success() } /** * Create the required notification channel for O+ devices. */ @TargetApi(Build.VERSION_CODES.O) private fun createNotificationChannel( channelId: String, name: String, disableSound: Boolean ): NotificationChannel { return NotificationChannel( channelId, name, NotificationManager.IMPORTANCE_HIGH ).also { channel -> if (disableSound) { channel.setSound(null, null) } notificationManager.createNotificationChannel(channel) } } }
15
TypeScript
111
898
3f79e220cc4235365207d5146d2784f4622503ab
3,062
covid-alert-app
Apache License 2.0
src/main/kotlin/de/larmic/unittesting/database/BookJpaRepository.kt
larmic
452,640,797
false
null
package de.larmic.unittesting.database import jakarta.persistence.Column import org.springframework.data.jpa.repository.JpaRepository import org.springframework.data.jpa.repository.Query import org.springframework.stereotype.Repository import java.time.LocalDate import java.util.* import jakarta.persistence.Entity import jakarta.persistence.Id import jakarta.persistence.Table @Repository interface BookJpaRepository : JpaRepository<BookEntity, UUID> { @Query(value = "SELECT b FROM book b WHERE b.title = ?1 LIMIT 1", nativeQuery = true) fun findByTitle(title: String) : BookEntity? } @Entity @Table(name = "book") data class BookEntity( @Id val id: UUID = UUID.randomUUID(), @Column(name = "title", nullable = false) val title: String, @Column(name = "create_date", nullable = false) val createDate: LocalDate, @Column(name = "author_first_name", nullable = false) val authorFirstName: String, @Column(name = "author_last_name", nullable = false) val authorLastName: String, )
5
null
0
6
695b533772c278439648a57881e0081080af548e
1,013
unit-testing-best-bad-practices
Apache License 2.0
vk-sdk-api/src/main/java/com/vk/sdk/api/auth/methods/AuthCheckPhone.kt
hackumono
359,598,859
true
{"Kotlin": 5863360, "Java": 37555}
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.auth.methods import com.vk.sdk.api.ApiRequestBase import com.vk.sdk.api.GsonHolder import com.vk.sdk.api.base.dto.BaseOkResponseDto import com.vk.sdk.api.base.responses.BaseOkResponse import kotlin.Boolean import kotlin.Int import kotlin.String import org.json.JSONObject /** * Checks a user's phone number for correctness. * @param phone Phone number. * @param clientId User ID. * @param clientSecret * @param authByPhone */ class AuthCheckPhone( private val phone: String, private val clientId: Int? = null, private val clientSecret: String? = null, private val authByPhone: Boolean? = null ) : ApiRequestBase<BaseOkResponseDto>(methodName = "auth.checkPhone") { init { addParam("phone", phone) clientId?.let { value -> addParam("client_id", value) } clientSecret?.let { value -> addParam("client_secret", value) } authByPhone?.let { value -> addParam("auth_by_phone", if (value) 1 else 0) } } override fun parse(r: JSONObject): BaseOkResponseDto = GsonHolder.gson.fromJson(r.toString(), BaseOkResponse::class.java).response }
0
null
0
0
9417300f321cae4f231d6cb0ee44002a140a2124
2,585
vk-android-sdk
MIT License
app/src/main/java/com/kgurgul/cpuinfo/features/information/gpu/GpuInfoViewModel.kt
kamgurgul
105,620,694
false
null
/* * Copyright 2017 KG Soft * * 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.kgurgul.cpuinfo.features.information.gpu import androidx.lifecycle.ViewModel import androidx.lifecycle.asLiveData import androidx.lifecycle.viewModelScope import com.kgurgul.cpuinfo.domain.observable.GpuDataObservable import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.map import javax.inject.Inject /** * ViewModel for GPU information. It is using custom SurfaceView to get more GPU details from OpenGL * * @author kgurgul */ @HiltViewModel class GpuInfoViewModel @Inject constructor( private val observableGpuData: GpuDataObservable ) : ViewModel() { val viewState = observableGpuData.observe() .distinctUntilChanged() .map { GpuInfoViewState(it) } .asLiveData(viewModelScope.coroutineContext) init { observableGpuData(GpuDataObservable.Params()) } fun onGlInfoReceived(glVendor: String?, glRenderer: String?, glExtensions: String?) { observableGpuData(GpuDataObservable.Params(glVendor, glRenderer, glExtensions)) } }
27
Kotlin
88
468
c14870ef298bc6be2c1355d36698c355c1f5fc51
1,684
cpu-info
Apache License 2.0