path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
756M
is_fork
bool
2 classes
languages_distribution
stringlengths
12
2.44k
content
stringlengths
6
6.29M
issues
float64
0
10k
main_language
stringclasses
128 values
forks
int64
0
54.2k
stars
int64
0
157k
commit_sha
stringlengths
40
40
size
int64
6
6.29M
name
stringlengths
1
100
license
stringclasses
104 values
app/src/main/java/com/example/foodike/presentation/details/DetailScreenEvent.kt
RushilBhupta
716,925,700
false
{"Kotlin": 143028}
package com.example.foodike.presentation.details sealed class DetailScreenEvent { object ToggleRecommendedSectionExpandedState : DetailScreenEvent() object ToggleNonVegSectionExpandedState : DetailScreenEvent() object ToggleVegSectionExpandedState : DetailScreenEvent() object ToggleLikedStatus : DetailScreenEvent() }
0
Kotlin
0
0
be11b4b34523fe860611bca33ad98466944f28c4
337
mofoodz
MIT License
viewer-backend/src/main/kotlin/dev/qixils/yahoo/api/MessageReference.kt
qixils
451,297,753
false
{"Svelte": 34137, "Kotlin": 12917, "Python": 9069, "JavaScript": 1431, "HTML": 1157, "CSS": 856, "TypeScript": 712}
package dev.qixils.yahoo.api data class MessageReference( val group: String, val id: Int )
3
Svelte
0
0
5aaf83b8946e393ed96fde30766daf412940624c
99
yahoo-groups-viewer
MIT License
moduleB/src/main/java/com/example/moduleb/ModuleBActivity.kt
chenkaik
366,401,086
false
null
package com.example.moduleb import android.os.Bundle import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import com.alibaba.android.arouter.facade.annotation.Autowired import com.alibaba.android.arouter.facade.annotation.Route import com.alibaba.android.arouter.launcher.ARouter import com.example.basemodule.ARouterPath import com.example.basemodule.BaseActivity /** * date: 2021/5/3 * desc: */ @Route(path = ARouterPath.PATH_MOUDULE_B) class ModuleBActivity : BaseActivity() { @Autowired(name = "key") @JvmField var data: String = "默认值" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.moduleb_activity_module_b) ARouter.getInstance().inject(this) val textView = findViewById<TextView>(R.id.moduleb_textview) textView.text = data } }
0
Kotlin
0
0
047ebcd5d22599af2416f268ac75ac08b23db5b2
895
MyCommon
Apache License 2.0
app/src/main/java/com/naedri/andro_potter/view/library/BucketAdapter.kt
Naedri
573,321,237
false
{"Kotlin": 17865}
package com.naedri.andro_potter.view.library import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.naedri.andro_potter.R import com.naedri.andro_potter.model.Book import com.naedri.andro_potter.model.Bucket class BucketAdapter(private val bucket: Bucket) : RecyclerView.Adapter<BucketAdapter.CartViewHolder>() { var onRemoveItemClick: ((Book) -> Unit)? = null; class CartViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val cartBookName: TextView = itemView.findViewById(R.id.bookBucketTitle) val cartBookPrice: TextView = itemView.findViewById(R.id.bookBucketPrice) val cartBookQuantity: TextView = itemView.findViewById(R.id.bookBucketQuantity) val cartRemoveButton: Button = itemView.findViewById(R.id.buttonRemoveBucket) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CartViewHolder { val vue = LayoutInflater.from(parent.context).inflate(R.layout.item_bucket, parent, false) return CartViewHolder(vue) } override fun onBindViewHolder(holder: CartViewHolder, position: Int) { val quantity = bucket.getItems()[position].quantity val book = bucket.getItems()[position].book holder.cartBookName.text = book.title holder.cartBookPrice.text = book.price.toString() + '€' holder.cartBookQuantity.text = quantity.toString() + 'x' holder.cartRemoveButton.setOnClickListener { Log.d( "BucketAdapter", "Try to delete book from bucket: ${book.title}" ) onRemoveItemClick?.invoke(book); if (quantity > 1) { Log.d( "BucketAdapter", "Keeping item for: ${book.title}" ) notifyItemChanged(position) } else { Log.d( "BucketAdapter", "Deleting item for: ${book.title}" ) notifyItemRemoved(position); //this line below gives you the animation and also updates the //list items after the deleted item notifyItemRangeChanged(position, quantity); } } } override fun getItemCount(): Int { return bucket?.getItems()?.size ?: 0 } }
0
Kotlin
0
0
9a67202fe01ab17cf829f22dfc8f7f608aaabd34
2,518
andro-potter
MIT License
plugins/git4idea/src/git4idea/index/actions/GitFileStatusNodeAction.kt
hieuprogrammer
284,920,751
true
null
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.index.actions import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.Presentation import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.ui.MessageType import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.ThrowableComputable import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vcs.ui.VcsBalloonProblemNotifier import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.vcsUtil.VcsFileUtil import com.intellij.vcsUtil.VcsUtil import com.intellij.xml.util.XmlStringUtil import git4idea.i18n.GitBundle import git4idea.index.ui.GIT_FILE_STATUS_NODES_STREAM import git4idea.index.ui.GitFileStatusNode import git4idea.index.ui.NodeKind import git4idea.index.vfs.GitIndexFileSystemRefresher import git4idea.util.GitFileUtils import java.util.function.Supplier import javax.swing.Icon import kotlin.streams.toList class GitAddAction : GitFileStatusNodeAction(GitAddOperation) class GitResetAction : GitFileStatusNodeAction(GitResetOperation) class GitRevertAction : GitFileStatusNodeAction(GitRevertOperation) abstract class GitFileStatusNodeAction(private val operation: StagingAreaOperation) : DumbAwareAction(operation.actionText, Presentation.NULL_STRING, operation.icon) { override fun update(e: AnActionEvent) { val statusInfoStream = e.getData(GIT_FILE_STATUS_NODES_STREAM) e.presentation.isEnabledAndVisible = e.project != null && statusInfoStream != null && statusInfoStream.anyMatch(operation::matches) } override fun actionPerformed(e: AnActionEvent) { val project = e.project!! val nodes = e.getRequiredData(GIT_FILE_STATUS_NODES_STREAM).filter(operation::matches).toList() performStageOperation(project, nodes, operation) } } object GitAddOperation : StagingAreaOperation { override val actionText get() = GitBundle.messagePointer("add.action.name") override val progressTitle get() = GitBundle.message("add.adding") override val icon = AllIcons.General.Add override fun matches(statusNode: GitFileStatusNode) = statusNode.kind == NodeKind.UNSTAGED || statusNode.kind == NodeKind.UNTRACKED override fun processPaths(project: Project, root: VirtualFile, paths: List<FilePath>) { GitFileUtils.addPaths(project, root, paths, false) } override fun showErrorMessage(project: Project, exceptions: Collection<VcsException>) { showErrorMessage(project, VcsBundle.message("error.adding.files.title"), exceptions) } } object GitResetOperation : StagingAreaOperation { override val actionText get() = GitBundle.messagePointer("stage.reset.action.text") override val progressTitle get() = GitBundle.message("stage.reset.process") override val icon = AllIcons.General.Remove override fun matches(statusNode: GitFileStatusNode) = statusNode.kind == NodeKind.STAGED override fun processPaths(project: Project, root: VirtualFile, paths: List<FilePath>) { GitFileUtils.resetPaths(project, root, paths) } override fun showErrorMessage(project: Project, exceptions: Collection<VcsException>) { showErrorMessage(project, GitBundle.message("stage.reset.error.title"), exceptions) } } object GitRevertOperation : StagingAreaOperation { override val actionText get() = GitBundle.messagePointer("stage.revert.action.text") override val progressTitle get() = GitBundle.message("stage.revert.process") override val icon = AllIcons.Actions.Rollback override fun matches(statusNode: GitFileStatusNode) = statusNode.kind == NodeKind.UNSTAGED override fun processPaths(project: Project, root: VirtualFile, paths: List<FilePath>) { GitFileUtils.revertUnstagedPaths(project, root, paths) LocalFileSystem.getInstance().refreshFiles(paths.mapNotNull { it.virtualFile }) } override fun showErrorMessage(project: Project, exceptions: Collection<VcsException>) { showErrorMessage(project, GitBundle.message("stage.revert.error.title"), exceptions) } } fun performStageOperation(project: Project, nodes: List<GitFileStatusNode>, operation: StagingAreaOperation) { FileDocumentManager.getInstance().saveAllDocuments() runProcess(project, operation.progressTitle, true) { val paths = nodes.map { it.filePath } val exceptions = mutableListOf<VcsException>() VcsUtil.groupByRoots(project, paths) { it }.forEach { (vcsRoot, paths) -> try { operation.processPaths(project, vcsRoot.path, paths) VcsFileUtil.markFilesDirty(project, paths) GitIndexFileSystemRefresher.getInstance(project).refresh { paths.contains(it.filePath) } } catch (ex: VcsException) { exceptions.add(ex) } } if (exceptions.isNotEmpty()) { operation.showErrorMessage(project, exceptions) } } } fun <T> runProcess(project: Project, @NlsContexts.ProgressTitle title: String, canBeCancelled: Boolean, process: () -> T): T { return ProgressManager.getInstance().runProcessWithProgressSynchronously<T, Exception>(ThrowableComputable { process() }, title, canBeCancelled, project) } private fun showErrorMessage(project: Project, messageTitle: String, exceptions: Collection<Exception>) { VcsBalloonProblemNotifier.showOverVersionControlView(project, XmlStringUtil.wrapInHtmlTag("$messageTitle:", "b") + "\n" + exceptions.joinToString("\n") { it.localizedMessage }, MessageType.ERROR) } interface StagingAreaOperation { val actionText: Supplier<String> val progressTitle: String val icon: Icon? fun matches(statusNode: GitFileStatusNode): Boolean @Throws(VcsException::class) fun processPaths(project: Project, root: VirtualFile, paths: List<FilePath>) fun showErrorMessage(project: Project, exceptions: Collection<VcsException>) }
1
null
0
2
dc846ecb926c9d9589c1ed8a40fdb20e47874db9
6,443
intellij-community
Apache License 2.0
chat-ui/src/main/java/com/fzm/chat/vm/ServerManageViewModel.kt
txchat
507,831,442
false
{"Kotlin": 2234450, "Java": 384844}
package com.fzm.chat.vm import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.fzm.chat.biz.db.AppDatabase import com.fzm.chat.biz.db.po.ServerHistory import com.fzm.chat.core.data.ChatConst import com.fzm.chat.core.data.bean.ServerGroupInfo import com.fzm.chat.core.data.bean.ServerNode import com.fzm.chat.core.repo.ContractRepository import com.fzm.chat.core.session.LoginDelegate import com.fzm.arch.connection.socket.ConnectionManager import com.fzm.chat.biz.data.repo.BusinessRepository import com.zjy.architecture.data.Result import com.zjy.architecture.mvvm.LoadingViewModel import com.zjy.architecture.mvvm.request /** * @author zhengjy * @since 2021/02/22 * Description: */ class ServerManageViewModel( private val repository: ContractRepository, private val discover: BusinessRepository, private val database: AppDatabase, val connection: ConnectionManager, delegate: LoginDelegate ) : LoadingViewModel(), LoginDelegate by delegate { private val _serverGroups by lazy { MutableLiveData<List<ServerGroupInfo>>() } val serverGroups: LiveData<List<ServerGroupInfo>> get() = _serverGroups private val _addResult by lazy { MutableLiveData<Any>() } val addResult: LiveData<Any> get() = _addResult private val _delResult by lazy { MutableLiveData<Any>() } val delResult: LiveData<Any> get() = _delResult private val _editResult by lazy { MutableLiveData<Any>() } val editResult: LiveData<Any> get() = _editResult private val _chatList = MutableLiveData<List<ServerNode.Node>>() val chatList: LiveData<List<ServerNode.Node>> get() = _chatList fun getServerGroupList() { request<Unit> { onRequest { val list = repository.getServerGroup() _serverGroups.value = list Result.Success(Unit) } } } fun addServerGroup(name: String, address: String) { request<String> { onRequest { database.serverHistoryDao().insert(ServerHistory(name = name, address = address, type = ChatConst.CHAT_SERVER)) repository.modifyServerGroup(listOf(ServerGroupInfo("", 1, name, address))) } onSuccess { repository.updateInfo() _addResult.value = it } } } fun deleteServerGroup(id: String) { request<String> { onRequest { repository.modifyServerGroup(listOf(ServerGroupInfo(id, 2, "", ""))) } onSuccess { repository.updateInfo() _delResult.value = it } } } fun editServerGroup(id: String, name: String, address: String) { request<String> { onRequest { database.serverHistoryDao().insert(ServerHistory(name = name, address = address, type = ChatConst.CHAT_SERVER)) repository.modifyServerGroup(listOf(ServerGroupInfo(id, 3, name, address))) } onSuccess { repository.updateInfo() _editResult.value = it } } } fun fetchServerList() { request<ServerNode>(false) { onRequest { val result = discover.fetchServerList() val chat = database.serverHistoryDao().getChatServerHistory().map { ServerNode.Node(it.name, it.address).apply { id = it.id } } val contract = database.serverHistoryDao().getContractServerHistory().map { ServerNode.Node(it.name, it.address).apply { id = it.id } } if (result.isSucceed()) { val data = result.data() Result.Success(ServerNode(data.servers + chat, data.nodes + contract)) } else { Result.Success(ServerNode(chat, contract)) } } onSuccess { _chatList.value = it.servers } } } }
0
Kotlin
1
1
6a3c6edf6ae341199764d4d08dffd8146877678b
4,129
ChatPro-Android
MIT License
prototype2/src/main/kotlin/com/seanshubin/game_4x/prototype2/CommandFactoryImpl.kt
SeanShubin
204,213,077
false
null
package com.seanshubin.game_4x.prototype2 import arrow.core.Either import arrow.core.left import arrow.core.right class CommandFactoryImpl : CommandFactory { override fun build(name: String, parameters: List<Item>): Either<String, Command> = when (name) { "add" -> buildAdd(parameters) "remove" -> buildRemove(parameters) else -> Messages.commandNotFound(name).left() } private fun buildAdd(parameters: List<Item>): Either<String, Command> { val item = parameters.getOrNull(0) ?: return Messages.missingParameter(0).left() return AddCommand(item).right() } private fun buildRemove(parameters: List<Item>): Either<String, Command> { val item = parameters.getOrNull(0) ?: return Messages.missingParameter(0).left() return RemoveCommand(item).right() } }
0
Kotlin
0
0
a05479651479b5ab1470b925c015c7fa74cd59cb
860
game-4x
The Unlicense
domain/src/main/java/com/wo1f/domain/usecases/remote/auth/LogOut.kt
adwardwolf
387,865,580
false
null
package com.wo1f.domain.usecases.remote.auth import com.wo1f.domain.repository.AuthRepository import com.wo1f.domain.usecases.cache.DeleteAllNotificationDataUseCase import com.wo1f.domain.usecases.cache.DeleteAllProfileDataUseCase import javax.inject.Inject class LogOut @Inject constructor( val authRepository: AuthRepository, val deleteAllProfileDataUseCase: DeleteAllProfileDataUseCase, val deleteAllNotificationDataUseCase: DeleteAllNotificationDataUseCase ) { suspend operator fun invoke() { authRepository.logOut() deleteAllProfileDataUseCase() deleteAllNotificationDataUseCase() } }
0
Kotlin
0
2
d9372ab26a0f74ff32e196ffc7457258f1d7270c
637
the-earth
Apache License 2.0
app/src/main/kotlin/tbrs/ocr/camera/CameraManager.kt
tbrs
176,351,966
true
{"Kotlin": 251697, "HTML": 6418, "CSS": 165}
/* * Copyright (C) 2008 ZXing authors * Copyright 2011 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tbrs.ocr.camera import android.content.Context import android.graphics.Rect import android.hardware.Camera import android.os.Handler import android.preference.PreferenceManager import android.view.SurfaceHolder import tbrs.ocr.PlanarYUVLuminanceSource import tbrs.ocr.PreferencesActivity import java.io.IOException /** * This object wraps the Camera service object and expects to be the only one talking to it. The * implementation encapsulates the steps needed to take preview-sized images, which are used for * both preview and decoding. * * The code for this class was adapted from the ZXing project: http://code.google.com/p/zxing */ class CameraManager(private val context: Context) { private val configManager: CameraConfigurationManager private var camera: Camera? = null private var autoFocusManager: AutoFocusManager? = null internal var framingRect: Rect? = null private var framingRectInPreview: Rect? = null private var initialized: Boolean = false private var previewing: Boolean = false private var reverseImage: Boolean = false private var requestedFramingRectWidth: Int = 0 private var requestedFramingRectHeight: Int = 0 /** * Preview frames are delivered here, which we pass on to the registered handler. Make sure to * clear the handler so it will only receive one message. */ private val previewCallback: PreviewCallback init { this.configManager = CameraConfigurationManager(context) previewCallback = PreviewCallback(configManager) } /** * Opens the camera driver and initializes the hardware parameters. * * @param holder The surface object which the camera will draw preview frames into. * @throws IOException Indicates the camera driver failed to open. */ @Synchronized @Throws(IOException::class) fun openDriver(holder: SurfaceHolder) { var theCamera = camera if (theCamera == null) { theCamera = Camera.open() if (theCamera == null) { throw IOException() } camera = theCamera } camera!!.setPreviewDisplay(holder) if (!initialized) { initialized = true configManager.initFromCameraParameters(theCamera) if (requestedFramingRectWidth > 0 && requestedFramingRectHeight > 0) { adjustFramingRect(requestedFramingRectWidth, requestedFramingRectHeight) requestedFramingRectWidth = 0 requestedFramingRectHeight = 0 } } configManager.setDesiredCameraParameters(theCamera) val prefs = PreferenceManager.getDefaultSharedPreferences(context) reverseImage = prefs.getBoolean(PreferencesActivity.KEY_REVERSE_IMAGE, false) } /** * Closes the camera driver if still in use. */ @Synchronized fun closeDriver() { if (camera != null) { camera!!.release() camera = null // Make sure to clear these each time we close the camera, so that any scanning rect // requested by intent is forgotten. framingRect = null framingRectInPreview = null } } /** * Asks the camera hardware to begin drawing preview frames to the screen. */ @Synchronized fun startPreview() { val theCamera = camera if (theCamera != null && !previewing) { theCamera.startPreview() previewing = true autoFocusManager = AutoFocusManager(context, camera!!) } } /** * Tells the camera to stop drawing preview frames. */ @Synchronized fun stopPreview() { if (autoFocusManager != null) { autoFocusManager!!.stop() autoFocusManager = null } if (camera != null && previewing) { camera!!.stopPreview() previewCallback.setHandler(null, 0) previewing = false } } /** * A single preview frame will be returned to the handler supplied. The data will arrive as byte[] * in the message.obj field, with width and height encoded as message.arg1 and message.arg2, * respectively. * * @param handler The handler to send the message to. * @param message The what field of the message to be sent. */ @Synchronized fun requestOcrDecode(handler: Handler, message: Int) { val theCamera = camera if (theCamera != null && previewing) { previewCallback.setHandler(handler, message) theCamera.setOneShotPreviewCallback(previewCallback) } } /** * Asks the camera hardware to perform an autofocus. * @param delay Time delay to send with the request */ @Synchronized fun requestAutoFocus(delay: Long) { autoFocusManager!!.start(delay) } /** * Calculates the framing rect which the UI should draw to show the user where to place the * barcode. This target helps with alignment as well as forces the user to hold the device * far enough away to ensure the image will be in focus. * * @return The rectangle to draw on screen in window coordinates. */ @Synchronized fun getFramingRect(): Rect? { if (framingRect == null) { if (camera == null) { return null } val screenResolution = configManager.screenResolution ?: // Called early, before init even finished return null var width = screenResolution.x * 3 / 5 if (width < MIN_FRAME_WIDTH) { width = MIN_FRAME_WIDTH } else if (width > MAX_FRAME_WIDTH) { width = MAX_FRAME_WIDTH } var height = screenResolution.y * 1 / 5 if (height < MIN_FRAME_HEIGHT) { height = MIN_FRAME_HEIGHT } else if (height > MAX_FRAME_HEIGHT) { height = MAX_FRAME_HEIGHT } val leftOffset = (screenResolution.x - width) / 2 val topOffset = (screenResolution.y - height) / 2 framingRect = Rect(leftOffset, topOffset, leftOffset + width, topOffset + height) } return framingRect } /** * Like [.getFramingRect] but coordinates are in terms of the preview frame, * not UI / screen. */ @Synchronized fun getFramingRectInPreview(): Rect? { if (framingRectInPreview == null) { val rect = Rect(getFramingRect()) val cameraResolution = configManager.cameraResolution val screenResolution = configManager.screenResolution if (cameraResolution == null || screenResolution == null) { // Called early, before init even finished return null } rect.left = rect.left * cameraResolution.x / screenResolution.x rect.right = rect.right * cameraResolution.x / screenResolution.x rect.top = rect.top * cameraResolution.y / screenResolution.y rect.bottom = rect.bottom * cameraResolution.y / screenResolution.y framingRectInPreview = rect } return framingRectInPreview } /** * Changes the size of the framing rect. * * @param deltaWidth Number of pixels to adjust the width * @param deltaHeight Number of pixels to adjust the height */ @Synchronized fun adjustFramingRect(deltaWidth: Int, deltaHeight: Int) { var deltaWidth = deltaWidth var deltaHeight = deltaHeight if (initialized) { val screenResolution = configManager.screenResolution // Set maximum and minimum sizes if (framingRect!!.width() + deltaWidth > screenResolution!!.x - 4 || framingRect!!.width() + deltaWidth < 50) { deltaWidth = 0 } if (framingRect!!.height() + deltaHeight > screenResolution.y - 4 || framingRect!!.height() + deltaHeight < 50) { deltaHeight = 0 } val newWidth = framingRect!!.width() + deltaWidth val newHeight = framingRect!!.height() + deltaHeight val leftOffset = (screenResolution.x - newWidth) / 2 val topOffset = (screenResolution.y - newHeight) / 2 framingRect = Rect(leftOffset, topOffset, leftOffset + newWidth, topOffset + newHeight) framingRectInPreview = null } else { requestedFramingRectWidth = deltaWidth requestedFramingRectHeight = deltaHeight } } /** * A factory method to build the appropriate LuminanceSource object based on the format * of the preview buffers, as described by Camera.Parameters. * * @param data A preview frame. * @param width The width of the image. * @param height The height of the image. * @return A PlanarYUVLuminanceSource instance. */ fun buildLuminanceSource(data: ByteArray, width: Int, height: Int): PlanarYUVLuminanceSource? { val rect = getFramingRectInPreview() ?: return null // Go ahead and assume it's YUV rather than die. return PlanarYUVLuminanceSource(data, width, height, rect.left, rect.top, rect.width(), rect.height(), reverseImage) } companion object { private val TAG = CameraManager::class.java.simpleName private val MIN_FRAME_WIDTH = 50 // originally 240 private val MIN_FRAME_HEIGHT = 20 // originally 240 private val MAX_FRAME_WIDTH = 800 // originally 480 private val MAX_FRAME_HEIGHT = 600 // originally 360 } }
0
Kotlin
0
1
f10d5b0bd96a9a86ee55a230a1a59aeb33e946d4
10,374
android-ocr
Apache License 2.0
runtime/runtime-common/src/main/kotlin/pbandk/Message.kt
cretz
135,504,546
false
null
package pbandk interface Message<T : Message<T>> { operator fun plus(other: T?): T val protoSize: Int fun protoMarshal(m: Marshaller) fun protoMarshal() = Marshaller.allocate(protoSize).also(::protoMarshal).complete()!! interface Companion<T : Message<T>> { fun protoUnmarshal(u: Unmarshaller): T fun protoUnmarshal(arr: ByteArray) = protoUnmarshal(Unmarshaller.fromByteArray(arr)) } interface Enum { val value: Int interface Companion<T : Enum> { fun fromValue(value: Int): T } } }
8
Kotlin
15
140
faa0d3674e1795dbe131612b7cd0a069a8b5a184
570
pb-and-k
MIT License
core/src/commonMain/kotlin/com/lhwdev/model/ModelReader.kt
lhwdev
344,445,376
false
null
package com.lhwdev.model interface ModelReader { fun readByte(): Byte fun readShort(): Short fun readInt(): Int fun readLong(): Long fun readFloat(): Float fun readDouble(): Double fun readBoolean(): Boolean fun readChar(): Char fun readString(): String fun <T> readModel(info: ModelInfo<T>): T fun beginCompositeReader(info: ModelInfo<*>): ModelCompositeReader fun endCompositeReader(reader: ModelCompositeReader) } inline fun <R> ModelReader.readComposite(info: ModelInfo<*>, block: ModelCompositeReader.() -> R): R { val reader = beginCompositeReader(info) return try { reader.block() } finally { endCompositeReader(reader) } }
0
Kotlin
0
1
29a8ed2ff773b02d95b274dcc41d5eebb7932051
657
Model
MIT License
domain-model/src/main/kotlin/net/octosystems/foodversity/model/nutrition/Water.kt
schmitzCatz
640,629,294
false
null
package net.octosystems.foodversity.model.nutrition import net.octosystems.foodversity.model.units.volume.VolumeUnit data class Water(val unit: VolumeUnit) : Nutrient
0
Kotlin
0
0
08dc2ea082be38244c504d0c9988bbf8cfcac446
168
foodversity
Apache License 2.0
src/main/kotlin/net/cerulan/luminality/block/entity/ShimmerInducer.kt
CerulanLumina
229,501,289
false
{"Kotlin": 102598, "Java": 1712, "Shell": 151}
package net.cerulan.luminality.block.entity import alexiil.mc.lib.attributes.Simulation import net.cerulan.luminality.LuminalityBlocks import net.cerulan.luminality.inventory.InventoryWrapper import net.cerulan.luminality.inventory.ShimmerInducerItemInv import net.cerulan.luminality.recipe.LuminalityRecipeTypes import net.fabricmc.fabric.api.block.entity.BlockEntityClientSerializable import net.minecraft.block.entity.BlockEntity import net.minecraft.entity.player.PlayerEntity import net.minecraft.nbt.CompoundTag import net.minecraft.util.Hand import net.minecraft.util.Tickable class ShimmerInducer : BlockEntity(LuminalityBlocks.BlockEntities.shimmerInducerEntity), BlockEntityClientSerializable, Tickable { companion object { val RECIPE_TYPE = LuminalityRecipeTypes.shimmerInducer } val inventory = ShimmerInducerItemInv(this) val sidedInventory = InventoryWrapper.create(inventory) var outputting = false set(v) { field = v world?.updateNeighbors(pos, cachedState.block) } init { inventory.addListener( { view, slot, previous, current -> run { sync() if (!previous.isEmpty && current.isEmpty) { outputting = false } } }, { }) } fun interact(player: PlayerEntity) { if (!player.getStackInHand(Hand.MAIN_HAND).isEmpty) { if (inventory.getInvStack(0).isEmpty) { val stack = player.getStackInHand(Hand.MAIN_HAND).copy() stack.count = 1 if (inventory.setInvStack(0, stack, Simulation.ACTION)) { --player.getStackInHand(Hand.MAIN_HAND).count } } else { val ext = inventory.extract(1) if (!ext.isEmpty) { val drop = player.dropStack(ext) drop!!.setPickupDelay(0) } } } else if (!inventory.getInvStack(0).isEmpty) { val ext = inventory.extract(1) if (!ext.isEmpty) { val drop = player.dropStack(ext) drop!!.setPickupDelay(0) } } sync() } override fun fromTag(tag: CompoundTag) { super.fromTag(tag) inventory.fromTag(tag.getCompound("inventory")) } override fun toTag(tag: CompoundTag): CompoundTag { tag.put("inventory", inventory.toTag()) return super.toTag(tag) } override fun toClientTag(tag: CompoundTag): CompoundTag { tag.put("inventory", inventory.toTag()) return tag } override fun fromClientTag(tag: CompoundTag) { inventory.fromTag(tag.getCompound("inventory")) } var lastTime = 0L override fun tick() { if (world!!.isClient) return if (world!!.timeOfDay > 6000 && lastTime <= 6000) { val res = world!!.recipeManager.getFirstMatch(RECIPE_TYPE, sidedInventory, world) if (res.isPresent) { val recipe = res.get() outputting = true inventory.setInvStack(0, recipe.output, Simulation.ACTION) sync() } } lastTime = world!!.timeOfDay } }
4
Kotlin
0
0
87c90f10f83b673b2aadcd91104cf80d11c3be64
3,344
luminality-mod-mc
MIT License
scalabot-app/src/main/kotlin/AppConfigs.kt
LamGC
448,478,454
false
{"Kotlin": 182501, "Java": 13033, "Dockerfile": 176}
package net.lamgc.scalabot import ch.qos.logback.core.PropertyDefinerBase import com.google.gson.Gson import com.google.gson.GsonBuilder import com.google.gson.JsonArray import mu.KotlinLogging import net.lamgc.scalabot.config.* import net.lamgc.scalabot.config.serializer.* import org.eclipse.aether.artifact.Artifact import org.eclipse.aether.repository.Authentication import org.eclipse.aether.repository.Proxy import org.eclipse.aether.repository.RemoteRepository import org.eclipse.aether.repository.RepositoryPolicy import org.slf4j.event.Level import org.telegram.telegrambots.bots.DefaultBotOptions import java.io.File import java.net.URL import java.nio.charset.StandardCharsets import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicInteger import java.util.function.Supplier import kotlin.reflect.KProperty private val log = KotlinLogging.logger { } internal fun ProxyType.toTelegramBotsType(): DefaultBotOptions.ProxyType { return when (this) { ProxyType.NO_PROXY -> DefaultBotOptions.ProxyType.NO_PROXY ProxyType.HTTP -> DefaultBotOptions.ProxyType.HTTP ProxyType.HTTPS -> DefaultBotOptions.ProxyType.HTTP ProxyType.SOCKS4 -> DefaultBotOptions.ProxyType.SOCKS4 ProxyType.SOCKS5 -> DefaultBotOptions.ProxyType.SOCKS5 } } internal fun ProxyConfig.toAetherProxy(): Proxy? { val typeStr = when (type) { ProxyType.HTTP -> Proxy.TYPE_HTTP ProxyType.HTTPS -> Proxy.TYPE_HTTPS else -> return null } return Proxy(typeStr, host, port) } internal fun MavenRepositoryConfig.toRemoteRepository(proxyConfig: ProxyConfig? = null): RemoteRepository { val repositoryId = if (id == null) { val generatedRepoId = createDefaultRepositoryId() log.debug { "仓库 Url `$url` 未设置仓库 Id, 已分配缺省 Id: $generatedRepoId" } generatedRepoId } else if ("local".contentEquals(id, ignoreCase = true)) { val generatedRepoId = createDefaultRepositoryId() log.debug { "仓库 Url `$url` 不允许使用 `local` 作为仓库 Id, 已分配缺省 Id: $generatedRepoId" } generatedRepoId } else { id } val builder = RemoteRepository.Builder(repositoryId, checkRepositoryLayout(layout), url.toString()) if (proxy != null) { val selfProxy = proxy!! builder.setProxy(selfProxy) log.debug { "仓库 $repositoryId 已使用独立的代理配置: ${selfProxy.type}://${selfProxy.host}:${selfProxy.port}" } } else if (proxyConfig != null) { if (proxyConfig.type in (ProxyType.HTTP..ProxyType.HTTPS)) { builder.setProxy(proxyConfig.toAetherProxy()) log.debug { "仓库 $repositoryId 已使用 全局/Bot 代理配置: $proxyConfig" } } else { log.debug { "仓库 $repositoryId 不支持 全局/Bot 的代理配置: `$proxyConfig` (仅支持 HTTP 和 HTTPS)" } } } else { log.debug { "仓库 $repositoryId 不使用代理." } } builder.setReleasePolicy( RepositoryPolicy( enableReleases, RepositoryPolicy.UPDATE_POLICY_NEVER, RepositoryPolicy.CHECKSUM_POLICY_FAIL ) ) builder.setSnapshotPolicy( RepositoryPolicy( enableSnapshots, RepositoryPolicy.UPDATE_POLICY_ALWAYS, RepositoryPolicy.CHECKSUM_POLICY_WARN ) ) return builder.build() } private fun checkRepositoryLayout(layoutType: String): String { val type = layoutType.trim().lowercase() if (type != "default" && type != "legacy") { throw IllegalArgumentException("Invalid layout type (expecting 'default' or 'legacy')") } return type } private val repoNumberGenerator = AtomicInteger(1) private fun createDefaultRepositoryId(): String { return "Repository-${repoNumberGenerator.getAndIncrement()}" } /** * 需要用到的路径. * * 必须提供 `pathSupplier` 或 `fileSupplier` 其中一个, 才能正常提供路径. */ internal enum class AppPaths( private val pathSupplier: PathSupplier, private val initializer: AppPaths.() -> Unit = AppPaths::defaultInitializer, private val fileSupplier: FileSupplier, ) { /** * 数据根目录. * * 所有运行数据的存放位置. * * 提示: 结尾不带 `/`. */ DATA_ROOT(fileSupplier = FileSupplier { File( System.getProperty(PathConst.PROP_DATA_PATH) ?: System.getenv(PathConst.ENV_DATA_PATH) ?: System.getProperty("user.dir") ?: "." ) }, initializer = { val f = file if (!f.exists()) { f.mkdirs() } }), CONFIG_APPLICATION(PathSupplier { "$DATA_ROOT/config.json" }, { if (!file.exists()) { file.bufferedWriter(StandardCharsets.UTF_8).use { GsonConst.appConfigGson.toJson( AppConfig( mavenRepositories = listOf( MavenRepositoryConfig( id = "central", url = URL(MavenRepositoryExtensionFinder.MAVEN_CENTRAL_URL) ) ) ), it ) } } }), CONFIG_BOT(PathSupplier { "$DATA_ROOT/bot.json" }, { if (!file.exists()) { file.bufferedWriter(StandardCharsets.UTF_8).use { GsonConst.botConfigGson.toJson( setOf( BotConfig( enabled = true, proxy = ProxyConfig(), account = BotAccount( "Bot Username", "Bot API Token", -1 ), extensions = emptySet() ) ), it ) } } }), DATA_DB({ "$DATA_ROOT/data/db/" }), DATA_LOGS({ "$DATA_ROOT/data/logs/" }), EXTENSIONS({ "$DATA_ROOT/extensions/" }), DATA_EXTENSIONS({ "$DATA_ROOT/data/extensions/" }), TEMP({ "$DATA_ROOT/tmp/" }) ; constructor(pathSupplier: PathSupplier, initializer: AppPaths.() -> Unit = AppPaths::defaultInitializer) : this( fileSupplier = FileSupplier { File(pathSupplier.path).canonicalFile }, pathSupplier = pathSupplier, initializer = initializer ) constructor(fileSupplier: FileSupplier, initializer: AppPaths.() -> Unit = AppPaths::defaultInitializer) : this( fileSupplier = fileSupplier, pathSupplier = PathSupplier { fileSupplier.file.canonicalPath }, initializer = initializer ) constructor(pathSupplier: () -> String) : this( fileSupplier = FileSupplier { File(pathSupplier.invoke()).canonicalFile }, pathSupplier = PathSupplier { pathSupplier.invoke() } ) val file: File by fileSupplier val path: String by pathSupplier private val initialized = AtomicBoolean(false) @Synchronized fun initial() { if (!initialized.get()) { initializer() initialized.set(true) } } /** * 一个内部方法, 用于将 [initialized] 状态重置. * * 如果不重置该状态, 将使得单元测试无法让 AppPath 重新初始化文件. * * 警告: 该方法不应该被非测试代码调用. */ @Suppress("unused") private fun reset() { log.warn { "初始化状态已重置: `${this.name}`, 如果在非测试环境中重置状态, 请报告该问题." } initialized.set(false) } override fun toString(): String { return path } object PathConst { const val PROP_DATA_PATH = "bot.path.data" const val ENV_DATA_PATH = "BOT_DATA_PATH" } private class FileSupplier(private val supplier: Supplier<File>) { operator fun getValue(appPaths: AppPaths, property: KProperty<*>): File = supplier.get() val file: File get() = supplier.get() } private class PathSupplier(private val supplier: Supplier<String>) { operator fun getValue(appPaths: AppPaths, property: KProperty<*>): String = supplier.get() val path: String get() = supplier.get() } } /** * 为 LogBack 提供日志目录路径. */ internal class LogDirectorySupplier : PropertyDefinerBase() { override fun getPropertyValue(): String { return AppPaths.DATA_LOGS.path } } internal class LogLevelSupplier : PropertyDefinerBase() { override fun getPropertyValue(): String { val property = System.getProperty("scalabot.log.level", System.getenv("BOT_LOG_LEVEL")) val level = if (property != null) { try { Level.valueOf(property.uppercase()) } catch (e: IllegalArgumentException) { addWarn("Invalid log level: `$property`, the log will be output using the Info log level.") Level.INFO } } else { Level.INFO } return level.name } } internal class NetworkVerboseLogSupplier : PropertyDefinerBase() { override fun getPropertyValue(): String { val propertyValue = System.getProperty("scalabot.log.network.verbose", "false") return if (propertyValue.toBoolean()) { "DEBUG" } else { "INFO" } } } internal object Const { val config = loadAppConfig() const val METRICS_NAMESPACE = "scalabot" } private fun AppPaths.defaultInitializer() { val f = file val p = path if (!f.exists()) { val result = if (p.endsWith("/")) { f.mkdirs() } else { f.createNewFile() } if (!result) { log.warn { "初始化文件(夹)失败: $p" } } } } /** * 执行 AppPaths 所有项目的初始化, 并检查是否停止运行, 让用户编辑配置. * * @return 如果需要让用户编辑配置, 则返回 `true`. */ internal fun initialFiles(): Boolean { val configFilesNotInitialized = !AppPaths.CONFIG_APPLICATION.file.exists() && !AppPaths.CONFIG_BOT.file.exists() for (path in AppPaths.values()) { path.initial() } if (configFilesNotInitialized) { log.warn { "配置文件已初始化, 请根据需要修改配置文件后重新启动本程序." } return true } return false } internal object GsonConst { private val baseGson: Gson = GsonBuilder() .setPrettyPrinting() .serializeNulls() .create() val appConfigGson: Gson = baseGson.newBuilder() .registerTypeAdapter(ProxyType::class.java, ProxyTypeSerializer) .registerTypeAdapter(MavenRepositoryConfig::class.java, MavenRepositoryConfigSerializer) .registerTypeAdapter(Authentication::class.java, AuthenticationSerializer) .registerTypeAdapter(UsernameAuthenticator::class.java, UsernameAuthenticatorSerializer) .create() val botConfigGson: Gson = baseGson.newBuilder() .registerTypeAdapter(ProxyType::class.java, ProxyTypeSerializer) .registerTypeAdapter(BotConfig::class.java, BotConfigSerializer) .registerTypeAdapter(Artifact::class.java, ArtifactSerializer) .registerTypeAdapter(BotAccount::class.java, BotAccountSerializer) .create() } internal fun loadAppConfig(configFile: File = AppPaths.CONFIG_APPLICATION.file): AppConfig { try { configFile.bufferedReader(StandardCharsets.UTF_8).use { return GsonConst.appConfigGson.fromJson(it, AppConfig::class.java)!! } } catch (e: Exception) { log.error { "读取 config.json 时发生错误, 请检查配置格式是否正确." } throw e } } internal fun loadBotConfigJson(botConfigFile: File = AppPaths.CONFIG_BOT.file): JsonArray? { try { botConfigFile.bufferedReader(StandardCharsets.UTF_8).use { return GsonConst.botConfigGson.fromJson(it, JsonArray::class.java)!! } } catch (e: Exception) { log.error(e) { "读取 Bot 配置文件 (bot.json) 时发生错误, 请检查配置格式是否正确." } return null } }
11
Kotlin
1
4
ddc4de1340cc86b7256009997f6c65d187817d83
12,335
ScalaBot
MIT License
src/main/kotlin/quickr/stravaimporter/internal/auth/Token.kt
wvanvlaenderen
185,858,482
false
null
package quickr.stravaimporter.internal.auth import com.google.gson.annotations.SerializedName data class Token( @SerializedName("access_token") val accessToken: String )
0
Kotlin
0
0
ffae7b1915717354c99ae9b79515c199215cb182
181
strava-importer
MIT License
warehouseservice/settings.gradle.kts
franckies
367,363,459
false
null
rootProject.name = "warehouseservice" bootJar.enabled = true jar.enabled = true
0
Kotlin
0
0
884650f45ba385ee98ee0d0fa685404865169e74
79
ecommerce-api
Apache License 2.0
data/slack-jackson-dto/src/main/kotlin/com/kreait/slack/api/contract/jackson/group/channels/Create.kt
wudmer
214,514,160
true
{"Kotlin": 1205090, "Shell": 935}
package com.kreait.slack.api.contract.jackson.group.channels import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.annotation.JsonSubTypes import com.fasterxml.jackson.annotation.JsonTypeInfo import com.kreait.slack.api.contract.jackson.common.types.Channel import com.kreait.slack.api.contract.jackson.util.JacksonDataClass @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "ok", visible = true) @JsonSubTypes( JsonSubTypes.Type(value = SuccessfulChannelsCreateResponse::class, name = "true"), JsonSubTypes.Type(value = ErrorChannelsCreateResponse::class, name = "false") ) @JacksonDataClass sealed class ChannelsCreateResponse constructor(@JsonProperty("ok") open val ok: Boolean) /** * Success-response of this request. * * @property ok will be true * @property channel the channel object that was created */ @JacksonDataClass data class SuccessfulChannelsCreateResponse constructor(override val ok: Boolean, @JsonProperty("channel") val channel: Channel) : ChannelsCreateResponse(ok) { companion object } /** * Failure-response of this request * * @property ok will be false * @property error contains the error description */ @JacksonDataClass data class ErrorChannelsCreateResponse constructor(override val ok: Boolean, @JsonProperty("error") val error: String, @JsonProperty("detail") val detail: String) : ChannelsCreateResponse(ok) { companion object } /** * Creates a channel. * * @property name the name of the channel you want to create * @property validate Whether to return errors on invalid channel name instead of modifying it to meet the specified criteria. * @see [Slack Api Method](https://api.slack.com/methods/channels.create) */ @JacksonDataClass data class ChannelsCreateRequest constructor(@JsonProperty("name") val name: String, @JsonProperty("validate") val validate: Boolean?) { companion object }
0
Kotlin
0
0
a46b9fcf8317d576133a4b1b4e64b89f6b3b1ca2
2,180
slack-spring-boot-starter
MIT License
app/src/main/kotlin/net/ketc/numeri/util/twitter/TwitterApp.kt
KetcKtsD
75,272,615
false
null
package net.ketc.numeri.util.twitter import android.content.Context import net.ketc.numeri.R interface TwitterApp { val apiSecret: String val apiKey: String val callbackUrl: String } class TwitterAppImpl(applicationContext: Context) : TwitterApp { override val apiSecret: String = applicationContext.getString(R.string.twitter_secret_key) override val apiKey: String = applicationContext.getString(R.string.twitter_api_key) override val callbackUrl: String init { val scheme = applicationContext.getString(R.string.twitter_callback_scheme) val host = applicationContext.getString(R.string.twitter_callback_host) callbackUrl = "$scheme://$host" } }
0
Kotlin
0
0
ea3b007ab7875ea6d1bc1c5c1cec871eee2685a5
708
numeri3
MIT License
judokit-android/src/main/java/com/judopay/judokit/android/ui/cardentry/model/FormModel.kt
Judopay
261,378,339
false
{"Kotlin": 924736}
package com.judopay.judokit.android.ui.cardentry.model data class FormModel( val cardDetailsInputModel: CardDetailsInputModel, val billingDetailsInputModel: BillingDetailsInputModel ) fun CardDetailsInputModel.valueOfFieldWithType(type: CardDetailsFieldType): String = when (type) { CardDetailsFieldType.NUMBER -> cardNumber CardDetailsFieldType.HOLDER_NAME -> cardHolderName CardDetailsFieldType.EXPIRATION_DATE -> expirationDate CardDetailsFieldType.SECURITY_NUMBER -> securityNumber CardDetailsFieldType.COUNTRY -> country CardDetailsFieldType.POST_CODE -> postCode } fun BillingDetailsInputModel.valueOfBillingDetailsFieldWithType(type: BillingDetailsFieldType): String = when (type) { BillingDetailsFieldType.COUNTRY -> countryCode BillingDetailsFieldType.STATE -> state BillingDetailsFieldType.POST_CODE -> postalCode BillingDetailsFieldType.EMAIL -> email BillingDetailsFieldType.PHONE_COUNTRY_CODE -> phoneCountryCode BillingDetailsFieldType.MOBILE_NUMBER -> mobileNumber BillingDetailsFieldType.ADDRESS_LINE_1 -> addressLine1 BillingDetailsFieldType.ADDRESS_LINE_2 -> addressLine2 BillingDetailsFieldType.ADDRESS_LINE_3 -> addressLine3 BillingDetailsFieldType.CITY -> city }
2
Kotlin
6
4
9255f02d876e1a19f750d13ff4ce4578c1bbf69d
1,307
JudoKit-Android
MIT License
src/maia/util/persist/error/NotAPersistenceError.kt
waikato-maia
387,324,750
false
{"Kotlin": 249102}
package maia.util.persist.error import maia.util.persist.Persists import kotlin.reflect.KClass /** * Error for when a class that is not set up to be a persistence is used in a persisting context. * * @param cls * The class that is not a persistence. * * @author <NAME> (csterlin at waikato dot ac dot nz) */ class NotAPersistenceError( cls: KClass<*> ): PersistError( "${cls.qualifiedName} is not a persistence. To make a class a persistence, implement ${Persists::class.qualifiedName} " + "on ${cls.qualifiedName}'s companion object" )
0
Kotlin
0
0
b8ca03697de549dad17dbd7c3860d44247e2e973
583
maia-util
Apache License 2.0
MapboxSearch/sdk/src/main/java/com/mapbox/search/utils/loader/InternalDataLoader.kt
mapbox
438,355,708
false
{"Kotlin": 1983845, "Java": 42091, "Python": 18979, "Shell": 16647}
package com.mapbox.search.utils.loader import android.content.Context import androidx.annotation.WorkerThread import com.mapbox.search.utils.file.FileSystem @WorkerThread internal class InternalDataLoader( private val context: Context, private val fileHelper: FileSystem ) : DataLoader<ByteArray> { override fun load(relativeDir: String, fileName: String): ByteArray { val dir = fileHelper.getAppRelativeDir(context, relativeDir) val file = fileHelper.createFile(dir, fileName) return if (!file.exists()) { ByteArray(0) } else { file.readBytes() } } override fun save(relativeDir: String, fileName: String, data: ByteArray) { val dir = fileHelper.getAppRelativeDir(context, relativeDir) val file = fileHelper.createFile(dir, fileName) file.writeBytes(data) } }
15
Kotlin
9
22
e79156c404231c78699a2f7cfc182e3c148bfc06
877
mapbox-search-android
Apache License 2.0
app/src/main/java/com/lateinit/rightweight/data/mapper/local/ToHistory.kt
boostcampwm-2022
563,132,819
false
{"Kotlin": 320392}
package com.lateinit.rightweight.data.mapper import com.lateinit.rightweight.data.database.entity.History import com.lateinit.rightweight.data.database.entity.HistoryExercise import com.lateinit.rightweight.data.database.entity.HistorySet import com.lateinit.rightweight.data.model.local.ExercisePartType import com.lateinit.rightweight.data.remote.model.HistoryExerciseField import com.lateinit.rightweight.data.remote.model.HistoryExerciseSetField import com.lateinit.rightweight.data.remote.model.HistoryField import com.lateinit.rightweight.ui.model.history.HistoryExerciseSetUiModel import com.lateinit.rightweight.ui.model.history.HistoryExerciseUiModel import com.lateinit.rightweight.ui.model.history.HistoryUiModel import com.lateinit.rightweight.util.DEFAULT_SET_COUNT import com.lateinit.rightweight.util.DEFAULT_SET_WEIGHT import java.time.LocalDate import java.time.format.DateTimeFormatter fun HistoryUiModel.toHistory(): History { return History( historyId = historyId, date = date, time = time, routineTitle = routineTitle, dayOrder = order, completed = completed ) } fun HistoryExerciseUiModel.toHistoryExercise(): HistoryExercise { return HistoryExercise( exerciseId = exerciseId, historyId = historyId, title = title, order = order, part = part.toExercisePartType() ) } fun HistoryExerciseSetUiModel.toHistorySet(): HistorySet { return HistorySet( setId = setId, exerciseId = exerciseId, weight = weight.ifEmpty { DEFAULT_SET_WEIGHT }, count = count.ifEmpty { DEFAULT_SET_COUNT }, order = order, checked = checked ) } fun HistoryField.toHistory(historyId: String): History { val refinedDateString = date.value val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'") val date = LocalDate.parse(refinedDateString, formatter) return History( historyId = historyId, date = date, time = time.value, routineTitle = routineTitle.value, dayOrder = order.value.toInt(), completed = true ) } fun HistoryExerciseField.toHistoryExercise(exerciseId: String): HistoryExercise { return HistoryExercise( exerciseId = exerciseId, historyId = historyId.value, title = title.value, order = order.value.toInt(), part = ExercisePartType.valueOf(part.value) ) } fun HistoryExerciseSetField.toHistorySet(exerciseSetId: String): HistorySet { return HistorySet( setId = exerciseSetId, exerciseId = exerciseId.value, weight = weight.value, count = count.value, order = order.value.toInt(), checked = true ) }
6
Kotlin
0
27
ff6116ee9e49bd8ed493d3c6928d0b9a7f892689
2,757
android09-RightWeight
MIT License
library/src/main/java/com/icetea09/vivid/camera/OnImageReadyListener.kt
trinhlbk1991
82,260,600
false
null
package com.icetea09.vivid.camera import com.icetea09.vivid.model.Image interface OnImageReadyListener { fun onImageReady(image: List<Image>) }
0
Kotlin
1
1
4739754767551d3914c3b570981b6503ff18f73e
150
vivid
MIT License
src/test/kotlin/tests/PerDirectoryTest.kt
jdmota
244,648,226
false
{"Kotlin": 259184, "Java": 231389, "ANTLR": 3114}
package tests import jatyc.JavaTypestateChecker import org.checkerframework.framework.test.CheckerFrameworkPerDirectoryTest import org.checkerframework.framework.test.TestConfigurationBuilder import org.checkerframework.framework.test.TestUtilities import org.junit.Test import java.io.File import java.util.* abstract class PerDirectoryTest(val originalTestDir: String, testFiles: List<File>, opts: Array<String>) : CheckerFrameworkPerDirectoryTest( testFiles, JavaTypestateChecker::class.java, originalTestDir, *opts ) { @Test override fun run() { if (only.isNotEmpty() && !only.contains(originalTestDir)) { return } if (ignore.contains(originalTestDir)) { return } val shouldEmitDebugInfo = TestUtilities.getShouldEmitDebugInfo() val customizedOptions = customizeOptions(Collections.unmodifiableList(checkerOptions)) val config = TestConfigurationBuilder.buildDefaultConfiguration( testDir, testFiles, listOf(JavaTypestateChecker::class.java.canonicalName), customizedOptions, shouldEmitDebugInfo) val testResult = OurTypecheckExecutor(testDir, testFiles).runTest(config) TestUtilities.assertTestDidNotFail(testResult) } }
0
Kotlin
3
13
e5706cf870b698ae92b264ca1a52153f8c922f3d
1,220
java-typestate-checker
MIT License
src/test/kotlin/Day24Test.kt
jcornaz
573,137,552
false
{"Kotlin": 76776}
import io.kotest.core.spec.style.FunSpec import org.amshove.kluent.shouldBeEqualTo private val EXAMPLE = """ """.trimIndent() private val INPUT = Day24Test::class.java.getResource("/day24_input.txt")?.readText().orEmpty().trim() class Day24Test : FunSpec({ context("part 1") { // TODO Set the expected value and enable the test by removing the 'x' prefix xtest("should return expected output for the example") { Day24.part1(EXAMPLE) shouldBeEqualTo 0 } // TODO Set the expected value and enable the test by removing the 'x' prefix xtest("should return expected output for the puzzle input") { Day24.part1(INPUT) shouldBeEqualTo 0 } listOf<Pair<String, Long>>( // TODO Add more test cases here ).forEach { (input, expectedOutput) -> test("part1(\"${input}\") = $expectedOutput") { Day24.part1(input) shouldBeEqualTo expectedOutput } } } context("part 2") { // TODO Set the expected value and enable the test by removing the 'x' prefix xtest("should return expected output for the example") { Day24.part2(EXAMPLE) shouldBeEqualTo 0 } // TODO Set the expected value and enable the test by removing the 'x' prefix xtest("should return expected output for the puzzle input") { Day24.part2(INPUT) shouldBeEqualTo 0 } listOf<Pair<String, Long>>( // TODO Add more test cases here ).forEach { (input, expectedOutput) -> test("part2(\"${input}\") = $expectedOutput") { Day24.part2(input) shouldBeEqualTo expectedOutput } } } })
1
Kotlin
0
0
979c00c4a51567b341d6936761bd43c39d314510
1,738
aoc-kotlin-2022
The Unlicense
src/test/kotlin/co/mercenary/creators/kotlin/minio/test/main/BucketsTest.kt
mercenary-creators
224,226,723
false
null
/* * Copyright (c) 2019, Mercenary Creators Company. 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 co.mercenary.creators.kotlin.minio.test.main import co.mercenary.creators.kotlin.minio.* import org.junit.jupiter.api.Test class BucketsTest : KotlinTest(MAIN_TEST_PROPERTIES) { @Test fun test() { minio.buckets().forEachIndexed { many, each -> info { "%2d : %s".format(many + 1, each.toJSONString(false)) } } when (val root = minio.bucketOf("root")) { null -> warn { root } else -> info { root } } when (val root = minio.bucketOf("oops")) { null -> warn { root } else -> info { root } } } }
0
Kotlin
0
1
b786ced3cc52f2bb996130c417d676a79f3ea7cd
1,258
mercenary-creators-kotlin-minio
Apache License 2.0
src/test/kotlin/com/terraformation/backend/seedbank/db/accessionStore/AccessionStoreLocationTest.kt
terraware
323,722,525
false
{"Kotlin": 3707833, "HTML": 88820, "Python": 46278, "FreeMarker": 16407, "PLpgSQL": 3305, "Makefile": 746, "Dockerfile": 674}
package com.terraformation.backend.seedbank.db.accessionStore import com.terraformation.backend.db.default_schema.SubLocationId import com.terraformation.backend.db.seedbank.AccessionId import com.terraformation.backend.db.seedbank.GeolocationId import com.terraformation.backend.seedbank.model.Geolocation import java.math.BigDecimal import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows internal class AccessionStoreLocationTest : AccessionStoreTest() { @Test fun `geolocations are inserted and deleted as needed`() { val initial = store.create( accessionModel( geolocations = setOf( Geolocation(BigDecimal(1), BigDecimal(2), BigDecimal(100)), Geolocation(BigDecimal(3), BigDecimal(4))))) val initialGeos = geolocationsDao.fetchByAccessionId(AccessionId(1)) // Insertion order is not defined by the API. assertEquals( setOf(GeolocationId(1), GeolocationId(2)), initialGeos.map { it.id }.toSet(), "Initial location IDs") assertEquals(100.0, initialGeos.firstNotNullOf { it.gpsAccuracy }, 0.1, "Accuracy is recorded") val desired = initial.copy( geolocations = setOf( Geolocation(BigDecimal(1), BigDecimal(2), BigDecimal(100)), Geolocation(BigDecimal(5), BigDecimal(6)))) store.update(desired) val updatedGeos = geolocationsDao.fetchByAccessionId(AccessionId(1)) assertTrue( updatedGeos.any { it.id == GeolocationId(3) && it.latitude?.toInt() == 5 && it.longitude?.toInt() == 6 }, "New geo inserted") assertTrue(updatedGeos.none { it.latitude == BigDecimal(3) }, "Missing geo deleted") assertEquals( initialGeos.filter { it.latitude == BigDecimal(1) }, updatedGeos.filter { it.latitude == BigDecimal(1) }, "Existing geo retained") } @Test fun `valid sub-locations are accepted`() { val locationId = SubLocationId(12345678) val locationName = "<NAME>" insertSubLocation(locationId, name = locationName) val initial = store.create(accessionModel()) store.update(initial.copy(subLocation = locationName)) assertEquals( locationId, accessionsDao.fetchOneById(AccessionId(1))?.subLocationId, "Existing sub-location ID was used") val updated = store.fetchOneById(initial.id!!) assertEquals(locationName, updated.subLocation, "Location name") } @Test fun `unknown sub-locations are rejected`() { assertThrows<IllegalArgumentException> { val initial = store.create(accessionModel()) store.update(initial.copy(subLocation = "bogus")) } } }
9
Kotlin
1
9
ab6fbb71381d0eda0684e9d06aa68004d9718b05
2,877
terraware-server
Apache License 2.0
core-ui/src/test/java/com/anytypeio/anytype/core_ui/features/page/BlockViewTest.kt
anyproto
647,371,233
false
{"Kotlin": 9971954, "Java": 69306, "Shell": 11126, "Makefile": 1276}
package com.anytypeio.anytype.core_ui.features.page import com.anytypeio.anytype.presentation.editor.editor.model.BlockView import com.anytypeio.anytype.presentation.editor.editor.model.types.Types.HOLDER_VIDEO import com.anytypeio.anytype.presentation.editor.editor.model.types.Types.HOLDER_VIDEO_ERROR import com.anytypeio.anytype.presentation.editor.editor.model.types.Types.HOLDER_VIDEO_PLACEHOLDER import com.anytypeio.anytype.presentation.editor.editor.model.types.Types.HOLDER_VIDEO_UPLOAD import com.anytypeio.anytype.test_utils.MockDataFactory import org.junit.Assert.assertEquals import org.junit.Test class BlockViewTest { @Test fun `should return video block with view type Empty`() { val block = BlockView.MediaPlaceholder.Video( id = MockDataFactory.randomUuid(), indent = MockDataFactory.randomInt(), isPreviousBlockMedia = false ) assertEquals(HOLDER_VIDEO_PLACEHOLDER, block.getViewType()) } @Test fun `should return video block with view type Error`() { val block = BlockView.Error.Video( id = MockDataFactory.randomUuid(), indent = MockDataFactory.randomInt() ) assertEquals(HOLDER_VIDEO_ERROR, block.getViewType()) } @Test fun `should return video block with view type Done`() { val block = BlockView.Media.Video( id = MockDataFactory.randomUuid(), targetObjectId = MockDataFactory.randomString(), url = MockDataFactory.randomString(), size = MockDataFactory.randomLong(), mime = MockDataFactory.randomString(), name = MockDataFactory.randomString(), indent = MockDataFactory.randomInt(), decorations = emptyList() ) assertEquals(HOLDER_VIDEO, block.getViewType()) } @Test fun `should return video block with view type Uploading`() { val block = BlockView.Upload.Video( id = MockDataFactory.randomString(), indent = MockDataFactory.randomInt() ) assertEquals(HOLDER_VIDEO_UPLOAD, block.getViewType()) } }
33
Kotlin
26
301
8b3b7dacae68c015fb8b1b7c9cc76e53f0706430
2,154
anytype-kotlin
RSA Message-Digest License
mobius-migration/src/main/java/org/simple/mobius/migration/ConsoleLogger.kt
simpledotorg
132,515,649
false
{"Kotlin": 5970450, "Shell": 1660, "HTML": 545}
package org.simple.mobius.migration import com.spotify.mobius.First import com.spotify.mobius.MobiusLoop import com.spotify.mobius.Next class ConsoleLogger<M, E, F> : MobiusLoop.Logger<M, E, F> { override fun beforeInit(model: M) { println("beforeInit: $model") } override fun afterInit(model: M, result: First<M, F>) { println("afterInit: $model, $result") } override fun beforeUpdate(model: M, event: E) { println("beforeUpdate: $model, $event") } override fun afterUpdate(model: M, event: E, result: Next<M, F>) { println("afterUpdate: $model, $event $result") } override fun exceptionDuringInit(model: M, exception: Throwable) { println("exceptionDuringInit: $model, $exception") } override fun exceptionDuringUpdate(model: M, event: E, exception: Throwable) { println("exceptionDuringUpdate: $model, $event, $exception") } }
4
Kotlin
73
223
58d14c702db2b27b9dc6c1298c337225f854be6d
885
simple-android
MIT License
src/main/kotlin/com/chromaticnoise/multiplatformswiftpackage/domain/extensions.kt
ge-org
303,140,022
false
{"Kotlin": 53566}
package com.chromaticnoise.multiplatformswiftpackage.domain import org.jetbrains.kotlin.konan.target.Family import org.jetbrains.kotlin.konan.target.KonanTarget internal val Family.swiftPackagePlatformName get() = when (this) { Family.OSX -> "macOS" Family.IOS -> "iOS" Family.TVOS -> "tvOS" Family.WATCHOS -> "watchOS" else -> null } internal val Collection<Either<List<PluginConfiguration.PluginConfigurationError>, TargetPlatform>>.platforms get() = filterIsInstance<Either.Right<List<PluginConfiguration.PluginConfigurationError>, TargetPlatform>>().map { it.value } internal val Collection<Either<List<PluginConfiguration.PluginConfigurationError>, TargetPlatform>>.errors get() = filterIsInstance<Either.Left<List<PluginConfiguration.PluginConfigurationError>, TargetPlatform>>().map { it.value }.flatten() internal val TargetName.konanTarget: KonanTarget get() = when (this) { TargetName.IOSarm64 -> KonanTarget.IOS_ARM64 TargetName.IOSx64 -> KonanTarget.IOS_X64 TargetName.WatchOSarm32 -> KonanTarget.WATCHOS_ARM32 TargetName.WatchOSarm64 -> KonanTarget.WATCHOS_ARM64 TargetName.WatchOSx86 -> KonanTarget.WATCHOS_X86 TargetName.WatchOSx64 -> KonanTarget.WATCHOS_X64 TargetName.TvOSarm64 -> KonanTarget.TVOS_ARM64 TargetName.TvOSx64 -> KonanTarget.TVOS_X64 TargetName.MacOSx64 -> KonanTarget.MACOS_X64 }
21
Kotlin
40
293
8d7c25ecc19841d4af515db885ae3426f7f32274
1,380
multiplatform-swiftpackage
Apache License 2.0
px-checkout/src/test/java/com/mercadopago/android/px/internal/util/TokenCreationWrapperTest.kt
mercadopago
49,529,486
false
null
package com.mercadopago.android.px.internal.util import com.mercadopago.android.px.addons.ESCManagerBehaviour import com.mercadopago.android.px.internal.repository.CardTokenRepository import com.mercadopago.android.px.model.Card import com.mercadopago.android.px.model.PaymentMethod import com.mercadopago.android.px.model.exceptions.CardTokenException import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test import org.mockito.Mock import org.mockito.MockitoAnnotations class TokenCreationWrapperTest { private lateinit var tokenCreationWrapper: TokenCreationWrapper @Mock private lateinit var cardTokenRepository: CardTokenRepository @Mock private lateinit var escManagerBehaviour: ESCManagerBehaviour @Mock private lateinit var card: Card @Mock private lateinit var paymentMethod: PaymentMethod @Before fun setUp() { MockitoAnnotations.initMocks(this) tokenCreationWrapper = TokenCreationWrapper.Builder(cardTokenRepository, escManagerBehaviour) .with(card) .with(paymentMethod).build() } @Test fun whenCVVisValidWithoutTokenThenPassesValidation() { assertTrue(tokenCreationWrapper.validateCVVFromToken("123")) } @Test(expected = CardTokenException::class) fun whenCVVisInvalidWithoutTokenThenFailsValidation() { tokenCreationWrapper.validateCVVFromToken("12345") } }
44
Java
77
98
b715075dd4cf865f30f6448f3c00d6e9033a1c21
1,414
px-android
MIT License
MatrixLib/src/main/java/com/comseung/matrixlib/MatrixExt.kt
comseung18
612,627,693
false
null
package com.comseung.matrixlib import kotlin.math.min fun zeros(rows: Int, cols: Int) = Matrix(rows, cols) fun zeros(n : Int) = zeros(n, n) fun ones(rows: Int, cols: Int) : Matrix { val ret = Matrix(rows, cols) for(r in 0 until rows) ret[r] = DoubleArray(cols) { 1.0 } return ret } fun ones(n: Int) = ones(n, n) fun identify(rows: Int, cols: Int) : Matrix { val ret = Matrix(rows, cols) for(i in 0 until rows) ret[i][i] = 1.0 return ret } fun identify(n: Int) = identify(n, n) fun Matrix.setCols(newCols : Int) : Matrix { val ret = Matrix(rows, newCols) for(r in 0 until rows) { ret[r] = DoubleArray(newCols) { if(it < cols) this[r][it] else 0.0 } } return ret } fun Matrix.setRows(newRows : Int) : Matrix { val ret = Matrix(newRows, cols) for(r in 0 until min(newRows, rows)) { ret[r] = this[r].copyOf() } return ret } operator fun Matrix.plus(matrix: Matrix): Matrix { if(matrix.rows != rows || matrix.cols != cols) throw IllegalArgumentException() val ret = Matrix(matrix.rows, matrix.cols) for(r in 0 until rows) for(c in 0 until cols) ret[r][c] = matrix[r][c] + this[r][c] return ret } operator fun Matrix.minus(matrix: Matrix): Matrix { if(matrix.rows != rows || matrix.cols != cols) throw IllegalArgumentException() val ret = Matrix(matrix.rows, matrix.cols) for(r in 0 until rows) for(c in 0 until cols) ret[r][c] = this[r][c] - matrix[r][c] return ret }
0
Kotlin
0
0
3e1af5ca45325d102e268dc6c5d575584b9279a9
1,569
MatrixExpert
Apache License 2.0
ShoeStore/app/src/main/java/github/informramiz/shoestore/view/home/MainActivity.kt
informramiz
254,038,239
false
null
package github.informramiz.shoestore.view.home import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.databinding.DataBindingUtil import androidx.navigation.findNavController import androidx.navigation.ui.setupActionBarWithNavController import github.informramiz.shoestore.R import github.informramiz.shoestore.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private val viewBinding: ActivityMainBinding by lazy { DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(viewBinding.root) setupActionBarWithNavController(findNavController(R.id.nav_host_fragment)) } override fun onSupportNavigateUp(): Boolean { return findNavController(R.id.nav_host_fragment).navigateUp() } }
0
Kotlin
0
0
e062f08e46f1aea4acd9f4090a70b870f51900f3
937
shoe-store
MIT License
app/src/main/java/com/example/recipeapp/ui/RecipeViewModel.kt
tej1562
379,551,379
false
null
package com.example.recipeapp.ui import android.app.Application import android.content.Context import android.net.ConnectivityManager import android.net.ConnectivityManager.* import android.net.NetworkCapabilities.* import android.os.Build import android.util.Log import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import com.example.recipeapp.RecipeApplication import com.example.recipeapp.model.RecipeResponse import com.example.recipeapp.model.SearchRecipeResponse import com.example.recipeapp.repository.RecipeRepository import com.example.recipeapp.util.Resource import kotlinx.coroutines.launch import retrofit2.Response import java.io.IOException class RecipeViewModel( app: Application, val repository: RecipeRepository ): AndroidViewModel(app) { val newRecipes: MutableLiveData<Resource<RecipeResponse>> = MutableLiveData() val numberNewRecipes = 20 val searchRecipes: MutableLiveData<Resource<SearchRecipeResponse>> = MutableLiveData() val numberSearchRecipes = 20 init { getNewRecipes() } fun getNewRecipes() = viewModelScope.launch{ safeNewRecipeCall() } fun searchForRecipes(query: String) = viewModelScope.launch{ safeSearchRecipeCall(query) } private suspend fun safeNewRecipeCall(){ newRecipes.postValue(Resource.Loading()) try { if (hasInternetConnection()) { val response = repository.getRecipes(numberNewRecipes) newRecipes.postValue(handleNewRecipeResponse(response)) } else { newRecipes.postValue(Resource.Error("No Internet Connection")) } } catch (t: Throwable){ when(t){ is IOException -> newRecipes.postValue(Resource.Error("Network Failure")) else -> newRecipes.postValue(Resource.Error("Response Conversion Error")) } } } private suspend fun safeSearchRecipeCall(query: String){ searchRecipes.postValue(Resource.Loading()) try { if (hasInternetConnection()) { val response = repository.searchRecipes(numberSearchRecipes,query) searchRecipes.postValue(handleSearchRecipeResponse(response)) } else { searchRecipes.postValue(Resource.Error("No Internet Connection")) } } catch (t: Throwable){ when(t){ is IOException -> searchRecipes.postValue(Resource.Error("Network Failure")) else -> searchRecipes.postValue(Resource.Error("Response Conversion Error")) } } } private fun handleNewRecipeResponse(response: Response<RecipeResponse>): Resource<RecipeResponse>{ if(response.isSuccessful) { response.body()?.let {resultResponse -> return Resource.Success(resultResponse) } } return Resource.Error(response.message(),response.body()) } private fun handleSearchRecipeResponse(response: Response<SearchRecipeResponse>): Resource<SearchRecipeResponse>{ if(response.isSuccessful) { response.body()?.let {resultResponse -> return Resource.Success(resultResponse) } } return Resource.Error(response.message(),response.body()) } fun hasInternetConnection(): Boolean{ val connectivityManager = getApplication<RecipeApplication>().getSystemService( Context.CONNECTIVITY_SERVICE ) as ConnectivityManager if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){ val activeNetwork = connectivityManager.activeNetwork ?: return false val capabilities = connectivityManager.getNetworkCapabilities(activeNetwork) ?: return false return when{ capabilities.hasTransport(TRANSPORT_WIFI) -> true capabilities.hasTransport(TRANSPORT_CELLULAR) -> true capabilities.hasTransport(TRANSPORT_ETHERNET) -> true else -> false } } else{ connectivityManager.activeNetworkInfo?.run{ return when(type){ TYPE_WIFI -> true TYPE_MOBILE -> true TYPE_ETHERNET -> true else -> false } } } return false } }
0
Kotlin
0
0
5dec0fba8da622b2ef206de5e8e9d85099a8cc94
4,487
RecipeApp
Apache License 2.0
OgrenciNot/app/src/main/java/com/mehmetcanmut/ogrencinot/view/RegisterActivity.kt
MehmetCan2121
474,529,184
false
{"Kotlin": 18624}
package com.mehmetcanmut.ogrencinot.view import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Toast import com.google.firebase.auth.FirebaseAuth import com.mehmetcanmut.ogrencinot.databinding.ActivityRegisterBinding class RegisterActivity : AppCompatActivity() { private lateinit var binding: ActivityRegisterBinding private lateinit var auth: FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityRegisterBinding.inflate(layoutInflater) val view = binding.root setContentView(view) auth = FirebaseAuth.getInstance() } fun kayitol(view: View) { val email = binding.emailText.text.toString() val sifre = binding.sifreText.text.toString() val ad = binding.adText.text.toString() val soyad = binding.soyadText.text.toString() val ogrencino = binding.ogrencinoText.text.toString().toInt() val universite = binding.universiteText.text.toString() val fakulte = binding.fakulteText.text.toString() val bolum = binding.bolumText.text.toString() val sinif = binding.sinifText.text.toString() val sifretekrar = binding.sifreText2.text.toString() if (email.equals("") || sifre.equals("") || ad.equals("") || soyad.equals("") || ogrencino.equals("") || universite.equals("") || fakulte.equals("") || bolum.equals("") || sinif.equals("") || sifretekrar.equals("") ) { Toast.makeText(this@RegisterActivity, "Boş alanları doldurunuz", Toast.LENGTH_LONG).show() } else { //success auth.createUserWithEmailAndPassword(email, sifre).addOnSuccessListener { Toast.makeText(this, "Kaydınız Başarılı", Toast.LENGTH_LONG).show() val intent = Intent(applicationContext, MainActivity::class.java) startActivity(intent) finish() }.addOnFailureListener { Toast.makeText(this, "Bir hata oluştu", Toast.LENGTH_LONG).show() } } } }
0
Kotlin
0
1
6a25d6fe5115dd7d2df45d058dd24112adafdcc7
2,247
hackathon-mobil-app
MIT License
backend/src/test/kotlin/com/github/davinkevin/podcastserver/IOUtils.kt
davinkevin
13,350,152
false
{"HTML": 13847656, "Kotlin": 1179034, "TypeScript": 162710, "JavaScript": 96744, "Java": 22047, "Less": 21773, "SCSS": 5172, "Shell": 2799, "Dockerfile": 2639}
package com.github.davinkevin.podcastserver import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths /** * Created by kevin on 23/07/2016. */ private object IOUtils {} fun toPath(uri: String): Path { val file = IOUtils::class.java.getResource(uri)?.toURI() ?: error("file $uri not found") return Paths.get(file) } fun fileAsString(uri: String): String { return Files.newInputStream(toPath(uri)) .bufferedReader() .use { it.readText() } } fun fileAsByteArray(uri: String): ByteArray { return Files.readAllBytes(toPath(uri)) }
0
HTML
43
183
35cbef91622d71262852a0a0683f339f6571a8c8
595
Podcast-Server
Apache License 2.0
libs/messaging/messaging-impl/src/main/kotlin/net/corda/messaging/utils/HTTPRetryExecutor.kt
iantstaley
733,471,799
false
{"Kotlin": 18721191, "Java": 318774, "Smarty": 101152, "Shell": 48766, "Groovy": 30252, "PowerShell": 6350, "TypeScript": 5826, "Solidity": 2024}
package net.corda.messaging.utils import java.net.http.HttpResponse import net.corda.messaging.api.exception.CordaHTTPClientErrorException import net.corda.messaging.api.exception.CordaHTTPServerErrorException import net.corda.utilities.trace import net.corda.v5.base.exceptions.CordaRuntimeException import org.slf4j.Logger import org.slf4j.LoggerFactory class HTTPRetryExecutor { companion object { private val log: Logger = LoggerFactory.getLogger(this::class.java.enclosingClass) fun <T> withConfig(config: HTTPRetryConfig, block: () -> HttpResponse<T>): HttpResponse<T> { var currentDelay = config.initialDelay for (i in 0 until config.times) { val result = tryAttempt(i, config, block) if (result != null) return result log.trace { "Attempt #${i + 1} failed. Retrying in $currentDelay ms..." } Thread.sleep(currentDelay) currentDelay = (currentDelay * config.factor).toLong() } val errorMsg = "Retry logic exhausted all attempts without a valid return or rethrow, though this shouldn't be possible." log.trace { errorMsg } throw CordaRuntimeException(errorMsg) } private fun <T> tryAttempt(i: Int, config: HTTPRetryConfig, block: () -> HttpResponse<T>): HttpResponse<T>? { return try { log.trace { "HTTPRetryExecutor making attempt #${i + 1}." } val result = block() checkResponseStatus(result.statusCode()) log.trace { "Operation successful after #${i + 1} attempt/s." } result } catch (e: Exception) { handleException(i, config, e) null } } private fun handleException(attempt: Int, config: HTTPRetryConfig, e: Exception) { val isFinalAttempt = attempt == config.times - 1 val isRetryable = config.retryOn.any { it.isInstance(e) } if (!isRetryable || isFinalAttempt) { val errorMsg = when { isFinalAttempt -> "Operation failed after ${config.times} attempts." else -> "HTTPRetryExecutor caught a non-retryable exception: ${e.message}" } log.trace { errorMsg } throw e } } private fun checkResponseStatus(statusCode: Int) { log.trace { "Received response with status code $statusCode" } when (statusCode) { in 400..499 -> throw CordaHTTPClientErrorException(statusCode, "Server returned status code $statusCode.") in 500..599 -> throw CordaHTTPServerErrorException(statusCode, "Server returned status code $statusCode.") } } } }
5
Kotlin
0
0
d53781fa0f2491102041417db92d6ded41c0522d
2,845
corda-runtime-os
Apache License 2.0
frontend/screen/conversational/src/commonMain/kotlin/com/mindovercnc/linuxcnc/screen/conversational/ui/ConversationalFab.kt
85vmh
543,628,296
false
{"Kotlin": 956103, "C++": 75148, "Java": 7157, "Makefile": 2742, "HTML": 419, "Shell": 398, "CSS": 108}
package com.mindovercnc.linuxcnc.screen.conversational.ui import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material3.ExtendedFloatingActionButton import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier @Composable fun ConversationalFab( onClick: () -> Unit, modifier: Modifier = Modifier, expanded: Boolean = true ) { ExtendedFloatingActionButton( text = { Text("Create New") }, onClick = onClick, icon = { Icon( Icons.Default.Add, contentDescription = null, ) }, expanded = expanded, modifier = modifier ) }
0
Kotlin
1
3
5cf42426895ba8691c9b53ba1b97c274bbdabc07
806
mindovercnclathe
Apache License 2.0
container-tasks-gradle-plugin/src/main/kotlin/task/runner/AsyncRunner.kt
mpetuska
482,828,109
false
{"Kotlin": 67335}
package dev.petuska.container.task.runner import org.gradle.deployment.internal.Deployment import org.gradle.deployment.internal.DeploymentHandle import org.gradle.internal.service.ServiceRegistry public interface AsyncRunner<EH : Any, ER : Any> { public fun execute(services: ServiceRegistry): ER public fun start(): EH public abstract class Handle<EH : Any> : DeploymentHandle { protected abstract val runner: AsyncRunner<EH, *> private var process: EH? = null final override fun isRunning(): Boolean = process != null final override fun start(deployment: Deployment) { process = runner.start() } final override fun stop() { val p = process if (p != null && abort(p)) { process = null } } public abstract fun abort(process: EH): Boolean } }
11
Kotlin
0
2
05265b4ec9dd977c863fd86c11991648aa1990a2
824
container-tasks-gradle
Apache License 2.0
src/main/kotlin/me/fzzyhmstrs/amethyst_core/item_util/ScepterLike.kt
fzzyhmstrs
507,177,454
false
{"Kotlin": 233763, "Java": 13591}
package me.fzzyhmstrs.amethyst_core.item_util import me.fzzyhmstrs.amethyst_core.scepter_util.augments.ScepterAugment import me.fzzyhmstrs.fzzy_core.coding_util.FzzyPort import me.fzzyhmstrs.fzzy_core.nbt_util.NbtKeys import net.minecraft.enchantment.EnchantmentHelper import net.minecraft.item.ItemStack import net.minecraft.nbt.NbtCompound import net.minecraft.util.Identifier interface ScepterLike{ /** * the fallback ID is used when a scepter needs a starting state, like a spell, modifier, or whatever other implementation. For Augment Scepters, this is the base augment added by default (Magic Missile for Amethyst Imbuement) */ val fallbackId: Identifier var noFallback: Boolean fun hasFallback(): Boolean{ return !noFallback } fun defaultAugments(): List<ScepterAugment>{ return listOf() } /** * Defines the spell power level of the scepter, generally 1, 2, or 3 (low, medium, high), but can be higher if higher tier spells are implemented. */ fun getTier(): Int /** * as needed implementations can add nbt needed for their basic funcitoning. * * Remember to call super. */ fun writeDefaultNbt(stack: ItemStack, scepterNbt: NbtCompound){ } /** * called to initialize NBT or other stored information in memory. useful if there are things that need tracking like progress on something, or an active state. Called when the item is crafted and as needed when used. * * Remember to call super. */ fun initializeScepter(stack: ItemStack, scepterNbt: NbtCompound){ writeDefaultNbt(stack, scepterNbt) } /** * function to define when a scepter needs post-crafting initialization. For states stored in memory, this will be at least once at the beginning of every game session (to repopulate a map or similar). */ fun needsInitialization(stack: ItemStack, scepterNbt: NbtCompound): Boolean fun canAcceptAugment(augment: ScepterAugment): Boolean{ return true } fun addDefaultEnchantments(stack: ItemStack, scepterNbt: NbtCompound){ if (scepterNbt.contains(me.fzzyhmstrs.amethyst_core.nbt_util.NbtKeys.ENCHANT_INIT.str() + stack.translationKey)) return val enchantToAdd = FzzyPort.ENCHANTMENT.get(this.fallbackId) if (enchantToAdd != null && hasFallback() && !scepterNbt.contains(me.fzzyhmstrs.amethyst_core.nbt_util.NbtKeys.FALLBACK_INIT.str())){ scepterNbt.putBoolean(me.fzzyhmstrs.amethyst_core.nbt_util.NbtKeys.FALLBACK_INIT.str(),true) if (EnchantmentHelper.getLevel(enchantToAdd,stack) == 0){ stack.addEnchantment(enchantToAdd,1) } } defaultAugments().forEach { if (EnchantmentHelper.getLevel(it,stack) == 0){ stack.addEnchantment(it,1) } } scepterNbt.putBoolean(me.fzzyhmstrs.amethyst_core.nbt_util.NbtKeys.ENCHANT_INIT.str() + stack.translationKey,true) } fun getActiveEnchant(stack: ItemStack): String{ val nbt: NbtCompound = stack.orCreateNbt return if (nbt.contains(NbtKeys.ACTIVE_ENCHANT.str())){ nbt.getString(NbtKeys.ACTIVE_ENCHANT.str()) } else { initializeScepter(stack,nbt) nbt.getString(NbtKeys.ACTIVE_ENCHANT.str()) } } }
0
Kotlin
1
0
d14441186e071af28d5cc19b217edf8fcd9d95c1
3,361
ac
MIT License
app/src/main/java/com/ifanr/tangzhi/ui/base/widget/FlatGridEpoxyRV.kt
cyrushine
224,551,311
false
{"Kotlin": 673925, "Java": 59856, "Python": 795}
package com.ifanr.tangzhi.ui.base.widget import android.content.Context import android.util.AttributeSet import android.view.MotionEvent import androidx.recyclerview.widget.GridLayoutManager open class FlatGridEpoxyRV: AppEpoxyRV { constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super( context, attrs, defStyleAttr ) init { isNestedScrollingEnabled = false } override fun canScrollHorizontally(direction: Int): Boolean { return false } override fun canScrollVertically(direction: Int): Boolean { return false } override fun onTouchEvent(e: MotionEvent?): Boolean { return false } class FlatGridLayoutManager: GridLayoutManager { constructor( context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int ) : super(context, attrs, defStyleAttr, defStyleRes) constructor(context: Context?, spanCount: Int) : super(context, spanCount) constructor( context: Context?, spanCount: Int, orientation: Int, reverseLayout: Boolean ) : super(context, spanCount, orientation, reverseLayout) override fun canScrollVertically(): Boolean { return false } override fun canScrollHorizontally(): Boolean { return true } } }
0
Kotlin
0
0
ab9a7a2eba7f53eca918e084da9d9907f7997cee
1,587
tangzhi_android
Apache License 2.0
src/main/kotlin/ch/leadrian/samp/kamp/gradle/plugin/textkeygen/TextKeysGeneratorPlugin.kt
Double-O-Seven
148,543,187
false
null
package ch.leadrian.samp.kamp.gradle.plugin.textkeygen import org.gradle.api.NonNullApi import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.plugins.JavaPluginConvention import org.gradle.api.tasks.SourceSet import org.gradle.api.tasks.compile.JavaCompile import org.jetbrains.kotlin.gradle.tasks.KotlinCompile @NonNullApi open class TextKeysGeneratorPlugin : Plugin<Project> { companion object { const val GENERATED_SOURCE_DIRECTORY = "generated-src/main/java" } override fun apply(project: Project) { createExtension(project) configureTask(project) configureSourceSets(project) } private fun createExtension(project: Project) { project.extensions.create("textKeyGenerator", TextKeysGeneratorPluginExtension::class.java) } private fun configureTask(project: Project) { val generateTextKeysTask = project.tasks.create("generateTextKeys", GenerateTextKeysTask::class.java) project.tasks.withType(JavaCompile::class.java) { it.dependsOn(generateTextKeysTask) } project.tasks.withType(KotlinCompile::class.java) { it.dependsOn(generateTextKeysTask) } } private fun configureSourceSets(project: Project) { project .convention .findPlugin(JavaPluginConvention::class.java) ?.sourceSets ?.getByName(SourceSet.MAIN_SOURCE_SET_NAME) ?.java ?.srcDir(project.buildDir.resolve(GENERATED_SOURCE_DIRECTORY)) } }
0
Kotlin
0
0
8915a0749dc5101a75cc9d6be744682ba29ec492
1,544
kamp-gradle-plugins
Apache License 2.0
app/src/main/java/com/mospolytech/mospolyhelper/data/addresses/local/AddressesLocalStorageDataSource.kt
tonykolomeytsev
341,524,793
true
{"Kotlin": 646693}
package com.mospolytech.mospolyhelper.data.addresses.local import android.util.Log import com.mospolytech.mospolyhelper.App import com.mospolytech.mospolyhelper.domain.addresses.model.AddressMap import com.mospolytech.mospolyhelper.utils.TAG import kotlinx.serialization.decodeFromString import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json class AddressesLocalStorageDataSource { companion object { const val ADDRESSES_FOLDER = "addresses" const val ADDRESSES_FILE = "cached_addresses" } fun get(): AddressMap? { val file = App.context!!.filesDir.resolve(ADDRESSES_FOLDER).resolve(ADDRESSES_FILE) // TODO: Add directory if (!file.exists()) { return null } return try { Json.decodeFromString<AddressMap>(file.readText()) } catch (e: Exception) { Log.e(TAG, "Addresses reading from the local storage and parsing exception", e) null } } fun set(addressMap: AddressMap) { val file = App.context!!.filesDir.resolve(ADDRESSES_FOLDER).resolve(ADDRESSES_FILE) if (file.exists()) { file.deleteRecursively() } else { file.parentFile?.mkdirs() } try { file.createNewFile() file.writeText(Json.encodeToString(addressMap)) } catch (e: Exception) { Log.e(TAG, "Addresses parsing and writing exception", e) } } }
0
null
0
0
379c9bb22913da1854f536bf33e348a459db48b9
1,489
mospolyhelper-android
MIT License
jps/jps-plugin/testData/incremental/pureKotlin/inlineModifiedWithUsage/usage.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
package foo fun useF() { println(f()) }
251
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
44
kotlin
Apache License 2.0
Coex-master/app/src/main/java/com/beko/coex/ui/main/allexpense/ExpenseAdapter.kt
bekir1184
467,304,085
false
{"Kotlin": 58987}
package com.beko.coex.ui.main.allexpense import android.view.LayoutInflater import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.beko.coex.R import com.beko.coex.databinding.ExpenseItemBinding import com.beko.coex.databinding.OneRowExpenseStatusBinding import com.beko.coex.models.Expense import com.beko.coex.models.ExpenseStatusModel class ExpenseAdapter() : ListAdapter<Expense,ExpenseAdapter.CustomViewHolder>(customCallBack){ private var onItemCoinClickListener: ((expense : Expense) -> Unit)? = null fun setOnItemCoinClickListener(onItemCoinClickListener: ((expense : Expense) -> Unit)?) { this.onItemCoinClickListener = onItemCoinClickListener } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomViewHolder { return CustomViewHolder( DataBindingUtil.inflate( LayoutInflater.from(parent.context), R.layout.expense_item, parent, false ) ) } override fun onBindViewHolder(holder: CustomViewHolder, position: Int) { holder.bind(getItem(position)) } inner class CustomViewHolder(private val binding: ExpenseItemBinding) : RecyclerView.ViewHolder(binding.root){ init { binding.root.setOnClickListener { onItemCoinClickListener?.invoke( getItem(adapterPosition) ) } } fun bind(expense: Expense ) { with(binding) { expenseModel = expense } } } companion object { val customCallBack = object : DiffUtil.ItemCallback<Expense>() { override fun areItemsTheSame(oldItem: Expense, newItem: Expense): Boolean { return oldItem.expenseName == newItem.expenseName } override fun areContentsTheSame(oldItem: Expense, newItem: Expense): Boolean { return oldItem == newItem } } } }
0
Kotlin
0
2
1ebfc1ef1608c303d47ba26c75ce1e0d35724622
2,179
CoexApp
MIT License
model/src/main/java/io/pixelplex/mobile/cryptoapi/model/data/btc/BtcRawTransaction.kt
cryptoapi-project
245,105,614
false
null
package io.pixelplex.mobile.cryptoapi.model.data.btc import com.google.gson.annotations.SerializedName data class BtcRawTransaction( @SerializedName("hash") val hash: String )
0
Kotlin
0
0
8362c0cd1fed18c67edbb7e98087beae0c023ac7
186
cryptoapi-kotlin
MIT License
src/main/kotlin/net/sileader/cyborg/view/widget/TextView.kt
SiLeader
107,783,361
false
null
package net.sileader.cyborg.view.widget class TextView { }
0
Kotlin
0
0
3fed3c6deb860d42379251079b0ec55fdaea9682
59
cyborg
Apache License 2.0
libraries/tools/kotlin-gradle-plugin/src/test/kotlin/org/jetbrains/kotlin/gradle/targets/native/internal/KotlinNativeStackTraceParserKtTest.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
/* * Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.gradle.targets.native.internal import org.junit.Assert.assertEquals import org.junit.Test class KotlinNativeStackTraceParserKtTest { @Test fun testDebug() { assertEquals( """ KotlinNativeStackTrace( message="kotlin.AssertionError: Expected <7>, actual <42>.", stacktrace=[ KotlinNativeStackTraceElement(bin=test.kexe, address=0x00000001048f3c86, className=kotlin.Error, methodName=<init>, signature=(kotlin.String?)kotlin.Error, offset=70, fileName=/Users/teamcity/buildAgent/work/4d622a065c544371/runtime/src/main/kotlin/kotlin/Exceptions.kt, lineNumber=12, columnNumber=5) KotlinNativeStackTraceElement(bin=test.kexe, address=0x00000001048f3ada, className=kotlin.AssertionError, methodName=<init>, signature=(kotlin.Any?)kotlin.AssertionError, offset=122, fileName=/Users/teamcity/buildAgent/work/4d622a065c544371/runtime/src/main/kotlin/kotlin/Exceptions.kt, lineNumber=128, columnNumber=5) KotlinNativeStackTraceElement(bin=test.kexe, address=0x0000000104987939, className=kotlin.test.DefaultAsserter, methodName=fail, signature=(kotlin.String?)kotlin.Nothing, offset=137, fileName=/Users/teamcity/buildAgent/work/4d622a065c544371/backend.native/build/stdlib/kotlin/test/DefaultAsserter.kt, lineNumber=16, columnNumber=19) KotlinNativeStackTraceElement(bin=test.kexe, address=0x0000000104987797, className=kotlin.test.Asserter, methodName=assertTrue, signature=(kotlin.Function0<kotlin.String?>;kotlin.Boolean), offset=263, fileName=/Users/teamcity/buildAgent/work/4d622a065c544371/backend.native/build/stdlib/kotlin/test/Assertions.kt, lineNumber=-1, columnNumber=-1) KotlinNativeStackTraceElement(bin=test.kexe, address=0x000000010498840c, className=kotlin.test.Asserter, methodName=assertEquals, signature=(kotlin.String?;kotlin.Any?;kotlin.Any?), offset=380, fileName=/Users/teamcity/buildAgent/work/4d622a065c544371/backend.native/build/stdlib/kotlin/test/Assertions.kt, lineNumber=-1, columnNumber=-1) KotlinNativeStackTraceElement(bin=test.kexe, address=0x000000010498b904, className=kotlin.test, methodName=assertEquals, signature=(#GENERIC;#GENERIC;kotlin.String?)Generic, offset=196, fileName=/Users/teamcity/buildAgent/work/4d622a065c544371/backend.native/build/stdlib/kotlin/test/Assertions.kt, lineNumber=-1, columnNumber=-1) KotlinNativeStackTraceElement(bin=test.kexe, address=0x000000010498b7fe, className=kotlin.test, methodName=assertEquals${'$'}default, signature=(#GENERIC;#GENERIC;kotlin.String?;kotlin.Int)Generic, offset=158, fileName=/Users/teamcity/buildAgent/work/4d622a065c544371/backend.native/build/stdlib/kotlin/test/Assertions.kt, lineNumber=-1, columnNumber=-1) KotlinNativeStackTraceElement(bin=test.kexe, address=0x000000010498b65c, className=sample.SampleTests, methodName=testMe, signature=(), offset=140, fileName=/Users/jetbrains/IdeaProjects/mpplib2/src/commonTest/kotlin/sample/SampleTests.kt, lineNumber=-1, columnNumber=-1) KotlinNativeStackTraceElement(bin=test.kexe, address=0x000000010498b593, className=sample.${'$'}SampleTests${'$'}test${'$'}0.${'$'}testMe${'$'}FUNCTION_REFERENCE${'$'}0, methodName=invoke#internal, signature=(sample.${'$'}SampleTests${'$'}test${'$'}0.${'$'}testMe${'$'}FUNCTION_REFERENCE${'$'}0.invoke#internal, offset=67, fileName=/Users/jetbrains/IdeaProjects/mpplib2/src/commonTest/kotlin/sample/SampleTests.kt, lineNumber=-1, columnNumber=-1) KotlinNativeStackTraceElement(bin=test.kexe, address=0x000000010498b4fb, className=sample.${'$'}SampleTests${'$'}test${'$'}0.${'$'}testMe${'$'}FUNCTION_REFERENCE${'$'}0, methodName=${'$'}<bridge-UNNN>invoke, signature=(#GENERIC)#internal, offset=75, fileName=/Users/jetbrains/IdeaProjects/mpplib2/src/commonTest/kotlin/sample/SampleTests.kt, lineNumber=10, columnNumber=6) KotlinNativeStackTraceElement(bin=test.kexe, address=0x0000000104985c1c, className=kotlin.native.internal.test.BaseClassSuite.TestCase, methodName=run, signature=(), offset=492, fileName=/Users/teamcity/buildAgent/work/4d622a065c544371/backend.native/build/stdlib/generated/_Collections.kt, lineNumber=98, columnNumber=7) KotlinNativeStackTraceElement(bin=test.kexe, address=0x000000010490649b, className=kotlin.native.internal.test.TestRunner, methodName=run#internal, signature=(kotlin.native.internal.test.TestRunner.run#internal, offset=1467, fileName=/Users/teamcity/buildAgent/work/4d622a065c544371/runtime/src/main/kotlin/kotlin/native/internal/test/TestRunner.kt, lineNumber=198, columnNumber=21) KotlinNativeStackTraceElement(bin=test.kexe, address=0x0000000104905287, className=kotlin.native.internal.test.TestRunner, methodName=runIteration#internal, signature=(kotlin.native.internal.test.TestRunner.runIteration#internal, offset=1863, fileName=/Users/teamcity/buildAgent/work/4d622a065c544371/runtime/src/main/kotlin/kotlin/system/Timing.kt, lineNumber=33, columnNumber=12) KotlinNativeStackTraceElement(bin=test.kexe, address=0x00000001049042d0, className=kotlin.native.internal.test.TestRunner, methodName=run, signature=()kotlin.Int, offset=816, fileName=/Users/teamcity/buildAgent/work/4d622a065c544371/runtime/src/main/kotlin/kotlin/native/internal/test/TestRunner.kt, lineNumber=232, columnNumber=17) KotlinNativeStackTraceElement(bin=test.kexe, address=0x0000000104902eae, className=kotlin.native.internal.test, methodName=testLauncherEntryPoint, signature=(kotlin.Array<kotlin.String>)kotlin.Int, offset=110, fileName=/Users/teamcity/buildAgent/work/4d622a065c544371/runtime/src/main/kotlin/kotlin/native/internal/test/Launcher.kt, lineNumber=19, columnNumber=47) KotlinNativeStackTraceElement(bin=test.kexe, address=0x0000000104902e12, className=kotlin.native.internal.test, methodName=main, signature=(kotlin.Array<kotlin.String>), offset=50, fileName=/Users/teamcity/buildAgent/work/4d622a065c544371/runtime/src/main/kotlin/kotlin/native/internal/test/Launcher.kt, lineNumber=23, columnNumber=5) KotlinNativeStackTraceElement(bin=test.kexe, address=0x0000000104902d67, className=null, methodName=Konan_start, signature=(Konan_start, offset=71, fileName=/Users/teamcity/buildAgent/work/4d622a065c544371/runtime/src/launcher/kotlin/konan/start.kt, lineNumber=-1, columnNumber=-1) KotlinNativeStackTraceElement(bin=test.kexe, address=0x0000000104902cf1, className=null, methodName=Konan_run_start, signature=(Konan_run_start, offset=113, fileName=null, lineNumber=-1, columnNumber=-1) KotlinNativeStackTraceElement(bin=test.kexe, address=0x0000000104902c6b, className=null, methodName=Konan_main, signature=(Konan_main, offset=27, fileName=null, lineNumber=-1, columnNumber=-1) KotlinNativeStackTraceElement(bin=libdyld.dylib, address=0x00007fff5ab4fed9, className=null, methodName=start, signature=(start, offset=1, fileName=null, lineNumber=-1, columnNumber=-1) ]) """.trim(), parseKotlinNativeStackTrace( """ kotlin.AssertionError: Expected <7>, actual <42>. at 0 test.kexe 0x00000001048f3c86 kfun:kotlin.Error.<init>(kotlin.String?)kotlin.Error + 70 (/Users/teamcity/buildAgent/work/4d622a065c544371/runtime/src/main/kotlin/kotlin/Exceptions.kt:12:5) at 1 test.kexe 0x00000001048f3ada kfun:kotlin.AssertionError.<init>(kotlin.Any?)kotlin.AssertionError + 122 (/Users/teamcity/buildAgent/work/4d622a065c544371/runtime/src/main/kotlin/kotlin/Exceptions.kt:128:5) at 2 test.kexe 0x0000000104987939 kfun:kotlin.test.DefaultAsserter.fail(kotlin.String?)kotlin.Nothing + 137 (/Users/teamcity/buildAgent/work/4d622a065c544371/backend.native/build/stdlib/kotlin/test/DefaultAsserter.kt:16:19) at 3 test.kexe 0x0000000104987797 kfun:kotlin.test.Asserter.assertTrue(kotlin.Function0<kotlin.String?>;kotlin.Boolean) + 263 (/Users/teamcity/buildAgent/work/4d622a065c544371/backend.native/build/stdlib/kotlin/test/Assertions.kt:<unknown>) at 4 test.kexe 0x000000010498840c kfun:kotlin.test.Asserter.assertEquals(kotlin.String?;kotlin.Any?;kotlin.Any?) + 380 (/Users/teamcity/buildAgent/work/4d622a065c544371/backend.native/build/stdlib/kotlin/test/Assertions.kt:<unknown>) at 5 test.kexe 0x000000010498b904 kfun:kotlin.test.assertEquals(#GENERIC;#GENERIC;kotlin.String?)Generic + 196 (/Users/teamcity/buildAgent/work/4d622a065c544371/backend.native/build/stdlib/kotlin/test/Assertions.kt:<unknown>) at 6 test.kexe 0x000000010498b7fe kfun:kotlin.test.assertEquals${'$'}default(#GENERIC;#GENERIC;kotlin.String?;kotlin.Int)Generic + 158 (/Users/teamcity/buildAgent/work/4d622a065c544371/backend.native/build/stdlib/kotlin/test/Assertions.kt:<unknown>) at 7 test.kexe 0x000000010498b65c kfun:sample.SampleTests.testMe() + 140 (/Users/jetbrains/IdeaProjects/mpplib2/src/commonTest/kotlin/sample/SampleTests.kt:<unknown>) at 8 test.kexe 0x000000010498b593 kfun:sample.${'$'}SampleTests${'$'}test${'$'}0.${'$'}testMe${'$'}FUNCTION_REFERENCE${'$'}0.invoke#internal + 67 (/Users/jetbrains/IdeaProjects/mpplib2/src/commonTest/kotlin/sample/SampleTests.kt:<unknown>) at 9 test.kexe 0x000000010498b4fb kfun:sample.${'$'}SampleTests${'$'}test${'$'}0.${'$'}testMe${'$'}FUNCTION_REFERENCE${'$'}0.${'$'}<bridge-UNNN>invoke(#GENERIC)#internal + 75 (/Users/jetbrains/IdeaProjects/mpplib2/src/commonTest/kotlin/sample/SampleTests.kt:10:6) at 10 test.kexe 0x0000000104985c1c kfun:kotlin.native.internal.test.BaseClassSuite.TestCase.run() + 492 (/Users/teamcity/buildAgent/work/4d622a065c544371/backend.native/build/stdlib/generated/_Collections.kt:98:7) at 11 test.kexe 0x000000010490649b kfun:kotlin.native.internal.test.TestRunner.run#internal + 1467 (/Users/teamcity/buildAgent/work/4d622a065c544371/runtime/src/main/kotlin/kotlin/native/internal/test/TestRunner.kt:198:21) at 12 test.kexe 0x0000000104905287 kfun:kotlin.native.internal.test.TestRunner.runIteration#internal + 1863 (/Users/teamcity/buildAgent/work/4d622a065c544371/runtime/src/main/kotlin/kotlin/system/Timing.kt:33:12) at 13 test.kexe 0x00000001049042d0 kfun:kotlin.native.internal.test.TestRunner.run()kotlin.Int + 816 (/Users/teamcity/buildAgent/work/4d622a065c544371/runtime/src/main/kotlin/kotlin/native/internal/test/TestRunner.kt:232:17) at 14 test.kexe 0x0000000104902eae kfun:kotlin.native.internal.test.testLauncherEntryPoint(kotlin.Array<kotlin.String>)kotlin.Int + 110 (/Users/teamcity/buildAgent/work/4d622a065c544371/runtime/src/main/kotlin/kotlin/native/internal/test/Launcher.kt:19:47) at 15 test.kexe 0x0000000104902e12 kfun:kotlin.native.internal.test.main(kotlin.Array<kotlin.String>) + 50 (/Users/teamcity/buildAgent/work/4d622a065c544371/runtime/src/main/kotlin/kotlin/native/internal/test/Launcher.kt:23:5) at 16 test.kexe 0x0000000104902d67 Konan_start + 71 (/Users/teamcity/buildAgent/work/4d622a065c544371/runtime/src/launcher/kotlin/konan/start.kt:<unknown>) at 17 test.kexe 0x0000000104902cf1 Konan_run_start + 113 at 18 test.kexe 0x0000000104902c6b Konan_main + 27 at 19 libdyld.dylib 0x00007fff5ab4fed9 start + 1 """.trim() ).toString() ) } @Test fun testRelease() { assertEquals( """ KotlinNativeStackTrace( message="Uncaught Kotlin exception: kotlin.Exception: Foo!", stacktrace=[ KotlinNativeStackTraceElement(bin=program.kexe, address=0x000000010d6ad726, className=kotlin.Exception, methodName=<init>, signature=(kotlin.String?)kotlin.Exception, offset=70, fileName=null, lineNumber=-1, columnNumber=-1) KotlinNativeStackTraceElement(bin=program.kexe, address=0x000000010d6bc7a9, className=org.test.A, methodName=<get-qux>, signature=()ValueType, offset=89, fileName=null, lineNumber=-1, columnNumber=-1) KotlinNativeStackTraceElement(bin=program.kexe, address=0x000000010d6bc712, className=org.test.A, methodName=baz, signature=()ValueType, offset=50, fileName=null, lineNumber=-1, columnNumber=-1) KotlinNativeStackTraceElement(bin=program.kexe, address=0x000000010d6bc633, className=org.test, methodName=bar, signature=()ValueType, offset=67, fileName=null, lineNumber=-1, columnNumber=-1) KotlinNativeStackTraceElement(bin=program.kexe, address=0x000000010d6bc5e9, className=org.test, methodName=foo, signature=()ValueType, offset=9, fileName=null, lineNumber=-1, columnNumber=-1) ]) """.trim(), parseKotlinNativeStackTrace( """ Uncaught Kotlin exception: kotlin.Exception: Foo! at 0 program.kexe 0x000000010d6ad726 kfun:kotlin.Exception.<init>(kotlin.String?)kotlin.Exception + 70 at 1 program.kexe 0x000000010d6bc7a9 kfun:org.test.A.<get-qux>()ValueType + 89 at 2 program.kexe 0x000000010d6bc712 kfun:org.test.A.baz()ValueType + 50 at 3 program.kexe 0x000000010d6bc633 kfun:org.test.bar()ValueType + 67 at 4 program.kexe 0x000000010d6bc5e9 kfun:org.test.foo()ValueType + 9 """.trim() ).toString() ) } }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
13,691
kotlin
Apache License 2.0
src/main/kotlin/app.kt
pjagielski
334,491,565
false
null
import io.ktor.client.features.websocket.* import io.ktor.http.* import io.ktor.http.cio.websocket.* import kotlinx.coroutines.MainScope import kotlinx.coroutines.channels.ClosedReceiveChannelException import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.css.* import kotlinx.html.TBODY import kotlinx.html.TD import kotlinx.html.TR import kotlinx.html.js.onClickFunction import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json import react.* import react.dom.RDOMBuilder import react.dom.tbody import react.dom.tr import styled.* val NOTE_NAMES = arrayOf("C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B") val NOTE_COLORS = arrayOf( Color("#FA0B0C"), // red Color("#F44712"), // red-orange Color("#F88010"), // orange Color("#F5D23B"), // orange-yellow Color("#F5F43C"), // yellow Color("#149033"), // green Color("#1B9081"), // green-blue Color("#1C0D82"), // blue Color("#4B0E7D"), // blue-purple Color("#7F087C"), // purple Color("#A61586"), // purple-violet Color("#D71285") // violet ) fun findColor(note: Int) = NOTE_COLORS[note % 12] fun findOctave(note: Int) = note / 12 fun findName(note: Int) = NOTE_NAMES[note % 12] fun isSharp(note: Int) = findName(note).contains("#") fun isC(note: Int) = note % 12 == 0 private val scope = MainScope() object Colors { val lightGray = Color("#cccccc") val gray = Color("#a7a7a7") val darkGray = Color("#878787") } private fun RDOMBuilder<TBODY>.gridRow(header: String = "", block: RDOMBuilder<TR>.() -> Unit) { tr { styledTd { css { textAlign = TextAlign.center fontSize = 14.px width = 50.px } + header } this.block() } } val Ticker = functionalComponent<RProps> { val (tickData, setTickData) = useState(TickData(0, 0.0, 1000)) useEffect(dependencies = emptyList()) { scope.launch { client.ws(method = HttpMethod.Get, host = "127.0.0.1", port = 8000, path = "/tick") { for (frame in incoming) { when (frame) { is Frame.Text -> { val text = frame.readText() val newTickData = Json.decodeFromString<TickData>(text) setTickData(newTickData) // we get tick every beat, so need to fill remaining gaps manually (1..3).forEach { i -> scope.launch { val delayToNextStep = newTickData.tickLength(0.25) * i delay(delayToNextStep.toLong()) setTickData(newTickData.copy(beat = newTickData.beat + (0.25 * i))) } } } } } } } } styledTable { css { marginBottom = 10.px marginTop = 10.px borderSpacing = 5.px } tbody { tr { styledTd { css { width = 35.px } + "" } styledTd { css { width = 100.px fontSize = 20.px } + "${tickData.bar} / ${tickData.beat}" } } } } styledTable { css { borderSpacing = 0.px marginBottom = 10.px } tbody { gridRow { var beat = 0.0 val currentBeat = tickData.beat val step = 0.25 while (beat < 8.0) { val rowBackground = when { beat == currentBeat -> Colors.gray else -> Colors.lightGray } styledTd { css { width = 35.px height = 15.px backgroundColor = rowBackground border = "1px solid ${Colors.darkGray.value}" if (beat % 1.0 == 0.0) { borderLeft = "2px solid ${Colors.darkGray.value}" } } attrs { colSpan = "$span" } +" " } beat += step } } } } } val App = functionalComponent<RProps> { _ -> val (notes, setNotes) = useState(NoteState.from(emptyList())) val (synth, setSynth) = useState<String?>(null) val selectedSynth = when { synth != null && notes.synths.contains(synth) -> synth else -> notes.synths.firstOrNull() } fun reloadNotes() { scope.launch { val currentState = NoteState.from(fetchNotes()) setNotes(currentState) } } fun schedulePing(ws: WebSocketSession) { scope.launch { delay(10000) ws.send(Frame.Text("ping")) schedulePing(ws) } } useEffect(dependencies = emptyList()) { reloadNotes() scope.launch { client.ws(method = HttpMethod.Get, host = "127.0.0.1", port = 8000, path = "/notes") { schedulePing(this) try { for (frame in incoming) { println("Got frame!!") when (frame) { is Frame.Text -> { println("Got notes!!") val text = frame.readText() val format = Json { ignoreUnknownKeys = true } val newNotes = format.decodeFromString<List<Note>>(text) setNotes(NoteState.from(newNotes)) } } } } catch (e: ClosedReceiveChannelException) { println("onClose ${closeReason.await()}") } catch (e: Throwable) { println("onError ${closeReason.await()}") e.printStackTrace() } } } } styledDiv { css { margin = "auto" fontFamily = "Roboto" } styledTable { css { marginBottom = 10.px marginTop = 10.px borderSpacing = 5.px } tbody { tr { styledTd { css { width = 35.px } + " " } styledTd { css { width = 125.px fontSize = 24.px } + "● punkt" } notes.synths.forEach { synthName -> styledTd { css { textAlign = TextAlign.center cursor = Cursor.pointer padding = "5px" marginLeft = 15.px width = 75.px backgroundColor = when { selectedSynth == synthName -> Colors.gray else -> Colors.lightGray } } attrs { onClickFunction = { setSynth(synthName) } } +synthName } } } } } child(Ticker) styledDiv { css { maxHeight = 800.px overflow = Overflow.auto } styledTable { css { borderSpacing = 0.px } tbody { (84 downTo 24).forEach { midinote -> val header = if (isC(midinote)) "${findName(midinote)}${findOctave(midinote)}" else "" gridRow(header) { var beat = 0.0 while (beat < 8.0) { val note = selectedSynth?.let { notes.noteMapFor(it)[beat]?.get(midinote) } val span = note?.duration?.let { (it * (1/0.25)).toInt() } ?: 1 val step = note?.duration ?: 0.25 val rowBackground = when { isSharp(midinote) -> Colors.gray else -> Colors.lightGray } styledTd { css { width = 35.px height = 15.px backgroundColor = note?.midinote?.let(::findColor) ?: rowBackground border = "1px solid ${Colors.darkGray.value}" if (isC(midinote)) { borderBottom = "2px solid ${Colors.darkGray.value}" } if (beat % 1.0 == 0.0) { borderLeft = "2px solid ${Colors.darkGray.value}" } } attrs { colSpan = "$span" } +" " } beat += step } } } } } } } }
0
Kotlin
0
0
bed1257d06dbb6390dd6d0c54c0707b549954403
10,622
punkt-gui
Apache License 2.0
features/settings/src/main/kotlin/com/schatzdesigns/features/settings/SettingsFragment.kt
zakayothuku
282,235,374
false
null
/* * Copyright 2020 <NAME>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.schatzdesigns.features.settings import android.view.Menu import android.view.MenuInflater import com.schatzdesigns.commons.ui.base.BaseFragment import com.schatzdesigns.features.settings.databinding.FragmentSettingsBinding import com.schatzdesigns.features.settings.di.DaggerSettingsComponent import com.schatzdesigns.features.settings.di.SettingsModule import com.schatzdesigns.template.TemplateApp /** * Cards principal view. * * @see BaseFragment */ class SettingsFragment : BaseFragment<FragmentSettingsBinding, SettingsViewModel>( layoutId = R.layout.fragment_settings ) { override fun onInitDependencyInjection() { DaggerSettingsComponent.builder() .coreComponent(TemplateApp.coreComponent(requireContext())) .settingsModule(SettingsModule(this)) .build() .inject(this) } override fun onInitDataBinding() { viewBinding.viewModel = viewModel } }
0
Kotlin
2
3
d1113d3490e3ff486d8e0c5aedc8ea8060e71466
1,554
kotlin-modular-mvvm-template
Apache License 2.0
lib/src/main/java/com/pmm/ui/core/dialog/BottomUpDialog.kt
caoyanglee
158,797,807
false
{"Kotlin": 347970, "Java": 743, "AIDL": 192}
package com.pmm.ui.core.dialog import android.view.Gravity import com.pmm.ui.R /** * Author:你需要一台永动机 * Date:2019/4/9 23:40 * Description: */ abstract class BottomUpDialog : BaseDialog() { override fun getGravity(): Int = Gravity.BOTTOM override fun getWindowAnimation(): Int = R.style.BottomToUpDialog }
0
Kotlin
1
2
ae06d2b28263113ba6013d6048701536f237b253
337
universalui
Apache License 2.0
app/src/main/java/com/artamonov/millionplanets/adapter/ScanResultAdapter.kt
Artikmars
160,610,860
false
null
package com.artamonov.millionplanets.adapter import android.graphics.Color import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.artamonov.millionplanets.R import com.artamonov.millionplanets.model.SpaceObject import com.artamonov.millionplanets.model.SpaceObjectType import kotlinx.android.synthetic.main.scan_result_items.view.* class ScanResultAdapter( private var objectList: List<SpaceObject>, val itemClickListener: ItemClickListener? = null ) : RecyclerView.Adapter<ScanResultAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder(LayoutInflater.from(parent.context) .inflate(R.layout.scan_result_items, parent, false)) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bindItem() } override fun getItemCount(): Int { return objectList.size } interface ItemClickListener { fun onItemClick(position: Int) } inner class ViewHolder internal constructor(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bindItem() { val spaceObject = objectList[adapterPosition] itemView.object_name.text = spaceObject.name itemView.distance_to_object.text = spaceObject.distance.toString() when (spaceObject.type) { SpaceObjectType.PLANET -> { itemView.object_name.setTextColor(Color.parseColor("#FFFF00")) itemView.distance_to_object.setTextColor(Color.parseColor("#FFFF00")) } SpaceObjectType.FUEL -> { itemView.object_name.setTextColor(Color.parseColor("#008000")) itemView.distance_to_object.setTextColor(Color.parseColor("#008000")) } else -> { itemView.object_name.setTextColor(Color.parseColor("#ff0000")) itemView.distance_to_object.setTextColor(Color.parseColor("#ff0000")) } } itemView.setOnClickListener { val position = adapterPosition itemClickListener?.onItemClick(position) } } } }
0
Kotlin
0
0
3848081064753e28ec2f031ef2b20203685be82b
2,343
MillionPlanets
Apache License 2.0
extension/core/src/main/kotlin/xyz/tynn/astring/core/AStringTextSwitcher.kt
tynn-xyz
319,101,606
false
{"Kotlin": 209162, "Java": 128256}
// Copyright 2020 <NAME> // SPDX-License-Identifier: Apache-2.0 @file:JvmName("AStringTextSwitcher") package xyz.tynn.astring.core import android.widget.TextSwitcher import xyz.tynn.astring.AString import xyz.tynn.astring.aString /** * Sets the text of the text view that is currently showing * @see TextSwitcher.setCurrentText */ public fun TextSwitcher.setCurrentText( text: AString?, ): Unit = setCurrentText( aString(text), ) /** * Sets the text of the next view and switches to the next view * @see TextSwitcher.setText */ public fun TextSwitcher.setText( text: AString?, ): Unit = setText( aString(text), )
0
Kotlin
0
4
b74fc50e872b11b58a641145ddd2dc16aa4995d6
654
AString
Apache License 2.0
hwast/src/hw_port.kt
AntonovAlexander
94,638,838
false
{"Assembly": 1428326, "Kotlin": 612063, "Stata": 327604, "Tcl": 281196, "C": 202068, "SystemVerilog": 150400, "Verilog": 71774, "Python": 62206, "Makefile": 6680, "C++": 4817, "Perl": 2921}
/* * hw_port.kt * * Created on: 05.06.2019 * Author: <NAME> <<EMAIL>> * License: See LICENSE file for details */ package hwast enum class PORT_DIR { IN, OUT, INOUT } class hw_port(name : String, var port_dir : PORT_DIR, vartype : hw_type, defimm : hw_imm) : hw_var(name, vartype, defimm) { constructor(name : String, port_dir : PORT_DIR, vartype : hw_type, defval : String) : this(name, port_dir, vartype, hw_imm(defval)) }
0
Assembly
19
23
9fb56072aaf9fd48712eb84f2f33426e3624549e
494
activecore
Apache License 2.0
app/src/main/java/com/example/midtermapp/MainFragment.kt
vidyakethineni
731,106,205
false
{"Kotlin": 22988}
package com.example.midtermapp import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.databinding.DataBindingUtil import androidx.lifecycle.ViewModelProvider import androidx.navigation.fragment.findNavController import com.example.midtermapp.databinding.FragmentMainBinding class MainFragment : Fragment() { private lateinit var binding: FragmentMainBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentMainBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val viewModel = ViewModelProvider(requireActivity())[GameViewModel::class.java] binding.viewModel = viewModel binding.lifecycleOwner = this binding.playGameButton.setOnClickListener { findNavController().navigate(R.id.action_mainFragment_to_gameFragment) } binding.viewHighScoresButton.setOnClickListener { findNavController().navigate(R.id.action_mainFragment_to_highScoreFragment) } viewModel.getScoreByUser(viewModel.userName.value?:"").observe(viewLifecycleOwner){ binding.welcomeTextView.setWelcomeText(it) binding.scoreTextView?.setSubText(it) } } }
0
Kotlin
0
0
018dbeaf6e18d56bf1defc47a26d3f599db9885d
1,537
MidtermApp
Apache License 2.0
src/main/kotlin/de/flapdoodle/sqlextract/db/TableResolver.kt
flapdoodle-oss
363,965,979
false
null
package de.flapdoodle.sqlextract.db import de.flapdoodle.sqlextract.io.Monitor fun interface TableResolver { fun byName(name: Name): Table fun withMonitor(): TableResolver { val that = this; return TableResolver { Monitor.message("inspect $it") that.byName(it) } } fun withPostProcess(postProcess: (Table) -> Table = { it }): TableResolver { val that = this; return TableResolver { postProcess(that.byName(it)) } } }
0
Kotlin
1
0
69aa6dd554dc011d3bbc75fabcddfad173b41a79
524
de.flapdoodle.sqlextract
Apache License 2.0
app/src/main/java/fr/azhot/realestatemanager/view/fragment/PropertyListFragment.kt
Azhot
350,879,057
false
null
package fr.azhot.realestatemanager.view.fragment import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.os.Bundle import android.view.* import android.widget.TextView import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.fragment.app.viewModels import androidx.lifecycle.Observer import androidx.navigation.NavController import androidx.navigation.Navigation import androidx.recyclerview.widget.LinearLayoutManager import fr.azhot.realestatemanager.R import fr.azhot.realestatemanager.RealEstateManagerApplication import fr.azhot.realestatemanager.databinding.FragmentPropertyListBinding import fr.azhot.realestatemanager.model.Property import fr.azhot.realestatemanager.model.PropertySearch import fr.azhot.realestatemanager.utils.forceRefresh import fr.azhot.realestatemanager.view.adapter.PropertyListAdapter import fr.azhot.realestatemanager.view.adapter.PropertyListAdapter.PropertyClickListener import fr.azhot.realestatemanager.viewmodel.PropertyListFragmentViewModel import fr.azhot.realestatemanager.viewmodel.PropertyListFragmentViewModelFactory import fr.azhot.realestatemanager.viewmodel.SharedViewModel import java.util.* class PropertyListFragment : Fragment(), PropertyClickListener, Observer<List<Property>> { // variables private lateinit var binding: FragmentPropertyListBinding private lateinit var navController: NavController private val viewModel: PropertyListFragmentViewModel by viewModels { PropertyListFragmentViewModelFactory( (activity?.application as RealEstateManagerApplication).propertyRepository ) } private val sharedViewModel: SharedViewModel by activityViewModels() // overridden functions override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentPropertyListBinding.inflate(layoutInflater) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) navController = Navigation.findNavController(requireActivity(), R.id.main_container_view) setHasOptionsMenu(true) setUpPropertyListRecyclerView() setUpFilterOnTextView() observePropertySearch() } override fun onResume() { super.onResume() // if landscape, load detail fragment to the respective fragment container (master-detail) if (activity?.resources?.getBoolean(R.bool.isLandscape) == true && sharedViewModel.liveProperty.value != null ) { childFragmentManager.beginTransaction() .replace(binding.detailContainerView!!.id, PropertyDetailFragment()) .commit() } } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.add_property -> navigateNewProperty() R.id.edit_property -> navigateEditProperty() R.id.search_property -> promptSearchFragment() } return super.onOptionsItemSelected(item) } override fun onChanged(propertyList: List<Property>) { binding.propertyListRecyclerView.apply { (adapter as PropertyListAdapter).setList(propertyList) scrollToPosition(0) } } override fun onPropertyClickListener(property: Property) { if (activity?.resources?.getBoolean(R.bool.isLandscape) == true) { if (property == sharedViewModel.liveProperty.value) return childFragmentManager.beginTransaction() .setCustomAnimations(R.anim.fade_in, R.anim.fade_out) .replace(binding.detailContainerView!!.id, PropertyDetailFragment()) .commit() } else { navController.navigate( PropertyListFragmentDirections.actionPropertyListFragmentToPropertyDetailFragment() ) } sharedViewModel.liveProperty.value = property } // functions private fun setUpPropertyListRecyclerView() { binding.propertyListRecyclerView.apply { layoutManager = LinearLayoutManager(context) adapter = PropertyListAdapter(mutableListOf(), this@PropertyListFragment) } } // sets the action on click either to the right drawable or the text of filter text view private fun setUpFilterOnTextView() { binding.filterOnTextView.apply { setOnTouchListener { v, event -> v.performClick() when (event.action) { MotionEvent.ACTION_DOWN -> { if (event.rawX >= (v.right - (v as TextView).compoundDrawables[2].bounds.width())) { sharedViewModel.livePropertySearch.apply { value?.clear() forceRefresh() } return@setOnTouchListener true } promptSearchFragment() return@setOnTouchListener true } } return@setOnTouchListener false } } } private fun observePropertySearch() { sharedViewModel.livePropertySearch.observe(viewLifecycleOwner) { propertySearch -> // get property data from room observePropertyFilterableList(propertySearch) // animate filter text view binding.filterOnTextView.apply { if (propertySearch.isOn()) { alpha = 0f text = propertySearch.toString(context) visibility = View.VISIBLE } else { if (visibility != View.GONE) { binding.propertyListRecyclerView .animate() .translationY(-height.toFloat()) .duration = 250 } } animate() .alpha(if (propertySearch.isOn()) 1f else 0f) .setDuration(250) .setListener(if (propertySearch.isOn()) null else object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator?) { super.onAnimationEnd(animation) text = null binding.propertyListRecyclerView.translationY = 0f visibility = View.GONE } }) } } } private fun observePropertyFilterableList(propertySearch: PropertySearch) { viewModel.getPropertyFilterableList(propertySearch).removeObserver(this) viewModel.getPropertyFilterableList(propertySearch) .observe(viewLifecycleOwner, this) } private fun promptSearchFragment() { navController.navigate( PropertyListFragmentDirections.actionPropertyListFragmentToSearchModalFragment() ) } private fun navigateNewProperty() { navController.navigate(PropertyListFragmentDirections.actionPropertyListFragmentToAddPhotoFragment()) } private fun navigateEditProperty() { navController.navigate( PropertyListFragmentDirections.actionPropertyListFragmentToAddPhotoFragment(true) ) } }
0
Kotlin
0
0
3bb6b80dba9c6715c8ee29319788c8ac6fc15416
7,587
RealEstateManager
MIT License
app/src/main/java/seng440/vaccinepassport/ui/main/ScannerFragment.kt
This-Is-Alex
363,792,496
false
null
package seng440.vaccinepassport.ui.main import android.Manifest import android.app.AlertDialog import android.content.DialogInterface import android.content.pm.PackageManager import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import androidx.activity.result.contract.ActivityResultContracts import androidx.camera.core.CameraSelector import androidx.camera.core.ImageAnalysis import androidx.camera.core.Preview import androidx.camera.lifecycle.ProcessCameraProvider import androidx.camera.view.PreviewView import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import androidx.fragment.app.FragmentTransaction import androidx.fragment.app.activityViewModels import seng440.vaccinepassport.BarcodeImageAnalyser import seng440.vaccinepassport.R import seng440.vaccinepassport.SerializableVPass import seng440.vaccinepassport.VaccineType import seng440.vaccinepassport.listeners.BarcodeScannedListener import seng440.vaccinepassport.room.VPassLiveRoomApplication import seng440.vaccinepassport.room.VPassViewModel import seng440.vaccinepassport.room.VPassViewModelFactory import java.io.ByteArrayInputStream import java.io.DataInputStream import java.util.* import java.util.concurrent.ExecutorService import java.util.concurrent.Executors class ScannerFragment : Fragment(), BarcodeScannedListener { private var cameraExecutor: ExecutorService? = null private var cameraState: Boolean = false private var hasPermission: Boolean = false companion object { fun newInstance() = ScannerFragment() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val permission = ContextCompat.checkSelfPermission( requireActivity(), Manifest.permission.CAMERA) if (permission == PackageManager.PERMISSION_GRANTED) { hasPermission = true } else if (permission == PackageManager.PERMISSION_DENIED){ if (ActivityCompat.shouldShowRequestPermissionRationale(requireActivity(), Manifest.permission.CAMERA)) { val builder = AlertDialog.Builder(context) builder.setMessage(R.string.why_camera_permission) .setPositiveButton(R.string.why_camera_permission, DialogInterface.OnClickListener { _, _ -> askCameraPermission() }) builder.create() } else { askCameraPermission() } } } private val model: MainViewModel by activityViewModels() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { return inflater.inflate(R.layout.fragment_scanner, container, false) } override fun onResume() { super.onResume() model.getActionBarTitle().value = getString(R.string.scanner_actionbar_title) model.getActionBarSubtitle().value = getString(R.string.scanner_actionbar_subtitle) model.gethideHeader().value = false if (!cameraState && hasPermission) { cameraState = true initCamera() } } override fun onPause() { super.onPause() cameraState = false cameraExecutor?.shutdown() } private fun askCameraPermission() { val requestPermissionLauncher = registerForActivityResult( ActivityResultContracts.RequestPermission() ) { isGranted: Boolean -> if (isGranted) { hasPermission = true initCamera() } else { // Permission was denied requireActivity().supportFragmentManager.popBackStackImmediate() } } requestPermissionLauncher.launch( Manifest.permission.CAMERA) } private fun initCamera() { cameraExecutor = Executors.newSingleThreadExecutor() val cameraProviderFuture = ProcessCameraProvider.getInstance(requireContext()) cameraProviderFuture.addListener(Runnable { val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get() val preview = Preview.Builder().build().also { it.setSurfaceProvider( requireView().findViewById<PreviewView>(R.id.viewFinder).createSurfaceProvider() ) } val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA try { cameraProvider.unbindAll() val analyser = BarcodeImageAnalyser(this as BarcodeScannedListener) val imageAnalysis = ImageAnalysis.Builder() .build() .also { it.setAnalyzer(cameraExecutor!!, analyser) } // Stops using the camera when the fragment stops, don't have to worry about resource usage cameraProvider.bindToLifecycle(this, cameraSelector, preview, imageAnalysis) } catch (e: Exception) { Log.e("ScannerFragment", "Camera binding failed", e) } }, ContextCompat.getMainExecutor(requireContext())) } private fun timestampToDate(timestamp: Int): Date { return Date(timestamp.toLong() * 86400L * 1000L) } private fun isLettersOrDigits(chars: String): Boolean { for (c in chars) { if (c !in 'A'..'Z' && c !in 'a'..'z' && c !in '0'..'9') { return false } } return true } override fun onScanned(rawData: ByteArray) { val inputStream: DataInputStream = DataInputStream(ByteArrayInputStream(rawData)) val dateAdministered = inputStream.readInt() val vaccineType = VaccineType.fromId(inputStream.readByte()) val dosageNumber = inputStream.readByte().toInt() val passportNumberRaw = ByteArray(9) inputStream.read(passportNumberRaw, 0, 9) val passportNumber = String(passportNumberRaw) .trimEnd(Integer.valueOf(0).toChar()) //trim 0s off the end val passportExpiry = inputStream.readInt() val dateOfBirth = inputStream.readInt() val countryRaw = ByteArray(3) inputStream.read(countryRaw, 0, 3) val country = String(countryRaw) Log.d("Barcode", "About to read names... $dateAdministered ${vaccineType?.fullName} $dosageNumber $passportNumber") val rawName = ByteArray(inputStream.readByte().toInt()) inputStream.read(rawName, 0, rawName.size) val rawDoctor = ByteArray(inputStream.readByte().toInt()) inputStream.read(rawDoctor, 0, rawDoctor.size) val name = String(rawName) val doctorName = String(rawDoctor) Log.d("Barcode", "Names are $name, $doctorName") if (inputStream.read() != -1) return //there is still more data, must be the wrong format if (vaccineType == null || !isLettersOrDigits(passportNumber) || !isLettersOrDigits(country)) return Log.d("Barcode", "Read successfully") val dataObject = SerializableVPass(dateAdministered, vaccineType.id, doctorName, dosageNumber.toShort(), name, passportNumber, passportExpiry, dateOfBirth, country) model.barcodeToDisplay.value = dataObject model.getShowingBarcodeInScannedBarcodeFragment().value = false requireActivity().supportFragmentManager.beginTransaction() .replace(R.id.container, ScannedBarcodeFragment(), "show_scan_result" ) .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN) .addToBackStack("show_scan_result") .commit() } }
0
Kotlin
0
1
d6d46a80951f922c8f48be9bac26c0165d5cfa6c
7,966
android-vaccine-passport
MIT License
app/src/main/java/com/feliipessantos/skateshop/data/listeners/GetPriceProductsCart.kt
feliipessantos
605,780,076
false
null
package com.feliipessantos.skateshop.data.listeners interface GetPriceProductsCart { fun getPrice(Price: String) }
0
Kotlin
0
0
3d34b9b0af31f831e155b50a7beb2a73f7c5448b
124
SkateShop-Kotlin
Apache License 2.0
app/src/main/java/com/jviniciusb/theboredapp/data/repository/ActivityRepositoryImpl.kt
jviniciusb
458,941,270
false
{"Kotlin": 7624}
package com.jviniciusb.theboredapp.data.repository import com.jviniciusb.theboredapp.domain.model.Activity class ActivityRepositoryImpl : ActivityRepository { override suspend fun getActivity(): Activity? { TODO("Not yet implemented") } }
0
Kotlin
0
0
ab6dfd484201bece3d2998259b5e05b96784e0b3
258
the-bored-app
MIT License
src/main/kotlin/no/nav/personbruker/internal/periodic/metrics/reporter/config/KafkaConsumerSetup.kt
navikt
400,413,252
false
null
package no.nav.personbruker.internal.periodic.metrics.reporter.config import no.nav.personbruker.internal.periodic.metrics.reporter.common.kafka.Consumer import org.apache.kafka.clients.consumer.KafkaConsumer import org.slf4j.Logger import org.slf4j.LoggerFactory import java.util.* object KafkaConsumerSetup { private val log: Logger = LoggerFactory.getLogger(KafkaConsumerSetup::class.java) fun <K, V> setupCountConsumer(kafkaProps: Properties, topic: String): Consumer<K, V> { val kafkaConsumer = KafkaConsumer<K, V>(kafkaProps) return Consumer(topic, kafkaConsumer) } fun startSubscriptionOnAllKafkaConsumersAiven(appContext: ApplicationContext) { appContext.beskjedCountAivenConsumer.startSubscription() appContext.oppgaveCountAivenConsumer.startSubscription() appContext.innboksCountAivenConsumer.startSubscription() appContext.doneCountAivenConsumer.startSubscription() if (isOtherEnvironmentThanProd()) { appContext.statusoppdateringCountAivenConsumer.startSubscription() } else { log.info("Er i produksjonsmiljø, unnlater å starte statusoppdateringconsumer på Aiven.") } } suspend fun stopAllKafkaConsumersAiven(appContext: ApplicationContext) { log.info("Begynner å stoppe kafka-pollerne på Aiven...") appContext.beskjedCountAivenConsumer.stop() appContext.oppgaveCountAivenConsumer.stop() appContext.innboksCountAivenConsumer.stop() appContext.doneCountAivenConsumer.stop() if (isOtherEnvironmentThanProd()) { appContext.statusoppdateringCountAivenConsumer.stop() } log.info("...ferdig med å stoppe kafka-pollerne på Aiven.") } suspend fun restartConsumersAiven(appContext: ApplicationContext) { stopAllKafkaConsumersAiven(appContext) appContext.reinitializeConsumersAiven() startSubscriptionOnAllKafkaConsumersAiven(appContext) } }
0
Kotlin
0
0
04cefba9314597cbc81585d7e849debc8f0cb58a
1,990
internal-periodic-metrics-reporter
MIT License
app/src/main/java/com/tariod/uphub/domain/contract/GetUserReposUseCase.kt
Tariod
265,461,418
false
null
package com.tariod.uphub.domain.contract import androidx.lifecycle.LiveData import androidx.paging.PagedList import com.tariod.uphub.data.database.model.Repository import com.tariod.uphub.domain.base.ImmutableState import com.tariod.uphub.utilities.coroutine.JobComposite interface GetUserReposUseCase { fun getUserRepos( jobComposite: JobComposite, userId: Int? ): LiveData<ImmutableState<PagedList<Repository>>> }
0
Kotlin
0
0
059d5e0cab46037dee0efda7785b6e19bfdf9bff
443
UpHub
MIT License
src/main/kotlin/dev/arli/openapi/mapper/PropertyMapper.kt
alipovatyi
487,519,792
false
{"Kotlin": 451322}
package dev.arli.openapi.mapper import dev.arli.openapi.model.property.DataType import dev.arli.openapi.model.property.Property import dev.arli.openapi.model.property.getDataType import kotlin.reflect.KProperty import kotlin.reflect.jvm.jvmErasure internal class PropertyMapper( private val stringPropertyMapper: StringPropertyMapper = StringPropertyMapper(), private val numberPropertyMapper: NumberPropertyMapper = NumberPropertyMapper(), private val integerPropertyMapper: IntegerPropertyMapper = IntegerPropertyMapper(), private val booleanPropertyMapper: BooleanPropertyMapper = BooleanPropertyMapper(), private val arrayPropertyMapper: ArrayPropertyMapper = ArrayPropertyMapper(), private val objectPropertyMapper: ObjectPropertyMapper = ObjectPropertyMapper(), private val mapPropertyMapper: MapPropertyMapper = MapPropertyMapper(), private val enumPropertyMapper: EnumPropertyMapper = EnumPropertyMapper() ) { fun map(property: KProperty<*>): Property { return when (getDataType(property.returnType.jvmErasure)) { DataType.STRING -> stringPropertyMapper.map(property) DataType.NUMBER -> numberPropertyMapper.map(property) DataType.INTEGER -> integerPropertyMapper.map(property) DataType.BOOLEAN -> booleanPropertyMapper.map(property) DataType.ARRAY -> arrayPropertyMapper.map(property) DataType.MAP -> mapPropertyMapper.map(property) DataType.OBJECT -> objectPropertyMapper.map(property) DataType.ENUM -> enumPropertyMapper.map(property) } } }
0
Kotlin
1
1
3637b43dc2e255f263b559a5a80ebf80f3e78d96
1,607
ktor-openapi
Apache License 2.0
kite/src/main/kotlin/com/cioccarellia/kite/resparser/compat/KiteColorStateLists.kt
zsmb13
320,859,385
true
{"Kotlin": 35261}
/** * Designed and developed by <NAME> (@cioccarellia) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("PARAMETER_NAME_CHANGED_ON_OVERRIDE") package com.cioccarellia.kite.resparser.compat import android.content.res.ColorStateList import androidx.annotation.ColorRes import androidx.annotation.IntRange import androidx.core.content.ContextCompat import com.cioccarellia.kite.resparser.KiteResParser /** * KiteColorStateLists Implementation * */ class KiteColorStateLists : KiteResParser<@ColorRes Int, ColorStateList>() { override operator fun get( @ColorRes @IntRange(from = 1) colorStateList: Int ): ColorStateList = ContextCompat.getColorStateList(kiteContext, colorStateList)!! }
0
null
0
1
e7374879b093522d37dbb2b90ade43a776a19faa
1,245
kite
Apache License 2.0
app/build.gradle.kts
rob729
680,605,109
false
{"Kotlin": 121328, "Ruby": 2437}
@file:Suppress("UnstableApiUsage") import java.util.Properties plugins { alias(libs.plugins.android.application) alias(libs.plugins.kotlin.android) alias(libs.plugins.ksp) alias(libs.plugins.kotlin.parcelize) alias(libs.plugins.androidx.baselineprofile) alias(libs.plugins.detekt) if (File("app/google-services.json").exists() && File("app/src/debug/google-services.json").exists()) { alias(libs.plugins.google.services) alias(libs.plugins.firebase.crashlytics) } } val debugAppSuffix = ".debug" val localPropertiesFile = rootProject.file("local.properties") val localProperties = Properties() var newsFeedApiKey = if (localPropertiesFile.exists()) { localProperties.load(localPropertiesFile.inputStream()) localProperties.getProperty("NEWS_FEED_API_KEY") ?: "\"${System.getenv("NEWS_FEED_API_KEY")}\"" } else { "\"${System.getenv("NEWS_FEED_API_KEY")}\"" } val keystorePropertiesFile = rootProject.file("keystore.properties") val keystoreProperties = Properties() if (keystorePropertiesFile.exists()) { keystoreProperties.load(keystorePropertiesFile.inputStream()) } android { experimentalProperties["android.experimental.art-profile-r8-rewriting"] = true experimentalProperties["android.experimental.r8.dex-startup-optimization"] = true signingConfigs { create("release") { storeFile = file("../Keystore.p12") storePassword = keystoreProperties["storePassword"] as? String keyAlias = keystoreProperties["keyAlias"] as? String keyPassword = keystoreProperties["keyPassword"] as? String } } compileSdk = 34 defaultConfig { applicationId = "com.rob729.newsfeed" minSdk = 24 targetSdk = 34 versionCode = 4 versionName = "1.2.0" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" vectorDrawables.useSupportLibrary = true buildConfigField("String", "NEWS_FEED_API_KEY", newsFeedApiKey) ksp { arg("room.schemaLocation", "$projectDir/schemas") } } buildTypes { getByName("debug") { applicationIdSuffix = debugAppSuffix } getByName("release") { isShrinkResources = true isMinifyEnabled = true isDebuggable = false signingConfig = signingConfigs.getByName("release") proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") } create("benchmark") { initWith(getByName("release")) signingConfig = signingConfigs.getByName("debug") proguardFiles("benchmark-rules.pro") matchingFallbacks += listOf("release") } } compileOptions { sourceCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17 } kotlinOptions { jvmTarget = "17" } buildFeatures { compose = true buildConfig = true } composeOptions { kotlinCompilerExtensionVersion = "1.5.8" } packaging { resources { excludes += "/META-INF/{AL2.0,LGPL2.1}" } } namespace = "com.rob729.newsfeed" } baselineProfile { dexLayoutOptimization = true baselineProfileRulesRewrite = true baselineProfileOutputDir = "../../src/main/baselineProfiles" } dependencies { implementation(libs.androidx.core.ktx) implementation(platform(libs.compose.bom)) implementation(libs.compose.ui) implementation(libs.androidx.compose.ui.tooling.preview) implementation(libs.androidx.lifecycle.runtime.ktx) implementation(libs.androidx.activity.compose) testImplementation(libs.junit) androidTestImplementation(libs.androidx.junit) androidTestImplementation(libs.androidx.espresso.core) "baselineProfile"(project(":baselineprofile")) debugImplementation(libs.androidx.compose.ui.tooling) debugImplementation(libs.androidx.compose.ui.test.manifest) implementation(libs.androidx.navigation.compose) implementation(libs.androidx.compose.material.icons.extended) implementation(libs.androidx.compose.material3) implementation(libs.androidx.lifecycle.viewmodel.compose) implementation(libs.androidx.constraintlayout.compose) implementation(libs.androidx.work.runtime.ktx) implementation(libs.androidx.browser) implementation(libs.androidx.profileinstaller) implementation(libs.androidx.startup.runtime) implementation(libs.androidx.datastore.preferences) implementation(libs.androidx.runtime.tracing) implementation(libs.coil) implementation(libs.coil.compose) implementation(libs.moshi.kotlin) ksp(libs.moshi.codegen) implementation(libs.orbit.viewmodel) implementation(libs.orbit.compose) implementation(libs.retrofit) implementation(libs.converter.moshi) implementation(libs.logging.interceptor) implementation(libs.kotlinx.datetime) implementation(libs.androidx.room.runtime) ksp(libs.androidx.room.compiler) implementation(libs.androidx.room.ktx) implementation(libs.koin.android) implementation(libs.koin.androidx.compose) debugImplementation(libs.pluto) releaseImplementation(libs.pluto.no.op) debugImplementation(libs.bundle.core) releaseImplementation(libs.bundle.core.no.op) if (File("${project.projectDir}/google-services.json").exists() && File("${project.projectDir}/src/debug/google-services.json").exists()) { implementation(platform(libs.firebase.bom)) implementation(libs.firebase.analytics) implementation(libs.firebase.crashlytics) } }
7
Kotlin
0
0
f455e37063697cc58af1efa4331b412f66a566f3
5,742
News-Feed
Apache License 2.0
src/main/kotlin/tech/gdragon/HttpServer.kt
mayoshia
422,197,374
true
{"Kotlin": 120496, "Clojure": 13560, "Shell": 6239, "HTML": 4444, "Dockerfile": 932, "Makefile": 785, "Batchfile": 629}
package tech.gdragon import fi.iki.elonen.NanoHTTPD import tech.gdragon.discord.Bot class HttpServer(bot: Bot, val port: Int) { val inviteUrl: String = bot.api().setRequiredScopes("applications.commands").getInviteUrl(Bot.PERMISSIONS) val server = object : NanoHTTPD(port) { override fun serve(session: IHTTPSession): Response { val uri = session.uri return when (uri.toLowerCase()) { "/ping" -> { newFixedLengthResponse("pong") } "/invite" -> { newFixedLengthResponse(Response.Status.REDIRECT, MIME_HTML, "") .apply { addHeader("Location", inviteUrl) } } else -> { newFixedLengthResponse(Response.Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT, "Error 404, file not found.") } } } } fun shutdown() { server.stop() } }
0
Kotlin
0
0
8499941fb8237cfe2deb59c58eadf65f8cd8d4aa
850
throw-voice
Apache License 2.0
feature/user/src/main/java/st/slex/csplashscreen/feature/user/ui/UserPagerTabResource.kt
stslex
413,161,718
false
{"Kotlin": 332621, "Ruby": 1145}
package st.slex.csplashscreen.feature.user.ui import androidx.paging.compose.LazyPagingItems import st.slex.csplashscreen.core.network.model.ui.CollectionDomainModel import st.slex.csplashscreen.core.network.model.ui.ImageModel sealed class UserPagerTabResource<T : Any>(val pagingItems: LazyPagingItems<T>) { abstract val title: String data class Photos( private val items: LazyPagingItems<ImageModel> ) : UserPagerTabResource<ImageModel>(items) { override val title: String = "Photos" } data class Likes( private val items: LazyPagingItems<ImageModel> ) : UserPagerTabResource<ImageModel>(items) { override val title: String = "Likes" } data class Collections( private val items: LazyPagingItems<CollectionDomainModel> ) : UserPagerTabResource<CollectionDomainModel>(items) { override val title: String = "Collections" } }
2
Kotlin
0
3
94b3ee35d150cc907f23f37601bef8bb877b8d3d
918
CSplashScreen
Apache License 2.0
src/com/wxx/design/design_18_proxy/demo/DaoService.kt
wuxinxi
192,182,654
false
null
package com.wxx.design.design_18_proxy.demo /** * @author :DELL on 2021/5/13 . * @packages :com.wxx.design.design_18_proxy.demo . * TODO:一句话描述 */ interface DaoService { fun add() fun delete() fun update() fun query() }
0
Kotlin
0
0
1fef75f988f384fb5f9ace7087ccca3b00d587fb
253
DesignPatternsDemo
MIT License
app/src/main/java/org/simple/clinic/bloodsugar/entry/confirmremovebloodsugar/ConfirmRemoveBloodSugarEffect.kt
simpledotorg
132,515,649
false
{"Kotlin": 5970450, "Shell": 1660, "HTML": 545}
package org.simple.clinic.bloodsugar.entry.confirmremovebloodsugar import java.util.UUID sealed class ConfirmRemoveBloodSugarEffect data class MarkBloodSugarAsDeleted(val bloodSugarMeasurementUuid: UUID) : ConfirmRemoveBloodSugarEffect() object CloseConfirmRemoveBloodSugarDialog : ConfirmRemoveBloodSugarEffect()
4
Kotlin
73
223
58d14c702db2b27b9dc6c1298c337225f854be6d
318
simple-android
MIT License
presentation/src/main/java/com/anytypeio/anytype/presentation/sets/model/Filter.kt
anyproto
647,371,233
false
{"Kotlin": 9971954, "Java": 69306, "Shell": 11126, "Makefile": 1276}
package com.anytypeio.anytype.presentation.sets.model import android.os.Parcelable import kotlinx.parcelize.Parcelize sealed class FilterValue { data class TextShort(val value: String?) : FilterValue() { fun isEmpty(): Boolean = this == empty() companion object { fun empty() = TextShort(null) } } data class Url(val value: String?) : FilterValue() { fun isEmpty(): Boolean = this == empty() companion object { fun empty() = Url(null) } } data class Email(val value: String?) : FilterValue() { fun isEmpty(): Boolean = this == empty() companion object { fun empty() = Email(null) } } data class Phone(val value: String?) : FilterValue() { fun isEmpty(): Boolean = this == empty() companion object { fun empty() = Phone(null) } } data class Text(val value: String?) : FilterValue() { fun isEmpty(): Boolean = this == empty() companion object { fun empty() = Text(null) } } data class Number(val value: String?) : FilterValue() { fun isEmpty(): Boolean = this == empty() companion object { fun empty() = Number(null) } } data class Date(val value: Long?) : FilterValue() { fun isEmpty(): Boolean = this.value == null || this == empty() companion object { fun empty() = Date(0L) } } data class Check(val value: Boolean?) : FilterValue() { fun isEmpty(): Boolean = this == empty() companion object { fun empty() = Check(null) } } data class Status(val value: StatusView?) : FilterValue() { fun isEmpty(): Boolean = this == empty() companion object { fun empty() = Status(null) } } data class Tag(val value: List<TagView>) : FilterValue() { fun isEmpty(): Boolean = this == empty() companion object { fun empty() = Tag(listOf()) } } data class Object(val value: List<ObjectView>) : FilterValue() { fun isEmpty(): Boolean = this == empty() companion object { fun empty() = Object(listOf()) } } } @Parcelize data class TagValue(val id: String, val text: String, val color: String): Parcelable
33
Kotlin
26
301
8b3b7dacae68c015fb8b1b7c9cc76e53f0706430
2,394
anytype-kotlin
RSA Message-Digest License
plugins/base/src/main/kotlin/transformers/pages/merger/FallbackPageMergerStrategy.kt
Mu-L
406,989,990
true
{"Kotlin": 3099728, "CSS": 38463, "JavaScript": 25336, "TypeScript": 13611, "HTML": 6976, "FreeMarker": 3872, "SCSS": 2808, "Java": 2188, "Shell": 970}
/* * Copyright 2014-2023 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package org.jetbrains.dokka.base.transformers.pages.merger import org.jetbrains.dokka.pages.ContentPage import org.jetbrains.dokka.pages.PageNode import org.jetbrains.dokka.utilities.DokkaLogger public class FallbackPageMergerStrategy( private val logger: DokkaLogger ) : PageMergerStrategy { override fun tryMerge(pages: List<PageNode>, path: List<String>): List<PageNode> { pages.map { (it as? ContentPage) } val renderedPath = path.joinToString(separator = "/") if (pages.size != 1) logger.warn("For $renderedPath: expected 1 page, but got ${pages.size}") return listOf(pages.first()) } }
1
Kotlin
0
0
a1c3b89871a3a4f90d6441db356685d48a84ab63
769
dokka
Apache License 2.0
app/src/main/java/tml/tools/apitest/modules/apieditor/ApiEditorFragment.kt
devngmo
422,236,239
false
{"Kotlin": 58170}
package tml.tools.apitest.modules.apieditor import android.os.Bundle import android.util.Log import android.view.* import android.widget.Toast import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import tml.common.Defs import tml.libs.cku.io.EventHub import tml.tools.apitest.R import tml.tools.apitest.databinding.FragmentApieditorBinding import tml.tools.apitest.domain.models.Api import tml.tools.apitest.modules.apibrowser.ApiManager import tml.tools.apitest.modules.apibrowser.BaseFragment /** * A simple [Fragment] subclass as the second destination in the navigation. */ class ApiEditorFragment : BaseFragment() { private var _binding: FragmentApieditorBinding? = null private val binding get() = _binding!! override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) d("setup option menu, hide FAB onCreate") setHasOptionsMenu(true) EventHub.ins.post(Defs.EVTC_MAIN_ACTIVITY, Defs.EVT_HIDE_FAB, null) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) d("inflat menu api editor") inflater.inflate(R.menu.menu_api_editor, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == R.id.action_save) { doSave() } return super.onOptionsItemSelected(item) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { d("onCreateView") _binding = FragmentApieditorBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) d("onViewCreated") binding.httpMethodList = Defs.httpMethodList binding.api = ApiEditViewModel() } private fun doSave() { val editModel = binding.api if (editModel != null) { ApiManager.ins.apiRepo.save(Api.create(editModel)) Toast.makeText(requireContext(), "API Saved: " + editModel.name, Toast.LENGTH_SHORT).show() back() } else { Log.w("-DBG-", "api is null") } } override fun onDestroyView() { super.onDestroyView() _binding = null } }
0
Kotlin
0
0
b06b40cfdea8cb990b512c773c8d2fdb46102eac
2,461
APITest-Android
MIT License
compiler/testData/diagnostics/tests/callableReference/genericCallWithReferenceAgainstVarargAndKFunction.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
// FIR_IDENTICAL // !DIAGNOSTICS: -UNUSED_PARAMETER fun <A1> fun2(f: kotlin.reflect.KFunction1<A1, Unit>, a: A1) { f.invoke(a) } fun containsRegex(vararg otherPatterns: String) {} fun main() { fun2(::containsRegex, arrayOf("foo")) }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
244
kotlin
Apache License 2.0
app/src/main/java/org/stepik/android/data/unit/source/UnitRemoteDataSource.kt
ethnoby
302,438,362
true
{"Kotlin": 3023532, "Java": 995603, "CSS": 5370, "Shell": 618, "Prolog": 98}
package org.stepik.android.data.unit.source import io.reactivex.Maybe import io.reactivex.Single import ru.nobird.android.domain.rx.maybeFirst import org.stepik.android.model.Unit interface UnitRemoteDataSource { fun getUnit(unitId: Long): Maybe<Unit> = getUnits(unitId).maybeFirst() fun getUnits(vararg unitIds: Long): Single<List<Unit>> fun getUnitsByLessonId(lessonId: Long): Single<List<Unit>> fun getUnitsByCourseAndLessonId(courseId: Long, lessonId: Long): Single<List<Unit>> }
0
Kotlin
0
0
65d6850663f17724bc7bae8becf09347e7bc1f90
512
stepik-android
Apache License 2.0
v1/src/main/kotlin/com/example/forsubmit/global/redis/RedisProperties.kt
jhhong0509
433,380,334
false
{"Kotlin": 84514, "Groovy": 81151, "Vim Snippet": 690}
package com.example.forsubmit.global.redis import org.springframework.boot.context.properties.ConfigurationProperties import org.springframework.boot.context.properties.ConstructorBinding @ConstructorBinding @ConfigurationProperties(prefix = "spring.redis") class RedisProperties( var port: Int, val host: String )
5
Kotlin
4
29
3f8effaca61e6d8f328e3aca7356cbd1d67335b4
324
Kopring-Best-Practice
Apache License 2.0
frontend/app/src/main/java/kr/ac/kpu/lbs_platform/fragment/FollowerFragment.kt
Lenend-KPU
323,903,267
false
null
package kr.ac.kpu.lbs_platform.fragment import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import kr.ac.kpu.lbs_platform.R import kr.ac.kpu.lbs_platform.adapter.FollowerAdapter import kr.ac.kpu.lbs_platform.global.Profile import kr.ac.kpu.lbs_platform.global.RequestHelper import kr.ac.kpu.lbs_platform.poko.remote.FriendRequest class FollowerFragment(val selectedProfile: kr.ac.kpu.lbs_platform.poko.remote.Profile) : Fragment(), Invalidatable { lateinit var followerRecyclerView: RecyclerView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment val inflated = inflater.inflate(R.layout.fragment_follower, container, false) followerRecyclerView = inflated.findViewById(R.id.followerRecyclerView) followerRecyclerView.layoutManager = LinearLayoutManager(this.activity) getFriendsFromServer(followerRecyclerView) return inflated } fun getFriendsFromServer(recyclerView: RecyclerView) { Log.i(this::class.java.name, "getFriendsFromServer") val profileNumber = selectedProfile!!.pk RequestHelper.Builder(FriendRequest::class) .apply { this.currentFragment = this@FollowerFragment this.destFragment = null this.urlParameter = "profiles/$profileNumber/friends/" this.method = com.android.volley.Request.Method.GET this.onSuccessCallback = { Log.i("FollowerFragment", it.toString()) recyclerView.adapter = FollowerAdapter(it, this@FollowerFragment) } } .build() .request() } override fun invalidateRecyclerView() { getFriendsFromServer(followerRecyclerView) } }
0
Kotlin
1
16
76807894f65be1e9c9905ceb3c91b9235b1abf3e
2,214
LBS-Platform
MIT License
app/src/main/java/monkeylord/XServer/api/WsScript.kt
Krosxx
314,980,358
true
{"JavaScript": 359428, "Java": 268492, "HTML": 37311, "Kotlin": 16894}
package monkeylord.XServer.api import android.app.AndroidAppHelper import android.os.Handler import android.os.HandlerThread import bsh.ConsoleInterface import bsh.Interpreter import cn.vove7.rhino.RhinoHelper import cn.vove7.rhino.api.RhinoApi import monkeylord.XServer.XServer import monkeylord.XServer.XServer.wsOperation import monkeylord.XServer.utils.InteractiveInterpreter import monkeylord.XServer.utils.NanoHTTPD.IHTTPSession import monkeylord.XServer.utils.NanoWSD.WebSocket import monkeylord.XServer.utils.NanoWSD.WebSocketFrame import monkeylord.XServer.utils.NanoWSD.WebSocketFrame.CloseCode import org.json.JSONObject import java.io.* import java.text.SimpleDateFormat import java.util.* /** * # WsScript * * @author Vove * 2020/11/22 */ class WsScript : wsOperation { companion object { @JvmStatic val PATH = "/wsScript" private val engineThread by lazy { HandlerThread("WsScript").also { it.start() } } val engineHandler by lazy { Handler(engineThread.looper) } private val rhinoEngine by lazy { RhinoHelper( AndroidAppHelper.currentApplication(), XServer.classLoader, mapOf("app" to AndroidAppHelper.currentApplication()) ) } } private val beanShellEngine by lazy { val sink = PipedInputStream() val out = PrintStream(object : PipedOutputStream(sink) { override fun flush() { super.flush() val bs = ByteArray(sink.available()) sink.read(bs) ws?.trySend(String(bs)) } }) InteractiveInterpreter(Interpreter(object : ConsoleInterface { override fun getIn(): Reader? = null override fun getOut(): PrintStream = out override fun getErr(): PrintStream = out override fun println(p0: Any?) { ws?.trySend(p0.toString()) } override fun print(p0: Any?) { ws?.trySend(p0.toString()) } override fun error(p0: Any?) { ws?.trySend("ERR: " + p0.toString()) } })).apply { this.interpreter.classManager.setClassLoader(XServer.classLoader) } } private var ws: WebSocketHandler? = null private val sf = SimpleDateFormat("HH:mm:ss:SSS", Locale.getDefault()) val onPrint: Function2<Int, String?, Unit> = { l: Int, s: String? -> ws?.trySend("[$l] $s") } override fun handle(handshake: IHTTPSession?): WebSocket { ws = WebSocketHandler(handshake) return ws!! } fun handleMessage(data: String?) = engineHandler.post { kotlin.runCatching { val jsonData = JSONObject(data) val type = jsonData.getString("type") val script = jsonData.getString("script") when (type) { "js" -> { ws?.trySend(rhinoEngine.evalString(script, null as Array<*>?).toString()) } "bean-shell" -> { ws?.trySend(beanShellEngine.execute(script)) } else -> { ws?.trySend("unsupported type: $type") } } }.onFailure { val sw = StringWriter() it.printStackTrace(PrintWriter(sw)) ws?.trySend(sw.toString()) } } private inner class WebSocketHandler( handshakeRequest: IHTTPSession? ) : WebSocket(handshakeRequest) { fun trySend(payload: String?) { try { send(sf.format(Date()) + ": " + payload) } catch (e: IOException) { e.printStackTrace() } } override fun onMessage(message: WebSocketFrame) { handleMessage(message.textPayload) } override fun onOpen() { RhinoApi.regPrint(onPrint) trySend("Connect Success...") } override fun onClose(code: CloseCode, reason: String, initiatedByRemote: Boolean) { RhinoApi.unregPrint(onPrint) rhinoEngine.release() } override fun onPong(pong: WebSocketFrame) { } override fun onException(exception: IOException) { exception.printStackTrace() } } }
0
JavaScript
0
1
cfe198b7846ab6540a4544349a0961fa232984f0
4,460
XServer
MIT License
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/regular/LeafOne.kt
Konyaco
574,321,009
false
{"Kotlin": 11029508, "Java": 256912}
package com.konyaco.fluent.icons.regular import androidx.compose.ui.graphics.vector.ImageVector import com.konyaco.fluent.icons.Icons import com.konyaco.fluent.icons.fluentIcon import com.konyaco.fluent.icons.fluentPath public val Icons.Regular.LeafOne: ImageVector get() { if (_leafOne != null) { return _leafOne!! } _leafOne = fluentIcon(name = "Regular.LeafOne") { fluentPath { moveTo(13.24f, 3.27f) arcToRelative(1.75f, 1.75f, 0.0f, false, false, -2.48f, 0.0f) lineToRelative(-3.7f, 3.71f) arcToRelative(7.0f, 7.0f, 0.0f, false, false, 4.19f, 11.91f) verticalLineToRelative(2.36f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, 1.5f, 0.0f) verticalLineToRelative(-2.36f) arcTo(7.0f, 7.0f, 0.0f, false, false, 16.95f, 7.0f) lineToRelative(-3.71f, -3.72f) close() moveTo(12.75f, 17.38f) verticalLineToRelative(-5.63f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, -1.5f, 0.0f) verticalLineToRelative(5.63f) arcToRelative(5.5f, 5.5f, 0.0f, false, true, -3.14f, -9.34f) lineToRelative(3.71f, -3.7f) curveToRelative(0.1f, -0.1f, 0.26f, -0.1f, 0.36f, 0.0f) lineToRelative(3.7f, 3.7f) arcToRelative(5.5f, 5.5f, 0.0f, false, true, -3.13f, 9.34f) close() } } return _leafOne!! } private var _leafOne: ImageVector? = null
4
Kotlin
4
155
9e86d93bf1f9ca63a93a913c990e95f13d8ede5a
1,628
compose-fluent-ui
Apache License 2.0
compiler/testData/launcher/reflectionUsage.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
class Foo(val bar: String?) fun main() { try { if (Foo::bar.returnType.isMarkedNullable) { print("Foo#bar is nullable") } } catch (e: KotlinReflectionNotSupportedError) { print("no reflection") } }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
247
kotlin
Apache License 2.0
compiler/testData/diagnostics/tests/typealias/kt62099.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
// FIR_IDENTICAL // ISSUE: KT-62099 abstract class Foo<T> { inner class Inner abstract fun render(context: Inner) } typealias TA = Foo<String> class Test : TA() { override fun render(context: Inner) {} } typealias TA2<T> = Foo<T> class Test2 : TA2<String>() { override fun render(context: Inner) {} } typealias TA3<T> = Foo<T> typealias TA3_2<T> = TA3<T> class Test3 : TA3_2<String>() { override fun render(context: Inner) {} } typealias TA4<T> = Foo<T> typealias TA4_2 = TA4<String> class Test4 : TA4_2() { override fun render(context: Inner) {} }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
582
kotlin
Apache License 2.0
features/mpaccount/src/main/java/com/jpp/mpaccount/account/UserAccountMoviesView.kt
perettijuan
156,444,935
false
null
package com.jpp.mpaccount.account import android.content.Context import android.util.AttributeSet import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.constraintlayout.widget.ConstraintLayout import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.jpp.mpaccount.R import com.jpp.mpdesign.ext.inflate import com.jpp.mpdesign.ext.setInvisible import com.jpp.mpdesign.ext.setVisible import com.jpp.mpdesign.views.MPImageView /** * Custom [ConstraintLayout] used in the account section to show the list * of user's movies (Favorite, Rated and/or in WatchList) in a horizontal * list. */ class UserAccountMoviesView : ConstraintLayout { /** * Generic interface definition to load the list of items. */ interface UserAccountMovieItem { fun getImageUrl(): String } private var userAccountMoviesTitle: TextView? = null private var userAccountMoviesList: RecyclerView? = null private var userAccountMoviesError: TextView? = null private var userAccountMoviesMoreIv: ImageView? = null constructor(context: Context) : this(context, null) constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super( context, attrs, defStyleAttr ) { init() val typedArray = context.obtainStyledAttributes(attrs, R.styleable.UserAccountMoviesView) try { setTitle(typedArray.getText(R.styleable.UserAccountMoviesView_accountMoviesTitleText)) } finally { typedArray.recycle() } } private fun init() { inflate(context, R.layout.layout_user_account_movies, this) userAccountMoviesTitle = findViewById(R.id.userAccountMoviesTitle) userAccountMoviesList = findViewById(R.id.userAccountMoviesList) userAccountMoviesError = findViewById(R.id.userAccountMoviesError) userAccountMoviesMoreIv = findViewById(R.id.userAccountMoviesMoreIv) } fun setTitle(title: CharSequence) { userAccountMoviesTitle?.text = title } fun items(movies: List<UserAccountMovieItem>?) { if (movies == null) { return } userAccountMoviesList?.apply { layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false) adapter = AccountMovieAdapter(movies) setVisible() } userAccountMoviesError?.setInvisible() } fun errorMessage(message: Int) { if (message == 0) { return } userAccountMoviesMoreIv?.setInvisible() userAccountMoviesList?.setInvisible() userAccountMoviesError?.apply { setText(message) setVisible() } } class AccountMovieAdapter(private val items: List<UserAccountMovieItem>) : RecyclerView.Adapter<AccountMovieAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder = ViewHolder(parent.inflate(R.layout.list_item_user_account_movies)) override fun getItemCount(): Int = items.size override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind(items[position]) } class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { fun bind(item: UserAccountMovieItem) { val userAccountMoviesItemIv: MPImageView = itemView.findViewById(R.id.userAccountMoviesItemIv) userAccountMoviesItemIv.imageUrl(item.getImageUrl()) } } } }
9
Kotlin
7
46
7921806027d5a9b805782ed8c1cad447444f476b
3,774
moviespreview
Apache License 2.0
arrow-inject-compiler-plugin/src/testData/box/value-arguments/provider_supports_multiple_contexts.kt
arrow-kt
471,344,439
false
{"Kotlin": 173600, "Java": 16812, "Shell": 230}
package foo.bar import arrow.inject.annotations.Inject import foo.bar.annotations.Config import foo.bar.annotations.Given @Given @Config internal val z: String = "yes!" @Inject fun foo(@Given x: String, @Config y: String): String = "$x to $y" fun box(): String { val result = foo() return if (result == "yes! to yes!") { "OK" } else { "Fail: $result" } }
14
Kotlin
3
10
f2d62a93fa18fc7f2944687642c8ad01a0d23bf5
375
arrow-proofs
Apache License 2.0
mutekt-core/src/commonMain/kotlin/dev/shreyaspatil/mutekt/core/MutektState.kt
PatilShreyas
519,557,649
false
{"Kotlin": 59686}
/** * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shreyaspatil.mutekt.core import kotlinx.coroutines.flow.StateFlow /** * Represents the state model of type [STATE]. */ interface MutektState<STATE> { fun asStateFlow(): StateFlow<STATE> } /** * Represents mutable state. * * @property STATE Immutable State model type * @property MUTABLE_STATE Mutable State model type */ interface MutektMutableState<STATE, MUTABLE_STATE : STATE> : MutektState<STATE> { /** * Updates the [MUTABLE_STATE]. * * @param mutate A lambda block which allows to perform mutation on [MUTABLE_STATE]. */ fun update(mutate: MUTABLE_STATE.() -> Unit) }
6
Kotlin
6
248
a65dec0f6e4fd5e96b822a71fa32dfa7754cec2c
1,222
mutekt
Apache License 2.0
app/src/main/java/at/rtr/rmbt/android/ui/fragment/TestResultDetailFragment.kt
rtr-nettest
195,193,208
false
null
package at.rtr.rmbt.android.ui.fragment import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.View import androidx.core.content.ContextCompat import androidx.recyclerview.widget.DividerItemDecoration import at.rtr.rmbt.android.R import at.rtr.rmbt.android.databinding.FragmentTestResultDetailBinding import at.rtr.rmbt.android.di.viewModelLazy import at.rtr.rmbt.android.ui.adapter.TestResultDetailAdapter import at.rtr.rmbt.android.util.listen import at.rtr.rmbt.android.viewmodel.TestResultDetailViewModel import at.specure.data.entity.TestResultDetailsRecord class TestResultDetailFragment : BaseFragment() { private val testResultDetailViewModel: TestResultDetailViewModel by viewModelLazy() private val binding: FragmentTestResultDetailBinding by bindingLazy() private val adapter: TestResultDetailAdapter by lazy { TestResultDetailAdapter() } override val layoutResId = R.layout.fragment_test_result_detail override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.recyclerViewTestResultDetail.adapter = adapter binding.recyclerViewTestResultDetail.apply { val itemDecoration = DividerItemDecoration(context, DividerItemDecoration.VERTICAL) ContextCompat.getDrawable(context, R.drawable.history_item_divider)?.let { itemDecoration.setDrawable(it) } binding.recyclerViewTestResultDetail.addItemDecoration(itemDecoration) } testResultDetailViewModel.state.testUUID = arguments?.getString(KEY_TEST_UUID) ?: throw IllegalArgumentException("Please pass test UUID") testResultDetailViewModel.testResultDetailsLiveData.listen(this) { it.sortedByDescending { title -> title.title } adapter.items = it as MutableList<TestResultDetailsRecord> adapter.actionCallback = { detailResultItem -> if (!detailResultItem.openTestUUID.isNullOrEmpty() && !testResultDetailViewModel.openDataPrefix.isNullOrEmpty()) { val openDataLink = testResultDetailViewModel.openDataPrefix + detailResultItem.openTestUUID + "#noMMenu" val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(openDataLink)) startActivity(browserIntent) } } } } companion object { private const val KEY_TEST_UUID: String = "KEY_TEST_UUID" fun newInstance(testUUID: String): TestResultDetailFragment { val args = Bundle() args.putString(KEY_TEST_UUID, testUUID) val fragment = TestResultDetailFragment() fragment.arguments = args return fragment } } }
2
Kotlin
9
15
0faf5304a99bde8c9564cc69f98d33562e6a612a
2,829
open-rmbt-android
Apache License 2.0
mpcop/src/test/kotlin/cz/muni/fi/mpcop/AsyncTest.kt
KristianMika
306,865,791
false
{"TypeScript": 109116, "Java": 79392, "Kotlin": 64008, "Shell": 3593, "HTML": 1717, "CSS": 1203, "Dockerfile": 1181, "Makefile": 97}
package cz.muni.fi.mpcop import io.vertx.core.DeploymentOptions import io.vertx.core.Verticle import io.vertx.core.Vertx import io.vertx.core.http.HttpClient import io.vertx.kotlin.coroutines.await import io.vertx.kotlin.coroutines.dispatcher import kotlinx.coroutines.runBlocking import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import kotlin.reflect.KClass /** * The basic async test class * Inspired by <NAME>'s article: * https://dev.to/wowselim/writing-async-tests-for-vert-x-using-kotlin-1ck6 */ abstract class AsyncTest( val vertx: Vertx, private val verticleClass: KClass<out Verticle>, private val deploymentOptions: DeploymentOptions = DeploymentOptions() ) { private lateinit var deploymentId: String protected val httpClient: HttpClient by lazy { vertx.createHttpClient() } open fun deployVerticle(): String = runBlocking(vertx.dispatcher()) { vertx.deployVerticle(verticleClass.java, deploymentOptions).await() } @BeforeEach fun assignDeploymentId() { deploymentId = deployVerticle() } @AfterEach fun undeployVerticle(): Unit = runBlocking(vertx.dispatcher()) { vertx.undeploy(deploymentId).await() } protected fun runTest(block: suspend () -> Unit): Unit = runBlocking<Unit>(vertx.dispatcher()) { block() } }
0
TypeScript
0
1
4d4d9f3ae41789ee02b3ac211b6a4c166516ef8b
1,359
MPC-Open-Platform
MIT License
remote-jvm-jedis/src/main/kotlin/br/com/devsrsouza/eventkt/jvm/jedis/JedisEventScope.kt
DevSrSouza
222,123,103
false
null
package br.com.devsrsouza.eventkt.jvm.jedis import br.com.devsrsouza.eventkt.remote.RemoteEncoder import br.com.devsrsouza.eventkt.remote.RemoteEventScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import redis.clients.jedis.Jedis import redis.clients.jedis.JedisPubSub class JedisEventScope( override val enconder: RemoteEncoder<String>, val subscribeJedis: Jedis, val publisherJedis: Jedis, val channelName: String = "br.com.devsrsouza.eventkt" ) : RemoteEventScope<String>() { private val pubSub = object : JedisPubSub() { override fun onMessage(channel: String, message: String) { if(channelName == channel) { try { publishFromRemote(message) }catch (e: Throwable) { /* Ignore */} } } } init { Thread { subscribeJedis.subscribe(pubSub, channelName) }.start() } override fun publishToRemote(value: String, eventUniqueId: String) { // TODO: use eventUniqueId launch(Dispatchers.IO) { publisherJedis.publish(channelName, value) } } }
0
Kotlin
2
47
530fd6d8ed9dd95a418dacb276ff90f7940722c4
1,161
EventKt
MIT License
ant/src/org/jetbrains/kotlin/ant/Kotlin2JsTask.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
/* * Copyright 2010-2015 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 org.jetbrains.kotlin.ant import org.apache.tools.ant.types.Path import java.io.File class Kotlin2JsTask : KotlinCompilerBaseTask() { override val compilerFqName = "org.jetbrains.kotlin.cli.js.K2JSCompiler" var libraries: Path? = null var outputPrefix: File? = null var outputPostfix: File? = null var sourceMap: Boolean = false var metaInfo: Boolean = false var moduleKind: String = "plain" /** * {@link K2JsArgumentConstants.CALL} (default) if need generate a main function call (main function will be auto detected) * {@link K2JsArgumentConstants.NO_CALL} otherwise. */ var main: String? = null fun createLibraries(): Path { val libraryPaths = libraries ?: return Path(getProject()).also { libraries = it } return libraryPaths.createPath() } override fun fillSpecificArguments() { args.add("-output") args.add(output!!.canonicalPath) // TODO: write test libraries?.let { args.add("-libraries") args.add(it.list().joinToString(File.pathSeparator) { File(it).canonicalPath }) } outputPrefix?.let { args.add("-output-prefix") args.add(it.canonicalPath) } outputPostfix?.let { args.add("-output-postfix") args.add(it.canonicalPath) } main?.let { args.add("-main") args.add(it) } if (noStdlib) args.add("-no-stdlib") if (sourceMap) args.add("-source-map") if (metaInfo) args.add("-meta-info") args += listOf("-module-kind", moduleKind) } }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
2,258
kotlin
Apache License 2.0
pluto-plugins/plugins/datastore/lib-no-op/src/main/java/com/pluto/plugins/datastore/pref/PlutoDatastoreWatcher.kt
androidPluto
390,471,457
false
{"Kotlin": 726093, "Shell": 646}
package com.pluto.plugins.datastore.pref import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences @Suppress("UnusedPrivateMember", "EmptyFunctionBlock") object PlutoDatastoreWatcher { fun watch(name: String, store: DataStore<Preferences>) { } // noop fun remove(name: String) { } // noop }
21
Kotlin
63
630
b8425e69bd9fea4427c4aa8b732cafaa14300054
339
pluto
Apache License 2.0
src/main/kotlin/io/finnhub/api/models/MarketHolidayData.kt
Finnhub-Stock-API
275,674,325
false
{"Kotlin": 596317, "Shell": 333}
/** * Finnhub API * * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1.0.0 * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. */ @file:Suppress( "ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport" ) package io.finnhub.api.models import com.squareup.moshi.Json import java.io.Serializable /** * * * @param eventName Holiday's name. * @param atDate Date. * @param tradingHour Trading hours for this day if the market is partially closed only. */ data class MarketHolidayData ( /* Holiday's name. */ @Json(name = "eventName") val eventName: kotlin.String? = null, /* Date. */ @Json(name = "atDate") val atDate: kotlin.String? = null, /* Trading hours for this day if the market is partially closed only. */ @Json(name = "tradingHour") val tradingHour: kotlin.String? = null ) : Serializable { companion object { private const val serialVersionUID: Long = 123 } }
1
Kotlin
8
29
6b85f7f81c720db4cec39a21c8099d034dd06989
1,180
finnhub-kotlin
Apache License 2.0
InPlayer/src/main/java/com/sdk/inplayer/mapper/account/InPlayerCredentialsMapper.kt
inplayer-org
161,477,099
false
null
package com.sdk.inplayer.mapper.account import com.sdk.domain.entity.account.CredentialsEntity import com.sdk.domain.entity.mapper.DomainMapper import com.sdk.inplayer.model.account.InPlayerCredentials internal class InPlayerCredentialsMapper : DomainMapper<CredentialsEntity, InPlayerCredentials> { override fun mapFromDomain(domainEntity: CredentialsEntity): InPlayerCredentials { return InPlayerCredentials(accessToken = domainEntity.accessToken, refreshToken = domainEntity.refreshToken) } override fun mapToDomain(viewModel: InPlayerCredentials): CredentialsEntity { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } }
3
Kotlin
0
5
b604c08c35143cb3e8b15ad99876a08dad0efb13
720
inplayer-android-sdk
MIT License
app/src/main/java/com/leizy/demo/test2/TestModel2.kt
Leizxy
223,341,470
false
null
package com.leizy.demo.test2 import android.util.Log import cn.leizy.lib.http.bean.HttpResponse import cn.leizy.lib.http.bean.LoginBean import cn.leizy.lib.http.bean.TestObj import cn.leizy.lib.retrofit.RetrofitUtil import cn.leizy.lib.retrofit.SuspendApi import cn.leizy.lib.retrofit.SuspendInterface import com.leizy.demo.test.TestContract /** * @author Created by wulei * @date 2020/9/28, 028 * @description */ class TestModel2 : CoroutinesModel(), TestContract.Model { override fun test(): Int { val params: MutableMap<String, Any> = HashMap() params["Moblie"] = "13245678978" params["MT"] = "" params["Password"] = "<PASSWORD>" params["Regid"] = "<PASSWORD>" launchRequest( { SuspendApi.getService(SuspendInterface::class.java) .login2(RetrofitUtil.getRequestBody(params)).await() }, { Log.i("TestModel2", "test: ") }/*, { err: String? -> Log.i("TestModel2", "test: $err") }*/) return 0 } override suspend fun test2(params: MutableMap<String, Any>): HttpResponse<LoginBean>? { return null } }
0
Kotlin
0
0
7f3a0cd0343fd851f4d4accbe5ab65ebd3af6bd8
1,218
MyKotlinMVP
MIT License
src/commonMain/kotlin/org/jetbrains/projector/common/protocol/data/PaintType.kt
SerVB
408,826,505
false
{"Kotlin": 192506}
package org.jetbrains.projector.common.protocol.data import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable enum class PaintType { @SerialName("a") DRAW, @SerialName("b") FILL, }
0
Kotlin
0
10
a933f6fb4cca2d3a8d8ab5eebb307dce3e3b6df4
231
korjector
MIT License
app/src/main/java/com/example/ez_tour/AppinfoActivity.kt
heuzz
376,480,666
false
null
package com.example.ez_tour import android.os.Bundle import android.widget.Button import android.widget.ImageButton import androidx.appcompat.app.AppCompatActivity class AppinfoActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_appinfo) val btn_back2 = findViewById<Button>(R.id.btn_back2) as ImageButton btn_back2.setOnClickListener { finish() } } }
0
Kotlin
0
0
c6d1a158de54f0b6e83467bc74969fc2b05861a4
520
niticecheck
Apache License 2.0
shared/src/commonMain/kotlin/composables/screens/create/models/DebtDirection.kt
SergStas
697,631,567
false
{"Kotlin": 97295, "Swift": 592, "Shell": 228}
package composables.screens.create.models enum class DebtDirection { ToPay, ToReceive; fun switch() = if (this == ToReceive) ToPay else ToReceive }
0
Kotlin
0
0
c196d27ec39b537433b0952acfd94e160ac23ca1
157
DebtsTrackerCompose
Apache License 2.0
lib-encrypt/src/main/java/com/codearms/maoqiqi/utils/DateUtils.kt
maoqiqi
332,238,518
false
null
package com.codearms.maoqiqi.utils object DateUtils { const val format_y = "yyyy" const val format_m = "MM" const val format_dd = "dd" const val format_hh = "HH" const val format_mm = "mm" const val format_ss = "ss" const val format_hh_mm = "HH:mm" const val format_h_mm_a = "h:mm a" const val format_hh_mm_ss = "HH:mm:ss" const val format_yyyy_mm_dd = "yyyy-MM-dd" const val format_yyyy_mm_dd_hh_mm = "yyyy-MM-dd HH:mm" const val format_yyyy_mm_dd_hh_mm_ss = "yyyy-MM-dd HH:mm:ss" const val format_yyyy_mm_dd_hh_mm_ss_ = "yyyy年MM月dd日 HH时mm分ss秒" /** * Get the current timestamp (accurate to seconds) * @return the current timestamp */ @JvmStatic fun getTimeStamp() = System.currentTimeMillis() }
0
Kotlin
0
0
c16b01503bf9a4bc854718a3ee9f31d2024886e6
789
AndroidLibraries
Apache License 2.0
plugins/world/player/skill/crafting/armorCrafting/HideArmor.kt
luna-rs
41,239,479
false
{"Java": 925616, "Kotlin": 290856, "CSS": 129}
package world.player.skill.crafting.armorCrafting import api.predef.* import com.google.common.collect.ArrayListMultimap import io.luna.game.model.item.Item import world.player.skill.crafting.hideTanning.Hide /** * An enum representing armor that can be crafted from [Hide]s. */ enum class HideArmor(val id: Int, val level: Int, val exp: Double, val hides: Pair<Hide, Int>? = null) { LEATHER_GLOVES(id = 1059, level = 1, exp = 13.8, hides = Pair(Hide.SOFT_LEATHER, 1)), LEATHER_BOOTS(id = 1061, level = 7, exp = 16.25, hides = Pair(Hide.SOFT_LEATHER, 1)), LEATHER_COWL(id = 1167, level = 9, exp = 25.0, hides = Pair(Hide.SOFT_LEATHER, 1)), LEATHER_VAMBRACES(id = 1063, level = 11, exp = 22.0, hides = Pair(Hide.SOFT_LEATHER, 1)), LEATHER_BODY(id = 1129, level = 14, exp = 25.0, hides = Pair(Hide.SOFT_LEATHER, 1)), LEATHER_CHAPS(id = 1095, level = 18, exp = 27.0, hides = Pair(Hide.SOFT_LEATHER, 1)), HARD_LEATHER_BODY(id = 1131, level = 28, exp = 35.0, hides = Pair(Hide.HARD_LEATHER, 1)), COIF(id = 1169, level = 38, exp = 37.0, hides = Pair(Hide.SOFT_LEATHER, 1)), STUDDED_BODY(id = 1133, level = 41, exp = 40.0), STUDDED_CHAPS(id = 1097, level = 44, exp = 42.0), SNAKESKIN_BOOTS(id = 6328, level = 45, exp = 30.0, hides = Pair(Hide.SNAKESKIN, 6)), SNAKESKIN_BRACE(id = 6330, level = 47, exp = 35.0, hides = Pair(Hide.SNAKESKIN, 8)), SNAKESKIN_BANDANA(id = 6326, level = 48, exp = 45.0, hides = Pair(Hide.SNAKESKIN, 5)), SNAKESKIN_CHAPS(id = 6324, level = 51, exp = 50.0, hides = Pair(Hide.SNAKESKIN, 12)), SNAKESKIN_BODY(id = 6322, level = 53, exp = 55.0, hides = Pair(Hide.SNAKESKIN, 15)), GREEN_DHIDE_VAMBRACES(id = 1065, level = 57, exp = 62.0, hides = Pair(Hide.GREEN_D_LEATHER, 1)), GREEN_DHIDE_CHAPS(id = 1099, level = 60, exp = 124.0, hides = Pair(Hide.GREEN_D_LEATHER, 2)), GREEN_DHIDE_BODY(id = 1135, level = 63, exp = 186.0, hides = Pair(Hide.GREEN_D_LEATHER, 3)), BLUE_DHIDE_VAMBRACES(id = 2487, level = 66, exp = 70.0, hides = Pair(Hide.BLUE_D_LEATHER, 1)), BLUE_DHIDE_CHAPS(id = 2493, level = 68, exp = 140.0, hides = Pair(Hide.BLUE_D_LEATHER, 2)), BLUE_DHIDE_BODY(id = 2499, level = 71, exp = 210.0, hides = Pair(Hide.BLUE_D_LEATHER, 3)), RED_DHIDE_VAMBRACES(id = 2489, level = 73, exp = 78.0, hides = Pair(Hide.RED_D_LEATHER, 1)), RED_DHIDE_CHAPS(id = 2495, level = 75, exp = 156.0, hides = Pair(Hide.RED_D_LEATHER, 2)), RED_DHIDE_BODY(id = 2501, level = 77, exp = 234.0, hides = Pair(Hide.RED_D_LEATHER, 3)), BLACK_DHIDE_VAMBRACES(id = 2491, level = 79, exp = 86.0, hides = Pair(Hide.BLACK_D_LEATHER, 1)), BLACK_DHIDE_CHAPS(id = 2497, level = 82, exp = 172.0, hides = Pair(Hide.BLACK_D_LEATHER, 2)), BLACK_DHIDE_BODY(id = 2503, level = 84, exp = 258.0, hides = Pair(Hide.BLACK_D_LEATHER, 3)); companion object { /** * Mappings of [HideArmor.id] to [HideArmor]. */ val ID_TO_ARMOR = values().associateBy { it.id } /** * Mappings of [Hide] to [IntArray]. */ val HIDE_TO_ARMOR = run { val map = ArrayListMultimap.create<Hide, Int>() for (armor in values()) { map.put(armor.hides?.first ?: Hide.SOFT_LEATHER, armor.id) } map.asMap().entries.map { it.key to it.value.toIntArray() }.toMap() } } /** * The armor item. */ val armorItem = Item(id) /** * The hides item. */ val hidesItem = when (hides) { null -> null else -> Item(hides.first.tan, hides.second) } /** * The formatted name. */ val formattedName = itemDef(id).name.toLowerCase() }
52
Java
43
147
16b40c4f4228a5627d1a188e9ef2e2905feedefe
5,315
luna
MIT License
src/main/kotlin/com/plugin/frege/annotator/FregeWarningAnnotator.kt
IntelliJ-Frege
343,041,006
false
null
package com.plugin.frege.annotator import com.intellij.codeInsight.intention.IntentionAction import com.intellij.lang.annotation.AnnotationHolder import com.intellij.lang.annotation.Annotator import com.intellij.lang.annotation.HighlightSeverity import com.intellij.psi.PsiElement import com.plugin.frege.psi.FregeStrongPackage import com.plugin.frege.intentions.FregePackageToModuleIntentionAction class FregeWarningAnnotator : Annotator { override fun annotate(element: PsiElement, holder: AnnotationHolder) { if (element is FregeStrongPackage) { annotateWithWeakWarning( element, holder, "It's not recommended to use the 'package' keyword", FregePackageToModuleIntentionAction(element) ) } } private fun annotateWithWeakWarning( element: PsiElement, holder: AnnotationHolder, message: String, intentionAction: IntentionAction? ) { val builder = holder.newAnnotation(HighlightSeverity.WEAK_WARNING, message) if (intentionAction != null) { builder.withFix(intentionAction) } builder.range(element) builder.create() } }
25
Kotlin
0
39
20c3653b79b0d9c45c32d44b30f3cc6bbe275727
1,231
intellij-frege
Apache License 2.0
app/src/main/java/com/example/twittercompose/ui/composables/image/CircularImage.kt
SharmaPrateek196
374,036,055
false
null
package com.example.twittercompose.ui.composables.image import androidx.compose.foundation.Image import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.unit.dp import com.example.twittercompose.R import com.example.twittercompose.ui.theme.circularShape import com.google.accompanist.coil.rememberCoilPainter @Composable fun CircularImage( imageResource: String, modifier: Modifier, imageViewSize: Int ) { Image( painter = rememberCoilPainter(request = imageResource, previewPlaceholder = R.drawable.twitter_logo) , null, contentScale = ContentScale.Crop, modifier = modifier .size(imageViewSize.dp) .clip( shape = circularShape ), ) }
0
Kotlin
1
3
c15d1fec3d2fe166f402d2c991245fa6ce5274d0
922
JetTwitterClone
Apache License 2.0
backend/src/main/kotlin/com/planetsf/clubhouse/controller/ChallengesController.kt
mrmaandi
322,327,619
false
{"TypeScript": 91813, "Kotlin": 15024, "SCSS": 5468, "JavaScript": 3595, "Less": 893, "HTML": 687, "Dockerfile": 172}
package com.planetsf.clubhouse.controller import com.planetsf.clubhouse.dto.ChallengeDto import com.planetsf.clubhouse.service.ChallengesService import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController @RestController @RequestMapping("challenges") class ChallengesController(private val challengesService: ChallengesService) { @GetMapping fun getChallenges(): List<ChallengeDto> { return challengesService.getChallenges() } /* @PostMapping("/add-challenge") fun addChallenge(@RequestBody requestBody: AddChallengeRequest) { return challengesService.addChallenge(requestBody) }*/ }
0
TypeScript
0
1
efa9045dfaf12c3752d19bfea3a18693cdaef2aa
748
clubhouse
MIT License
temp-test/src/jsMain/kotlin/client.kt
dss99911
138,060,985
false
{"Kotlin": 356216, "Swift": 24520, "Ruby": 6567, "Shell": 4020}
import react.dom.render import kotlinx.browser.document import kotlinx.browser.window fun main() { window.onload = { render(document.getElementById("root")) { child(Welcome::class) { attrs { name = "Kotlin/JS" } } } } }
2
Kotlin
2
38
e9da57fdab9c9c1169fab422fac7432143e2c02c
321
kotlin-simple-architecture
Apache License 2.0