path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fc-webflux/webflux-examples/examples/kotlin-coroutine/src/main/kotlin/com/grizz/wooman/coroutine/advanced/ChannelConflatedExample.kt | devYSK | 461,887,647 | false | {"Java": 3507759, "JavaScript": 659549, "Kotlin": 563136, "HTML": 455168, "CSS": 446825, "Shell": 57444, "Groovy": 54414, "Batchfile": 47890, "Go": 26805, "Python": 9963, "Handlebars": 8554, "Makefile": 7837, "Vue": 5706, "TypeScript": 5172, "Dockerfile": 436, "Vim Snippet": 362, "Assembly": 278, "Procfile": 199} | package com.grizz.wooman.coroutine.advanced
import com.grizz.wooman.coroutine.help.kLogger
import com.grizz.wooman.coroutine.help.logger
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
private val log = kLogger()
fun main() {
runBlocking {
val channel = Channel<Int>(Channel.Factory.CONFLATED)
launch(Dispatchers.IO) {
channel.send(1)
log.info("sent 1")
channel.send(2)
log.info("sent 2")
channel.send(3)
log.info("sent 3")
channel.close()
}
for (i in channel) {
delay(100)
log.info("value: {}", channel.receive())
}
}
} | 1 | null | 1 | 1 | 7a7c6b1bab3dc2c84527f8c528b06b9408872635 | 861 | study_repo | MIT License |
app/src/main/java/com/foreveross/atwork/modules/meeting/route/manager/MeetingRouteActionProducer.kt | AoEiuV020 | 421,650,297 | false | {"Java": 8618305, "Kotlin": 1733509, "JavaScript": 719597, "CSS": 277438, "HTML": 111559} | package com.foreveross.atwork.modules.meeting.route.manager
import com.foreveross.atwork.modules.meeting.route.JoinMeetingRouteAction
import com.foreveross.atwork.modules.route.action.RouteAction
import com.foreveross.atwork.modules.route.manager.IRouteActionProducer
import com.foreveross.atwork.modules.route.model.RouteParams
class MeetingRouteActionProducer: IRouteActionProducer {
override fun produce(routeParams: RouteParams): RouteAction? {
val uri = routeParams.getUri()
val type = uri?.getQueryParameter("type")
val action = uri?.getQueryParameter("action")
when(type) {
"umeeting" -> {
when(action) {
"join" -> {
return JoinMeetingRouteAction(routeParams)
}
}
}
"bizconf", "zoom" -> {
when(action) {
"join" -> {
return JoinMeetingRouteAction(routeParams)
}
}
}
}
return null
}
} | 1 | null | 1 | 1 | 1c4ca5bdaea6d5230d851fb008cf2578a23b2ce5 | 1,096 | w6s_lite_android | MIT License |
edusdk-api/src/main/kotlin/io/agora/education/api/manager/EduManager.kt | jiayanana | 385,456,456 | false | {"Java": 490767, "Kotlin": 317412, "Python": 1650} | package io.agora.education.api.manager
import android.app.Activity
import android.text.TextUtils
import io.agora.education.api.BuildConfig
import io.agora.education.api.EduCallback
import io.agora.education.api.base.EduError
import io.agora.education.api.logger.DebugItem
import io.agora.education.api.logger.LogLevel
import io.agora.education.api.manager.listener.EduManagerEventListener
import io.agora.education.api.room.EduRoom
import io.agora.education.api.room.data.RoomCreateOptions
import io.agora.rte.RteEngineImpl
/**0代表正常
* 1-10 本地错误code
* 101 RTM错误-通信错误
* 201 RTC错误-媒体错误
* 301 HTTP错误-网络错误*/
abstract class EduManager(
val options: EduManagerOptions
) {
companion object {
val TAG = EduManager::class.java.simpleName
/**创建EduManager 和 登录rtm
* code:message
* 1:parameter XXX is invalid
* 2:internal error:可以内部订阅具体什么错误
* 101:communication error:code,透传rtm错误code。
* 301:network error,透传后台错误msg字段*/
@JvmStatic
fun init(options: EduManagerOptions, callback: EduCallback<EduManager>) {
if (TextUtils.isEmpty(options.appId)) {
callback.onFailure(EduError.parameterError("appId"))
return
}
if (TextUtils.isEmpty(options.customerId)) {
callback.onFailure(EduError.parameterError("customerId"))
return
}
if (TextUtils.isEmpty(options.customerCertificate)) {
callback.onFailure(EduError.parameterError("customerCertificate"))
return
}
if (TextUtils.isEmpty(options.userUuid)) {
callback.onFailure(EduError.parameterError("userUuid"))
return
}
if (TextUtils.isEmpty(options.userName)) {
callback.onFailure(EduError.parameterError("userName"))
return
}
val cla = Class.forName("io.agora.education.impl.manager.EduManagerImpl")
val eduManager = cla.getConstructor(EduManagerOptions::class.java).newInstance(options) as EduManager
val methods = cla.methods
val iterator = methods.iterator()
while (iterator.hasNext()) {
val element = iterator.next()
if (element.name == "login") {
element.invoke(eduManager, options.userUuid, object : EduCallback<Unit> {
override fun onSuccess(res: Unit?) {
callback.onSuccess(eduManager)
}
override fun onFailure(error: EduError) {
callback.onFailure(error)
}
})
}
}
}
fun version(): String {
return RteEngineImpl.version().plus(".").plus(BuildConfig.SDK_VERSION)
}
}
var eduManagerEventListener: EduManagerEventListener? = null
abstract fun createClassroom(config: RoomCreateOptions): EduRoom?
abstract fun release()
/**code:message
* 1:parameter XXX is invalid
* 2:internal error:可以内部订阅具体什么错误*/
abstract fun logMessage(message: String, level: LogLevel): EduError
/**日志上传之后,会通过回调把serialNumber返回
* serialNumber:日志序列号,可以用于查询日志
* code:message
* 1:parameter XXX is invalid
* 2:internal error:可以内部订阅具体什么错误
* 301:network error,透传后台错误msg字段*/
abstract fun uploadDebugItem(item: DebugItem, callback: EduCallback<String>): EduError
}
| 1 | null | 1 | 1 | 5d0632ad1b3d1a76009978b1f0b49e56a0cab76a | 3,554 | eEducation-Android | MIT License |
Application-Challenge/【Dooze】CircleLive/app/src/main/java/com/dong/circlelive/live/model/LiveChannel.kt | AgoraIO-Community | 355,093,340 | false | {"Ignore List": 167, "Markdown": 122, "Gradle": 122, "Java Properties": 55, "Shell": 53, "Batchfile": 22, "Proguard": 69, "Java": 1189, "XML": 1726, "INI": 44, "C": 158, "C++": 988, "CMake": 25, "HTML": 797, "CSS": 246, "JavaScript": 1271, "PHP": 209, "SVG": 100, "Text": 103, "YAML": 78, "Python": 413, "JSON": 363, "EditorConfig": 9, "Browserslist": 6, "Vue": 137, "Less": 172, "Microsoft Visual Studio Solution": 2, "Unity3D Asset": 3701, "C#": 572, "ShaderLab": 40, "GLSL": 42, "HLSL": 6, "JSON with Comments": 9, "Git Attributes": 5, "SCSS": 81, "Kotlin": 915, "GraphQL": 7, "Dockerfile": 9, "Prisma": 1, "TOML": 3, "SQL": 4, "TSX": 81, "EJS": 5, "Ruby": 7, "OpenStep Property List": 55, "Objective-C": 2089, "Makefile": 753, "D": 1, "Swift": 37, "Pug": 3, "ABNF": 1, "Git Config": 2, "Go": 68, "Go Checksums": 1, "Go Module": 1, "robots.txt": 5, "Fluent": 3, "Dart": 31, "AIDL": 13, "Gradle Kotlin DSL": 5, "Groovy": 1, "Rust": 5, "Nginx": 3, "Objective-C++": 7, "Handlebars": 24, "Procfile": 1, "Dotenv": 3, "Hack": 1, "ApacheConf": 2, "Blade": 2, "Gettext Catalog": 1, "CoffeeScript": 12, "Cython": 9, "Starlark": 1, "Wavefront Object": 9, "Java Server Pages": 2, "Smarty": 4, "QMake": 1} | package com.dong.circlelive.live.model
import androidx.lifecycle.MutableLiveData
import cn.leancloud.AVObject
import cn.leancloud.AVQuery
import cn.leancloud.AVUser
import cn.leancloud.annotation.AVClassName
import com.dong.circlelive.base.Timber
import com.dong.circlelive.live
import com.dong.circlelive.rtc.LiveRtmChannel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.util.concurrent.ConcurrentHashMap
/**
* Create by dooze on 2021/5/18 8:06 下午
* Email: <EMAIL>
* Description:
*/
val subscriberChannels = mutableMapOf<String, SubscriberChannel>()
val subscriberChannelMessages = ConcurrentHashMap<String, LiveMessage>()
val subscriberChannelMessagesLD = MutableLiveData<String>()
val subscriberUpdate = MutableLiveData<Boolean>()
const val MAX_SUBSCRIBER_CHANNEL = 5
class SubscriberChannel(val id: String, val liveChannel: LiveChannel)
class ChannelComparator : Comparator<LiveChannel> {
override fun compare(o1: LiveChannel?, o2: LiveChannel?): Int {
if (o1 == null || o2 == null) return 0
if (o1.isSubscriber && !o2.isSubscriber) return -1
if (!o1.isSubscriber && o2.isSubscriber) return 1
return (o2.updateAt - o1.updateAt).toInt()
}
}
@AVClassName("LiveChannel")
class LiveChannel(private val avObject: AVObject) {
val creator: AVUser
get() = avObject.getAVObject("creator")
val id: String
get() = avObject.objectId
val name: String
get() = avObject.getString("name")
val desc: String
get() = avObject.getString("desc")
val status: Int
get() = avObject.getInt("status")
val livingTimes: Long
get() = avObject.getLong("livingTimes")
val updateAt: Long
get() = avObject.updatedAt.time
val isSelf: Boolean get() = creator.objectId == AVUser.currentUser().objectId
val isSubscriber: Boolean get() = subscriberChannels.containsKey(id)
suspend fun subscriber(): Boolean {
if (subscriberChannels.size >= MAX_SUBSCRIBER_CHANNEL) return false
withContext(Dispatchers.IO) {
val avObject = AVObject("SubscribeLiveChannel").apply {
put("creator", AVUser.currentUser())
put("liveChannel", avObject)
}
avObject.save()
subscriberChannels[id] = SubscriberChannel(avObject.objectId, this@LiveChannel)
live.liveRtmChannels[id] = LiveRtmChannel(channelId = id, name).apply {
startAsync()
}
}
return true
}
suspend fun unSubscriber(uiInvoke: () -> Unit) {
val channel = subscriberChannels.remove(id) ?: return
uiInvoke.invoke()
withContext(Dispatchers.IO) {
AVObject.createWithoutData("SubscribeLiveChannel", channel.id).delete()
live.liveRtmChannels[id]?.leave()
}
}
fun delete() {
val cid = id
avObject.delete()
subscriberChannels[cid]?.id?.let {
AVObject.createWithoutData("SubscribeLiveChannel", it).delete()
}
subscriberChannels.remove(cid)
}
suspend fun incLivingTimes() = withContext(Dispatchers.IO) {
avObject.increment("livingTimes", 1)
avObject.saveEventually()
}
companion object
}
suspend fun LiveChannel.Companion.syncSubscriberChannel(): List<SubscriberChannel> {
val user = AVUser.currentUser()
val avQuery = AVQuery<AVObject>("SubscribeLiveChannel")
avQuery.cachePolicy = AVQuery.CachePolicy.NETWORK_ELSE_CACHE
avQuery.include("liveChannel")
avQuery.orderByDescending("updatedAt")
avQuery.whereEqualTo("creator", user)
val list = withContext(Dispatchers.IO) {
val res = mutableListOf<SubscriberChannel>()
avQuery.find().forEach {
val liveChannel = LiveChannel(it.getAVObject("liveChannel") ?: return@forEach)
val subscriberChannel = SubscriberChannel(it.objectId, liveChannel)
subscriberChannels[liveChannel.id] = subscriberChannel
res.add(subscriberChannel)
}
res
}
subscriberUpdate.postValue(true)
return list
}
suspend fun LiveChannel.Companion.fetch(owner: AVObject? = null): List<LiveChannel> = withContext(Dispatchers.IO) {
val avQuery = AVQuery<AVObject>("LiveChannel")
avQuery.cachePolicy = AVQuery.CachePolicy.NETWORK_ELSE_CACHE
avQuery.include("creator")
if (owner != null) {
avQuery.whereEqualTo("creator", owner)
}
avQuery.orderByDescending("updatedAt")
val list = avQuery.find().map { LiveChannel(it) }.toMutableList()
list.sortWith(ChannelComparator())
list
}
suspend fun LiveChannel.Companion.publish(title: String, desc: String): String = withContext(Dispatchers.IO) {
val avObject = AVObject("LiveChannel").apply {
put("creator", AVUser.currentUser())
put("name", title)
put("desc", desc)
}
avObject.save()
avObject.objectId
}
| 1 | null | 1 | 1 | 558c96cf0f029fb02188ca83f60920c89afd210f | 4,977 | RTE-2021-Innovation-Challenge | MIT License |
app/src/main/java/com/example/todo/TodoModel.kt | mist232 | 809,101,270 | false | {"Gradle Kotlin DSL": 3, "Java Properties": 3, "Shell": 1, "Text": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "JSON": 2, "Kotlin": 9, "XML": 24, "Java": 21} | package com.example.todo
import androidx.room.Entity
import androidx.room.PrimaryKey
// we are making list for each task
@Entity
data class TodoModel(
var title:String,
var category: String,
var date:Long,
var time:Long,
var isFinished : Int = 0,
@PrimaryKey(autoGenerate = true)
var id:Long = 0
)
| 0 | Java | 0 | 0 | 3adc8364fb00b686f274579aa11b4b002abff67a | 328 | ToDo | Apache License 2.0 |
Kotlin/App.Coroutine/app/src/main/java/com/sercan/coroutines/ScopeCoroutines.kt | sebetci | 499,716,185 | false | {"Java": 294457, "Kotlin": 194532} | package com.sercan.coroutines
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
fun main() {
runBlocking {
launch {
delay(5000)
println("Run blocking running")
}
coroutineScope {
launch {
delay(3000)
println("Coroutine scope running")
}
}
}
} | 1 | null | 1 | 1 | 5d75faf7f4ca8ee74398280a49e6ed7d9881ee17 | 459 | Android-Apps | MIT License |
fxgl/src/main/kotlin/com/almasb/fxgl/service/impl/display/DialogPane.kt | blixenkrone | 86,496,399 | true | {"YAML": 2, "Maven POM": 11, "Markdown": 14, "Text": 10, "Ignore List": 1, "Java": 611, "Kotlin": 172, "kvlang": 1, "Java Properties": 3, "XML": 12, "CSS": 7, "JavaScript": 5, "Ragel": 1, "JSON": 3} | /*
* The MIT License (MIT)
*
* FXGL - JavaFX Game Library
*
* Copyright (c) 2015-2017 AlmasB (<EMAIL>)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.almasb.fxgl.service.impl.display
import com.almasb.fxgl.app.FXGL
import com.almasb.fxgl.scene.FXGLScene
import com.almasb.fxgl.service.Display
import com.almasb.fxgl.ui.FXGLButton
import com.sun.javafx.scene.traversal.Algorithm
import com.sun.javafx.scene.traversal.Direction
import com.sun.javafx.scene.traversal.ParentTraversalEngine
import com.sun.javafx.scene.traversal.TraversalContext
import javafx.beans.binding.Bindings
import javafx.geometry.Point2D
import javafx.geometry.Pos
import javafx.scene.Node
import javafx.scene.control.Button
import javafx.scene.control.TextField
import javafx.scene.effect.BoxBlur
import javafx.scene.effect.Effect
import javafx.scene.layout.*
import javafx.scene.paint.Color
import javafx.scene.shape.Rectangle
import javafx.scene.text.Text
import jfxtras.scene.control.window.Window
import java.io.PrintWriter
import java.io.StringWriter
import java.nio.file.Files
import java.nio.file.Paths
import java.util.*
import java.util.function.Consumer
import java.util.function.Predicate
/**
* In-game dialog pane.
* The pane fills the whole scene area so that user
* input does not pass through to the underlying nodes.
*
* @author <NAME> (AlmasB) (<EMAIL>)
*/
class DialogPane
internal constructor(private val display: Display) : Pane() {
private val window = Window()
private var onShown: Runnable? = null
private var onClosed: Runnable? = null
init {
display.currentSceneProperty().addListener { o, oldScene, newScene ->
// if we somehow changed scene while the dialog is showing
if (isShowing) {
closeInScene(oldScene)
openInScene(newScene)
}
}
val width = FXGL.getSettings().width.toDouble()
val height = FXGL.getSettings().height.toDouble()
setPrefSize(width, height)
background = Background(BackgroundFill(Color.rgb(127, 127, 123, 0.5), null, null))
window.isResizableWindow = false
window.isMovable = false
window.background = Background(BackgroundFill(Color.BLACK, null, null))
window.layoutXProperty().bind(window.widthProperty().divide(2).negate().add(width / 2))
window.layoutYProperty().bind(window.heightProperty().divide(2).negate().add(height / 2))
children.add(window)
// this is a workaround to avoid users traversing "through" the dialog to underlying nodes
initTraversalPolicy()
}
@Suppress("DEPRECATION")
private fun initTraversalPolicy() {
this.impl_traversalEngine = ParentTraversalEngine(this, object : Algorithm {
override fun select(owner: Node, dir: Direction, context: TraversalContext): Node {
return window
}
override fun selectFirst(context: TraversalContext): Node {
return window
}
override fun selectLast(context: TraversalContext): Node {
return window
}
})
}
val isShowing: Boolean
get() = parent != null
/**
* Shows a simple message box with OK button.
* Calls back the given runnable on close.
*
*
* Opening more than 1 dialog box is not allowed.
* @param message message to show
* *
* @param callback function to call when closed
*/
@JvmOverloads internal fun showMessageBox(message: String, callback: Runnable = Runnable { }) {
val text = createMessage(message)
val btnOK = FXGLButton("OK")
btnOK.setOnAction {
close()
callback.run()
}
val vbox = VBox(50.0, text, btnOK)
vbox.setAlignment(Pos.CENTER)
vbox.setUserData(Point2D(Math.max(text.layoutBounds.width, 200.0), text.layoutBounds.height * 2 + 50))
setContent("Message", vbox)
show()
}
/**
* Shows an error box with OK and LOG buttons.
*
*
* Opening more than 1 dialog box is not allowed.
*
* @param errorMessage error message to show
*/
internal fun showErrorBox(errorMessage: String) {
showErrorBox(RuntimeException(errorMessage))
}
/**
* Shows an error box with OK and LOG buttons.
*
*
* Opening more than 1 dialog box is not allowed.
* @param errorMessage error message to show
* *
* @param callback function to call back when closed
*/
internal fun showErrorBox(errorMessage: String, callback: Runnable) {
showErrorBox(RuntimeException(errorMessage), callback)
}
/**
* Shows an error box with OK and LOG buttons.
*
*
* Opening more than 1 dialog box is not allowed.
* @param error error to show
* *
* @param callback function to call when closed
*/
@JvmOverloads internal fun showErrorBox(error: Throwable, callback: Runnable = Runnable { }) {
val text = createMessage(error.toString())
val btnOK = FXGLButton("OK")
btnOK.setOnAction { e ->
close()
callback.run()
}
val btnLog = FXGLButton("LOG")
btnLog.setOnAction { e ->
close()
val sw = StringWriter()
val pw = PrintWriter(sw)
error.printStackTrace(pw)
pw.close()
try {
Files.write(Paths.get("LastException.log"), Arrays.asList(*sw.toString().split("\n".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()))
showMessageBox("Log has been saved as LastException.log")
} catch (ex: Exception) {
showMessageBox("Failed to save log file")
}
callback.run()
}
val hbox = HBox(btnOK, btnLog)
hbox.alignment = Pos.CENTER
val vbox = VBox(50.0, text, hbox)
vbox.setAlignment(Pos.CENTER)
vbox.setUserData(Point2D(Math.max(text.layoutBounds.width, 400.0), text.layoutBounds.height * 2 + 50))
setContent("Error", vbox)
show()
}
/**
* Shows confirmation message box with YES and NO buttons.
*
*
* The callback function will be invoked with boolean answer
* as parameter.
*
*
* Opening more than 1 dialog box is not allowed.
* @param message message to show
* *
* @param resultCallback result function to call back
*/
internal fun showConfirmationBox(message: String, resultCallback: Consumer<Boolean>) {
val text = createMessage(message)
val btnYes = FXGLButton("YES")
btnYes.setOnAction { e ->
close()
resultCallback.accept(true)
}
val btnNo = FXGLButton("NO")
btnNo.setOnAction { e ->
close()
resultCallback.accept(false)
}
val hbox = HBox(btnYes, btnNo)
hbox.alignment = Pos.CENTER
val vbox = VBox(50.0, text, hbox)
vbox.setAlignment(Pos.CENTER)
vbox.setUserData(Point2D(Math.max(text.layoutBounds.width, 400.0), text.layoutBounds.height * 2 + 50))
setContent("Confirmation", vbox)
show()
}
/**
* Shows input box with input field and OK button.
* The button will stay disabled until there is at least
* 1 character in the input field.
*
*
* The callback function will be invoked with input field text
* as parameter.
*
*
* Opening more than 1 dialog box is not allowed.
* @param message message to show
* *
* @param resultCallback result function to call back
*/
internal fun showInputBox(message: String, resultCallback: Consumer<String>) {
showInputBox(message, Predicate { true }, resultCallback)
}
/**
* Shows input box with input field and OK button.
* The button will stay disabled until the input passes given filter.
*
*
* The callback function will be invoked with input field text
* as parameter.
*
*
* Opening more than 1 dialog box is not allowed.
* @param message message to show
* *
* @param filter the filter to validate input
* *
* @param resultCallback result function to call back
*/
internal fun showInputBox(message: String, filter: Predicate<String>, resultCallback: Consumer<String>) {
val text = createMessage(message)
val field = TextField()
field.maxWidth = Math.max(text.layoutBounds.width, 200.0)
field.font = FXGL.getUIFactory().newFont(18.0)
val btnOK = FXGLButton("OK")
field.textProperty().addListener { observable, oldValue, newInput -> btnOK.isDisable = newInput.isEmpty() || !filter.test(newInput) }
btnOK.isDisable = true
btnOK.setOnAction { e ->
close()
resultCallback.accept(field.text)
}
val vbox = VBox(50.0, text, field, btnOK)
vbox.setAlignment(Pos.CENTER)
vbox.setUserData(Point2D(Math.max(text.layoutBounds.width, 200.0), text.layoutBounds.height * 3 + 50 * 2))
setContent("Input", vbox)
show()
}
/**
* Shows input box with input field and OK button.
* The button will stay disabled until the input passes given filter.
*
*
* The callback function will be invoked with input field text
* as parameter.
*
*
* Opening more than 1 dialog box is not allowed.
* @param message message to show
* *
* @param filter the filter to validate input
* *
* @param resultCallback result function to call back or empty string if use cancelled the dialog
*/
internal fun showInputBoxWithCancel(message: String, filter: Predicate<String>, resultCallback: Consumer<String>) {
val text = createMessage(message)
val field = TextField()
field.maxWidth = Math.max(text.layoutBounds.width, 200.0)
field.font = FXGL.getUIFactory().newFont(18.0)
val btnOK = FXGL.getUIFactory().newButton("OK")
field.textProperty().addListener { observable, oldValue, newInput -> btnOK.isDisable = newInput.isEmpty() || !filter.test(newInput) }
btnOK.isDisable = true
btnOK.setOnAction { e ->
close()
resultCallback.accept(field.text)
}
val btnCancel = FXGL.getUIFactory().newButton("CANCEL")
btnCancel.setOnAction { e ->
close()
resultCallback.accept("")
}
val hBox = HBox(btnOK, btnCancel)
hBox.alignment = Pos.CENTER
val vbox = VBox(50.0, text, field, hBox)
vbox.setAlignment(Pos.CENTER)
vbox.setUserData(Point2D(Math.max(text.layoutBounds.width, 200.0), text.layoutBounds.height * 3 + 50 * 2))
setContent("Input", vbox)
show()
}
/**
* Shows arbitrary box with message, content and given buttons.
* @param message the header message
* *
* @param content the box content
* *
* @param buttons buttons present in the box
*/
internal fun showBox(message: String, content: Node, vararg buttons: Button) {
for (btn in buttons) {
val handler = btn.onAction
btn.setOnAction { e ->
close()
handler?.handle(e)
}
}
val text = createMessage(message)
val hbox = HBox(*buttons)
hbox.alignment = Pos.CENTER
val vbox = VBox(50.0, text, content, hbox)
vbox.setAlignment(Pos.CENTER)
vbox.setUserData(Point2D(Math.max(text.layoutBounds.width, 200.0),
text.layoutBounds.height * 3 + (50 * 2).toDouble() + content.layoutBounds.height))
setContent("Dialog", vbox)
show()
}
private fun createMessage(message: String): Text {
return FXGL.getUIFactory().newText(message)
}
/**
* Replaces all content of the scene root by given node.
* Creates an appropriate size rectangle box around the node
* to serve as background.
* @param title window title
* *
* @param n content node
*/
private fun setContent(title: String, n: Node) {
if (isShowing) {
// dialog was requested while being shown so remember state
states.push(DialogData(window.title, window.contentPane))
}
val size = n.userData as Point2D
val box = Rectangle()
box.widthProperty().bind(Bindings.max(size.x + 200, window.widthProperty()))
box.height = size.y + 100
box.translateY = 3.0
box.stroke = Color.AZURE
val root = StackPane()
root.children.setAll(box, n)
window.title = title
window.contentPane = root
}
internal fun setOnClosed(onClosed: Runnable) {
this.onClosed = onClosed
}
internal fun setOnShown(onShown: Runnable) {
this.onShown = onShown
}
private val states = ArrayDeque<DialogData>()
internal fun show() {
if (!isShowing) {
openInScene(display.currentScene)
this.requestFocus()
if (onShown != null)
onShown!!.run()
}
}
internal fun close() {
if (states.isEmpty()) {
closeInScene(display.currentScene)
if (onClosed != null)
onClosed!!.run()
} else {
val data = states.pop()
window.title = data.title
window.contentPane = data.contentPane
}
}
private val bgBlur = BoxBlur(5.0, 5.0, 3)
private var savedEffect: Effect? = null
private fun openInScene(scene: FXGLScene) {
savedEffect = scene.effect
scene.effect = bgBlur
scene.root.children.add(this)
}
private fun closeInScene(scene: FXGLScene) {
scene.root.children.remove(this)
scene.effect = savedEffect
}
private class DialogData internal constructor(internal var title: String, internal var contentPane: Pane)
companion object {
@JvmField val ALPHANUM = Predicate<String> { input -> input.matches("^[\\pL\\pN]+$".toRegex()) }
}
}
/**
* Shows a simple message box with OK button.
*
*
* Opening more than 1 dialog box is not allowed.
* @param message message to show
*/
/**
* Shows an error box with OK and LOG buttons.
*
*
* Opening more than 1 dialog box is not allowed.
* @param error error to show
*/
| 0 | Java | 0 | 0 | 1f15e02f1b8dfda8fb2ec895bd00d7e5872ba834 | 15,599 | FXGL | MIT License |
plugins/kotlin/idea/tests/testData/copyPaste/imports/PartiallySelectedBlock.to.kt | JetBrains | 2,489,216 | false | {"Text": 9788, "INI": 517, "YAML": 423, "Ant Build System": 11, "Batchfile": 34, "Dockerfile": 10, "Shell": 633, "Markdown": 750, "Ignore List": 141, "Git Revision List": 1, "Git Attributes": 11, "EditorConfig": 260, "XML": 7904, "SVG": 4537, "Kotlin": 60205, "Java": 84268, "HTML": 3803, "Java Properties": 217, "Gradle": 462, "Maven POM": 95, "JavaScript": 232, "CSS": 79, "JSON": 1436, "JFlex": 33, "Makefile": 5, "Diff": 137, "XSLT": 113, "Gradle Kotlin DSL": 735, "Groovy": 3102, "desktop": 1, "JAR Manifest": 17, "PHP": 47, "Microsoft Visual Studio Solution": 2, "C#": 33, "Smalltalk": 17, "Erlang": 1, "Perl": 9, "Jupyter Notebook": 13, "Rich Text Format": 2, "AspectJ": 2, "HLSL": 2, "Objective-C": 15, "CoffeeScript": 2, "HTTP": 2, "JSON with Comments": 73, "GraphQL": 127, "Nginx": 1, "HAProxy": 1, "OpenStep Property List": 47, "Python": 17095, "C": 110, "C++": 42, "Protocol Buffer": 3, "fish": 2, "PowerShell": 3, "Go": 36, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "TeX": 11, "HCL": 4, "F#": 1, "GLSL": 1, "Elixir": 2, "Ruby": 4, "XML Property List": 85, "E-mail": 18, "Roff": 289, "Roff Manpage": 40, "Swift": 3, "TOML": 196, "Checksums": 49, "Java Server Pages": 11, "Vue": 1, "Dotenv": 1, "reStructuredText": 67, "SQL": 1, "Vim Snippet": 8, "AMPL": 4, "Linux Kernel Module": 1, "CMake": 15, "Handlebars": 1, "Rust": 20, "Go Checksums": 1, "Go Module": 1, "NSIS": 8, "PlantUML": 6, "SCSS": 2, "Thrift": 3, "Cython": 13, "Regular Expression": 3, "JSON5": 4, "OASv3-json": 3, "OASv3-yaml": 1} | package to
class B {
<caret>
} | 1 | null | 1 | 1 | 0d546ea6a419c7cb168bc3633937a826d4a91b7c | 35 | intellij-community | Apache License 2.0 |
aws-auth-cognito/src/test/java/featureTest/utilities/APIExecutor.kt | tdunietz1 | 676,729,628 | true | {"Java Properties": 6, "Gradle Kotlin DSL": 25, "Markdown": 8, "Shell": 8, "Batchfile": 3, "INI": 33, "Java": 882, "Kotlin": 536, "Proguard": 2, "Ruby": 2} | /*
* Copyright 2022 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 featureTest.utilities
import aws.sdk.kotlin.runtime.endpoint.functions.parseArn
import aws.sdk.kotlin.services.cognitoidentityprovider.model.SignUpRequest
import aws.sdk.kotlin.services.cognitoidentityprovider.model.SignUpResponse
import aws.smithy.kotlin.runtime.content.Document
import aws.smithy.kotlin.runtime.util.length
import com.amplifyframework.auth.AuthDevice
import com.amplifyframework.auth.AuthException
import com.amplifyframework.auth.AuthPlugin
import com.amplifyframework.auth.cognito.AWSCognitoAuthPlugin
import com.amplifyframework.auth.cognito.AWSCognitoAuthService
import com.amplifyframework.auth.cognito.RealAWSCognitoAuthPlugin
import com.amplifyframework.auth.cognito.featuretest.API
import com.amplifyframework.auth.cognito.featuretest.AuthAPI
import com.amplifyframework.auth.options.AuthSignUpOptions
import com.amplifyframework.auth.result.AuthSignUpResult
import com.amplifyframework.core.Action
import com.amplifyframework.core.Consumer
import com.google.gson.Gson
import featureTest.utilities.APICaptorFactory.Companion.onError
import generated.model.ApiCall
import generated.model.TypeResponse
import io.mockk.CapturingSlot
import io.mockk.coEvery
import io.mockk.mockk
import io.mockk.slot
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import kotlin.reflect.KClass
import kotlin.reflect.KFunction
import kotlin.reflect.KParameter
import kotlin.reflect.full.declaredFunctions
/**
* Executes the API on given [AWSCognitoAuthPlugin] instance
*/
internal val apiExecutor: (AWSCognitoAuthPlugin, ApiCall, TypeResponse) -> Any = { authPlugin: AWSCognitoAuthPlugin, api: ApiCall, responseType : TypeResponse ->
lateinit var result: Any
val latch = CountDownLatch(1)
val targetApis = authPlugin::class.declaredFunctions.filter { it.name == api.name }
val mapped : Map<String, Document?> = api!!.params!!.asMap()
var requiredParams: Map<KParameter, Any?>? = null
var targetApi: KFunction<*>? = null
println(api.name)
for (currentApi in targetApis) {
try {
val currentParams = currentApi.parameters.associateWith { kParam ->
when {
kParam.kind == KParameter.Kind.INSTANCE -> authPlugin
kParam.type.classifier as KClass<*> == Action::class -> Action {
result = Unit
latch.countDown()
}
kParam.type.classifier as KClass<*> == Consumer::class -> Consumer<Any> { value ->
result = value
latch.countDown()
}
kParam.name == "options" -> AuthOptionsFactory.create(AuthAPI.valueOf(api.name!!), api.options!!.asMap()!!)
else -> kParam.name?.let { getParam(it, kParam, mapped) }
}
}
targetApi = currentApi
requiredParams = currentParams
break
} catch (ex: Exception) {
print(ex.toString())
}
}
if (targetApi == null || requiredParams == null)
throw Exception("No matching api function with required parameters found")
targetApi.callBy(requiredParams)
latch.await(5, TimeUnit.SECONDS)
result
}
/**
* Traverses given json to find value of paramName
*/
private inline fun getParam(paramName: String, kParam: KParameter, paramsObject: Map<String, Document?>): kotlin.Any {
paramsObject.entries.first {
it.key == paramName
}.apply {
return Gson().fromJson(value!!.asString(), (kParam.type.classifier as KClass<*>).javaObjectType)
}
} | 0 | Java | 0 | 0 | e803fe4765081fbce5250355fdeea64737eb0693 | 4,253 | amplify-android | Apache License 2.0 |
server/game/core/src/main/kotlin/rsbox/core/command/CommandDsl.kt | rsbox | 704,269,853 | false | {"Java": 2428938, "Kotlin": 633136} | package rsbox.core.command
import io.rsbox.server.engine.model.Privilege
import io.rsbox.server.engine.model.entity.Player
@DslMarker
annotation class CommandDsl
@CommandDsl
fun on_command(
command: String,
privilege: Privilege = Privilege.PLAYER,
action: (player: Player, args: List<String>) -> Unit
) {
CommandManager.registerCommand(Command(command, privilege, action))
} | 1 | null | 1 | 1 | 187049de600faa9d8de244ee2ed14785d9123475 | 393 | rsbox | Apache License 2.0 |
shopiroller/src/main/java/com/shopiroller/models/FilterOptionsResponse.kt | shopiroller | 552,768,909 | false | {"Gradle": 6, "Java Properties": 2, "Shell": 1, "Text": 2, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "YAML": 1, "Proguard": 1, "Kotlin": 55, "XML": 186, "INI": 1, "Java": 153} | package com.shopiroller.models
import com.google.gson.annotations.SerializedName
import java.io.Serializable
data class VariationsItem(
@field:SerializedName("id")
val id: String? = null,
@field:SerializedName("value")
val value: String? = null,
var isChecked: Boolean = false
) : Serializable
data class VariationGroupsItem(
@field:SerializedName("updateDate")
val updateDate: String? = null,
@field:SerializedName("variations")
val variations: List<VariationsItem?>? = null,
@field:SerializedName("name")
val name: String? = null,
@field:SerializedName("id")
val id: String? = null,
@field:SerializedName("isActive")
val isActive: Boolean? = null,
@field:SerializedName("createDate")
val createDate: String? = null,
var selectedItems: String? = null
) : Serializable
data class FilterOptionsResponse(
@field:SerializedName("variationGroups")
val variationGroups: List<VariationGroupsItem?>? = null,
@field:SerializedName("brands")
val brands: List<BrandsItem?>? = null,
@field:SerializedName("categories")
val categories: List<CategoriesItem?>? = null
) : Serializable
data class BrandsItem(
@field:SerializedName("updateDate")
val updateDate: String? = null,
@field:SerializedName("name")
val name: String? = null,
@field:SerializedName("icon")
val icon: ProductImage? = null,
@field:SerializedName("id")
val id: String? = null,
@field:SerializedName("isActive")
val isActive: Boolean? = null,
@field:SerializedName("createDate")
val createDate: String? = null,
var isChecked: Boolean = false
) : Serializable
data class CategoriesItem(
@field:SerializedName("updateDate")
val updateDate: String? = null,
@field:SerializedName("name")
val name: Map<String, String?>? = null,
@field:SerializedName("icon")
val icon: ProductImage? = null,
@field:SerializedName("totalProduct")
val totalProduct: Int? = null,
@field:SerializedName("orderIndex")
val orderIndex: Int? = null,
@field:SerializedName("parentCategoryId")
val parentCategoryId: String? = null,
@field:SerializedName("isActive")
val isActive: Boolean? = null,
@field:SerializedName("categoryId")
val categoryId: String? = null,
@field:SerializedName("subCategories")
val subCategories: List<CategoriesItem?>? = null,
@field:SerializedName("createDate")
val createDate: String? = null,
var isSelected: Boolean = false
) : Serializable
data class MultiChoiceItem(
@field:SerializedName("name")
val name: String? = null,
@field:SerializedName("id")
val id: String? = null,
var isChecked: Boolean = false
) : Serializable
| 0 | Java | 0 | 6 | 133793ba9c7f7167de30668662c5a37201d6eb02 | 2,771 | shopiroller-uikit-android | MIT License |
SDKChallengeProject/TAAS/android_basic/customerlib/src/main/java/com/framing/module/customer/data/bean/NutrientBean.kt | softwarekk | 285,520,801 | true | {"Markdown": 10, "Java Properties": 2, "Gradle": 12, "Shell": 1, "Batchfile": 1, "Ignore List": 10, "INI": 9, "Proguard": 9, "Kotlin": 104, "XML": 64, "Java": 40, "JSON": 28} | package com.framing.module.customer.data.bean
/*
* Des
* Author Young
* Date
* nitrogen 氮
* phosphorus 磷
* potassium 钾
* organic 有机质
* PH 酸碱
* 硼 boron
* Mo 钼
* copper 铜
* Iron 铁
* manganese 锰
* zinc 锌
* calcium 钙
* magnesium 镁
*
*/data class NutrientBean(var nitrogen:String,
var phosphorus:String,
var potassium:String,
var organic:String,
var ph:String,
var boron:String,
var mo:String,
var copper:String,
var iron:String,
var manganese:String,
var zinc:String,
var calcium:String,
var magnesium:String
) | 0 | Java | 0 | 2 | 7bcadf38900d8ce23ebfdc4f69a716cd926595e8 | 852 | RTE-Innovation-Challenge-2020 | MIT License |
dsl/camel-kotlin-api/src/generated/kotlin/org/apache/camel/kotlin/dataformats/BeanioDataFormatDsl.kt | Gayathrichennaioutlook | 759,948,930 | true | {"Text": 253, "Shell": 19, "Maven POM": 578, "Batchfile": 4, "YAML": 72, "Markdown": 26, "Git Attributes": 1, "XML": 1779, "Ignore List": 19, "JSON": 2339, "Git Config": 1, "Java": 21257, "Java Properties": 990, "AsciiDoc": 1285, "Kotlin": 489, "JavaScript": 32, "Groovy": 162, "OASv3-json": 16, "Dockerfile": 5, "JAR Manifest": 44, "CSS": 2, "XSLT": 61, "SVG": 2, "HTML": 150, "INI": 20, "OASv2-json": 9, "OASv3-yaml": 8, "Thrift": 2, "Public Key": 16, "Protocol Buffer": 5, "Ruby": 1, "GraphQL": 4, "SQL": 37, "Fluent": 9, "XQuery": 5, "TOML": 2, "Rust": 1, "Tcl": 5, "Jsonnet": 2, "Mustache": 7, "RobotFramework": 7, "ASN.1": 1, "Apex": 3, "Erlang": 1, "OASv2-yaml": 3} | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.kotlin.dataformats
import kotlin.Boolean
import kotlin.String
import kotlin.Unit
import org.apache.camel.kotlin.CamelDslMarker
import org.apache.camel.kotlin.DataFormatDsl
import org.apache.camel.model.dataformat.BeanioDataFormat
public fun DataFormatDsl.beanio(i: BeanioDataFormatDsl.() -> Unit) {
def = BeanioDataFormatDsl().apply(i).def
}
@CamelDslMarker
public class BeanioDataFormatDsl {
public val def: BeanioDataFormat
init {
def = BeanioDataFormat()}
public fun id(id: String) {
def.id = id
}
public fun mapping(mapping: String) {
def.mapping = mapping
}
public fun streamName(streamName: String) {
def.streamName = streamName
}
public fun ignoreUnidentifiedRecords(ignoreUnidentifiedRecords: Boolean) {
def.ignoreUnidentifiedRecords = ignoreUnidentifiedRecords.toString()
}
public fun ignoreUnidentifiedRecords(ignoreUnidentifiedRecords: String) {
def.ignoreUnidentifiedRecords = ignoreUnidentifiedRecords
}
public fun ignoreUnexpectedRecords(ignoreUnexpectedRecords: Boolean) {
def.ignoreUnexpectedRecords = ignoreUnexpectedRecords.toString()
}
public fun ignoreUnexpectedRecords(ignoreUnexpectedRecords: String) {
def.ignoreUnexpectedRecords = ignoreUnexpectedRecords
}
public fun ignoreInvalidRecords(ignoreInvalidRecords: Boolean) {
def.ignoreInvalidRecords = ignoreInvalidRecords.toString()
}
public fun ignoreInvalidRecords(ignoreInvalidRecords: String) {
def.ignoreInvalidRecords = ignoreInvalidRecords
}
public fun encoding(encoding: String) {
def.encoding = encoding
}
public fun beanReaderErrorHandlerType(beanReaderErrorHandlerType: String) {
def.beanReaderErrorHandlerType = beanReaderErrorHandlerType
}
public fun unmarshalSingleObject(unmarshalSingleObject: Boolean) {
def.unmarshalSingleObject = unmarshalSingleObject.toString()
}
public fun unmarshalSingleObject(unmarshalSingleObject: String) {
def.unmarshalSingleObject = unmarshalSingleObject
}
}
| 0 | null | 0 | 0 | a55c79bb05912e557c9041705b2693054e88c5f1 | 2,834 | camel | Apache License 2.0 |
kotlin/JSON Database/Stage 3/server/JSONDatabase.kt | YuraVolk | 699,763,308 | false | {"Java": 270149, "Kotlin": 160960, "JavaScript": 46154, "CSS": 25589, "HTML": 21447} | package jsondatabase.server
class JSONDatabase {
private var array: MutableList<String?> = MutableList(1000) { null }
fun setValue(index: Int, data: String?) = if (index - 1 !in array.indices) "ERROR" else "OK".also { array[index - 1] = data }
operator fun get(index: Int) = if (index - 1 !in array.indices || array[index - 1] == null) "ERROR" else array[index - 1] ?: "ERROR"
fun delete(index: Int) = if (index - 1 !in array.indices) "ERROR" else "OK".also { array[index - 1] = null }
}
| 1 | null | 1 | 1 | 8ceb6e2c20bb347a4a9b6cd5d121170d199c8667 | 506 | hyperskill-projects | The Unlicense |
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/test/ExampleTeleOp.kt | Sherif-Abdou | 223,775,485 | false | {"Java": 39432, "Kotlin": 27895} | package org.firstinspires.ftc.teamcode
import com.qualcomm.robotcore.eventloop.opmode.Disabled
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode
import com.qualcomm.robotcore.eventloop.opmode.TeleOp
import com.qualcomm.robotcore.hardware.DcMotor
import com.qualcomm.robotcore.hardware.DcMotorSimple
import com.qualcomm.robotcore.util.Range
@TeleOp(name = "TestTeleOp")
@Disabled
class TestTeleOp : LinearOpMode() {
var left_motors: MutableList<DcMotor> = mutableListOf()
var right_motors: MutableList<DcMotor> = mutableListOf()
override fun runOpMode() {
for (i in 0 until 4) {
var motor = hardwareMap.get("motor_$i") as DcMotor
motor.zeroPowerBehavior = DcMotor.ZeroPowerBehavior.BRAKE
if (i % 2 == 0) {
motor.direction = DcMotorSimple.Direction.REVERSE
right_motors.add(motor)
} else {
left_motors.add(motor)
}
}
waitForStart()
while (opModeIsActive()) {
var leftPower: Double = 0.0
var rightPower: Double = 0.0
var turn = gamepad1.left_stick_x
var drive = -gamepad1.left_stick_y
var strafe = gamepad1.right_stick_x.toDouble()
rightPower = Range.clip(drive - turn, -1.0f, 1.0f).toDouble()
leftPower = Range.clip(drive + turn, -1.0f, 1.0f).toDouble()
if (rightPower != 0.0 && leftPower != 0.0) {
for (motor in right_motors) {
motor.power = rightPower
}
for (motor in left_motors) {
motor.power = leftPower
}
} else if (strafe != 0.0) {
left_motors[1].power = strafe
left_motors[0].power = -strafe
right_motors[0].power = strafe
right_motors[1].power = -strafe
} else {
for (motor in right_motors) {
motor.power = 0.0
}
for (motor in left_motors) {
motor.power = 0.0
}
}
telemetry.addData("Oui Oui im in me mum car", "Left: $leftPower Right: $rightPower")
telemetry.update()
}
}
}
| 1 | null | 1 | 1 | 12a1b322fa54c9abae93567fa13e7391d2cf618f | 2,293 | Syntax-Error-Skystone | MIT License |
packages/SystemUI/tests/src/com/android/systemui/unfold/TestUnfoldTransitionProvider.kt | liu-wanshun | 595,904,109 | true | null | package com.android.systemui.unfold
import com.android.systemui.unfold.UnfoldTransitionProgressProvider.TransitionProgressListener
class TestUnfoldTransitionProvider : UnfoldTransitionProgressProvider, TransitionProgressListener {
private val listeners = arrayListOf<TransitionProgressListener>()
override fun destroy() {
listeners.clear()
}
override fun addCallback(listener: TransitionProgressListener) {
listeners.add(listener)
}
override fun removeCallback(listener: TransitionProgressListener) {
listeners.remove(listener)
}
override fun onTransitionStarted() {
listeners.forEach { it.onTransitionStarted() }
}
override fun onTransitionFinished() {
listeners.forEach { it.onTransitionFinished() }
}
override fun onTransitionProgress(progress: Float) {
listeners.forEach { it.onTransitionProgress(progress) }
}
}
| 0 | Java | 1 | 2 | e99201cd9b6a123b16c30cce427a2dc31bb2f501 | 926 | platform_frameworks_base | Apache License 2.0 |
clients/ktorm-schema/generated/src/main/kotlin/org/openapitools/database/models/IntegrationRequestPatch.kt | oapicf | 489,369,143 | false | {"Markdown": 13009, "YAML": 64, "Text": 6, "Ignore List": 43, "JSON": 688, "Makefile": 2, "JavaScript": 2261, "F#": 1305, "XML": 1120, "Shell": 44, "Batchfile": 10, "Scala": 4677, "INI": 23, "Dockerfile": 14, "Maven POM": 22, "Java": 13384, "Emacs Lisp": 1, "Haskell": 75, "Swift": 551, "Ruby": 1149, "Cabal Config": 2, "OASv3-yaml": 16, "Go": 2224, "Go Checksums": 1, "Go Module": 4, "CMake": 9, "C++": 6688, "TOML": 3, "Rust": 556, "Nim": 541, "Perl": 540, "Microsoft Visual Studio Solution": 2, "C#": 1645, "HTML": 545, "Xojo": 1083, "Gradle": 20, "R": 1079, "JSON with Comments": 8, "QMake": 1, "Kotlin": 3280, "Python": 1, "Crystal": 1060, "ApacheConf": 2, "PHP": 3940, "Gradle Kotlin DSL": 1, "Protocol Buffer": 538, "C": 1598, "Ada": 16, "Objective-C": 1098, "Java Properties": 2, "Erlang": 1097, "PlantUML": 1, "robots.txt": 1, "HTML+ERB": 2, "Lua": 1077, "SQL": 512, "AsciiDoc": 1, "CSS": 3, "PowerShell": 1083, "Elixir": 5, "Apex": 1054, "Visual Basic 6.0": 3, "TeX": 1, "ObjectScript": 1, "OpenEdge ABL": 1, "Option List": 2, "Eiffel": 583, "Gherkin": 1, "Dart": 538, "Groovy": 539, "Elm": 31} | /**
* Pinterest REST API
* Pinterest's REST API
*
* The version of the OpenAPI document: 5.12.0
* Contact: <EMAIL>
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.database.models
import org.ktorm.dsl.*
import org.ktorm.schema.*
import org.ktorm.database.Database
import .*
/**
* Schema used for updating the integration metadata.
* @param connectedMerchantId
* @param connectedAdvertiserId
* @param connectedLbaId
* @param connectedTagId
* @param partnerAccessToken
* @param partnerRefreshToken
* @param partnerPrimaryEmail
* @param partnerAccessTokenExpiry
* @param partnerRefreshTokenExpiry
* @param scopes
* @param additionalId1
* @param partnerMetadata
*/
object IntegrationRequestPatchs : BaseTable<IntegrationRequestPatch>("IntegrationRequestPatch") {
val connectedMerchantId = text("connected_merchant_id") /* null */
val connectedAdvertiserId = text("connected_advertiser_id") /* null */
val connectedLbaId = text("connected_lba_id") /* null */
val connectedTagId = text("connected_tag_id") /* null */
val partnerAccessToken = text("partner_access_token") /* null */
val partnerRefreshToken = text("partner_refresh_token") /* null */
val partnerPrimaryEmail = text("partner_primary_email") /* null */
val partnerAccessTokenExpiry = decimal("partner_access_token_expiry") /* null */
val partnerRefreshTokenExpiry = decimal("partner_refresh_token_expiry") /* null */
val scopes = text("scopes") /* null */
val additionalId1 = text("additional_id_1") /* null */
val partnerMetadata = text("partner_metadata") /* null */
/**
* Create an entity of type IntegrationRequestPatch from the model
*/
override fun doCreateEntity(row: QueryRowSet, withReferences: Boolean) = IntegrationRequestPatch(
connectedMerchantId = row[connectedMerchantId] /* kotlin.String? */,
connectedAdvertiserId = row[connectedAdvertiserId] /* kotlin.String? */,
connectedLbaId = row[connectedLbaId] /* kotlin.String? */,
connectedTagId = row[connectedTagId] /* kotlin.String? */,
partnerAccessToken = row[partnerAccessToken] /* kotlin.String? */,
partnerRefreshToken = row[partnerRefreshToken] /* kotlin.String? */,
partnerPrimaryEmail = row[partnerPrimaryEmail] /* kotlin.String? */,
partnerAccessTokenExpiry = row[partnerAccessTokenExpiry] /* java.math.BigDecimal? */,
partnerRefreshTokenExpiry = row[partnerRefreshTokenExpiry] /* java.math.BigDecimal? */,
scopes = row[scopes] /* kotlin.String? */,
additionalId1 = row[additionalId1] /* kotlin.String? */,
partnerMetadata = row[partnerMetadata] /* kotlin.String? */
)
/**
* Assign all the columns from the entity of type IntegrationRequestPatch to the DML expression.
*
* Usage:
*
* ```kotlin
* let entity = IntegrationRequestPatch()
* database.update(IntegrationRequestPatchs, {
* assignFrom(entity)
* })
* ```
* @return the builder with the columns for the update or insert.
*/
fun AssignmentsBuilder.assignFrom(entity: IntegrationRequestPatch) {
this.apply {
set(IntegrationRequestPatchs.connectedMerchantId, entity.connectedMerchantId)
set(IntegrationRequestPatchs.connectedAdvertiserId, entity.connectedAdvertiserId)
set(IntegrationRequestPatchs.connectedLbaId, entity.connectedLbaId)
set(IntegrationRequestPatchs.connectedTagId, entity.connectedTagId)
set(IntegrationRequestPatchs.partnerAccessToken, entity.partnerAccessToken)
set(IntegrationRequestPatchs.partnerRefreshToken, entity.partnerRefreshToken)
set(IntegrationRequestPatchs.partnerPrimaryEmail, entity.partnerPrimaryEmail)
set(IntegrationRequestPatchs.partnerAccessTokenExpiry, entity.partnerAccessTokenExpiry)
set(IntegrationRequestPatchs.partnerRefreshTokenExpiry, entity.partnerRefreshTokenExpiry)
set(IntegrationRequestPatchs.scopes, entity.scopes)
set(IntegrationRequestPatchs.additionalId1, entity.additionalId1)
set(IntegrationRequestPatchs.partnerMetadata, entity.partnerMetadata)
}
}
}
| 0 | Java | 0 | 2 | dcd328f1e62119774fd8ddbb6e4bad6d7878e898 | 4,368 | pinterest-sdk | MIT License |
src/main/kotlin/com/deflatedpickle/squidfriends/mojank/FollowParentSquidGoal.kt | DeflatedPickle | 614,750,808 | false | {"Java": 13101, "Kotlin": 5559} | /* Copyright (c) 2023 DeflatedPickle under the MIT license */
package com.deflatedpickle.squidfriends.mojank
import com.deflatedpickle.squidfriends.api.IBreedable
import net.minecraft.entity.ai.goal.Goal
import net.minecraft.entity.passive.SquidEntity
open class FollowParentSquidGoal(
private val animal: SquidEntity,
private val speed: Double
) : Goal() {
companion object {
const val HORIZONTAL_SCAN_RANGE = 8
const val VERTICAL_SCAN_RANGE = 4
const val FOLLOW_MIN_DISTANCE = 3
}
private var parent: SquidEntity? = null
private var delay = 0
override fun canStart(): Boolean {
return if ((animal as IBreedable).isAdult()) {
false
} else {
val list = animal.world.getNonSpectatingEntities(animal.javaClass, animal.boundingBox.expand(8.0, 4.0, 8.0))
var animalEntity: SquidEntity? = null
var d = Double.MAX_VALUE
for (animalEntity2 in list) {
if (animalEntity2.isAdult()) {
val e = animal.squaredDistanceTo(animalEntity2)
if (!(e > d)) {
d = e
animalEntity = animalEntity2
}
}
}
if (animalEntity == null) {
false
} else if (d < 9.0) {
false
} else {
parent = animalEntity
true
}
}
}
override fun shouldContinue(): Boolean {
return if ((animal as IBreedable).isAdult()) {
false
} else if (!parent!!.isAlive) {
false
} else {
val d = animal.squaredDistanceTo(parent)
!(d < 9.0) && !(d > 256.0)
}
}
override fun start() {
delay = 0
}
override fun stop() {
parent = null
}
override fun tick() {
if (--delay <= 0) {
delay = getTickCount(10)
animal.navigation.startMovingTo(parent, speed)
}
}
}
| 1 | null | 1 | 1 | 00cb8412f21cb578c1712e1b95365084e6f99675 | 2,070 | SquidFriends | MIT License |
libbase/src/main/java/com/earth/libbase/network/request/PhotoAddDetail.kt | engineerrep | 643,933,914 | false | {"Java": 2291635, "Kotlin": 1651449} | package com.earth.libbase.network.request
import com.google.gson.annotations.SerializedName
data class PhotoAddDetail(
@SerializedName("friendMobilePhoneName")
var friendMobilePhoneName: String? = null,
@SerializedName("friendMobilePhoneNumber")
var friendMobilePhoneNumber: String? = null
)
| 1 | null | 1 | 1 | 415e0417870b6ff2c84a9798d1f3f3a4e6921354 | 310 | EarthAngel | MIT License |
Wechat_chatroom_helper_android/app/src/main/kotlin/com/zdy/project/wechat_chatroom_helper/helper/manager/PermissionHelper.kt | zhudongya123 | 96,015,224 | false | {"Text": 1, "Ignore List": 3, "Markdown": 2, "Gradle": 4, "Java Properties": 2, "Shell": 1, "Batchfile": 1, "INI": 1, "XML": 36, "Java": 11, "Proguard": 1, "Kotlin": 68} | package com.zdy.project.wechat_chatroom_helper.helper.manager
import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.blankj.utilcode.util.SPUtils
import com.zdy.project.wechat_chatroom_helper.io.WechatJsonUtils
import com.zdy.project.wechat_chatroom_helper.helper.ui.main.MainActivity
import com.zdy.project.wechat_chatroom_helper.helper.ui.newConfig.PermissionResult
/**
* Created by Mr.Zdy on 2017/11/3.
*/
class PermissionHelper(private var context: Context) {
companion object {
@JvmStatic
val ALLOW = 0
@JvmStatic
val DENY = 2
@JvmStatic
val ASK = 1
@JvmStatic
fun checkFile(activity: Activity): PermissionHelper {
val permissionHelper = PermissionHelper(activity)
//没有权限
if (ContextCompat.checkSelfPermission(
activity,
Manifest.permission.WRITE_EXTERNAL_STORAGE
) != PackageManager.PERMISSION_GRANTED
) {
//拒絕過權限授予,直接提醒跳轉到設置
if (!ActivityCompat.shouldShowRequestPermissionRationale(
activity,
Manifest.permission.WRITE_EXTERNAL_STORAGE
)
&& SPUtils.getInstance().getBoolean("Permission_Flag", false)
) {
}
//請求權限授予
else {
}
}
//有权限,初始化文件
else {
WechatJsonUtils.init(activity)
}
return permissionHelper
}
@JvmStatic
fun requestPermission(activity: Activity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
val intent = Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION)
activity.startActivity(intent)
} else {
SPUtils.getInstance().put("Permission_Flag", true)
ActivityCompat.requestPermissions(
activity,
arrayOf(
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE
),
MainActivity.WRITE_EXTERNAL_STORAGE_RESULT_CODE
)
}
}
@JvmStatic
fun gotoPermissionPage(activity: Activity) {
val intent = Intent().also { intent ->
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
intent.data = Uri.fromParts("package", activity.packageName, null)
}
activity.startActivity(intent)
}
@SuppressLint("NewApi")
@JvmStatic
fun check(activity: Activity): PermissionResult {
//没有权限
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
return PermissionResult.Pass
} else {
val isHavePermission = ContextCompat.checkSelfPermission(
activity,
Manifest.permission.WRITE_EXTERNAL_STORAGE
) != PackageManager.PERMISSION_GRANTED
return if (isHavePermission) {
//拒絕過權限授予
if (!ActivityCompat.shouldShowRequestPermissionRationale(
activity, Manifest.permission.WRITE_EXTERNAL_STORAGE
)
&& SPUtils.getInstance().getBoolean("Permission_Flag", false)
) {
PermissionResult.Deny
}
//請求權限授予
else {
PermissionResult.Ask
}
} else PermissionResult.Pass
}
}
}
} | 11 | Kotlin | 21 | 86 | 641d8d004212196d443056a7b428ba03be60b4ec | 4,166 | WechatChatRoomHelper | Apache License 2.0 |
Common/src/main/java/at/petrak/hexcasting/common/casting/operators/selectors/OpGetEntityAt.kt | tynberry | 555,974,628 | true | {"Java Properties": 1, "Groovy": 1, "Text": 3, "Gradle": 5, "Shell": 1, "Markdown": 2, "Git Attributes": 1, "Batchfile": 1, "Ignore List": 1, "INI": 4, "Kotlin": 178, "Java": 281, "JSON": 1012, "GLSL": 1, "YAML": 1, "HTML": 1, "Python": 1, "TOML": 1} | package at.petrak.hexcasting.common.casting.operators.selectors
import at.petrak.hexcasting.api.spell.ConstManaOperator
import at.petrak.hexcasting.api.spell.SpellDatum
import at.petrak.hexcasting.api.spell.asSpellResult
import at.petrak.hexcasting.api.spell.casting.CastingContext
import at.petrak.hexcasting.api.spell.getChecked
import net.minecraft.world.entity.Entity
import net.minecraft.world.phys.AABB
import net.minecraft.world.phys.Vec3
import java.util.function.Predicate
class OpGetEntityAt(val checker: Predicate<Entity>) : ConstManaOperator {
override val argc = 1
override fun execute(args: List<SpellDatum<*>>, ctx: CastingContext): List<SpellDatum<*>> {
val pos = args.getChecked<Vec3>(0, argc)
ctx.assertVecInRange(pos)
val aabb = AABB(pos.add(Vec3(-0.5, -0.5, -0.5)), pos.add(Vec3(0.5, 0.5, 0.5)))
val entitiesGot = ctx.world.getEntities(null, aabb)
{ checker.test(it) && ctx.isEntityInRange(it) && it.isAlive && !it.isSpectator }
val entity = entitiesGot.getOrNull(0)
return entity.asSpellResult
}
}
| 0 | null | 0 | 0 | 5193a20a0a909a68b60cbafc9115c9833c18cc45 | 1,094 | HexMod | MIT License |
UtilsSample/Dagger/src/main/java/sample/util/develop/android/dagger/mvp/presenter/MVPPresenter.kt | dulexu | 215,254,226 | true | {"Markdown": 85, "Text": 4, "Ignore List": 74, "HTML": 101, "Java Properties": 43, "Gradle": 114, "Shell": 25, "Batchfile": 25, "Proguard": 44, "Java": 646, "XML": 544, "Kotlin": 197, "CSS": 1, "INI": 8, "JSON": 9, "JavaScript": 7, "CMake": 1, "C++": 1, "JSON with Comments": 1, "Git Attributes": 1, "Starlark": 2, "Objective-C": 4, "OpenStep Property List": 4} | package sample.util.develop.android.dagger.mvp.presenter
/**
* by y on 2017/5/31.
*/
interface MVPPresenter {
fun startNetWork()
}
| 0 | null | 0 | 0 | f8e5e02467b2ff6dd1e9d2cdfdf766320c5dedd2 | 139 | AndroidDevelop | Apache License 2.0 |
referencedumpsview/src/main/java/com/yan/referencecount/dumps/view/AutoShowProvider.kt | genius158 | 314,809,675 | false | {"Markdown": 3, "Gradle": 14, "Java Properties": 2, "Shell": 1, "Ignore List": 12, "Batchfile": 1, "INI": 9, "Proguard": 11, "XML": 22, "Java": 25, "Kotlin": 28, "Checksums": 6, "CMake": 25, "C++": 44, "C": 7, "Soong": 1, "JSON": 25, "Text": 57, "Ninja": 12} | package com.yan.referencecount.dumps.view
import android.app.Application
import android.content.ContentProvider
import android.content.ContentValues
import android.database.Cursor
import android.net.Uri
import com.yan.referencecount.dump.objectcalculate.ObjectCalculator
import com.yan.referencecount.dumps.ReferenceMgr
/**
* @author Bevan (Contact me: https://github.com/genius158)
* @since 2020/11/28
*/
class AutoShowProvider : ContentProvider() {
override fun onCreate(): Boolean {
ReferenceMgr.setOnDumpListener(OnDumpWithSizeListener.ins)
val app = context?.applicationContext as Application
WindowPop.attachDumpView(app)
ObjectCalculator.ins.loadCtx(app)
return true
}
override fun insert(uri: Uri, values: ContentValues?): Uri? {
throw NotImplementedError()
}
override fun query(uri: Uri, projection: Array<out String>?, selection: String?, selectionArgs: Array<out String>?, sortOrder: String?): Cursor? {
throw NotImplementedError()
}
override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int {
throw NotImplementedError()
}
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int {
throw NotImplementedError()
}
override fun getType(uri: Uri): String? {
throw NotImplementedError()
}
} | 1 | null | 1 | 1 | eeaf6fdff33f1a515670b84019bb11ea13fc3bac | 1,425 | ReferenceDump | Apache License 2.0 |
app/src/main/java/com/loan/golden/cash/money/loan/data/response/RaddlemanResponse.kt | williamXw | 693,063,899 | false | {"Java": 2423785, "Kotlin": 747998} | package com.loan.golden.cash.money.loan.data.response
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
/**
* @Author : hxw
* @Date : 2023/10/18 14:28
* @Describe :
*/
@Parcelize
class RaddlemanResponse(
var status: Int = 0,
var time: Long = 0,
var maxAge: Int = 0,
var message: String = "",
var model: ModelBean? = null
) : Parcelable {
@Parcelize
class ModelBean(
var id: String = "",
var created: Long = 0,
var modified: Long = 0,
var typeId: String = "",
var content: String = "",
var images: ArrayList<String> = arrayListOf(),
var thirdOrderId: String = "",
var reply: Boolean = false
) : Parcelable
} | 1 | null | 1 | 1 | 2ba6be236ce6de634dda7d02f78d87b4a6f9c7f6 | 743 | goldenMoney | Apache License 2.0 |
baselibrary/src/main/java/com/hh/baselibrary/mvp/BaseActivity.kt | hHui056 | 673,264,161 | false | {"Java": 261954, "Kotlin": 113384, "C": 402, "Batchfile": 225} | package com.hh.baselibrary.mvp
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.app.AppCompatActivity
import com.hh.baselibrary.util.StatusBarUtil
import com.hh.baselibrary.util.ToastUtil
import com.hh.baselibrary.util.licence.LicenceUtil
import com.hh.baselibrary.widget.MyAlertDialog
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.util.*
import kotlin.system.exitProcess
/**
* Create By hHui on 2021/3/23 0023
*
* Activity基类,所有Activity都继承此类
*/
abstract class BaseActivity : AppCompatActivity(), BaseContract.View {
val tag = this.javaClass.simpleName
lateinit var alertDialog: MyAlertDialog //提示框
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
alertDialog = MyAlertDialog(this, BaseApplication.dialogStyle)
BaseApplication.instance.addActivity(this)
setStatusBar()
}
override fun onDestroy() {
super.onDestroy()
BaseApplication.instance.removeActivity(this)
}
abstract fun initView()
abstract fun transportStatusBar(): Boolean
override fun showProgress(msg: String) {
alertDialog.showDialogLoading(msg)
}
override fun showProgressCanCle(
msg: String,
cancelText: String,
callback: MyAlertDialog.CancelClickBack?
) {
alertDialog.showDialogLoadingCancel(msg, cancelText, callback)
}
override fun closeProgress() {
alertDialog.closeDialogLoading()
}
override fun alertError(title: String, msg: String) {
alertDialog.alertErrorMsg(title, msg)
}
override fun alertSuccess(msg: String) {
alertDialog.alertSuccessMsg(msg)
}
override fun alertOption(
title: String,
msg: String,
callback: MyAlertDialog.AlertClickBack,
cancel: String,
sure: String
) {
alertDialog.alertOption(title, msg, callback, cancel, sure)
}
override fun alertOneButtonOption(
title: String, msg: String, callback: MyAlertDialog.ClickBack, buttonText: String
) {
alertDialog.alertOneButtonOption(title, msg, callback, buttonText)
}
override fun showToast(msg: String) {
ToastUtil.showToast(this, msg)
}
override fun miss() = finish()
fun <T> jump2Activity(cla: Class<T>, isFinishBefore: Boolean) {
startActivity(Intent(this, cla))
if (isFinishBefore) finish()
}
fun <T> jump2Activity(cla: Class<T>, map: Map<String, String>, isFinishBefore: Boolean) {
val intent = Intent(this, cla)
map.forEach { intent.putExtra(it.key, it.value) }
startActivity(intent)
if (isFinishBefore) finish()
}
/**
* 设置沉浸式状态栏
*/
private fun setStatusBar() {
if (transportStatusBar()) {
StatusBarUtil.setTranslucentStatus(this)
} else {
StatusBarUtil.setRootViewFitsSystemWindows(this, true)
StatusBarUtil.setStatusBarColor(this, BaseApplication.logoColor)
}
}
/**
* 关闭软键盘
*/
fun hintKeyBoard() {
//拿到InputMethodManager
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
//如果window上view获取焦点 && view不为空
if (imm.isActive && currentFocus != null) {
//拿到view的token 不为空
if (currentFocus?.windowToken != null) {
//表示软键盘窗口总是隐藏,除非开始时以SHOW_FORCED显示。
imm.hideSoftInputFromWindow(
currentFocus?.windowToken, InputMethodManager.HIDE_NOT_ALWAYS
)
}
}
}
override fun onTouchEvent(event: MotionEvent): Boolean {
if (event.action == MotionEvent.ACTION_DOWN) {
if (currentFocus != null) {
hintKeyBoard()
}
}
return super.onTouchEvent(event)
}
@SuppressLint("CheckResult")
private fun checkLicence() {
LicenceUtil.instance.getLicence().subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()).subscribe({
try {
if (!it!!.permanentValidity && it.endAt!!.before(Date())) {
alertOutDate()
}
} catch (e: Exception) {
e.printStackTrace()
}
}, {
Log.e("pj_log", "check licence fail: ${it.localizedMessage}")
if (it.localizedMessage.contains("404")) {
alertOutDate()
}
})
}
private fun alertOutDate() {
alertOption("提示", "应用未授权或授权已过期,请联系开发人员", object : MyAlertDialog.AlertClickBack {
override fun onConfirm() = exitProcess(0)
override fun onCancel() = exitProcess(0)
})
}
} | 1 | null | 1 | 1 | ef73087afb2269623d6a2eac534ed1cde7b86050 | 5,059 | android_mvp_generate | Mulan Permissive Software License, Version 2 |
issue-repro/src/main/kotlin/com/airbnb/lottie/issues/IssueReproActivity.kt | oOJohn6Oo | 763,420,318 | true | {"Markdown": 9, "JavaScript": 1, "Batchfile": 1, "Shell": 6, "INI": 4, "Java Properties": 1, "Proguard": 2, "Kotlin": 171, "Java": 222} | package com.airbnb.lottie.issues
import android.os.Bundle
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.airbnb.lottie.LottieAnimationView
import com.airbnb.lottie.LottieDrawable
import com.airbnb.lottie.issues.databinding.IssueReproActivityBinding
class IssueReproActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = IssueReproActivityBinding.inflate(layoutInflater)
setContentView(binding.root)
// Reproduce any issues here.
binding.animationView.setAnimation(R.raw.heart)
binding.animationView.setOnClickListener {
if((it as LottieAnimationView).drawable is LottieDrawable){
it.setImageDrawable(ContextCompat.getDrawable(this, R.mipmap.ic_launcher))
}else{
it.setAnimation(R.raw.heart)
it.playAnimation()
}
}
}
}
| 0 | Java | 0 | 0 | 7981f35ed9ca7d6d0fd71b478cd625ddec680a5d | 1,035 | lottie-android | Apache License 2.0 |
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/powerplay/Robot.kt | Chonks1000000 | 562,622,515 | true | {"Java Properties": 1, "Gradle": 6, "Shell": 1, "Markdown": 9, "Batchfile": 1, "Text": 4, "Ignore List": 2, "XML": 19, "INI": 1, "Java": 87, "Kotlin": 55} | package org.firstinspires.ftc.teamcode.powerplay
import com.qualcomm.robotcore.hardware.HardwareMap
import org.firstinspires.ftc.teamcode.powerplay.subsystems.Claw
import org.firstinspires.ftc.teamcode.powerplay.subsystems.Slides
import org.firstinspires.ftc.teamcode.util.Subsystem
class Robot: Subsystem {
private val claw = Claw()
private val slides = Slides()
private val subsystems = mutableListOf(
claw,slides
)
fun clawOpened() {
claw.openClaw()
}
fun clawClosed() {
claw.closeClaw()
}
fun slidesUp() {
slides.up()
}
fun slidesDown() {
slides.down()
}
fun slidesOff() {
slides.off()
}
override fun init(hardwareMap: HardwareMap) {
subsystems.forEach{it.init(hardwareMap)}
}
override fun update() {
subsystems.forEach{it.update()}
}
override fun reset() {
subsystems.forEach{it.reset()}
}
} | 0 | Java | 0 | 0 | 80321ac8bbbf7176346d543c504f2158dd3a040a | 958 | Testing | BSD 3-Clause Clear License |
app/src/main/java/com/example/owocewarzywa/utils/FirestoreUtil.kt | Bublelift | 786,259,761 | false | {"Gradle": 3, "JSON": 136, "Java Properties": 5, "Markdown": 3, "Shell": 1, "Text": 11, "Batchfile": 1, "Proguard": 1, "XML": 220, "Kotlin": 40, "Java": 83, "INI": 1, "Motorola 68K Assembly": 5, "SQL": 4, "SVG": 1} | package com.example.owocewarzywa.utils
import android.content.Context
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import com.example.owocewarzywa.model.*
import com.example.owocewarzywa.recyclerview.item.PersonItem
import com.example.owocewarzywa.recyclerview.item.TextMessageItem
import com.google.apphosting.datastore.testing.DatastoreTestTrace.FirestoreV1Action.Listen
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.DocumentReference
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.ListenerRegistration
import com.google.firebase.firestore.ktx.toObject
import com.xwray.groupie.kotlinandroidextensions.Item
//JK
object FirestoreUtil {
private val firestoreInstance: FirebaseFirestore by lazy { FirebaseFirestore.getInstance() }
private val currentUserDocRef: DocumentReference
get() = firestoreInstance.document("users/${FirebaseAuth.getInstance().uid}")
private val chatChannelsCollectionRef = firestoreInstance.collection("chatChannels")
private var userList = "swing" ?: null
fun updateCurrentUser(name: String = "", bio: String = "", profilePicturePath: String? = null) {
val userFieldMap = mutableMapOf<String, Any>()
userFieldMap["uid"] = FirebaseAuth.getInstance().currentUser!!.uid
if (name.isNotBlank()) userFieldMap["name"] = name
if (bio.isNotBlank()) userFieldMap["bio"] = bio
if (profilePicturePath != null) userFieldMap["profilePicturePath"] = profilePicturePath
currentUserDocRef.update(userFieldMap)
}
fun initCurrentUserIfFirstTime(onComplete: () -> Unit) {
currentUserDocRef.get().addOnSuccessListener { documentSnapshot ->
if (!documentSnapshot.exists()) {
val newUser = User(
name = FirebaseAuth.getInstance().currentUser?.displayName ?: "",
bio = "",
profilePicturePath = null,
score = 0L
)
currentUserDocRef.set(newUser).addOnSuccessListener { onComplete() }
} else onComplete()
}
}
fun getCurrentUser(onComplete: (User) -> Unit) {
Log.e("FirestoreUtil", currentUserDocRef.get().toString())
currentUserDocRef.get().addOnSuccessListener { onComplete(it.toObject(User::class.java)!!) }
}
fun addUsersListener(context: Context, onListen: (List<Item>) -> Unit): ListenerRegistration {
return firestoreInstance.collection("users")
.addSnapshotListener { querySnapshot, firebaseFirestoreException ->
if (firebaseFirestoreException != null) {
Log.e(
"Firestore",
"Dupa na firestoreutil.kt 59",
firebaseFirestoreException
)
return@addSnapshotListener
}
val items = mutableListOf<Item>()
querySnapshot?.documents?.forEach {
if (it.id != FirebaseAuth.getInstance().currentUser?.uid)
items.add(PersonItem(it.toObject(User::class.java)!!, it.id, context))
}
onListen(items)
}
}
fun removeListener(registration: ListenerRegistration) = registration.remove()
fun getOrCreateChatChannel(otherUserId: String, onComplete: (channelId: String) -> Unit) {
currentUserDocRef.collection("engagedChatChannels").document(otherUserId).get()
.addOnSuccessListener {
if (it.exists()) {
onComplete(it["channelId"] as String)
return@addOnSuccessListener
}
val currentUserId = FirebaseAuth.getInstance().currentUser!!.uid
val newChannel = chatChannelsCollectionRef.document()
newChannel.set(ChatChannel(mutableListOf(currentUserId, otherUserId)))
currentUserDocRef.collection("engagedChatChannels")
.document(otherUserId)
.set(mapOf("channelId" to newChannel.id))
firestoreInstance.collection("users").document(otherUserId)
.collection("engagedChatChannels")
.document(currentUserId)
.set(mapOf("channelId" to newChannel.id))
onComplete(newChannel.id)
}
}
fun addChatMessagesListener(channelId: String, context: Context, onListen: (List<Item>) -> Unit) : ListenerRegistration {
return chatChannelsCollectionRef.document(channelId).collection("messages").orderBy("time")
.addSnapshotListener{
querySnapshot, firebaseFirestoreException ->
if (firebaseFirestoreException != null) {
Log.e("FirestoreException", "Wywaliło się na FirestoreUtil 102", firebaseFirestoreException)
return@addSnapshotListener
}
val items = mutableListOf<Item>()
querySnapshot!!.documents.forEach {
items.add(TextMessageItem(it.toObject(TextMessage::class.java)!!, context))
}
onListen(items)
}
}
fun sendMessage(message: TextMessage, channelId: String) {
chatChannelsCollectionRef.document(channelId).collection("messages").add(message)
}
fun getMsgReadStatus(chatroomId: String, onSuccess: (toReadBy: String) -> Unit){
var toReadBy: String? = null
chatChannelsCollectionRef.document(chatroomId).get()
.addOnSuccessListener { if (it.exists()) {
toReadBy = it["status"].toString()
}
if (toReadBy == null || toReadBy!!.isBlank())
onSuccess("")
else onSuccess(toReadBy!!)
}
}
fun setMsgReadStatus(chatroomId: String, status: String) {
val currentUserId = FirebaseAuth.getInstance().currentUser!!.uid
chatChannelsCollectionRef.document(chatroomId).update("status", status)
}
fun sendFeedback(feedback: String) {
firestoreInstance.collection("feedbacks").add(
mapOf("uid" to FirebaseAuth.getInstance().currentUser!!.uid, "feedback" to feedback)
)
}
fun updateUserScore(score: Int) {
currentUserDocRef.get().addOnSuccessListener {
val current_score = ((it.data?.get("score") as Long?)?.toInt() ?: 0) + score
currentUserDocRef.update("score", current_score)
}
}
} | 0 | Java | 0 | 0 | d5478359fd64fcebbcc5fe8953d346dbb04d9a47 | 6,666 | app-eng | Apache License 2.0 |
src/main/java/com/tabnine/binary/requests/autocomplete/SnippetContext.kt | qauzy | 587,655,659 | true | {"Shell": 7, "Markdown": 2, "Batchfile": 1, "Kotlin": 73, "Java": 115, "INI": 1} | package com.tabnine.binary.requests.autocomplete
data class SnippetContext(
val stop_reason: String?,
val generated_tokens: Int?,
val user_intent: UserIntent,
val intent_metadata: SnippetIntentMetadata?,
val response_time_ms: Int?,
val is_cached: Boolean?,
val context_len: Int?,
val first_token_score: String?,
)
data class SnippetIntentMetadata(
val current_line_indentation: Int?,
val previous_line_indentation: Int?,
val triggered_after_character: Char?
)
| 1 | null | 1 | 1 | 7255f29a951c758d5850504113c16f5d2485bf7f | 506 | tabnine-intellij | MIT License |
packages/SystemUI/animation/src/com/android/systemui/surfaceeffects/ripple/RippleAnimation.kt | liu-wanshun | 595,904,109 | true | null | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.systemui.surfaceeffects.ripple
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
import androidx.annotation.VisibleForTesting
import androidx.core.graphics.ColorUtils
/** A single ripple animation. */
class RippleAnimation(private val config: RippleAnimationConfig) {
@VisibleForTesting(otherwise = VisibleForTesting.PACKAGE_PRIVATE)
val rippleShader: RippleShader = RippleShader(config.rippleShape)
private val animator: ValueAnimator = ValueAnimator.ofFloat(0f, 1f)
init {
applyConfigToShader()
}
/** Updates the ripple color during the animation. */
fun updateColor(color: Int) {
config.apply { config.color = color }
applyConfigToShader()
}
@JvmOverloads
fun play(onAnimationEnd: Runnable? = null) {
if (isPlaying()) {
return // Ignore if ripple effect is already playing
}
animator.duration = config.duration
animator.addUpdateListener { updateListener ->
val now = updateListener.currentPlayTime
val progress = updateListener.animatedValue as Float
rippleShader.progress = progress
rippleShader.distortionStrength = if (config.shouldDistort) 1 - progress else 0f
rippleShader.time = now.toFloat()
}
animator.addListener(
object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator?) {
onAnimationEnd?.run()
}
}
)
animator.start()
}
/** Indicates whether the animation is playing. */
fun isPlaying(): Boolean = animator.isRunning
private fun applyConfigToShader() {
rippleShader.setCenter(config.centerX, config.centerY)
rippleShader.setMaxSize(config.maxWidth, config.maxHeight)
rippleShader.rippleFill = config.shouldFillRipple
rippleShader.pixelDensity = config.pixelDensity
rippleShader.color = ColorUtils.setAlphaComponent(config.color, config.opacity)
rippleShader.sparkleStrength = config.sparkleStrength
}
}
| 0 | Java | 1 | 2 | e99201cd9b6a123b16c30cce427a2dc31bb2f501 | 2,811 | platform_frameworks_base | Apache License 2.0 |
kotlin/코틀린 완벽 가이드/080250/Chapter14/KoTest/src/test/kotlin/NumbersTest7.kt | devYSK | 461,887,647 | false | {"Java": 3507759, "JavaScript": 659549, "Kotlin": 563136, "HTML": 455168, "CSS": 446825, "Shell": 57444, "Groovy": 54414, "Batchfile": 47890, "Go": 26805, "Python": 9963, "Handlebars": 8554, "Makefile": 7837, "Vue": 5706, "TypeScript": 5172, "Dockerfile": 436, "Vim Snippet": 362, "Assembly": 278, "Procfile": 199} | import io.kotest.core.spec.style.FeatureSpec
import io.kotest.matchers.shouldBe
class NumbersTest7 : FeatureSpec({
feature("Arithmetic") {
val x = 1
scenario("x is 1 at first") { x shouldBe 1 }
feature("increasing by") {
scenario("1 gives 2") { (x + 1) shouldBe 2 }
scenario("2 gives 3") { (x + 2) shouldBe 3 }
}
}
}) | 1 | null | 1 | 1 | 7a7c6b1bab3dc2c84527f8c528b06b9408872635 | 350 | study_repo | MIT License |
src/main/java/mods/eln/transparentnode/LargeRheostat.kt | VoXaN24 | 286,433,584 | false | {"Java": 2449574, "Kotlin": 322226, "Shell": 1146, "Python": 489, "Nix": 459} | package mods.eln.transparentnode
import mods.eln.gui.GuiContainerEln
import mods.eln.gui.GuiHelperContainer
import mods.eln.gui.HelperStdContainer
import mods.eln.i18n.I18N
import mods.eln.i18n.I18N.tr
import mods.eln.misc.*
import mods.eln.misc.series.SerieEE
import mods.eln.node.NodeBase
import mods.eln.node.transparent.*
import mods.eln.sim.ElectricalLoad
import mods.eln.sim.IProcess
import mods.eln.sim.ThermalLoad
import mods.eln.sim.mna.component.Resistor
import mods.eln.sim.mna.misc.MnaConst
import mods.eln.sim.nbt.NbtElectricalGateInput
import mods.eln.sim.nbt.NbtElectricalLoad
import mods.eln.sim.nbt.NbtThermalLoad
import mods.eln.sim.process.destruct.ThermalLoadWatchDog
import mods.eln.sim.process.destruct.WorldExplosion
import mods.eln.sim.process.heater.ResistorHeatThermalLoad
import mods.eln.sixnode.electricalcable.ElectricalCableDescriptor
import mods.eln.sixnode.resistor.ResistorContainer
import mods.eln.transparentnode.thermaldissipatorpassive.ThermalDissipatorPassiveDescriptor
import net.minecraft.client.gui.GuiScreen
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.inventory.IInventory
import net.minecraft.item.ItemStack
import org.lwjgl.opengl.GL11
import java.io.DataInputStream
import java.io.DataOutputStream
// TODO: Make the whole thing brighter when it heats up, not just redder.
class LargeRheostatDescriptor(name: String, val dissipator: ThermalDissipatorPassiveDescriptor, val cable: ElectricalCableDescriptor, val series: SerieEE) :
TransparentNodeDescriptor(name, LargeRheostatElement::class.java, LargeRheostatRender::class.java) {
init {
voltageLevelColor = VoltageLevelColor.Neutral
}
fun getRsValue(inventory: IInventory): Double {
val core = inventory.getStackInSlot(ResistorContainer.coreId)
return series.getValue(core.count)
}
fun draw(position: Float = 0f) {
dissipator.draw()
GL11.glRotatef((1f - position) * 300f, 0f, 1f, 0f)
dissipator.obj.getPart("wiper")?.draw()
}
// TODO(1.10): Items rendering.
// override fun handleRenderType(item: ItemStack, type: IItemRenderer.ItemRenderType) = true
// override fun shouldUseRenderHelper(type: IItemRenderer.ItemRenderType, item: ItemStack,
// helper: IItemRenderer.ItemRendererHelper) = type != IItemRenderer.ItemRenderType.INVENTORY
//
// override fun renderItem(type: IItemRenderer.ItemRenderType, item: ItemStack, vararg data: Any) =
// if (type != IItemRenderer.ItemRenderType.INVENTORY) draw() else super.renderItem(type, item, *data)
}
class LargeRheostatElement(node: TransparentNode, desc_: TransparentNodeDescriptor) :
TransparentNodeElement(node, desc_) {
val desc = desc_ as LargeRheostatDescriptor
var nominalRs = 1.0
private var inventory = TransparentNodeElementInventory(2, 64, this)
val aLoad = NbtElectricalLoad("aLoad")
val bLoad = NbtElectricalLoad("bLoad")
val resistor = Resistor(aLoad, bLoad).apply { setR(nominalRs) }
val control = NbtElectricalGateInput("control")
val controlProcess = ControlProcess()
val thermalLoad = NbtThermalLoad("thermalLoad")
val heater = ResistorHeatThermalLoad(resistor, thermalLoad)
val thermalWatchdog = ThermalLoadWatchDog()
init {
// Electrics
grounded = false
electricalLoadList.add(aLoad)
electricalLoadList.add(bLoad)
electricalComponentList.add(resistor)
electricalLoadList.add(control)
slowProcessList.add(controlProcess)
// Heating
thermalLoadList.add(thermalLoad)
thermalFastProcessList.add(heater)
slowProcessList.add(thermalWatchdog)
thermalWatchdog.set(thermalLoad).setTMax(desc.dissipator.warmLimit)
.set(WorldExplosion(this).machineExplosion())
}
inner class ControlProcess() : IProcess {
var lastC = -1000.0
var lastH = -1000.0
override fun process(time: Double) {
val desiredRs = (control.normalized + 0.01) / 1.01 * nominalRs
if (desiredRs > lastC * 1.01 || desiredRs < lastC * 0.99) {
resistor.r = desiredRs
lastC = desiredRs
needPublish()
}
if (thermalLoad.Tc > lastH * 1.05 || thermalLoad.Tc < lastH * 0.95) {
lastH = thermalLoad.Tc
needPublish()
}
}
}
override fun getElectricalLoad(side: Direction, lrdu: LRDU): ElectricalLoad? {
if (lrdu != LRDU.Down) return null
return when (side) {
front.right() -> aLoad
front.left() -> bLoad
front -> control
else -> null
}
}
override fun getThermalLoad(side: Direction, lrdu: LRDU): ThermalLoad? {
if (lrdu != LRDU.Down) return null
// This one's insulated, since its max heat is 1000C.
return when (side) {
front.back() -> thermalLoad
else -> null
}
}
override fun getConnectionMask(side: Direction, lrdu: LRDU): Int {
if (lrdu != LRDU.Down) return 0
return when (side) {
front -> NodeBase.maskElectricalInputGate
front.back() -> NodeBase.maskThermal
else -> NodeBase.maskElectricalPower
}
}
fun setupPhysical() {
nominalRs = desc.getRsValue(inventory)
controlProcess.process(0.0)
}
override fun inventoryChange(inventory: IInventory?) {
super.inventoryChange(inventory)
setupPhysical()
}
override fun multiMeterString(side: Direction): String {
val u = -Math.abs(aLoad.u - bLoad.u)
val i = Math.abs(resistor.i)
return Utils.plotOhm(Utils.plotUIP(u, i), resistor.r) + Utils.plotPercent("C", control.normalized)
}
override fun thermoMeterString(side: Direction) =
Utils.plotCelsius("T: ", thermalLoad.Tc) + Utils.plotPower("P: ", thermalLoad.power)
override fun initialize() {
desc.dissipator.applyTo(thermalLoad)
aLoad.rs = MnaConst.noImpedance
bLoad.rs = MnaConst.noImpedance
setupPhysical()
connect()
}
override fun networkSerialize(stream: DataOutputStream) {
super.networkSerialize(stream)
stream.writeFloat(thermalLoad.Tc.toFloat())
stream.writeFloat(control.normalized.toFloat())
}
override fun hasGui() = true
override fun getInventory() = inventory
override fun onBlockActivated(entityPlayer: EntityPlayer?, side: Direction?, vx: Float, vy: Float, vz: Float) = false
override fun newContainer(side: Direction?, player: EntityPlayer?) = ResistorContainer(player, inventory)
override fun getWaila(): Map<String, String> = mutableMapOf(
Pair(I18N.tr("Resistance"), Utils.plotOhm("", resistor.r)),
Pair(I18N.tr("Temperature"), Utils.plotCelsius("", thermalLoad.t)),
Pair(I18N.tr("Power loss"), Utils.plotPower("", resistor.p))
)
}
class LargeRheostatRender(entity: TransparentNodeEntity, desc: TransparentNodeDescriptor) :
TransparentNodeElementRender(entity, desc) {
val desc = desc as LargeRheostatDescriptor
val inventory = TransparentNodeElementInventory(1, 64, this)
override fun getInventory(): IInventory {
return inventory
}
val baseColor = BlackBodyColor(1f, 1f, 1f)
var color = BlackBodyTemperature(0f)
val positionAnimator = SlewLimiter(0.3f)
init {
positionAnimator.target = -1f
}
override fun draw() {
front.glRotateZnRef()
// TODO: Get this thing *really* glowing.
// glColor doesn't let me exceed 1.0, the way I'd quite like to do.
GL11.glColor3f(color.red, color.green, color.blue)
desc.draw(positionAnimator.position)
}
override fun refresh(deltaT: Float) {
super.refresh(deltaT)
positionAnimator.step(deltaT)
}
override fun networkUnserialize(stream: DataInputStream) {
super.networkUnserialize(stream)
val temp = stream.readFloat() + 273
val c = BlackBodyTemperature(temp)
val p = BlackBodyPower(temp)
var bbc = c * (p / desc.dissipator.nominalP.toFloat())
color = (bbc + baseColor).normalize()
if (positionAnimator.target == -1f) {
positionAnimator.target = stream.readFloat()
positionAnimator.position = positionAnimator.target
} else {
positionAnimator.target = stream.readFloat()
}
}
override fun newGuiDraw(side: Direction, player: EntityPlayer): GuiScreen {
return LargeRheostatGUI(player, inventory, this)
}
}
class LargeRheostatGUI(player: EntityPlayer, inventory: IInventory, internal var render: LargeRheostatRender) :
GuiContainerEln(ResistorContainer(player, inventory)) {
override fun postDraw(f: Float, x: Int, y: Int) {
helper.drawString(8, 12, -16777216, tr("Nom. Resistance: %s", Utils.plotValue(render.desc.getRsValue(render.inventory), "Ohm")))
super.postDraw(f, x, y)
}
override fun newHelper(): GuiHelperContainer {
return HelperStdContainer(this)
}
}
| 1 | null | 1 | 1 | 8b54855a8709438dd66cd11273ce59e368800f91 | 9,187 | electricalage-1.12 | Creative Commons Zero v1.0 Universal |
airbyte-cdk/java/airbyte-cdk/core/src/main/kotlin/io/airbyte/cdk/db/jdbc/streaming/JdbcStreamingQueryConfig.kt | tim-werner | 511,419,970 | false | {"Java Properties": 8, "Shell": 57, "Markdown": 1170, "Batchfile": 1, "Makefile": 3, "JavaScript": 31, "CSS": 9, "Python": 4183, "Kotlin": 845, "Java": 723, "INI": 10, "Dockerfile": 27, "HTML": 7, "SQL": 527, "PLpgSQL": 8, "TSQL": 1, "PLSQL": 2} | /*
* Copyright (c) 2023 Airbyte, Inc., all rights reserved.
*/
package io.airbyte.cdk.db.jdbc.streaming
import io.airbyte.commons.functional.CheckedBiConsumer
import java.sql.*
/*
* Interface that defines how to stream results from a Jdbc database. This involves determining
* updating what the fetch size should be based on the size of the existing rows. 1. The config
* initializes the fetch size and sets up the estimator. 2. The config then accepts each row and
* feeds it to the estimator. If the estimator has a new estimate, it updates the fetch size.
*/
interface JdbcStreamingQueryConfig : CheckedBiConsumer<ResultSet, Any, SQLException> {
@Throws(SQLException::class) fun initialize(connection: Connection, statement: Statement)
}
| 1 | null | 1 | 1 | b2e7895ed3e1ca7c1600ae1c23578dd1024f20ff | 754 | airbyte | MIT License |
src/main/kotlin/com/koresframework/kores/extra/UnifiedAnnotation.kt | koresframework | 85,362,482 | false | {"Gradle": 2, "INI": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "YAML": 1, "Java": 7, "Kotlin": 6, "Markdown": 139} | /*
* Kores-Extra - Kores Extras
*
* The MIT License (MIT)
*
* Copyright (c) 2021 JonathanxD <https://github.com/JonathanxD/Kores-Extra>
* Copyright (c) contributors
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.koresframework.kores.extra
import com.koresframework.kores.type.KoresType
/**
* Unified annotation base interface.
*
* **This interface is a trait**.
*/
interface UnifiedAnnotation {
/**
* Gets the annotation type of unified annotation.
*/
fun annotationType(): KoresType
/**
* Gets the annotation data.
*/
fun getUnifiedAnnotationData(): UnifiedAnnotationData
/**
* Returns the element that originated this annotation. (may be [Unit])
*/
fun getUnifiedAnnotationOrigin(): Any
} | 1 | Kotlin | 0 | 0 | b349a4fdd1ee961ef5894067df7eae12db9fd711 | 1,904 | Kores-Extra | MIT License |
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/test/ElevatorTest.kt | Petelax | 671,336,777 | false | {"Gradle": 6, "Java Properties": 1, "Shell": 1, "Text": 4, "Ignore List": 2, "Batchfile": 1, "Markdown": 7, "INI": 1, "XML": 20, "Java": 67, "Kotlin": 66} | package org.firstinspires.ftc.teamcode.drive.test
import com.acmerobotics.dashboard.FtcDashboard
import com.acmerobotics.dashboard.telemetry.MultipleTelemetry
import com.qualcomm.robotcore.eventloop.opmode.OpMode
import com.qualcomm.robotcore.eventloop.opmode.TeleOp
import org.firstinspires.ftc.teamcode.subsystems.Elevator
@TeleOp(group = "test")
class ElevatorTest: OpMode() {
private lateinit var elevator: Elevator
//private lateinit var elevator: MotorGroup
override fun init() {
telemetry = MultipleTelemetry(telemetry, FtcDashboard.getInstance().telemetry)
elevator = Elevator(hardwareMap, Elevator.Mode.RAW)
}
override fun loop() {
if (gamepad1.a) {
elevator.setpoint = Elevator.TOP
}
if (gamepad1.b) {
elevator.setpoint = Elevator.BOTTOM
}
elevator.set(-1.0*gamepad1.left_stick_y.toDouble())
elevator.periodic()
telemetry.addData("elevator", elevator.getCurrentPosition())
telemetry.addData("speed", elevator.get())
telemetry.update()
}
} | 0 | Java | 0 | 0 | a66accb94638fb15c099bf5a86a2938c348881b9 | 1,090 | FTC16413-CenterStage | BSD 3-Clause Clear License |
src/main/java/com/resuscitation/Instagram/user/entity/UserRole.kt | Team-Resuscitation | 675,347,330 | false | {"Java": 34331, "Kotlin": 6557} | package com.resuscitation.Instagram.user.entity
import org.springframework.security.core.GrantedAuthority
enum class UserRole : GrantedAuthority {
ROLE_ADMIN, ROLE_CLIENT;
override fun getAuthority(): String {
return name;
}
} | 1 | null | 1 | 1 | 59a423e6a92ef7b5b00a7c5403501b5f1cfc5ca3 | 249 | instagram-Server | MIT License |
packages/SystemUI/shared/src/com/android/systemui/unfold/system/ActivityManagerActivityTypeProvider.kt | liu-wanshun | 595,904,109 | true | null | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.android.systemui.unfold.system
import android.app.ActivityManager
import android.app.WindowConfiguration
import com.android.systemui.unfold.util.CurrentActivityTypeProvider
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ActivityManagerActivityTypeProvider @Inject constructor(
private val activityManager: ActivityManager
) : CurrentActivityTypeProvider {
override val isHomeActivity: Boolean?
get() {
val activityType = activityManager.getRunningTasks(/* maxNum= */ 1)
?.getOrNull(0)?.topActivityType ?: return null
return activityType == WindowConfiguration.ACTIVITY_TYPE_HOME
}
}
| 0 | Java | 1 | 2 | e99201cd9b6a123b16c30cce427a2dc31bb2f501 | 1,311 | platform_frameworks_base | Apache License 2.0 |
helper/src/main/java/me/hgj/mvvmhelper/core/livedata/DoubleLiveData.kt | williamXw | 693,063,899 | false | {"Java": 2423785, "Kotlin": 747998} | package me.hgj.mvvmhelper.core.livedata
import androidx.lifecycle.MutableLiveData
/**
* 作者 : hxw
* 时间 : 2023/9/3
* 描述 :自定义的Double类型 MutableLiveData 提供了默认值,避免取值的时候还要判空
*/
class DoubleLiveData : MutableLiveData<Double>() {
override fun getValue(): Double {
return super.getValue() ?: 0.0
}
} | 1 | null | 1 | 1 | 2ba6be236ce6de634dda7d02f78d87b4a6f9c7f6 | 312 | goldenMoney | Apache License 2.0 |
app/src/main/java/com/tntra/pargo2/model/notification/Notification.kt | milan656 | 395,915,799 | false | {"Gradle": 3, "YAML": 1, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 2, "Python": 1, "JSON": 1, "Proguard": 1, "Java": 21, "XML": 111, "Kotlin": 157} | package com.tntra.pargo2.model.notification
data class Notification(
val attributes: Attributes,
val id: String,
val type: String,
var addressTitle: String,
var fullAddress: String,
var date: String,
var building_uuid: String,
var dateFormated: String,
var createdAt: Long = 0,
val updatedAt: Long = 0,
val requestAccepted: Boolean
) | 1 | null | 1 | 1 | d4747dfaf535e0500d2ca3d10aec6289b536c791 | 378 | pargo | MIT License |
slayTheMiko/src/main/kotlin/slayTheMiko/relics/YoimiyaEye.kt | Obdormio | 516,196,427 | false | {"Java": 76658, "Kotlin": 59971} | package slayTheMiko.relics
import basemod.abstracts.CustomRelic
import com.badlogic.gdx.graphics.Texture
import slayTheMiko.SlayTheMikoMod
import slayTheMiko.util.TextureLoader
class YoimiyaEye : CustomRelic(ID, IMG, OUTLINE, RelicTier.STARTER, LandingSound.MAGICAL) {
companion object {
val ID = SlayTheMikoMod.makeID("YoimiyaEye")
val IMG: Texture = TextureLoader.getTexture(SlayTheMikoMod.makeRelicPath(("YoimiyaEye.png")))
val OUTLINE: Texture = TextureLoader.getTexture(SlayTheMikoMod.makeRelicOutlinePath("YoimiyaEye.png"))
}
}
| 1 | null | 1 | 1 | 67e2966a38efef2834c1970f24238c16c2367498 | 568 | slayTheMiko | MIT License |
Android/Courses/Android-Basics-with-Compose/Unit-1-Your-first-Android-app/1-Introduction-to-programming-in-Kotlin/4-Create-and-use-variables-in-Kotlin/4-Update-variables.kts | ronkitay | 10,026,035 | false | {"Text": 5, "Ignore List": 11, "Git Attributes": 2, "Go Workspace": 1, "Markdown": 26, "YAML": 34, "Gradle": 6, "Shell": 7, "Batchfile": 5, "INI": 8, "Java": 53, "OASv3-yaml": 1, "Maven POM": 9, "XML": 39, "Java Properties": 7, "Scala": 13, "JSON": 3, "Dockerfile": 2, "Python": 54, "Makefile": 1, "TOML": 7, "Gradle Kotlin DSL": 6, "Proguard": 2, "Kotlin": 22, "Go": 42, "Go Module": 42, "Lua": 2, "C++": 2} | var cartTotal = 0
println("Total: $cartTotal")
cartTotal = 20
println("Total: $cartTotal")
cartTotal = cartTotal + 1
println("Total: $cartTotal")
cartTotal++
println("Total: $cartTotal")
cartTotal--
println("Total: $cartTotal")
| 2 | Python | 0 | 0 | 27032d11ebb0903f5c920b1be50981250f38cb20 | 228 | Rons-Tutorials | MIT License |
src/main/kotlin/no/nav/veilarbaktivitet/aktivitetskort/idmapping/IdMapping.kt | navikt | 160,188,405 | false | {"Gradle Kotlin DSL": 2, "Markdown": 3, "CODEOWNERS": 1, "Dockerfile": 1, "INI": 3, "Shell": 2, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "Java": 267, "Java Properties": 2, "XML": 2, "JSON": 31, "Kotlin": 104, "SVG": 2, "OASv3-yaml": 1, "YAML": 41, "HTML": 2, "JavaScript": 2, "CSS": 1, "GraphQL": 2, "SQL": 116} | package no.nav.veilarbaktivitet.aktivitetskort.idmapping
import no.nav.veilarbaktivitet.aktivitet.domain.AktivitetStatus
import no.nav.veilarbaktivitet.aktivitetskort.dto.aktivitetskort.MessageSource
import no.nav.veilarbaktivitet.arena.model.ArenaId
import java.time.LocalDateTime
import java.util.*
data class IdMapping(
val arenaId: ArenaId,
val aktivitetId: Long,
val funksjonellId: UUID,
)
data class IdMappingWithAktivitetStatus (
val arenaId: ArenaId,
val aktivitetId: Long,
val funksjonellId: UUID,
val status: AktivitetStatus,
val historiskDato: LocalDateTime?,
val source: MessageSource
) | 6 | Java | 0 | 0 | 7d406657ed8e5542b6752baf3f77fdf90dea6f14 | 637 | veilarbaktivitet | MIT License |
test/src/main/java/com/example/test/kotlinPratice/base/Song.kt | Tzy2001 | 750,701,200 | false | {"Gradle": 29, "Java Properties": 4, "Shell": 2, "Text": 2, "Ignore List": 29, "Batchfile": 2, "Markdown": 1, "Proguard": 23, "Kotlin": 238, "XML": 461, "Java": 187, "INI": 1, "JSON": 1} | package com.example.test.kotlinPratice.base
data class Song(val name: String, val person: String, val year: String, val count: Int) {
// fun isPopular(): Boolean {
// return this.count >= 1000
// }
val isPopular: Boolean
get() = count >= 1000
fun printSong() {
println("[$name],performed by $person,was released in [$year]")
}
}
fun main() {
val song = Song("shuixingji", "guoding", "2022.12.23", 1200)
println(song.isPopular)
song.printSong()
} | 0 | Java | 0 | 0 | b54ec3624624885750df5e90041152f411c236d4 | 502 | Android-Demos | Apache License 2.0 |
app/src/main/java/com/tsl/app/activity/main/MainActivity.kt | Jowney23 | 566,658,372 | false | {"Java": 578069, "Kotlin": 286202} | package com.tsl.app.activity.main
import android.app.ActivityOptions
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View
import com.airbnb.lottie.LottieAnimationView
import com.jaeger.library.StatusBarUtil
import com.lxj.xpopup.XPopup
import com.open.face.camera.ColorCamera
import com.open.face.core.FaceRecognizeThread
import com.open.face.core.IFaceBusiness
import com.open.face.model.EventTips
import com.open.face.model.TipMessageCode
import com.open.face.view.ColorPreviewTextureView
import com.open.face.view.FaceCoveringCircleView
import com.tsl.app.R
import com.tsl.app.activity.BaseActivity
import com.tsl.app.activity.set.SettingActivity
import kotlinx.android.synthetic.main.activity_main_camera.view.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
class MainActivity : BaseActivity() {
companion object {
var TAG = "JLogin"
}
private lateinit var mCameraPreview: ColorPreviewTextureView
private lateinit var mFaceDetectView: FaceCoveringCircleView
private lateinit var mFaceBusinessThread: FaceRecognizeThread
private lateinit var mLottieAnimationView: LottieAnimationView
private lateinit var mGestureDetector: GestureDetector
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main_camera)
EventBus.getDefault().register(this)
mGestureDetector = GestureDetector(this, object :MainActivityGestureListener(){
override fun onVerticalSlide() {
mFaceBusinessThread.setMode(IFaceBusiness.ENROLL_MODE)
}
override fun onLongPress(e: MotionEvent?) {
super.onLongPress(e)
XPopup.Builder(this@MainActivity)
.hasStatusBarShadow(false) //.dismissOnBackPressed(false)
.isDestroyOnDismiss(true) //对于只使用一次的弹窗,推荐设置这个
.autoOpenSoftInput(true)
.isDarkTheme(false)
.autoFocusEditText(true) //是否让弹窗内的EditText自动获取焦点,默认是true
.moveUpToKeyboard(true) //是否移动到软键盘上面,默认为true
.dismissOnTouchOutside(false)
.hasShadowBg(true)
.hasBlurBg(true)
.asInputConfirm(
"进入设置界面", null, null, "请输入密码"
) {
if (it == "1234")
[email protected](
Intent(this@MainActivity, SettingActivity::class.java),
ActivityOptions.makeSceneTransitionAnimation(this@MainActivity)
.toBundle()
)
}
.show()
}
})
mCameraPreview = findViewById(R.id.amc_camera_preview)
mFaceDetectView = findViewById(R.id.amc_face_detect_view)
mLottieAnimationView = findViewById(R.id.amc_lottie_eyes)
mLottieAnimationView.repeatCount = -1
mCameraPreview.setView(mFaceDetectView)
mFaceBusinessThread = FaceRecognizeThread("face_j")
mFaceBusinessThread.start()
Log.d(TAG, "onCreate")
}
override fun onResume() {
super.onResume()
Log.d(TAG, "onResume")
}
override fun onStop() {
super.onStop()
Log.d(TAG, "onStop")
}
override fun onDestroy() {
super.onDestroy()
Log.d(TAG, "onDestroy")
EventBus.getDefault().unregister(this)
mFaceBusinessThread.destroy()
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (hasFocus) {
Log.d(TAG, "获得焦点")
mFaceBusinessThread.resume()
ColorCamera.getInstance().startCamera()
} else {
Log.d(TAG, "失去焦点")
mFaceBusinessThread.pause()
ColorCamera.getInstance().stopCamera()
}
}
override fun setStatusBar() {
StatusBarUtil.setTransparent(this)
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onEventBusTips(event: EventTips<String>) {
when (event.code) {
TipMessageCode.Message_Color_Recognize_Resume -> {
mFaceBusinessThread.resume()
mLottieAnimationView.pauseAnimation()
mLottieAnimationView.visibility = View.INVISIBLE
}
TipMessageCode.Message_Color_Recognize_Pause -> {
mFaceBusinessThread.pause()
mLottieAnimationView.playAnimation()
mLottieAnimationView.visibility = View.VISIBLE
}
}
}
override fun onBackPressed() {
Log.d("Jowney", this.supportFragmentManager.backStackEntryCount.toString())
true
}
override fun onTouchEvent(event: MotionEvent?): Boolean {
return mGestureDetector.onTouchEvent(event)
}
} | 1 | null | 1 | 1 | 9393621a33e6e387cb58cba0d1b82a6ec38ee8ed | 5,148 | FaceRecognize | Apache License 2.0 |
kotest-framework/kotest-framework-api/src/commonMain/kotlin/io/kotest/core/concurrency/CoroutineDispatcherFactory.kt | kotest | 47,071,082 | false | {"Gradle Kotlin DSL": 57, "JSON": 18, "Markdown": 1115, "Java Properties": 1, "Shell": 2, "Text": 5, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 2, "EditorConfig": 1, "SVG": 4, "Kotlin": 1691, "TOML": 1, "INI": 4, "YAML": 18, "JavaScript": 4, "CSS": 3, "MDX": 22, "HTTP": 3, "Java": 1} | package io.kotest.core.concurrency
import io.kotest.core.test.TestCase
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
/**
* Switches the [kotlinx.coroutines.CoroutineDispatcher] used for test and spec execution.
*/
interface CoroutineDispatcherFactory {
/**
* Execute the given function [f] on a [kotlinx.coroutines.CoroutineDispatcher] chosen by this implementation.
* It may be the same dispatcher as the calling coroutine.
*/
suspend fun <T> withDispatcher(testCase: TestCase, f: suspend () -> T): T
/**
* Close dispatchers created by the factory, releasing resources.
*/
fun close() {}
}
inline fun <T: CoroutineDispatcherFactory, R> T.use(block: (factory: T) -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return try {
block(this).also {
close()
}
} catch (e: Throwable) {
try {
close()
} catch (_: Throwable) {
}
throw e
}
}
| 137 | Kotlin | 623 | 4,318 | e7f7e52a732010fae899d1fcc4d074c055463e0b | 996 | kotest | Apache License 2.0 |
server/src/main/java/de/materna/dmn/tester/servlets/model/entities/Documentation.kt | michaelschmitz13 | 499,430,432 | false | {"YAML": 2, "Markdown": 5, "Dockerfile": 1, "Ignore List": 5, "JSON": 61, "JSON with Comments": 1, "JavaScript": 12, "Vue": 34, "SVG": 1, "CSS": 1, "Maven POM": 1, "Java": 63, "Java Properties": 1, "XML": 7, "Kotlin": 1} | package de.materna.dmn.tester.servlets.model.entities
import org.apache.commons.lang3.StringUtils
import org.kie.dmn.api.core.DMNModel
import org.kie.dmn.api.core.DMNType
import org.kie.dmn.api.core.ast.BusinessKnowledgeModelNode
import org.kie.dmn.api.core.ast.DecisionNode
import org.kie.dmn.model.api.*
import org.kie.dmn.model.v1_3.TLiteralExpression
import java.util.*
open class DMNElementDocumentation(element: DMNElement) {
var description: String? = null
init {
this.description = element.description
}
}
class ModelDocumentation() {
var name: String? = null
var namespace: String? = null
var description: String? = null
var itemDefinitions: ArrayList<ItemDefinitionDocumentation>? = null
var decisions: ArrayList<DecisionDocumentation>? = null
var knowledgeModels: ArrayList<KnowledgeModelDocumentation>? = null
var dependencies: ArrayList<String>? = null
constructor(model: DMNModel) : this() {
name = model.definitions.name
namespace = model.definitions.namespace
description = model.definitions.description
itemDefinitions = ArrayList()
for (itemDefinition in model.itemDefinitions) {
itemDefinitions!!.add(ItemDefinitionDocumentation(itemDefinition.name, itemDefinition.type))
}
decisions = ArrayList()
for (decision in model.decisions) {
decisions!!.add(DecisionDocumentation(decision))
}
knowledgeModels = ArrayList()
for (knowledgeModel in model.businessKnowledgeModels) {
knowledgeModels!!.add(KnowledgeModelDocumentation(knowledgeModel))
}
dependencies = ArrayList()
for (import in model.definitions.import) {
dependencies!!.add(import.namespace)
}
}
}
class ItemDefinitionDocumentation(name: String, type: DMNType) {
var name: String? = null
var isCollection: Boolean? = null
var allowedValues: String? = null
var type: String? = null
var children: ArrayList<ItemDefinitionDocumentation>? = null
init {
this.name = name
this.isCollection = type.isCollection
if (type.allowedValues.size > 0) {
this.allowedValues = StringUtils.join(type.allowedValues, ", ")
}
val baseType = getBaseType(type).name
if (baseType != name) {
this.type = baseType;
}
children = ArrayList()
for (field in type.fields) {
children!!.add(ItemDefinitionDocumentation(field.key, field.value))
}
}
}
private fun getBaseType(type: DMNType): DMNType {
if (type.baseType == null) {
return type
}
return getBaseType(type.baseType)
}
class DecisionDocumentation(decisionNode: DecisionNode) {
var name: String? = null
var description: String? = null
var returnType: String? = null
var question: String? = null
var answers: List<String>? = null
var expression: ExpressionDocumentation? = null
init {
val decision = decisionNode.decision
this.name = decision.name
this.description = decision.description
this.returnType = decision.variable.typeRef?.localPart
this.question = decision.question
this.answers = decision.allowedAnswers?.split("\n")
this.expression = resolveExpression(decision.expression)
}
}
class KnowledgeModelDocumentation(knowledgeModel: BusinessKnowledgeModelNode) {
var name: String? = null
var description: String? = null
var returnType: String? = null
var parameters: ArrayList<FunctionParameterDocumentation>? = null
var expression: ExpressionDocumentation? = null
init {
val knowledgeModel = knowledgeModel.businessKnowledModel
this.name = knowledgeModel.name
this.description = knowledgeModel.description
this.returnType = knowledgeModel.variable.typeRef?.localPart
this.parameters = ArrayList()
for (parameter in knowledgeModel.encapsulatedLogic.formalParameter) {
this.parameters!!.add(FunctionParameterDocumentation(parameter.name, parameter.typeRef?.localPart))
}
this.expression = resolveExpression(knowledgeModel.encapsulatedLogic.expression)
}
}
enum class ExpressionType {
LITERAL_EXPRESSION,
CONTEXT,
CONTEXT_ENTRY,
DECISION_TABLE,
FUNCTION_DEFINITION,
RELATION,
LIST,
INVOCATION,
}
open class ExpressionDocumentation(expressionType: ExpressionType, expression: DMNElement) : DMNElementDocumentation(expression) {
var expressionType: ExpressionType? = null
init {
this.expressionType = expressionType
}
}
class FunctionParameterDocumentation(name: String, type: String?) {
var name: String? = null
var type: String? = null
init {
this.name = name
this.type = type
}
}
class FunctionDefinitionDocumentation(functionDefinition: FunctionDefinition) : ExpressionDocumentation(ExpressionType.FUNCTION_DEFINITION, functionDefinition) {
var parameters: ArrayList<FunctionParameterDocumentation>? = null
var expression: ExpressionDocumentation? = null
init {
this.parameters = ArrayList()
for (parameter in functionDefinition.formalParameter) {
this.parameters!!.add(FunctionParameterDocumentation(parameter.name, parameter.typeRef?.localPart))
}
this.expression = resolveExpression(functionDefinition.expression)
}
}
class RelationDocumentation(relation: Relation) : ExpressionDocumentation(ExpressionType.RELATION, relation) {
var columns: ArrayList<RelationColumnDocumentation>? = null
var rows: ArrayList<RelationRowDocumentation>? = null
init {
this.columns = ArrayList()
for (column in relation.column) {
columns!!.add(RelationColumnDocumentation(column))
}
this.rows = ArrayList()
for (row in relation.row) {
rows!!.add(RelationRowDocumentation(row))
}
}
}
class RelationColumnDocumentation(column: InformationItem) : DMNElementDocumentation(column) {
var name: String? = null
var type: String? = null
init {
this.name = column.name
this.type = column.typeRef?.localPart
}
}
class RelationRowDocumentation(row: org.kie.dmn.model.api.List) {
var expressions: ArrayList<ExpressionDocumentation>? = null
init {
this.expressions = ArrayList()
for (expression in row.expression) {
expressions!!.add(resolveExpression(expression))
}
}
}
class ListDocumentation(list: org.kie.dmn.model.api.List) : ExpressionDocumentation(ExpressionType.LIST, list) {
var expressions: ArrayList<ExpressionDocumentation>? = null
init {
this.expressions = ArrayList()
for (expression in list.expression) {
expressions!!.add(resolveExpression(expression))
}
}
}
class InvocationDocumentation(invocation: Invocation) : ExpressionDocumentation(ExpressionType.INVOCATION, invocation) {
var name: String? = null
var bindings: ArrayList<InvocationBindingDocumentation>? = null
init {
this.name = (invocation.expression as LiteralExpression).text
this.bindings = ArrayList()
for (binding in invocation.binding) {
bindings!!.add(InvocationBindingDocumentation(binding))
}
}
}
class InvocationBindingDocumentation(binding: Binding) {
var name: String? = null
var type: String? = null
var description: String? = null
var expression: ExpressionDocumentation? = null
init {
this.name = binding.parameter.name
this.type = binding.parameter.typeRef?.localPart
this.description = binding.parameter.description
this.expression = resolveExpression(binding.expression)
}
}
class RelationCellDocumentation(column: InformationItem) : DMNElementDocumentation(column) {
var name: String? = null
var type: String? = null
init {
this.name = column.name
this.type = column.typeRef?.localPart
}
}
class LiteralExpressionDocumentation(literalExpression: LiteralExpression) : ExpressionDocumentation(ExpressionType.LITERAL_EXPRESSION, literalExpression) {
var type: String? = null
var text: String? = null
init {
this.type = literalExpression.typeRef?.localPart
this.text = literalExpression.text
}
}
class ContextDocumentation(context: Context) : ExpressionDocumentation(ExpressionType.CONTEXT, context) {
var entries: ArrayList<ContextEntryDocumentation>? = null
init {
entries = ArrayList()
for (entry in context.contextEntry) {
entries!!.add(ContextEntryDocumentation(entry))
}
}
}
class ContextEntryDocumentation(contextEntry: ContextEntry) : ExpressionDocumentation(ExpressionType.CONTEXT_ENTRY, contextEntry.variable ?: contextEntry) {
var name: String? = null
var type: String? = null
var expression: ExpressionDocumentation? = null
init {
this.name = contextEntry.variable?.name
this.type = contextEntry.variable?.typeRef?.localPart
this.expression = resolveExpression(contextEntry.expression)
}
}
class DecisionTableDocumentation(decisionTable: DecisionTable) : ExpressionDocumentation(ExpressionType.DECISION_TABLE, decisionTable) {
var hitPolicy: String? = null
var inputs: ArrayList<DecisionTableInputDocumentation>? = null
var outputs: ArrayList<DecisionTableOutputDocumentation>? = null
var annotations: ArrayList<DecisionTableAnnotationDocumentation>? = null
var rules: ArrayList<DecisionTableRuleDocumentation>? = null
init {
this.hitPolicy = decisionTable.hitPolicy.name
inputs = ArrayList()
for (input in decisionTable.input) {
inputs!!.add(DecisionTableInputDocumentation(input))
}
outputs = ArrayList()
for (output in decisionTable.output) {
outputs!!.add(DecisionTableOutputDocumentation(output))
}
annotations = ArrayList()
for (annotation in decisionTable.annotation) {
annotations!!.add(DecisionTableAnnotationDocumentation(annotation))
}
rules = ArrayList()
for (rule in decisionTable.rule) {
rules!!.add(DecisionTableRuleDocumentation(rule))
}
}
}
class DecisionTableInputDocumentation(input: InputClause) : DMNElementDocumentation(input) {
var name: String? = null
var type: String? = null
init {
this.name = input.inputExpression.text
this.type = input.inputExpression.typeRef?.localPart
}
}
class DecisionTableOutputDocumentation(output: OutputClause) : DMNElementDocumentation(output) {
var name: String? = null
var type: String? = null
init {
this.name = output.name
this.type = output.typeRef?.localPart
}
}
class DecisionTableAnnotationDocumentation(annotation: RuleAnnotationClause) {
var name: String? = null
init {
this.name = annotation.name
}
}
class DecisionTableRuleDocumentation(rule: DecisionRule) {
var entries: ArrayList<DecisionTableRuleEntryDocumentation>? = null
init {
entries = ArrayList()
for (entry in rule.inputEntry) {
entries!!.add(DecisionTableRuleEntryDocumentation(entry))
}
for (entry in rule.outputEntry) {
entries!!.add(DecisionTableRuleEntryDocumentation(entry))
}
for (entry in rule.annotationEntry) {
entries!!.add(DecisionTableRuleEntryDocumentation(entry))
}
}
}
class DecisionTableRuleEntryDocumentation {
var description: String? = null
var text: String? = null
constructor(expression: UnaryTests) {
this.description = expression.description
this.text = expression.text
}
constructor(expression: LiteralExpression) {
this.description = expression.description
this.text = expression.text
}
constructor(expression: RuleAnnotation) {
this.text = expression.text
}
}
fun resolveExpression(expression: Expression): ExpressionDocumentation {
if (expression is LiteralExpression) {
return LiteralExpressionDocumentation(expression)
}
if (expression is Context) {
return ContextDocumentation(expression)
}
if (expression is DecisionTable) {
return DecisionTableDocumentation(expression)
}
if (expression is FunctionDefinition) {
return FunctionDefinitionDocumentation(expression)
}
if (expression is Relation) {
return RelationDocumentation(expression)
}
if (expression is org.kie.dmn.model.api.List) {
return ListDocumentation(expression)
}
if (expression is Invocation) {
return InvocationDocumentation(expression)
}
val errorExpression = TLiteralExpression()
errorExpression.text = expression.javaClass.name + " is not implemented yet!"
return LiteralExpressionDocumentation(errorExpression)
} | 1 | null | 1 | 1 | bfd96b4c7f453c5105b4ef099cba9bb9739cc9b6 | 11,741 | declab | Apache License 2.0 |
app/src/main/java/com/lyh/cn/passwordbook/fragment/entry/UrlFragment.kt | liyuhaolol | 623,347,438 | false | {"Gradle Kotlin DSL": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "TOML": 1, "Proguard": 1, "XML": 25, "Java": 8, "Kotlin": 11} | package com.lyh.cn.passwordbook.fragment.entry
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.lyh.cn.passwordbook.activity.entry.InitActivity
import com.lyh.cn.passwordbook.base.BaseFragment
import com.lyh.cn.passwordbook.databinding.FragmentUrlBinding
import com.lyh.cn.passwordbook.utils.AesGcmCipher
import com.lyh.cn.passwordbook.utils.MySpUtils
class UrlFragment : BaseFragment(){
private lateinit var b:FragmentUrlBinding
private var typeMark = 0//0是url1是本地
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
b = FragmentUrlBinding.inflate(inflater, container, false)
return b.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
b.skip.setOnClickListener(View.OnClickListener {
if (checkAES()){
val activity = requireActivity() as InitActivity
activity.changePage(1)
}
})
b.key.setText(AesGcmCipher.createAesKey())
b.gen.setOnClickListener(View.OnClickListener {
b.key.setText(AesGcmCipher.createAesKey())
})
b.localArea.visibility = View.GONE
b.useUrl.setOnClickListener(View.OnClickListener {
b.webArea.visibility = View.VISIBLE
b.localArea.visibility = View.GONE
typeMark = 0
})
b.useLocal.setOnClickListener(View.OnClickListener {
b.webArea.visibility = View.GONE
b.localArea.visibility = View.VISIBLE
typeMark = 1
})
}
private fun checkAES():Boolean{
val key = b.key.text.toString()
if (TextUtils.isEmpty(key)){
showToast("密钥不能为空")
return false
}else{
MySpUtils.setAesKey(requireActivity(),key)
return true
}
}
} | 0 | Java | 0 | 0 | 215d5fe80d58adecf0d21c5a66104da80186d180 | 2,079 | PasswordBook | MIT License |
app/src/main/java/com/lyh/cn/passwordbook/fragment/entry/UrlFragment.kt | liyuhaolol | 623,347,438 | false | {"Gradle Kotlin DSL": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "TOML": 1, "Proguard": 1, "XML": 25, "Java": 8, "Kotlin": 11} | package com.lyh.cn.passwordbook.fragment.entry
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.lyh.cn.passwordbook.activity.entry.InitActivity
import com.lyh.cn.passwordbook.base.BaseFragment
import com.lyh.cn.passwordbook.databinding.FragmentUrlBinding
import com.lyh.cn.passwordbook.utils.AesGcmCipher
import com.lyh.cn.passwordbook.utils.MySpUtils
class UrlFragment : BaseFragment(){
private lateinit var b:FragmentUrlBinding
private var typeMark = 0//0是url1是本地
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
b = FragmentUrlBinding.inflate(inflater, container, false)
return b.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
b.skip.setOnClickListener(View.OnClickListener {
if (checkAES()){
val activity = requireActivity() as InitActivity
activity.changePage(1)
}
})
b.key.setText(AesGcmCipher.createAesKey())
b.gen.setOnClickListener(View.OnClickListener {
b.key.setText(AesGcmCipher.createAesKey())
})
b.localArea.visibility = View.GONE
b.useUrl.setOnClickListener(View.OnClickListener {
b.webArea.visibility = View.VISIBLE
b.localArea.visibility = View.GONE
typeMark = 0
})
b.useLocal.setOnClickListener(View.OnClickListener {
b.webArea.visibility = View.GONE
b.localArea.visibility = View.VISIBLE
typeMark = 1
})
}
private fun checkAES():Boolean{
val key = b.key.text.toString()
if (TextUtils.isEmpty(key)){
showToast("密钥不能为空")
return false
}else{
MySpUtils.setAesKey(requireActivity(),key)
return true
}
}
} | 0 | Java | 0 | 0 | 215d5fe80d58adecf0d21c5a66104da80186d180 | 2,079 | PasswordBook | MIT License |
Kotiln/security/chapter18/src/main/kotlin/com/example/chapter18/repository/WorkoutRepository.kt | bekurin | 558,176,225 | false | {"Git Config": 1, "Text": 12, "Ignore List": 96, "Markdown": 58, "YAML": 55, "JSON with Comments": 2, "JSON": 46, "HTML": 104, "robots.txt": 6, "SVG": 10, "TSX": 15, "CSS": 64, "Gradle Kotlin DSL": 107, "Shell": 72, "Batchfile": 71, "HTTP": 15, "INI": 112, "Kotlin": 682, "EditorConfig": 1, "Gradle": 40, "Java": 620, "JavaScript": 53, "Go": 8, "XML": 38, "Go Module": 1, "SQL": 7, "Dockerfile": 1, "Gherkin": 1, "Python": 153, "SCSS": 113, "Java Properties": 3, "AsciiDoc": 5, "Java Server Pages": 6, "Unity3D Asset": 451, "C#": 48, "Objective-C": 51, "C": 8, "Objective-C++": 1, "Smalltalk": 1, "OpenStep Property List": 12, "Dart": 17, "Swift": 8, "Ruby": 1} | package com.example.chapter18.repository
import com.example.chapter18.entity.Workout
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.Query
interface WorkoutRepository : JpaRepository<Workout, Long> {
@Query("select w from Workout w where w.username = ?#{authentication.name}")
fun findAllByUser(): List<Workout>
} | 0 | Java | 0 | 2 | ede7cdb0e164ed1d3d2ee91c7770327b2ee71e4d | 383 | blog_and_study | MIT License |
paybutton/src/main/java/io/paysky/ui/fragment/listcards/SavedCardsAdapter.kt | payskyCompany | 158,552,907 | false | {"Gradle": 4, "Maven POM": 1, "Java Properties": 1, "YAML": 1, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "INI": 2, "XML": 64, "Java": 130, "Proguard": 1, "Kotlin": 25} | package io.paysky.ui.fragment.listcards
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.RadioButton
import android.widget.TextView
import androidx.core.widget.doAfterTextChanged
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.example.paybutton.R
import io.paysky.data.model.response.CardItem
import io.paysky.ui.activity.payment.PaymentActivity
import io.paysky.util.hideSoftKeyboard
class SavedCardsAdapter(
val onSubmitDataValid: (CardItem) -> Unit,
val onChangeItem: (Int) -> Unit,
val activity: PaymentActivity
) : RecyclerView.Adapter<SavedCardsAdapter.SavedCardViewHolder>() {
private val savedCardsList = mutableListOf<CardItem>()
private var selectedItemPosition = -1
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SavedCardViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_saved_card, parent, false)
return SavedCardViewHolder(view)
}
override fun getItemCount(): Int {
return savedCardsList.size
}
override fun onBindViewHolder(holder: SavedCardViewHolder, position: Int) {
holder.setCardData(savedCardsList[position], position)
}
fun setItems(cardsLists: List<CardItem>) {
val diffCallback = CardsCallback(this.savedCardsList, cardsLists)
val diffResult = DiffUtil.calculateDiff(diffCallback)
savedCardsList.clear()
savedCardsList.addAll(cardsLists)
diffResult.dispatchUpdatesTo(this)
}
fun submit() {
if (selectedItemPosition != -1) {
if (savedCardsList[selectedItemPosition].cvv.isNullOrEmpty()) {
savedCardsList[selectedItemPosition].isError = true
notifyItemChanged(selectedItemPosition)
} else {
savedCardsList[selectedItemPosition].isError = false
onSubmitDataValid(savedCardsList[selectedItemPosition])
notifyItemChanged(selectedItemPosition)
}
}
}
inner class SavedCardViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private var position: Int = -1
private val cvv: EditText = itemView.findViewById(R.id.ccv_editText)
private val maskedCardNumber: TextView =
itemView.findViewById(R.id.masked_card_number_text_view)
private val cardName: TextView = itemView.findViewById(R.id.card_name_textview)
private val selectCard: RadioButton = itemView.findViewById(R.id.card_selected_radio_button)
private val cvvRequired: View = itemView.findViewById(R.id.cvv_required)
fun setCardData(cardItem: CardItem, position: Int) {
selectCard.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
updateSelectedCard(position)
}
}
cvv.doAfterTextChanged {
savedCardsList[position].cvv = it.toString()
if (!it.isNullOrEmpty()) {
savedCardsList[position].isError = false
}
updateCvvBackground(cardItem)
}
this.position = position
maskedCardNumber.text = cardItem.maskedCardNumber
cardName.text = cardItem.displayName
if (cardItem.isSelected) {
selectedItemPosition = position
selectCard.isChecked = true
cvv.visibility = View.VISIBLE
cvv.setText(cardItem.cvv ?: "")
} else {
selectCard.isChecked = false
cvv.visibility = View.INVISIBLE
cvv.setText("")
}
cvv.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
hideSoftKeyboard(activity = activity)
true
} else false
}
}
private fun updateCvvBackground(cardItem: CardItem) {
if (cardItem.isError) {
cvv.setBackgroundResource(R.drawable.error_border_background)
cvvRequired.visibility = View.VISIBLE
} else {
cvv.setBackgroundResource(R.drawable.cvv_border_background)
cvvRequired.visibility = View.GONE
}
}
}
private fun updateSelectedCard(position: Int) {
if (selectedItemPosition != -1) {
savedCardsList[selectedItemPosition] =
savedCardsList[selectedItemPosition].copy(isSelected = false, isError = false)
}
savedCardsList[position] =
savedCardsList[position].copy(isSelected = true)
onChangeItem(position)
if (selectedItemPosition != -1) {
onChangeItem(selectedItemPosition)
}
this.selectedItemPosition = position
}
} | 0 | Java | 0 | 0 | 7c57ff4dd570155a0aa9b494a523fcd4f9ff1209 | 5,054 | paybutton-sdk | Apache License 2.0 |
ftc-2021-2022-offseason/TeamCode/src/main/java/org/firstinspires/ftc/teamcode/autonomy/AutoRed6Cycles.kt | QubeRomania | 491,215,964 | false | {"Java": 210390, "Kotlin": 52111} | package org.firstinspires.ftc.teamcode.autonomy
class AutoRed6Cycles {
} | 1 | null | 1 | 1 | 6a19b7460d416fa4bddf442b7ef4dcf539c7ae9b | 73 | ftc-2021-2022-offseason | Apache License 2.0 |
java_pro/src/main/kotlin/kt/com/tencent/cain/desigin_pattern/adapter/Player.kt | JayRichrd | 510,423,945 | false | {"Java": 77189, "Kotlin": 54914, "C++": 5055, "CMake": 529} | package kt.com.tencent.cain.desigin_pattern.adapter
/**
* @author cainjiang
* @date 2020/4/15
*/
abstract class Player(val name: String) {
abstract fun attack()
abstract fun defense()
} | 1 | null | 1 | 1 | 00e247591b9e95083d6de362bca512429169af96 | 197 | design_pattern_structure | MIT License |
clients/kotlin-server/generated/src/main/kotlin/org/openapitools/server/apis/CampaignsApi.kt | oapicf | 489,369,143 | false | {"Markdown": 13009, "YAML": 64, "Text": 6, "Ignore List": 43, "JSON": 688, "Makefile": 2, "JavaScript": 2261, "F#": 1305, "XML": 1120, "Shell": 44, "Batchfile": 10, "Scala": 4677, "INI": 23, "Dockerfile": 14, "Maven POM": 22, "Java": 13384, "Emacs Lisp": 1, "Haskell": 75, "Swift": 551, "Ruby": 1149, "Cabal Config": 2, "OASv3-yaml": 16, "Go": 2224, "Go Checksums": 1, "Go Module": 4, "CMake": 9, "C++": 6688, "TOML": 3, "Rust": 556, "Nim": 541, "Perl": 540, "Microsoft Visual Studio Solution": 2, "C#": 1645, "HTML": 545, "Xojo": 1083, "Gradle": 20, "R": 1079, "JSON with Comments": 8, "QMake": 1, "Kotlin": 3280, "Python": 1, "Crystal": 1060, "ApacheConf": 2, "PHP": 3940, "Gradle Kotlin DSL": 1, "Protocol Buffer": 538, "C": 1598, "Ada": 16, "Objective-C": 1098, "Java Properties": 2, "Erlang": 1097, "PlantUML": 1, "robots.txt": 1, "HTML+ERB": 2, "Lua": 1077, "SQL": 512, "AsciiDoc": 1, "CSS": 3, "PowerShell": 1083, "Elixir": 5, "Apex": 1054, "Visual Basic 6.0": 3, "TeX": 1, "ObjectScript": 1, "OpenEdge ABL": 1, "Option List": 2, "Eiffel": 583, "Gherkin": 1, "Dart": 538, "Groovy": 539, "Elm": 31} | /**
* Pinterest REST API
* Pinterest's REST API
*
* The version of the OpenAPI document: 5.12.0
* Contact: <EMAIL>
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.server.apis
import com.google.gson.Gson
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.response.*
import org.openapitools.server.Paths
import io.ktor.server.resources.options
import io.ktor.server.resources.get
import io.ktor.server.resources.post
import io.ktor.server.resources.put
import io.ktor.server.resources.delete
import io.ktor.server.resources.head
import io.ktor.server.resources.patch
import io.ktor.server.routing.*
import org.openapitools.server.infrastructure.ApiPrincipal
import org.openapitools.server.models.AdsAnalyticsTargetingType
import org.openapitools.server.models.CampaignCreateRequest
import org.openapitools.server.models.CampaignCreateResponse
import org.openapitools.server.models.CampaignResponse
import org.openapitools.server.models.CampaignUpdateRequest
import org.openapitools.server.models.CampaignUpdateResponse
import org.openapitools.server.models.CampaignsAnalyticsResponseInner
import org.openapitools.server.models.CampaignsList200Response
import org.openapitools.server.models.ConversionReportAttributionType
import org.openapitools.server.models.Error
import org.openapitools.server.models.Granularity
import org.openapitools.server.models.MetricsResponse
fun Route.CampaignsApi() {
val gson = Gson()
val empty = mutableMapOf<String, Any?>()
authenticate("pinterest_oauth2") {
get<Paths.campaignTargetingAnalyticsGet> {
val principal = call.authentication.principal<OAuthAccessTokenResponse>()!!
val exampleContentType = "application/json"
val exampleContentString = """{
"data" : [ {
"targeting_type" : "KEYWORD",
"targeting_value" : "christmas decor ideas",
"metrics" : {
"AD_GROUP_ID" : 2680067996745,
"DATE" : "2022-04-26",
"SPEND_IN_DOLLAR" : 240
}
}, {
"targeting_type" : "APPTYPE",
"targeting_value" : "iphone",
"metrics" : {
"AD_GROUP_ID" : 2680067996745,
"DATE" : "2022-04-26",
"SPEND_IN_DOLLAR" : 240
}
}, {
"targeting_type" : "APPTYPE",
"targeting_value" : "ipad",
"metrics" : {
"AD_GROUP_ID" : 2680067996745,
"DATE" : "2022-04-26",
"SPEND_IN_DOLLAR" : 240
}
}, {
"targeting_type" : "APPTYPE",
"targeting_value" : "web",
"metrics" : {
"AD_GROUP_ID" : 2680067996745,
"DATE" : "2022-04-26",
"SPEND_IN_DOLLAR" : 240
}
}, {
"targeting_type" : "APPTYPE",
"targeting_value" : "web_mobile",
"metrics" : {
"AD_GROUP_ID" : 2680067996745,
"DATE" : "2022-04-26",
"SPEND_IN_DOLLAR" : 240
}
}, {
"targeting_type" : "APPTYPE",
"targeting_value" : "android_mobile",
"metrics" : {
"AD_GROUP_ID" : 2680067996745,
"DATE" : "2022-04-26",
"SPEND_IN_DOLLAR" : 240
}
}, {
"targeting_type" : "APPTYPE",
"targeting_value" : "android_tablet",
"metrics" : {
"AD_GROUP_ID" : 2680067996745,
"DATE" : "2022-04-26",
"SPEND_IN_DOLLAR" : 240
}
}, {
"targeting_type" : "GENDER",
"targeting_value" : "female",
"metrics" : {
"AD_GROUP_ID" : 2680067996745,
"DATE" : "2022-04-26",
"SPEND_IN_DOLLAR" : 240
}
}, {
"targeting_type" : "LOCATION",
"targeting_value" : 500,
"metrics" : {
"AD_GROUP_ID" : 2680067996745,
"DATE" : "2022-04-26",
"SPEND_IN_DOLLAR" : 240
}
}, {
"targeting_type" : "PLACEMENT",
"targeting_value" : "SEARCH",
"metrics" : {
"AD_GROUP_ID" : 2680067996745,
"DATE" : "2022-04-26",
"SPEND_IN_DOLLAR" : 240
}
}, {
"targeting_type" : "COUNTRY",
"targeting_value" : "US",
"metrics" : {
"AD_GROUP_ID" : 2680067996745,
"DATE" : "2022-04-26",
"SPEND_IN_DOLLAR" : 240
}
}, {
"targeting_type" : "TARGETED_INTEREST",
"targeting_value" : "Food and Drinks",
"metrics" : {
"AD_GROUP_ID" : 2680067996745,
"DATE" : "2022-04-26",
"SPEND_IN_DOLLAR" : 240
}
}, {
"targeting_type" : "PINNER_INTEREST",
"targeting_value" : "Chocolate Cookies",
"metrics" : {
"AD_GROUP_ID" : 2680067996745,
"DATE" : "2022-04-26",
"SPEND_IN_DOLLAR" : 240
}
}, {
"targeting_type" : "AUDIENCE_INCLUDE",
"targeting_value" : 254261234567,
"metrics" : {
"AD_GROUP_ID" : 2680067996745,
"DATE" : "2022-04-26",
"SPEND_IN_DOLLAR" : 240
}
}, {
"targeting_type" : "GEO",
"targeting_value" : "US:94102",
"metrics" : {
"AD_GROUP_ID" : 2680067996745,
"DATE" : "2022-04-26",
"SPEND_IN_DOLLAR" : 240
}
}, {
"targeting_type" : "AGE_BUCKET",
"targeting_value" : "45-49",
"metrics" : {
"AD_GROUP_ID" : 2680067996745,
"DATE" : "2022-04-26",
"SPEND_IN_DOLLAR" : 240
}
}, {
"targeting_type" : "REGION",
"targeting_value" : "US-CA",
"metrics" : {
"AD_GROUP_ID" : 2680067996745,
"DATE" : "2022-04-26",
"SPEND_IN_DOLLAR" : 240
}
} ]
}"""
when (exampleContentType) {
"application/json" -> call.respond(gson.fromJson(exampleContentString, empty::class.java))
"application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml)
else -> call.respondText(exampleContentString)
}
}
}
authenticate("pinterest_oauth2") {
get<Paths.campaignsAnalytics> {
val principal = call.authentication.principal<OAuthAccessTokenResponse>()!!
val exampleContentType = "application/json"
val exampleContentString = """[ {
"DATE" : "2021-04-01",
"CAMPAIGN_ID" : "547602124502",
"SPEND_IN_DOLLAR" : 30,
"TOTAL_CLICKTHROUGH" : 216
}, {
"DATE" : "2021-04-01",
"CAMPAIGN_ID" : "547602124502",
"SPEND_IN_DOLLAR" : 30,
"TOTAL_CLICKTHROUGH" : 216
} ]"""
when (exampleContentType) {
"application/json" -> call.respond(gson.fromJson(exampleContentString, empty::class.java))
"application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml)
else -> call.respondText(exampleContentString)
}
}
}
authenticate("pinterest_oauth2") {
post<Paths.campaignsCreate> {
val principal = call.authentication.principal<OAuthAccessTokenResponse>()!!
val exampleContentType = "application/json"
val exampleContentString = """{
"items" : [ {
"data" : { },
"exceptions" : [ {
"code" : 2,
"message" : "Advertiser not found."
}, {
"code" : 2,
"message" : "Advertiser not found."
} ]
}, {
"data" : { },
"exceptions" : [ {
"code" : 2,
"message" : "Advertiser not found."
}, {
"code" : 2,
"message" : "Advertiser not found."
} ]
} ]
}"""
when (exampleContentType) {
"application/json" -> call.respond(gson.fromJson(exampleContentString, empty::class.java))
"application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml)
else -> call.respondText(exampleContentString)
}
}
}
authenticate("pinterest_oauth2") {
get<Paths.campaignsGet> {
val principal = call.authentication.principal<OAuthAccessTokenResponse>()!!
val exampleContentType = "application/json"
val exampleContentString = """{
"created_time" : 1432744744,
"updated_time" : 1432744744,
"lifetime_spend_cap" : 1432744744,
"end_time" : 1644023526,
"is_flexible_daily_budgets" : true,
"daily_spend_cap" : 1432744744,
"summary_status" : "summary_status",
"is_campaign_budget_optimization" : true,
"type" : "campaign",
"tracking_urls" : {
"engagement" : [ "engagement", "engagement" ],
"audience_verification" : [ "audience_verification", "audience_verification" ],
"impression" : [ "impression", "impression" ],
"buyable_button" : [ "buyable_button", "buyable_button" ],
"click" : [ "click", "click" ]
},
"ad_account_id" : "549755885175",
"start_time" : 1580865126,
"name" : "ACME Tools",
"order_line_id" : "549755885175",
"id" : "549755885175",
"status" : "status"
}"""
when (exampleContentType) {
"application/json" -> call.respond(gson.fromJson(exampleContentString, empty::class.java))
"application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml)
else -> call.respondText(exampleContentString)
}
}
}
authenticate("pinterest_oauth2") {
get<Paths.campaignsList> {
val principal = call.authentication.principal<OAuthAccessTokenResponse>()!!
val exampleContentType = "application/json"
val exampleContentString = """{
"bookmark" : "bookmark",
"items" : [ {
"created_time" : 1432744744,
"updated_time" : 1432744744,
"lifetime_spend_cap" : 1432744744,
"end_time" : 1644023526,
"is_flexible_daily_budgets" : true,
"daily_spend_cap" : 1432744744,
"summary_status" : "summary_status",
"is_campaign_budget_optimization" : true,
"type" : "campaign",
"tracking_urls" : {
"engagement" : [ "engagement", "engagement" ],
"audience_verification" : [ "audience_verification", "audience_verification" ],
"impression" : [ "impression", "impression" ],
"buyable_button" : [ "buyable_button", "buyable_button" ],
"click" : [ "click", "click" ]
},
"ad_account_id" : "549755885175",
"start_time" : 1580865126,
"name" : "<NAME>",
"order_line_id" : "549755885175",
"id" : "549755885175",
"status" : "status"
}, {
"created_time" : 1432744744,
"updated_time" : 1432744744,
"lifetime_spend_cap" : 1432744744,
"end_time" : 1644023526,
"is_flexible_daily_budgets" : true,
"daily_spend_cap" : 1432744744,
"summary_status" : "summary_status",
"is_campaign_budget_optimization" : true,
"type" : "campaign",
"tracking_urls" : {
"engagement" : [ "engagement", "engagement" ],
"audience_verification" : [ "audience_verification", "audience_verification" ],
"impression" : [ "impression", "impression" ],
"buyable_button" : [ "buyable_button", "buyable_button" ],
"click" : [ "click", "click" ]
},
"ad_account_id" : "549755885175",
"start_time" : 1580865126,
"name" : "<NAME>",
"order_line_id" : "549755885175",
"id" : "549755885175",
"status" : "status"
} ]
}"""
when (exampleContentType) {
"application/json" -> call.respond(gson.fromJson(exampleContentString, empty::class.java))
"application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml)
else -> call.respondText(exampleContentString)
}
}
}
authenticate("pinterest_oauth2") {
patch<Paths.campaignsUpdate> {
val principal = call.authentication.principal<OAuthAccessTokenResponse>()!!
val exampleContentType = "application/json"
val exampleContentString = """{
"items" : [ {
"data" : { },
"exceptions" : [ {
"code" : 2,
"message" : "Advertiser not found."
}, {
"code" : 2,
"message" : "Advertiser not found."
} ]
}, {
"data" : { },
"exceptions" : [ {
"code" : 2,
"message" : "Advertiser not found."
}, {
"code" : 2,
"message" : "Advertiser not found."
} ]
} ]
}"""
when (exampleContentType) {
"application/json" -> call.respond(gson.fromJson(exampleContentString, empty::class.java))
"application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml)
else -> call.respondText(exampleContentString)
}
}
}
}
| 0 | Java | 0 | 2 | dcd328f1e62119774fd8ddbb6e4bad6d7878e898 | 15,555 | pinterest-sdk | MIT License |
src/main/kotlin/nitrolang/backend/Monomorphization.kt | cout970 | 699,028,788 | false | {"Markdown": 2, "Gradle Kotlin DSL": 2, "ANTLR": 2, "INI": 2, "Shell": 2, "Ignore List": 2, "Batchfile": 1, "Git Attributes": 1, "Text": 1, "Kotlin": 86, "Java": 6, "JSON with Comments": 1, "HTML": 3, "HTTP": 1, "XML": 2} | package nitrolang.backend
import nitrolang.ast.*
import nitrolang.backend.wasm.heapSize
import nitrolang.parsing.ANNOTATION_EXTERN
import nitrolang.parsing.LAMBDA_CALL_FUNCTION
import nitrolang.typeinference.TType
import nitrolang.util.Span
// Search if a given function signature matches an already converted MonoFunction, if not, create a new one and return it
fun MonoBuilder.getOrCreateMonoFunction(key: MonoFuncSignature, onInit: (MonoFunction) -> Unit): MonoFunction {
if (key in funcCache) return funcCache[key]!!
val nameIndex = globalNames.getOrDefault(key.fullName, 0)
globalNames[key.fullName] = nameIndex + 1
val finalName = if (nameIndex == 0) "$${key.fullName}" else "$${key.fullName}-${nameIndex}"
val mono = MonoFunction(id = lastFuncId++, signature = key, finalName)
funcCache[key] = mono
try {
onInit(mono)
} catch (e: UnresolvedGenericTypeError) {
throw RuntimeException(e)
}
return mono
}
// Given a function and a context return the corresponding MonoFunction, if it doesn't exist, we create it
fun MonoBuilder.getMonoFunction(func: LstFunction, ctx: MonoCtx): MonoFunction {
if (func.tag != null) {
error("Calling invalid function!")
}
// External functions cannot be duplicated, generics become plain pointers, represented with Int
val key = if (func.isExternal && !func.autogenerate) {
val params = func.params.map {
typeToMonoType(program.removeAllGenerics(it.type), ctx)
}
val returnType = typeToMonoType(program.removeAllGenerics(func.returnType), ctx)
MonoFuncSignature(func.ref, func.fullName, params, returnType, emptyList())
} else {
val typeParams = func.typeParameters.map {
typeToMonoType(program.typeEnv.generic(it), ctx)
}
MonoFuncSignature(
func.ref, func.fullName,
func.params.map { typeToMonoType(it.type, ctx) },
typeToMonoType(func.returnType, ctx),
typeParams
)
}
key.function = func
func.isDeadCode = false
return getOrCreateMonoFunction(key) { mono ->
createMonoFunction(mono, func, key, ctx)
}
}
// Given a lambda function and a context return the corresponding MonoFunction, if it doesn't exist, we create it
fun MonoBuilder.getMonoLambdaFunction(lambda: LstLambdaFunction, ctx: MonoCtx): MonoFunction {
val key = MonoFuncSignature(
lambda.ref, "lambda-${lambda.ref.id}",
lambda.params.map { typeToMonoType(it.type, ctx) },
typeToMonoType(lambda.returnType, ctx),
emptyList()
)
key.lambda = lambda
return getOrCreateMonoFunction(key) { mono ->
createMonoLambdaFunction(mono, lambda, key, ctx)
}
}
// Fills a MonoFunction with the necessary components from the original LstFunction and the given context
fun MonoBuilder.createMonoFunction(
mono: MonoFunction,
function: LstFunction,
signature: MonoFuncSignature,
ctx: MonoCtx
) {
val prev = current
mono.code = MonoCode(function.body)
mono.name = signature.fullName
mono.returnType = signature.returnType
mono.annotations += function.annotations
mono.code.isExternal = function.isExternal && !function.autogenerate
current = mono.code
processCode(mono.code, ctx)
if (function.autogenerate) {
// Let the wasm backend handle this part
mono.code.instructions.clear()
mono.code.variables.clear()
mono.code.instructions += MonoAutogenerate(mono.code.nextId(), function.span, signature)
}
current = prev
}
// Fills a MonoFunction with the necessary components from the original LstLambdaFunction and the given context
fun MonoBuilder.createMonoLambdaFunction(
mono: MonoFunction,
function: LstLambdaFunction,
signature: MonoFuncSignature,
ctx: MonoCtx
) {
mono.name = signature.fullName
mono.returnType = signature.returnType
mono.code = MonoCode(function.body)
mono.code.isLambda = true
// Lambdas have a hidden self parameter that points to the lambda closure,
// This closure has an index to the function and a list of pointers to the closure captured values (upvalues)
val selfType = typeToMonoType(program.typeEnv.find("Int"), ctx)
mono.code.params += MonoParam(
name = "lambda-self",
type = selfType,
monoVar = null,
)
val prev = current
current = mono.code
processCode(mono.code, ctx)
builder.onCompileLambda(mono)
current = prev
}
fun MonoBuilder.processCode(monoCode: MonoCode, ctx: MonoCtx) {
var varIndex = monoCode.variables.size
for (variable in monoCode.code.variables) {
var tType = if (monoCode.isExternal) program.removeAllGenerics(variable.type) else variable.type
// Upvalues are references to the heap
if (variable.isUpValue) {
val ptrType = program.typeEnv.findBase("Ptr")
tType = program.typeEnv.composite(ptrType, listOf(tType))
}
val type = typeToMonoType(tType, ctx)
val monoVar = MonoVar(
id = varIndex,
name = variable.name,
type = type,
varRef = variable.ref,
isUpValue = variable.isUpValue,
isParam = variable.isParam,
)
varIndex++
if (variable.isParam) {
monoCode.params += MonoParam(
name = variable.name,
type = type,
monoVar = monoVar,
)
}
if (variable.name == "_") {
continue
}
if (variable.isUpValue) {
monoVar.upValueSlot = monoCode.upValues.size
monoCode.upValues += monoVar
monoCode.instructions += MonoCreateUpValue(monoCode.nextId(), variable.span, monoVar)
}
monoCode.variableMap[variable.ref] = monoVar
monoCode.variables += monoVar
}
for (variable in monoCode.code.outerVariables) {
var tType = if (monoCode.isExternal) program.removeAllGenerics(variable.type) else variable.type
// Upvalues are references to the heap
val ptrType = program.typeEnv.findBase("Ptr")
tType = program.typeEnv.composite(ptrType, listOf(tType))
val type = typeToMonoType(tType, ctx)
val monoVar = MonoVar(
id = varIndex,
name = variable.name,
type = type,
varRef = variable.ref,
isUpValue = true,
)
varIndex++
monoCode.variableMap[variable.ref] = monoVar
monoVar.upValueSlot = monoCode.upValues.size
monoCode.upValues += monoVar
monoCode.variables += monoVar
if (variable.definedIn == monoCode.code) {
monoCode.instructions += MonoCreateUpValue(monoCode.nextId(), variable.span, monoVar)
} else {
if (!monoCode.isLambda) error("Attempt to access outer variable in non-lambda function")
monoCode.instructions += MonoInitUpValue(monoCode.nextId(), variable.span, monoVar)
}
}
if (monoCode.isExternal) {
return
}
monoCode.params.forEach { param ->
if (param.monoVar == null || param.name == "_") return@forEach
monoCode.instructions += MonoLoadParam(monoCode.nextId(), Span.internal(), param)
if (param.monoVar.isUpValue) {
monoCode.instructions += MonoStoreUpValue(monoCode.nextId(), Span.internal(), param.monoVar)
} else {
monoCode.instructions += MonoStoreVar(monoCode.nextId(), Span.internal(), param.monoVar)
}
}
for (inst in monoCode.code.nodes) {
processInst(inst, monoCode, ctx)
}
for ((index, inst) in monoCode.instructions.toList().withIndex()) {
if (inst is MonoProvider) {
if (inst.consumers.isEmpty()) {
monoCode.instructions[index] = MonoDrop(monoCode.nextId(), inst.span, inst.type)
continue
}
if (inst.consumers.size == 1 && inst.consumers.first().id == inst.id + 1) {
monoCode.instructions[index] = MonoNoop(monoCode.nextId(), inst.span)
continue
}
val variable = MonoVar(
id = monoCode.variables.size,
name = "tmp${inst.id}",
type = inst.type,
varRef = null
)
monoCode.variables += variable
monoCode.instructions[index] = MonoStoreVar(monoCode.nextId(), inst.span, variable)
inst.consumers.forEach { it.variable = variable }
}
if (inst is MonoConsumer) {
if (inst.variable == null) {
monoCode.instructions[index] = MonoNoop(monoCode.nextId(), inst.span)
continue
}
monoCode.instructions[index] = MonoLoadVar(monoCode.nextId(), inst.span, inst.variable!!)
}
}
if (monoCode.code.returnType.isNothing()) {
monoCode.instructions += MonoInt(monoCode.nextId(), Span.internal(), 0)
} else {
val last = monoCode.instructions.lastOrNull()
if (last is MonoEndBlock) {
val msg = "Added to suppress error, 'end' returns nothing"
monoCode.instructions += MonoComment(monoCode.nextId(), Span.internal(), msg)
monoCode.instructions += MonoInt(monoCode.nextId(), Span.internal(), 0)
} else if (last is MonoDrop) {
val msg = "Added to suppress error, type mismatch in implicit return, expected [i32] but got []"
monoCode.instructions += MonoComment(monoCode.nextId(), Span.internal(), msg)
monoCode.instructions += MonoUnreachable(monoCode.nextId(), Span.internal())
}
}
}
fun MonoBuilder.processInst(
inst: LstInstruction,
code: MonoCode,
ctx: MonoCtx,
) {
comment(inst.span, inst.toString())
when (inst) {
is LstFunCall -> {
val function = inst.function ?: error("Function not bound: $inst")
processFunctionCall(code, function, inst, ctx)
}
is LstComment -> {
code.instructions += MonoComment(code.nextId(), inst.span, inst.comment)
}
is LstBoolean -> {
val type = typeToMonoType(inst.type, ctx)
code.instructions += MonoBoolean(code.nextId(), inst.span, inst.value)
provider(inst.span, inst.ref, type)
}
is LstFloat -> {
val type = typeToMonoType(inst.type, ctx)
code.instructions += MonoFloat(code.nextId(), inst.span, inst.value)
provider(inst.span, inst.ref, type)
}
is LstInt -> {
val type = typeToMonoType(inst.type, ctx)
code.instructions += MonoInt(code.nextId(), inst.span, inst.value)
provider(inst.span, inst.ref, type)
}
is LstLong -> {
val type = typeToMonoType(inst.type, ctx)
code.instructions += MonoLong(code.nextId(), inst.span, inst.value)
provider(inst.span, inst.ref, type)
}
is LstNothing -> {
val type = typeToMonoType(inst.type, ctx)
code.instructions += MonoNothing(code.nextId(), inst.span)
provider(inst.span, inst.ref, type)
}
is LstString -> {
val type = typeToMonoType(inst.type, ctx)
code.instructions += MonoString(code.nextId(), inst.span, inst.value, type)
provider(inst.span, inst.ref, type)
}
is LstSizeOf -> {
val type = typeToMonoType(inst.type, ctx)
val sizeType = typeToMonoType(inst.typeUsageBox!!.type, ctx)
code.instructions += MonoInt(code.nextId(), inst.span, sizeType.heapSize())
provider(inst.span, inst.ref, type)
}
is LstAlloc -> {
val type = typeToMonoType(inst.type, ctx)
// $1 = memory_alloc_internal(size_of<Type>)
int(inst.span, type.heapSize())
call(inst.span, "memory_alloc_internal", ctx)
val monoStruct = type.base as? MonoStruct
val option = monoStruct?.instance?.parentOption
if (option != null) {
val index = option.items.indexOf(type.base.instance)
check(index != -1)
// $1.variant = index
dup(inst.span, type)
int(inst.span, index + 1)
code.instructions += MonoStoreField(code.nextId(), inst.span, type, monoStruct.fields.first())
}
provider(inst.span, inst.ref, type)
}
is LstLambdaInit -> {
val type = typeToMonoType(inst.type, ctx)
val monoLambda = getMonoLambdaFunction(inst.lambda, ctx)
val localUpValues = monoLambda.code.upValues.map { lam ->
lam to code.upValues.find { local -> local.varRef == lam.varRef }!!
}
code.instructions += MonoLambdaInit(code.nextId(), inst.span, type, monoLambda, localUpValues)
provider(inst.span, inst.ref, type)
}
is LstIsType -> {
val type = typeToMonoType(inst.type, ctx)
val typePattern = patternToMonoTypePattern(inst.typePattern, ctx)
val expr = code.code.getInst(inst.expr) as LstExpression
val exprType = typeToMonoType(expr.type, ctx)
if (!typePattern.isOptionOrOptionItem() || !exprType.isOptionOrOptionItem()) {
// Compile type check
int(inst.span, if (typePattern.match(exprType)) 1 else 0)
provider(inst.span, inst.ref, type)
} else if (typePattern.isOptionItem() && exprType.isOptionOrOptionItem()) {
// Runtime check
val struct = (typePattern.base as MonoTypeBasePattern.PatternStruct).instance
val index = struct.parentOption!!.items.indexOf(typePattern.base.instance)
check(index != -1)
consumer(inst.span, inst.expr)
int(inst.span, index + 1)
if (!initIsTypeInternal) {
initIsTypeInternal = true
getMonoFunction(program.getFunction("is_type_internal"), ctx)
}
call(inst.span, "is_type_internal", ctx)
provider(inst.span, inst.ref, type)
} else {
// Invalid check
this.program.collector.report(
"Invalid type check, types must be known at compile type or be options",
inst.span
)
unreachable(inst.span)
provider(inst.span, inst.ref, type)
}
}
is LstAsType -> {
val type = typeToMonoType(inst.type, ctx)
val typeParam = typeToMonoType(inst.typeUsageBox!!.type, ctx)
val expr = code.code.getInst(inst.expr) as LstExpression
val exprType = typeToMonoType(expr.type, ctx)
if (typeParam.isValueType() || exprType.isValueType()) {
// Compile type cast
if (exprType == typeParam) {
consumer(inst.span, inst.expr)
provider(inst.span, inst.ref, type)
return
}
} else if (typeParam.isOptionItem() && (exprType.isOptionItem() || exprType.isOption())) {
// Runtime cast
val struct = (typeParam.base as MonoStruct).instance
val index = struct.parentOption!!.items.indexOf(typeParam.base.instance)
check(index != -1)
consumer(inst.span, inst.expr)
int(inst.span, index + 1)
if (!initAsTypeInternal) {
initAsTypeInternal = true
getMonoFunction(program.getFunction("as_type_internal"), ctx)
}
call(inst.span, "as_type_internal", ctx)
provider(inst.span, inst.ref, type)
return
}
// Invalid cast
this.program.collector.report("Invalid type cast", inst.span)
unreachable(inst.span)
consumer(inst.span, inst.expr)
provider(inst.span, inst.ref, type)
}
is LstIfChoose -> {
val type = typeToMonoType(inst.type, ctx)
consumer(inst.span, inst.ifTrue)
consumer(inst.span, inst.ifFalse)
consumer(inst.span, inst.cond)
code.instructions += MonoIfChoose(code.nextId(), inst.span)
provider(inst.span, inst.ref, type)
}
is LstReturn -> {
// Always never
val type = typeToMonoType(inst.type, ctx)
consumer(inst.span, inst.expr)
code.instructions += MonoReturn(code.nextId(), inst.span)
provider(inst.span, inst.ref, type)
}
is LstLoadVar -> {
if (inst.constant != null) {
val const = inst.constant!!
val constType = typeToMonoType(const.type, ctx)
if (const.isDeadCode) {
error("Internal error: attempt to access constant marked as dead code: ${const.fullName}")
}
val monoConst = consts[const.ref.id] ?: run {
error("Missing const: ${const.fullName}, with id: ${const.ref.id}")
}
code.instructions += MonoLoadConst(code.nextId(), inst.span, monoConst)
provider(inst.span, inst.ref, constType)
return
}
val instVar = inst.variable ?: error("Invalid state: $inst")
if (instVar.isUpValue) {
val upValue = code.upValues.find { it.varRef == instVar.ref }
?: error("Missing upValue: $instVar")
code.instructions += MonoLoadUpValue(code.nextId(), inst.span, upValue)
val ptrType = upValue.type
val type = ptrType.params.first()
provider(inst.span, inst.ref, type)
return
}
val variable = code.variableMap[instVar.ref] ?: error("Missing variable: $instVar")
code.instructions += MonoLoadVar(code.nextId(), inst.span, variable)
provider(inst.span, inst.ref, variable.type)
}
is LstStoreVar -> {
if (inst.constant != null) {
program.collector.report("Cannot override const ${inst.constant!!.fullName}", inst.span)
return
}
if (inst.variable!!.isUpValue) {
val upValue = code.upValues.find { it.varRef == inst.variable!!.ref }
?: error("Missing upValue: ${inst.variable}")
consumer(inst.span, inst.expr)
code.instructions += MonoStoreUpValue(code.nextId(), inst.span, upValue)
return
}
val variable = code.variableMap[inst.variable!!.ref]
?: error("Missing variable: ${inst.variable}")
consumer(inst.span, inst.expr)
code.instructions += MonoStoreVar(code.nextId(), inst.span, variable)
}
is LstLoadField -> {
val instance = code.code.getInst(inst.instance) as LstExpression
val instanceType = typeToMonoType(instance.type, ctx)
val type = typeToMonoType(inst.type, ctx)
val struct = instanceType.base as MonoStruct
val field = struct.fields[inst.field!!.index]
consumer(inst.span, inst.instance)
// Field offset
code.instructions += MonoGetFieldAddress(code.nextId(), inst.span, struct, field)
if (field.type.isValueType() && !field.type.isIntrinsic()) {
// Field offset is already the pointer to the struct
provider(inst.span, inst.ref, type)
} else {
// Load value from pointer
code.instructions += MonoLoadField(code.nextId(), inst.span, instanceType, field)
provider(inst.span, inst.ref, type)
}
}
is LstStoreField -> {
val instance = code.code.getInst(inst.instance) as LstExpression
val instanceType = typeToMonoType(instance.type, ctx)
val struct = instanceType.base as MonoStruct
val field = struct.fields[inst.field!!.index]
val fieldType = field.type
if (fieldType.heapSize() == 0) {
return
}
consumer(inst.span, inst.instance)
// Field offset
code.instructions += MonoGetFieldAddress(code.nextId(), inst.span, struct, field)
// Value
consumer(inst.span, inst.expr)
if (fieldType.isValueType() && !fieldType.isIntrinsic()) {
// Copy value
int(inst.span, fieldType.heapSize())
if (!initMemoryCopyInternal) {
initMemoryCopyInternal = true
getMonoFunction(program.getFunction("memory_copy_internal"), ctx)
}
call(inst.span, "memory_copy_internal", ctx)
drop(inst.span, fieldType)
} else {
// Copy pointer
code.instructions += MonoStoreField(code.nextId(), inst.span, instanceType, field)
}
}
is LstIfStart -> {
consumer(inst.span, inst.cond)
code.instructions += MonoIfStart(code.nextId(), inst.span)
}
is LstIfElse -> {
code.instructions += MonoIfElse(code.nextId(), inst.span)
}
is LstIfEnd -> {
code.instructions += MonoEndBlock(code.nextId(), inst.span, "if")
}
is LstWhenStart -> {
val type = typeToMonoType(inst.type, ctx)
val variable = MonoVar(
id = code.variables.size,
name = "when-${inst.ref.id}",
type = type,
varRef = null,
)
code.helperVars[inst.ref] = variable
code.variables += variable
code.instructions += MonoStartBlock(code.nextId(), inst.span)
}
is LstWhenJump -> {
code.instructions += MonoJump(code.nextId(), inst.span, inst.block.depth - inst.whenBlock.depth, false)
}
is LstWhenStore -> {
val variable = code.helperVars[inst.start.ref]!!
consumer(inst.span, inst.expr)
code.instructions += MonoStoreVar(code.nextId(), inst.span, variable)
}
is LstWhenEnd -> {
code.instructions += MonoEndBlock(code.nextId(), inst.span, "when")
if (!inst.isStatement) {
val whenVar = code.helperVars[inst.start.ref]!!
code.instructions += MonoLoadVar(code.nextId(), inst.span, whenVar)
provider(inst.span, inst.ref, whenVar.type)
}
}
is LstLoopStart -> {
code.instructions += MonoStartBlock(code.nextId(), inst.span)
code.instructions += MonoStartLoop(code.nextId(), inst.span)
}
is LstLoopJump -> {
code.instructions += MonoJump(
code.nextId(),
inst.span,
inst.block.depth - inst.loopBlock!!.depth,
inst.backwards
)
}
is LstLoopEnd -> {
code.instructions += MonoEndBlock(code.nextId(), inst.span, "loop")
code.instructions += MonoEndBlock(code.nextId(), inst.span, "block")
}
is LstLetVar -> {
// no-op
}
}
}
fun MonoBuilder.processFunctionCall(mono: MonoCode, function: LstFunction, inst: LstFunCall, ctx: MonoCtx) {
val finalType = typeToMonoType(inst.type, ctx)
if (builder.onCompileFunctionCall(mono, function, inst, finalType)) {
return
}
val external = function.getAnnotation(ANNOTATION_EXTERN)
// External function in JS
if (external != null) {
val lib = (external.args["lib"] as? ConstString)?.value
val name = (external.args["name"] as? ConstString)?.value
if (lib == null || name == null) {
error("Missing attributes on @External annotation")
}
if (inst.usesImplicitThis != null) {
val thisVar = mono.variableMap[inst.usesImplicitThis!!.ref]!!
mono.instructions += MonoLoadVar(mono.nextId(), inst.span, thisVar)
}
val generics = mutableMapOf<LstTypeParameter, MonoType>()
if (function.autogenerate) {
val replacements = mutableMapOf<LstTypeParameter, TType>()
repeat(function.typeParameters.size) {
val tp = function.typeParameters[it]
replacements[tp] = inst.typeParamsTypes[it].type
}
for ((key, type) in replacements) {
generics[key] = typeToMonoType(program.replaceGenerics(type, replacements), ctx)
}
}
val newCtx = MonoCtx(generics, ctx)
inst.arguments.forEach { ref -> consumer(inst.span, ref) }
mono.instructions += MonoFunCall(mono.nextId(), inst.span, getMonoFunction(function, newCtx))
provider(inst.span, inst.ref, finalType)
return
}
// Lambda dynamic dispatch
if (function.isIntrinsic && function.fullName == LAMBDA_CALL_FUNCTION) {
val lambdaParam = inst.arguments.first()
val lambdaType = typeOf(lambdaParam)
val intType = typeToMonoType(program.typeEnv.find("Int"), ctx)
consumer(inst.span, lambdaParam)
dup(inst.span, lambdaType)
memLoad(inst.span, intType, 0)
storeTmp(inst.span, intType, 0)
val args = inst.arguments.drop(1)
args.forEach { ref -> consumer(inst.span, ref) }
loadTmp(inst.span, intType, 0)
mono.instructions += MonoLambdaCall(mono.nextId(), inst.span, lambdaType, args.size)
provider(inst.span, inst.ref, finalType)
return
}
// Regular function call
val replacements = mutableMapOf<LstTypeParameter, TType>()
val generics = mutableMapOf<LstTypeParameter, MonoType>()
repeat(function.typeParameters.size) {
val tp = function.typeParameters[it]
replacements[tp] = inst.typeParamsTypes[it].type
}
for ((key, type) in replacements) {
generics[key] = typeToMonoType(program.replaceGenerics(type, replacements), ctx)
}
val tag = function.tag
// Call to tag function, must be replaced by the concrete implementation
val monoFunction = if (tag != null) {
val param = function.typeParameters.first()
val paramType = generics[param] ?: error("No replacement for param: $param")
val (ty, finalFunction) = findTagImplementation(tag, paramType, function.fullName)
?: error("Invalid state, no implementation found for $paramType: $function")
findReplacements(ty, paramType, generics)
val newCtx = MonoCtx(generics, ctx)
getMonoFunction(finalFunction, newCtx)
} else {
val newCtx = MonoCtx(generics, ctx)
getMonoFunction(function, newCtx)
}
if (inst.usesImplicitThis != null) {
val thisVar = mono.variableMap[inst.usesImplicitThis!!.ref]!!
mono.instructions += MonoLoadVar(mono.nextId(), inst.span, thisVar)
}
inst.arguments.forEach { ref -> consumer(inst.span, ref) }
mono.instructions += MonoFunCall(mono.nextId(), inst.span, monoFunction)
provider(inst.span, inst.ref, finalType)
if (monoFunction.returnType.isNever()) {
unreachable(inst.span)
}
}
| 0 | Java | 0 | 3 | 9f501d19da02bd7022ac9029f23cd1d19205d150 | 27,794 | NitroLang | MIT License |
kotlinmultiplatformsharedmodule/src/androidMain/kotlin/com/ping/kotlinmultiplatformsharedmodule/AndroidLogger.kt | jeyanthanperiyasamy | 783,864,786 | false | {"Gradle Kotlin DSL": 9, "TOML": 2, "Markdown": 3, "Java Properties": 10, "Gradle": 10, "Shell": 1, "Text": 3, "Ignore List": 12, "Batchfile": 1, "Proguard": 10, "XML": 154, "Kotlin": 239, "Java": 352, "JSON": 48, "YAML": 13, "INI": 3, "Ruby": 1, "Makefile": 2, "C++": 1, "Swift": 5, "OpenStep Property List": 3, "SVG": 1, "CSS": 1, "FreeMarker": 2} | package com.ping.kotlinmultiplatformsharedmodule
import android.util.Log
import java.lang.String.format
class AndroidMFDefaultLogger : MFLoggerInterface {
private fun log(
level: MFLogger.Level,
tag: String,
t: Throwable?,
message: String,
) {
val value =
try {
format(
"[%s] [%s]: ",
"BuildConfig.VERSION_NAME",
tag,
) + format(message)
} catch (e: Exception) {
""
}
when (level) {
MFLogger.Level.DEBUG -> {
Log.d(MFLogger.FORGE_ROCK, value)
return
}
MFLogger.Level.INFO -> {
Log.i(MFLogger.FORGE_ROCK, value)
return
}
MFLogger.Level.WARN -> {
Log.w(MFLogger.FORGE_ROCK, value, t)
return
}
MFLogger.Level.ERROR -> Log.e(MFLogger.FORGE_ROCK, value, t)
else -> {
}
}
}
override fun error(
tag: String?,
t: Throwable?,
message: String?,
) {
log(MFLogger.Level.ERROR, tag ?: "", t, message ?: "")
}
override fun error(
tag: String?,
message: String?,
) {
log(MFLogger.Level.ERROR, tag ?: "", null, message ?: "")
}
override fun warn(
tag: String?,
message: String?,
) {
log(MFLogger.Level.WARN, tag ?: "", null, message ?: "")
}
override fun warn(
tag: String?,
t: Throwable?,
message: String?,
) {
log(MFLogger.Level.WARN, tag ?: "", t, message ?: "")
}
override fun debug(
tag: String?,
message: String?,
) {
log(MFLogger.Level.DEBUG, tag ?: "", null, message ?: "")
}
override fun info(
tag: String?,
message: String?,
) {
log(MFLogger.Level.INFO, tag ?: "", null, message ?: "")
}
override fun network(
tag: String?,
message: String?,
) {
log(MFLogger.Level.DEBUG, tag ?: "", null, message ?: "")
}
override fun isNetworkEnabled(): Boolean {
return MFLogger.isDebugEnabled()
}
}
actual fun getLogger(): MFLoggerInterface = AndroidMFDefaultLogger()
| 0 | Java | 0 | 0 | 2c3fde50e89eba384bd3b051a971a7c782c27c02 | 2,364 | KotlinMultiPlatform | MIT License |
kt/tools-common/src/main/kotlin/godot/tools/common/constants/FileExtensions.kt | utopia-rise | 289,462,532 | false | {"Python": 1, "Text": 8, "C++": 127, "C": 7, "CMake": 1, "YAML": 27, "Ignore List": 11, "Git Attributes": 6, "EditorConfig": 1, "Markdown": 46, "SVG": 20, "Gradle Kotlin DSL": 27, "INI": 17, "Shell": 12, "Batchfile": 7, "Kotlin": 1298, "XML": 3, "JSON": 10, "TOML": 1, "JavaScript": 1, "Godot Resource": 27, "GDScript": 115, "Microsoft Visual Studio Solution": 1, "C#": 5, "Java Properties": 1, "Java": 2} | package godot.tools.common.constants
object FileExtensions {
object GodotKotlinJvm {
// keep in sync with godotkotlin_defs.h!
val registrationFile = "gdj"
}
object Godot {
val sceneFile = "tscn"
}
}
| 63 | Kotlin | 36 | 537 | cf2ead14402f4fee8caff4573fb8cd82114735e9 | 241 | godot-kotlin-jvm | MIT License |
modules/src/main/java/ir/awlrhm/modules/extentions/Activity.kt | Nikafarinegan | 638,830,639 | false | {"Java": 139207, "Kotlin": 123074} | package ir.awlrhm.modules.extentions
import android.Manifest
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.StrictMode
import android.util.DisplayMetrics
import android.view.View
import android.widget.TextView
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.content.ContextCompat
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.snackbar.Snackbar
import com.karumi.dexter.Dexter
import com.karumi.dexter.MultiplePermissionsReport
import com.karumi.dexter.PermissionToken
import com.karumi.dexter.listener.PermissionDeniedResponse
import com.karumi.dexter.listener.PermissionGrantedResponse
import com.karumi.dexter.listener.PermissionRequest
import com.karumi.dexter.listener.multi.MultiplePermissionsListener
import com.karumi.dexter.listener.single.PermissionListener
import ir.awlrhm.modules.enums.FlashbarDuration
import ir.awlrhm.modules.enums.MessageStatus
import ir.awlrhm.modules.utils.OnPermissionListener
import ir.awrhm.flashbar.Flashbar
import ir.awrhm.flashbar.Flashbar.Companion.DURATION_LONG
import ir.awrhm.flashbar.Flashbar.Companion.DURATION_SHORT
import ir.awrhm.modules.R
import java.io.File
fun Activity.configBottomSheet(view: View, divide: Float) {
val params = (view.parent as View).layoutParams as CoordinatorLayout.LayoutParams
//val behavior = params.behavior
val parent = view.parent as View
parent.fitsSystemWindows = true
val bottomSheetBehavior = BottomSheetBehavior.from(parent)
view.measure(0, 0)
val dm = DisplayMetrics()
windowManager?.defaultDisplay?.getMetrics(dm)
val screenHeight = dm.heightPixels
bottomSheetBehavior.peekHeight = (screenHeight / divide).toInt()
params.height = screenHeight
parent.layoutParams = params
}
fun Activity.openPdf(path: String, filename: String?) {
val file = File(path + File.separator + filename)
val builder = StrictMode.VmPolicy.Builder()
StrictMode.setVmPolicy(builder.build())
val uri = Uri.fromFile(file)
val intent = Intent(Intent.ACTION_VIEW)
if (uri.toString().contains(".pdf")) {
intent.setDataAndType(uri, "application/pdf")
}
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
}
fun Activity.ySnake(message: String, action: String) {
val snackbar = Snackbar
.make(
this.findViewById(android.R.id.content),
message,
Snackbar.LENGTH_INDEFINITE
)
snackbar.setAction(action) {
snackbar.dismiss()
}
snackbar.setActionTextColor(
ContextCompat.getColor(
this,
R.color.light_green_A700
)
)
val sbView = snackbar.view
val textView: TextView =
sbView.findViewById<View>(R.id.snackbar_text) as TextView
textView.setTextColor(ContextCompat.getColor(this, R.color.white))
snackbar.show()
}
fun Activity.checkWriteStoragePermission(
callback: () -> Unit
){
Dexter.withActivity(this)
.withPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
.withListener(object : PermissionListener {
override fun onPermissionGranted(response: PermissionGrantedResponse) {
callback.invoke()
}
override fun onPermissionDenied(response: PermissionDeniedResponse) {
yToast(
getString(R.string.set_permission_for_operations),
MessageStatus.ERROR
)
}
override fun onPermissionRationaleShouldBeShown(
permission: PermissionRequest,
token: PermissionToken
) {
token.continuePermissionRequest()
}
}).check()
}
fun Activity.checkCameraPhoneState(callback: OnPermissionListener){
Dexter.withActivity(this)
.withPermission(Manifest.permission.CAMERA)
.withListener(object: PermissionListener {
override fun onPermissionGranted(response: PermissionGrantedResponse?) {
callback.onPermissionGranted()
}
override fun onPermissionDenied(response: PermissionDeniedResponse?) {
callback.onPermissionDenied()
}
override fun onPermissionRationaleShouldBeShown(
permission: PermissionRequest?,
token: PermissionToken?
) {
token?.continuePermissionRequest()
}
}).check()
}
fun Activity.checkReadWriteStoragePermission(
callback: () -> Unit
){
Dexter.withActivity(this)
.withPermissions(
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
)
.withListener(object : MultiplePermissionsListener {
override fun onPermissionsChecked(report: MultiplePermissionsReport?) {
report?.let {
if (report.areAllPermissionsGranted()) {
callback.invoke()
} else {
yToast(
getString(R.string.set_permission_add_attachment),
MessageStatus.ERROR
)
}
}
}
override fun onPermissionRationaleShouldBeShown(
permissions: MutableList<PermissionRequest>?,
token: PermissionToken?
) {
token?.continuePermissionRequest()
}
})
.withErrorListener {
yToast(
getString(R.string.set_permission_add_attachment),
MessageStatus.ERROR
)
}
.check()
}
fun Activity.checkReadPhoneState(callback: OnPermissionListener){
Dexter.withActivity(this)
.withPermission(Manifest.permission.READ_PHONE_STATE)
.withListener(object : PermissionListener {
override fun onPermissionGranted(response: PermissionGrantedResponse) {
callback.onPermissionGranted()
}
override fun onPermissionDenied(response: PermissionDeniedResponse) {
callback.onPermissionDenied()
}
override fun onPermissionRationaleShouldBeShown(
permission: PermissionRequest,
token: PermissionToken
) {
token.continuePermissionRequest()
}
}).check()
}
fun Activity.successOperation(message: String? = getString(R.string.success_operation)){
yToast(
message ?: getString(R.string.success_operation) ,
MessageStatus.SUCCESS
)
}
fun Activity.failureOperation(message: String? = getString(R.string.failed_operation)){
yToast(
message ?: getString(R.string.failed_operation),
MessageStatus.ERROR
)
}
fun Activity.showFlashbarWithBackPressed(
title: String,
message: String,
status: MessageStatus
) {
Flashbar.Builder(this)
.gravity(Flashbar.Gravity.TOP)
.title(if (title.isEmpty()) getString(R.string.error) else title)
.icon(
when (status) {
MessageStatus.ERROR -> R.drawable.ic_warning
MessageStatus.SUCCESS -> R.drawable.ic_success
MessageStatus.INFORMATION -> R.drawable.ic_information
}
)
.titleColorRes(R.color.black)
.titleSizeInSp(16f)
.message(message)
.messageColorRes(R.color.black)
.backgroundDrawable(
when (status) {
MessageStatus.SUCCESS -> R.color.green_A400
MessageStatus.INFORMATION -> R.color.blue_500
MessageStatus.ERROR -> R.color.orange_500
}
)
.listenOutsideTaps(object : Flashbar.OnTapListener {
override fun onTap(flashbar: Flashbar) {
onBackPressed()
flashbar.dismiss()
}
})
.build()
.show()
}
fun Activity.showFlashbar(
title: String,
message: String,
status: MessageStatus,
duration: FlashbarDuration = FlashbarDuration.LONG
) {
Flashbar.Builder(this)
.gravity(Flashbar.Gravity.TOP)
.title(if (title.isEmpty()) getString(R.string.error) else title)
.icon(
when (status) {
MessageStatus.ERROR -> R.drawable.ic_warning
MessageStatus.SUCCESS -> R.drawable.ic_success
MessageStatus.INFORMATION -> R.drawable.ic_information
}
)
.titleColorRes(R.color.black)
.titleSizeInSp(16f)
.message(message)
.messageColorRes(R.color.black)
.backgroundDrawable(
when (status) {
MessageStatus.SUCCESS -> R.color.green_A400
MessageStatus.INFORMATION -> R.color.blue_500
MessageStatus.ERROR -> R.color.orange_500
}
)
.duration(if(duration == FlashbarDuration.LONG) DURATION_LONG else DURATION_SHORT)
.build()
.show()
}
fun Activity.showActionFlashbar(
title: String,
message: String,
okCallback: () -> Unit
) {
Flashbar.Builder(this)
.gravity(Flashbar.Gravity.TOP)
.title(if (title.isEmpty()) getString(R.string.warning) else title)
.icon(R.drawable.ic_warning)
.titleColorRes(R.color.black)
.titleSizeInSp(16f)
.message(message)
.messageColorRes(R.color.black)
.backgroundDrawable(R.color.orange_500)
.positiveActionText(R.string.ok)
.negativeActionText(R.string.cancel)
.positiveActionTapListener(object : Flashbar.OnActionTapListener {
override fun onActionTapped(bar: Flashbar) {
okCallback.invoke()
bar.dismiss()
}
})
.negativeActionTapListener(object : Flashbar.OnActionTapListener {
override fun onActionTapped(bar: Flashbar) {
bar.dismiss()
}
})
.build()
.show()
}
| 1 | null | 1 | 1 | b24175d93e44b8218fa2c76bffd109734b764cc0 | 10,180 | Module | MIT License |
Example/SilverMobInternalTestApp/src/main/java/com/silvermob/sdk/renderingtestapp/plugplay/bidding/gam/original/GamOriginalInterstitialRandomMultiformatFragment.kt | silvermob | 748,214,980 | true | {"Batchfile": 1, "Shell": 9, "Markdown": 4, "Java Properties": 6, "INI": 5, "Proguard": 4, "Java": 787, "JavaScript": 3, "HTML": 10, "Kotlin": 175} | package com.silvermob.sdk.renderingtestapp.plugplay.bidding.gam.original
import com.silvermob.sdk.renderingtestapp.R
import java.util.EnumSet
import kotlin.random.Random
class GamOriginalInterstitialRandomMultiformatFragment : GamOriginalInterstitialFragment() {
override fun createAdUnit(adUnitFormat: com.silvermob.sdk.api.data.AdUnitFormat): com.silvermob.sdk.AdUnit {
val configId =
if (Random.nextBoolean()) getString(R.string.imp_prebid_id_interstitial_320_480) else getString(R.string.imp_prebid_id_video_interstitial_320_480_original_api)
val adUnit = com.silvermob.sdk.InterstitialAdUnit(configId, EnumSet.of(com.silvermob.sdk.api.data.AdUnitFormat.DISPLAY, com.silvermob.sdk.api.data.AdUnitFormat.VIDEO))
adUnit.videoParameters = com.silvermob.sdk.VideoParameters(listOf("video/mp4"))
return adUnit
}
} | 0 | Java | 0 | 0 | 876b9f6838055e4a6f05df30ef2e19f94478675c | 868 | silvermob-sdk-android | Apache License 2.0 |
environment/src/main/kotlin/jetbrains/exodus/tree/btree/BTreeDup.kt | mohammadfarari1360 | 637,398,375 | true | {"Java Properties": 1, "Gradle Kotlin DSL": 16, "Shell": 1, "Markdown": 6, "Batchfile": 1, "Java": 478, "Kotlin": 390, "INI": 1} | /*
* Copyright 2010 - 2023 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.exodus.tree.btree
import jetbrains.exodus.*
import jetbrains.exodus.log.CompressedUnsignedLongByteIterable.Companion.getCompressedSize
import jetbrains.exodus.log.Loggable
import jetbrains.exodus.tree.TreeCursor
internal class BTreeDup(mainTree: BTreeBase, leafNodeDup: LeafNodeDup) :
BTreeBase(mainTree.log, mainTree.balancePolicy, false, mainTree.structureId) {
private val leafNodeDup: LeafNodeDup
// get key from tree
private val leafNodeDupKey: ByteIterable
var startAddress: Long = 0
private var dataOffset: Byte = 0
init {
dataIterator = mainTree.getDataIterator(Loggable.NULL_ADDRESS)
this.leafNodeDup = leafNodeDup
leafNodeDupKey = leafNodeDup.key
val iterator = leafNodeDup.getRawValue(0).iterator()
val l = iterator.compressedUnsignedLong
size = l shr 1
if (l and 1L == 1L) {
val offset = iterator.compressedUnsignedLong
startAddress = leafNodeDup.address - offset
dataOffset = (getCompressedSize(l)
+ getCompressedSize(offset)).toByte()
} else {
startAddress = Loggable.NULL_ADDRESS
dataOffset = getCompressedSize(l).toByte()
}
}
override val rootAddress: Long
get() {
throw UnsupportedOperationException("BTreeDup has no root in 'Loggable' terms")
}
override val mutableCopy: BTreeDupMutable
get() = BTreeDupMutable(this, leafNodeDupKey)
override fun openCursor(): TreeCursor {
return TreeCursor(BTreeTraverser(this.root))
}
override val root: BasePage
get() = loadPage(
leafNodeDup.type, leafNodeDup.getRawValue(dataOffset.toInt()),
leafNodeDup.insideSinglePage
)
override fun loadLeaf(address: Long): LeafNode {
val loggable = getLoggable(address)
return if (loggable.type == DUP_LEAF) {
object : LeafNode(log, loggable) {
override val isDupLeaf: Boolean
get() = true
override val value: ByteIterable
get() = leafNodeDupKey
override fun toString(): String {
return "DLN {key:" + key + "} @ " + this.address
}
}
} else {
throw IllegalArgumentException("Unexpected loggable type " + loggable.type + " at address " + loggable.address)
}
}
override fun isDupKey(address: Long): Boolean {
return false
}
}
| 0 | null | 0 | 1 | 07f82043044f2a967c0f3c6c00bcc82b6e9126ef | 3,153 | xodus | Apache License 2.0 |
samples/src/main/kotlin/01DownloadHistory.kt | larry-brand | 537,620,997 | false | {"Java": 128409, "Kotlin": 96972} | package org.cryptolosers.samples
import org.cryptolosers.history.HistoryService
import org.cryptolosers.history.HistoryTickerId
import org.cryptolosers.history.Timeframe
/**
* Sample
* Download full history from Finam to C:\Users\username\.koto-trader\finam\Si\1 day
*/
fun main() {
val service = HistoryService()
service.downloadFullHistory(HistoryTickerId("Si"), Timeframe.ONE_DAY)
} | 1 | null | 1 | 1 | 05f222e8847ce1c23f5e735e11e8840485ea23ea | 398 | koto-trader | Apache License 2.0 |
app/src/main/java/cz/josefadamcik/trackontrakt/util/RxSchedulers.kt | josefadamcik | 86,170,190 | false | {"Gradle": 4, "YAML": 3, "Markdown": 2, "Java Properties": 1, "Shell": 5, "Ignore List": 2, "Batchfile": 1, "INI": 1, "Proguard": 1, "Kotlin": 118, "XML": 64, "HTML": 1, "JSON": 17, "Java": 1} | package cz.josefadamcik.trackontrakt.util
import io.reactivex.Scheduler
/**
* Enables DI of schedulers and thus simple replacement in tests.
*/
data class RxSchedulers(val subscribe: Scheduler, val observe: Scheduler) | 1 | null | 1 | 1 | b43bfae21f085d84a0f3aeac74f5a38b087b2032 | 221 | TrackOnTrakt | Apache License 2.0 |
app/src/main/java/com/mjr/app/alleasy/fragment/physics/hydrodynamics/fluidflow/TimeFragment1.kt | gabrielmjr | 508,812,095 | false | {"Java": 62070, "Kotlin": 43799} | package com.mjr.app.alleasy.fragment.physics.hydrodynamics.fluidflow
import com.mjr.app.alleasy.R
import com.mjr.app.alleasy.model.Data
import com.mjr.app.alleasy.activity.AbstractPhysicalCalculation
import com.mjr.app.alleasy.adapter.PhysicCalculationsTemplateAdapter
import com.mjr.twaire.code.physic.hydrodynamics.fluidflow.Time
class TimeFragment1: AbstractPhysicalCalculation() {
override fun setTemplateAttributes() {
datas?.apply {
add(Data("V = ", "m³"))
add(Data("Q = ", "m³/s"))
}
formula?.text = (calculation as Time).formula
}
override fun onCalculateClickListener() {
formula?.setOnClickListener{
val volumeEditText = (dataContainer.findViewHolderForAdapterPosition(0) as PhysicCalculationsTemplateAdapter.ViewHolder).value
val flowRateEditText = (dataContainer.findViewHolderForAdapterPosition(1) as PhysicCalculationsTemplateAdapter.ViewHolder).value
val volumeString = volumeEditText.text.toString()
val flowRateString = flowRateEditText.text.toString()
if (com.mjr.app.alleasy.utils.Util.isEmpty(volumeString)) {
volumeEditText.error = getText(R.string.null_field)
return@setOnClickListener
}
if (com.mjr.app.alleasy.utils.Util.isEmpty(flowRateString)) {
flowRateEditText.error = getText(R.string.null_field)
return@setOnClickListener
}
calculate(volumeString, flowRateString)
}
}
private fun calculate(volumeString: String, flowRateString: String) {
resolution?.text = (calculation as Time).apply {
volume = java.lang.Double.parseDouble(volumeString)
flowRate = java.lang.Double.parseDouble(flowRateString)
calculate()
}.steps
}
} | 1 | null | 1 | 1 | 6bca4475b1cb3af00e605677c4afd56e0862c3cc | 1,864 | AllEasy | Apache License 2.0 |
tracker/src/main/kotlin/com/moebius/tracker/assembler/TradeAssembler.kt | team-moebius | 271,893,640 | false | {"Java": 201502, "Groovy": 79521, "Kotlin": 44086, "HTML": 10921, "Dockerfile": 2383} | package com.moebius.tracker.assembler
import com.moebius.backend.dto.trade.TradeDto
import com.moebius.tracker.domain.trades.TradeDocument
import com.moebius.tracker.dto.upbit.UpbitTradeDto
import org.springframework.stereotype.Component
import java.time.LocalDateTime
import java.util.*
@Component
class TradeAssembler {
fun toCommonDto(upbitTradeDto: UpbitTradeDto): TradeDto = with(upbitTradeDto) {
val tradeDto = TradeDto()
tradeDto.id = UUID.randomUUID().toString()
tradeDto.exchange = exchange
tradeDto.symbol = symbol
tradeDto.tradeType = askBid
tradeDto.change = change
tradeDto.price = tradePrice
tradeDto.volume = tradeVolume
tradeDto.prevClosingPrice = prevClosingPrice
tradeDto.changePrice = changePrice
tradeDto.createdAt = LocalDateTime.now()
tradeDto.receivedTime = tradeTimestamp
tradeDto.sequentialId = sequentialId
tradeDto
}
fun toTradeDocument(upbitTradeDto: UpbitTradeDto): TradeDocument = with(upbitTradeDto) {
TradeDocument.of(exchange, symbol, askBid, change, tradePrice, tradeVolume, prevClosingPrice, changePrice)
}
} | 1 | null | 1 | 1 | 09a52e6bee119f6c51488aebb7403e86c7f4f013 | 1,182 | hashmain-data-pipeline | MIT License |
tracker/src/main/kotlin/com/moebius/tracker/assembler/TradeAssembler.kt | team-moebius | 271,893,640 | false | {"Java": 201502, "Groovy": 79521, "Kotlin": 44086, "HTML": 10921, "Dockerfile": 2383} | package com.moebius.tracker.assembler
import com.moebius.backend.dto.trade.TradeDto
import com.moebius.tracker.domain.trades.TradeDocument
import com.moebius.tracker.dto.upbit.UpbitTradeDto
import org.springframework.stereotype.Component
import java.time.LocalDateTime
import java.util.*
@Component
class TradeAssembler {
fun toCommonDto(upbitTradeDto: UpbitTradeDto): TradeDto = with(upbitTradeDto) {
val tradeDto = TradeDto()
tradeDto.id = UUID.randomUUID().toString()
tradeDto.exchange = exchange
tradeDto.symbol = symbol
tradeDto.tradeType = askBid
tradeDto.change = change
tradeDto.price = tradePrice
tradeDto.volume = tradeVolume
tradeDto.prevClosingPrice = prevClosingPrice
tradeDto.changePrice = changePrice
tradeDto.createdAt = LocalDateTime.now()
tradeDto.receivedTime = tradeTimestamp
tradeDto.sequentialId = sequentialId
tradeDto
}
fun toTradeDocument(upbitTradeDto: UpbitTradeDto): TradeDocument = with(upbitTradeDto) {
TradeDocument.of(exchange, symbol, askBid, change, tradePrice, tradeVolume, prevClosingPrice, changePrice)
}
} | 1 | null | 1 | 1 | 09a52e6bee119f6c51488aebb7403e86c7f4f013 | 1,182 | hashmain-data-pipeline | MIT License |
DroidMedia/medialibs/audiolib/src/main/kotlin/com/me/harris/audiolib/oboe/OboeAudioPlayer.kt | Haldir65 | 55,217,175 | false | {"Markdown": 61, "Dockerfile": 3, "Text": 47, "Ignore List": 34, "YAML": 32, "JSON": 3, "Gradle Kotlin DSL": 17, "Java Properties": 6, "Shell": 89, "Batchfile": 20, "EditorConfig": 1, "Makefile": 41, "INI": 26, "Gradle": 19, "Proguard": 27, "Kotlin": 348, "XML": 264, "TOML": 1, "Java": 594, "GLSL": 110, "Motorola 68K Assembly": 7, "C++": 411, "Unix Assembly": 10, "CMake": 37, "C": 599, "Roff Manpage": 3, "M4Sugar": 8, "Microsoft Visual Studio Solution": 4, "Awk": 3, "Module Management System": 1, "DIGITAL Command Language": 3, "Microsoft Developer Studio Project": 3, "GN": 6, "Python": 34, "Soong": 1, "Git Attributes": 1, "CoffeeScript": 1, "AIDL": 2, "Objective-C": 1, "Assembly": 4, "JSON with Comments": 3} | package com.me.harris.audiolib.oboe
import android.content.res.AssetManager
class OboeAudioPlayer {
companion object {
init {
System.loadLibrary("myaudio")
}
}
external fun startPlaying( fileName:String,assetmanager:AssetManager,sampleRate:Int);
external fun stopPlaying();
}
| 1 | null | 1 | 1 | f117ab6ef4a6c8874030cb5cd78aa72259158cf9 | 324 | Camera2Training | MIT License |
baselib/src/main/java/com/fenghuang/baselib/widget/dialog/MaterialConfirmDialog.kt | tracyly | 262,531,465 | false | {"Java": 1886821, "Kotlin": 1650417, "HTML": 41991} | package com.fenghuang.baselib.widget.dialog
import android.content.Context
import android.content.DialogInterface
import androidx.appcompat.app.AlertDialog
import com.fenghuang.baselib.R
import com.fenghuang.baselib.utils.ViewUtils
/**
* 确认对话框
*/
class MaterialConfirmDialog private constructor(context: Context) : MaterialDialog(context) {
class Builder(context: Context,
private val msg: String,
private val title: String? = ViewUtils.getString(R.string.app_tips),
private val confirmText: String? = ViewUtils.getString(R.string.app_confirm),
private val listener: DialogInterface.OnClickListener? = null) : MaterialDialog.Builder(context) {
override fun show(): AlertDialog {
setTitle(title)
setMessage(msg)
setPositiveButton(confirmText, listener)
setNegativeButton(ViewUtils.getString(R.string.app_cancel)) { dialog, _ -> dialog?.dismiss() }
return super.show()
}
}
} | 1 | null | 1 | 1 | b4f57b41ba0018299d47be4d7705f0dfb1b8cf04 | 1,034 | cpb2.0 | Apache License 2.0 |
inf-java-to-kotlin-springboot/src/main/kotlin/com/group/libraryapp/util/ExceptionUtils.kt | devYSK | 461,887,647 | false | {"Java": 3507759, "JavaScript": 659549, "Kotlin": 563136, "HTML": 455168, "CSS": 446825, "Shell": 57444, "Groovy": 54414, "Batchfile": 47890, "Go": 26805, "Python": 9963, "Handlebars": 8554, "Makefile": 7837, "Vue": 5706, "TypeScript": 5172, "Dockerfile": 436, "Vim Snippet": 362, "Assembly": 278, "Procfile": 199} | package com.group.libraryapp.util
fun fail(): Nothing { // Nothing 타입은 이 함수는 항상 정상적으로 종료되지 않는다는 의미이다.
throw IllegalArgumentException()
} | 1 | null | 1 | 1 | 7a7c6b1bab3dc2c84527f8c528b06b9408872635 | 141 | study_repo | MIT License |
proto/src/main/java/com/hik/proto/event/ApiListener.kt | DeveloperLinus | 538,288,229 | false | {"Java": 343699, "Kotlin": 118261} | /*
* Copyright 2020-present hikvision
*
* 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.hik.proto.event
import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import com.hik.proto.base.ApiInit.ApiUploadListener
import com.hik.proto.base.ApiInit.registerApi
import com.hik.proto.base.ApiInit.unregisterApi
import com.hik.proto.data.event.*
import com.hik.proto.data.param.UploadEventType
import com.hik.proto.utils.json.JsonUtil
import com.hik.proto.utils.json.JsonUtil.getValue
/**
* Created by linzijian on 2021/2/22.
*/
class ApiListener : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
private fun startListener() {
registerApi(object : ApiUploadListener {
override fun onUpload(body: String) {
Log.d("onUpload", "body=$body")
val str = getValue(body, "eventType")
when {
UploadEventType.AccessControllerEvent.name == str -> {
//门禁控制事件
ApiEvent.setAccessControllerEvent(
JsonUtil.toJsonBean(
body,
AccessControllerEvent::class.java
)
)
}
UploadEventType.voiceTalkEvent.name == str -> {
//通话对讲事件
ApiEvent.setVoiceTalkEvent(
JsonUtil.toJsonBean(
body,
VoiceTalkEvent::class.java
)
)
}
UploadEventType.OperationNotificationEvent.name == str -> {
//操作通知事件
ApiEvent.setOperationNotificationEvent(
JsonUtil.toJsonBean(
body,
OperationNotificationEvent::class.java
)
)
}
UploadEventType.CaptureDataProcessEvent.name == str -> {
//特征采集事件
ApiEvent.setCaptureDataProcessEvent(
JsonUtil.toJsonBean(
body,
CaptureDataProcessEvent::class.java
)
)
}
UploadEventType.ACSStatusChangeEvent.name == str -> {
//状态变化事件
ApiEvent.setACSStatusChangeEventBean(
JsonUtil.toJsonBean(
body,
ACSStatusChangeEventBean::class.java
)
)
}
UploadEventType.KeyEvent.name == str -> {
//按键操作事件
ApiEvent.setKeyEventBean(
JsonUtil.toJsonBean(
body,
KeyEventBean::class.java
)
)
}
UploadEventType.AdminVerifyResultEvent.name == str -> {
//管理员认证事件
ApiEvent.setAdminVerifyResultEvent(
JsonUtil.toJsonBean(
body,
AdminVerifyResultEvent::class.java
)
)
}
}
}
})
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
private fun stopListener() {
unregisterApi()
}
} | 1 | null | 1 | 1 | abc54ce42e65acb9f135006a5ac1f297b555f132 | 4,416 | HEOP_DEMO_V3.1.0_personSource | MIT License |
plugins/kotlin/j2k/shared/tests/test/org/jetbrains/kotlin/j2k/AbstractJavaToKotlinConverterTest.kt | qb345801622 | 285,457,947 | false | {"Text": 9390, "INI": 514, "YAML": 419, "Ant Build System": 11, "Batchfile": 33, "Dockerfile": 10, "Shell": 633, "Markdown": 744, "Ignore List": 142, "Git Revision List": 1, "Git Attributes": 11, "EditorConfig": 260, "XML": 7836, "SVG": 4421, "Kotlin": 58527, "Java": 83779, "HTML": 3782, "Java Properties": 220, "Gradle": 447, "Maven POM": 95, "JavaScript": 229, "CSS": 79, "JSON": 1419, "JFlex": 33, "Makefile": 5, "Diff": 137, "XSLT": 113, "Gradle Kotlin DSL": 715, "Groovy": 3116, "desktop": 1, "JAR Manifest": 17, "PHP": 47, "Microsoft Visual Studio Solution": 2, "C#": 33, "Smalltalk": 17, "Erlang": 1, "Perl": 9, "Jupyter Notebook": 13, "Rich Text Format": 2, "AspectJ": 2, "HLSL": 2, "Objective-C": 26, "CoffeeScript": 2, "HTTP": 2, "JSON with Comments": 72, "GraphQL": 125, "Nginx": 1, "HAProxy": 1, "OpenStep Property List": 47, "Python": 17038, "C": 110, "C++": 42, "Protocol Buffer": 3, "fish": 2, "PowerShell": 3, "Go": 36, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "TeX": 11, "HCL": 4, "Elixir": 2, "Ruby": 4, "XML Property List": 84, "E-mail": 18, "Roff": 283, "Roff Manpage": 40, "Swift": 3, "TOML": 196, "Checksums": 49, "Java Server Pages": 11, "Vue": 1, "Dotenv": 1, "reStructuredText": 67, "SQL": 1, "Vim Snippet": 8, "AMPL": 4, "Linux Kernel Module": 1, "CMake": 17, "Handlebars": 1, "Rust": 18, "Go Checksums": 1, "Go Module": 1, "NSIS": 8, "PlantUML": 6, "SCSS": 2, "Thrift": 3, "Cython": 13, "Regular Expression": 3, "JSON5": 4, "OASv3-json": 3, "OASv3-yaml": 1} | // Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.j2k
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.testFramework.LightProjectDescriptor
import org.jetbrains.kotlin.idea.base.test.IgnoreTests.DIRECTIVES.IGNORE_K1
import org.jetbrains.kotlin.idea.base.test.IgnoreTests.DIRECTIVES.IGNORE_K2
import org.jetbrains.kotlin.idea.base.test.KotlinRoot
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.idea.test.dumpTextWithErrors
import org.jetbrains.kotlin.psi.KtFile
import java.io.File
private val ignoreDirectives: Set<String> = setOf(IGNORE_K1, IGNORE_K2)
abstract class AbstractJavaToKotlinConverterTest : KotlinLightCodeInsightFixtureTestCase() {
override fun getProjectDescriptor(): LightProjectDescriptor = J2K_PROJECT_DESCRIPTOR
protected fun addFile(fileName: String, dirName: String? = null) {
addFile(File(KotlinRoot.DIR, "j2k/shared/tests/testData/$fileName"), dirName)
}
protected fun addFile(file: File, dirName: String? = null): VirtualFile {
return addFile(FileUtil.loadFile(file, true), file.name, dirName)
}
protected fun addFile(text: String, fileName: String, dirName: String?): VirtualFile {
val filePath = (if (dirName != null) "$dirName/" else "") + fileName
return myFixture.addFileToProject(filePath, text).virtualFile
}
protected fun deleteFile(virtualFile: VirtualFile) {
runWriteAction { virtualFile.delete(this) }
}
protected fun getDisableTestDirective(): String =
if (isFirPlugin) IGNORE_K2 else IGNORE_K1
protected fun File.getFileTextWithoutDirectives(): String =
readText().getTextWithoutDirectives()
protected fun String.getTextWithoutDirectives(): String =
split("\n").filterNot { it.trim() in ignoreDirectives }.joinToString(separator = "\n")
protected fun KtFile.getFileTextWithErrors(): String =
if (isFirPlugin) getK2FileTextWithErrors(this) else dumpTextWithErrors()
protected fun addJpaColumnAnnotations() {
myFixture.addClass(
"""
package javax.persistence;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
@Target({METHOD, FIELD})
public @interface Column {}
""".trimIndent()
)
myFixture.addClass(
"""
package jakarta.persistence;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
@Target({METHOD, FIELD})
public @interface Column {}
""".trimIndent()
)
}
} | 1 | null | 1 | 1 | 42b634b24fe0888a43485b6ba01d4cd559f7ccdf | 3,078 | intellij-community | Apache License 2.0 |
Demo/src/main/java/com/danny/demo/home/LoveActivity.kt | dannycx | 643,140,932 | false | {"Gradle": 12, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 10, "Batchfile": 1, "Markdown": 58, "INI": 8, "Proguard": 9, "Kotlin": 149, "XML": 117, "Java": 130, "JSON": 2} | package com.danny.demo.home
import android.os.Bundle
import com.danny.demo.R
import com.danny.xbase.base.BaseActivity
class LoveActivity: BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_circle_image)
}
}
| 0 | Java | 0 | 0 | 31020de9d942f1d0013c1bf7a8115decd229e296 | 321 | XLib | Apache License 2.0 |
samples/server/petstore/kotlin-springboot-multipart-request-model/src/main/kotlin/org/openapitools/model/MultipartMixedStatus.kt | levno-dev | 753,912,321 | true | {"Markdown": 8755, "Batchfile": 147, "Ruby": 852, "Shell": 464, "Dockerfile": 40, "Java": 10054, "INI": 275, "JavaScript": 474, "HTML": 126, "Java Properties": 19, "Kotlin": 2150, "PHP": 971, "Blade": 2, "CMake": 28, "Scala": 332, "Apex": 29, "Rust": 516, "Haskell": 56, "HTML+ERB": 4, "CSS": 23, "TypeScript": 1285, "Python": 1236, "Gradle Kotlin DSL": 34, "Go": 404, "Makefile": 5, "C#": 5226, "C++": 451, "F#": 49, "Julia": 27, "SQL": 76, "Perl": 135, "Objective-C": 134, "MATLAB": 1, "PowerShell": 249, "Swift": 962, "QMake": 1, "Proguard": 3, "Lua": 24, "C": 92, "Ada": 8} | package org.openapitools.model
import java.util.Objects
import com.fasterxml.jackson.annotation.JsonValue
import com.fasterxml.jackson.annotation.JsonProperty
import javax.validation.constraints.DecimalMax
import javax.validation.constraints.DecimalMin
import javax.validation.constraints.Email
import javax.validation.constraints.Max
import javax.validation.constraints.Min
import javax.validation.constraints.NotNull
import javax.validation.constraints.Pattern
import javax.validation.constraints.Size
import javax.validation.Valid
import io.swagger.v3.oas.annotations.media.Schema
/**
* additional field as Enum
* Values: ALLOWED,IN_PROGRESS,REJECTED
*/
enum class MultipartMixedStatus(val value: kotlin.String) {
@JsonProperty("ALLOWED") ALLOWED("ALLOWED"),
@JsonProperty("IN_PROGRESS") IN_PROGRESS("IN_PROGRESS"),
@JsonProperty("REJECTED") REJECTED("REJECTED")
}
| 0 | Java | 0 | 0 | a058c982b53b9e43878357e0daeac1c45a7a4113 | 884 | openapi-generator | Apache License 2.0 |
app/src/main/java/com/digitaldream/linkskool/dialog/StaffELearningCreateCourseOutlineDialogFragment.kt | Toochidennis | 706,639,845 | false | {"Gradle": 3, "Java Properties": 5, "Shell": 1, "Text": 2, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "JSON": 1, "Java": 225, "XML": 1015, "Kotlin": 246, "JavaScript": 1, "HTML": 2, "INI": 2} | package com.digitaldream.linkskool.dialog
import android.content.Context
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageButton
import android.widget.Toast
import androidx.fragment.app.DialogFragment
import com.android.volley.Request
import com.android.volley.VolleyError
import com.digitaldream.linkskool.R
import com.digitaldream.linkskool.config.DatabaseHelper
import com.digitaldream.linkskool.models.CourseTable
import com.digitaldream.linkskool.utils.FunctionUtils.sendRequestToServer
import com.digitaldream.linkskool.utils.VolleyCallback
import com.google.android.material.textfield.TextInputLayout
import com.j256.ormlite.dao.DaoManager
import org.json.JSONArray
import org.json.JSONObject
class StaffELearningCreateCourseOutlineDialogFragment(
private val onCreated: (String) -> Unit
) : DialogFragment() {
private lateinit var mBackBtn: ImageButton
private lateinit var mCreateBtn: Button
private lateinit var mCourseOutlineTitleInputText: TextInputLayout
private lateinit var mDescriptionInputText: TextInputLayout
private var classList = mutableListOf<CourseTable>()
private var selectedClasses = hashMapOf<String, String>()
private lateinit var mDatabaseHelper: DatabaseHelper
private var year: String? = null
private var term: String? = null
private var userId: String? = null
private var userName: String? = null
private var levelId: String? = null
private var courseName: String? = null
private var courseId: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setStyle(STYLE_NORMAL, R.style.FullScreenDialog)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(
R.layout.dialog_fragment_staff_e_learning_create_course_outline,
container, false
)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setUpViews(view)
loadClasses()
editTextWatcher()
createOutline()
dismissDialog()
}
private fun setUpViews(view: View) {
view.apply {
mBackBtn = findViewById(R.id.backBtn)
mCreateBtn = findViewById(R.id.createBtn)
mCourseOutlineTitleInputText = findViewById(R.id.courseOutlineTitleInputText)
mDescriptionInputText = findViewById(R.id.descriptionInputText)
}
mDatabaseHelper = DatabaseHelper(requireContext())
val sharedPreferences =
requireActivity().getSharedPreferences("loginDetail", Context.MODE_PRIVATE)
with(sharedPreferences) {
year = getString("school_year", "")
term = getString("term", "")
userId = getString("user_id", "")
userName = getString("user", "")
courseId = getString("courseId", "")
levelId = getString("level", "")
courseName = getString("course_name", "")
}
}
private fun loadClasses() {
try {
val classDao = DaoManager.createDao(
mDatabaseHelper.connectionSource, CourseTable::class.java
)
classList = classDao.queryBuilder().groupBy("classId")
.where().eq("levelId", levelId).query()
classList.forEach { item ->
selectedClasses[item.classId] = item.className
}
} catch (e: Exception) {
e.printStackTrace()
}
}
private fun editTextWatcher() {
mCreateBtn.isEnabled = false
mCourseOutlineTitleInputText.editText?.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
override fun afterTextChanged(s: Editable?) {
mCreateBtn.isEnabled = s.toString().isNotEmpty()
}
})
}
private fun createOutline() {
mCreateBtn.setOnClickListener {
postOutline()
}
}
private fun prepareOutline(): HashMap<String, String> {
val title = mCourseOutlineTitleInputText.editText?.text.toString().trim()
val description = mDescriptionInputText.editText?.text.toString().trim()
val classJsonArray = JSONArray()
if (selectedClasses.isNotEmpty()) {
selectedClasses.forEach { (classId, className) ->
JSONObject().apply {
put("id", classId)
put("name", className)
}.let {
classJsonArray.put(it)
}
}
}
return HashMap<String, String>().apply {
put("title", title)
put("description", description)
put("class", if (selectedClasses.isEmpty()) "" else classJsonArray.toString())
put("teacher", "")
put("course", courseId ?: "")
put("course_name", courseName ?: "")
put("level", levelId ?: "")
put("author_id", userId ?: "")
put("author_name", userName ?: "")
put("year", year ?: "")
put("term", term ?: "")
}
}
private fun postOutline() {
val data = prepareOutline()
val url = "${requireContext().getString(R.string.base_url)}/addOutline.php"
sendRequestToServer(
Request.Method.POST,
url,
requireContext(),
data,
object : VolleyCallback {
override fun onResponse(response: String) {
onCreated("created")
dismiss()
}
override fun onError(error: VolleyError) {
Toast.makeText(
requireContext(),
"Something went wrong, please try again.",
Toast.LENGTH_SHORT
).show()
}
}
)
}
private fun dismissDialog() {
mBackBtn.setOnClickListener {
dismiss()
}
}
} | 1 | Java | 0 | 1 | 551e25524b77efaba17cb9bd89a07b8ccc01b13e | 6,567 | linkskool | MIT License |
sandwichclub/src/main/java/de/pacheco/sandwichclub/utils/JsonUtils.kt | pachecoberlin | 294,999,252 | false | {"Gradle": 9, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 9, "Batchfile": 1, "Markdown": 1, "Proguard": 7, "XML": 88, "Java": 21, "Kotlin": 28, "JSON": 1, "INI": 2} | package de.pacheco.sandwichclub.utils
import android.util.Log
import de.pacheco.sandwichclub.model.Sandwich
import org.json.JSONException
import org.json.JSONObject
import java.util.*
private const val TAG = "JsonUtils.kt"
fun parseSandwichJson(json: String): Sandwich {
val jsonObject: JSONObject
val name: JSONObject
try {
jsonObject = JSONObject(json)
name = jsonObject.getJSONObject("name")
} catch (e: JSONException) {
Log.e(TAG, "Error while parsing JSON", e)
return Sandwich()
}
val mainName = getString(name, "mainName")
val alsoKnownAs = getList(name, "alsoKnownAs")
val placeOfOrigin = getString(jsonObject, "placeOfOrigin")
val description = getString(jsonObject, "description")
val image = getString(jsonObject, "image")
val ingredients = getList(jsonObject, "ingredients")
return Sandwich(mainName, alsoKnownAs, placeOfOrigin, description, image, ingredients)
}
private fun getList(name: JSONObject, string: String): List<String> {
val list: MutableList<String> = LinkedList()
try {
val jsonArray = name.getJSONArray(string)
for (i in 0 until jsonArray.length()) {
list.add(jsonArray.getString(i))
}
} catch (e: JSONException) {
Log.e(TAG, "Error while no $string in JSON", e)
}
return list
}
private fun getString(jsonObject: JSONObject, string: String): String {
return try {
jsonObject.getString(string)
} catch (e: JSONException) {
Log.e(TAG, "Error while no $string in JSON", e)
""
}
}
| 0 | Kotlin | 0 | 0 | 39a3596703b2e593bd441fb99b0c62151f80cdb1 | 1,588 | Capstone-Project | The Unlicense |
app/src/main/java/app/allever/android/lib/project/DialogActivity.kt | xinji6651 | 577,139,816 | true | {"Java Properties": 2, "Gradle": 20, "Shell": 1, "Markdown": 3, "Batchfile": 1, "Text": 1, "Ignore List": 19, "INI": 18, "Proguard": 18, "XML": 128, "Kotlin": 301, "Java": 95, "JSON": 1} | package app.allever.android.lib.project
import app.allever.android.lib.common.BaseActivity
import app.allever.android.lib.mvvm.base.BaseViewModel
import app.allever.android.lib.mvvm.base.MvvmConfig
import app.allever.android.lib.project.databinding.ActivityDialogBinding
import app.allever.android.lib.widget.ripple.RippleHelper
class DialogActivity: BaseActivity<ActivityDialogBinding, DialogViewModel>() {
override fun getContentMvvmConfig() = MvvmConfig(R.layout.activity_dialog, BR.dialogVM)
override fun init() {
initTopBar("弹窗")
RippleHelper.addRippleView(binding.btnBottomDialog)
RippleHelper.addRippleView(binding.btnCenterDialog)
RippleHelper.addRippleView(binding.btnNotificationPopWindow)
RippleHelper.addRippleView(binding.btnAbstractPopupWindow)
binding.btnBottomDialog.setOnClickListener {
BottomDialog().show(supportFragmentManager)
}
binding.btnCenterDialog.setOnClickListener {
CenterDialog(this).show()
}
val firstPopWindow = FirstPopWindow(this)
val firstPopWindow2 = FirstPopWindow(this)
binding.btnNotificationPopWindow.setOnClickListener {
firstPopWindow.show(offsetYDp = 42)
}
binding.btnAbstractPopupWindow.setOnClickListener {
NotificationWindow(this).show(window.decorView)
}
}
}
class DialogViewModel : BaseViewModel() {
override fun init() {
}
} | 0 | null | 0 | 1 | 0f9b13685b2e7c64e3389fec5799a64f7ca17c98 | 1,464 | AndroidBaseLibs | Apache License 2.0 |
idea/testData/parameterInfo/functionCall/NamedParameter3.kt | sandramulyana | 293,153,579 | true | {"Markdown": 67, "Gradle": 708, "Gradle Kotlin DSL": 527, "Java Properties": 14, "Shell": 10, "Ignore List": 12, "Batchfile": 9, "Git Attributes": 7, "Protocol Buffer": 12, "Java": 6528, "Kotlin": 59930, "Proguard": 12, "XML": 1598, "Text": 11767, "INI": 192, "JavaScript": 269, "JAR Manifest": 2, "Roff": 212, "Roff Manpage": 39, "AsciiDoc": 1, "HTML": 493, "SVG": 49, "Groovy": 33, "JSON": 177, "JFlex": 3, "Maven POM": 107, "CSS": 5, "JSON with Comments": 9, "Ant Build System": 50, "Graphviz (DOT)": 77, "C": 1, "Ruby": 6, "Objective-C": 8, "OpenStep Property List": 7, "Swift": 7, "Scala": 1, "YAML": 15} | open class A(x: Int) {
fun m(x: Int, y: Boolean) = 1
fun d(x: Int) {
m(y = false, <caret>)
}
}
/*
Text: ([y: Boolean], [x: Int]), Disabled: false, Strikeout: false, Green: true
*/ | 1 | null | 0 | 1 | 81339d54eb699660a23e3b209b97b4ae51d22695 | 200 | kotlin | Apache License 2.0 |
src/main/java/thedarkcolour/futuremc/config/FConfig.kt | Pidrosax | 257,567,349 | false | {"Text": 2, "INI": 3, "Gradle": 1, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Java": 52, "Kotlin": 170, "JSON": 390} | package thedarkcolour.futuremc.config
import net.minecraftforge.common.config.Config
import net.minecraftforge.common.config.Config.*
object FConfig {
val updateAquatic: UpdateAquatic
get() = _Internal.updateAquatic
val villageAndPillage: VillageAndPillage
get() = _Internal.villageAndPillage
val buzzyBees: BuzzyBees
get() = _Internal.buzzyBees
val netherUpdate: NetherUpdate
get() = _Internal.netherUpdate
val useVanillaCreativeTabs: Boolean
get() = _Internal.useVanillaCreativeTabs
class UpdateAquatic {
@Name("futuremc.config.blue_ice")
@Comment("Whether Blue Ice is enabled.")
@RequiresMcRestart
@JvmField
var blueIce = true
//@Name("Data Command")
//@Comment("Whether the /data command is enabled.")
//@RequiresMcRestart
//@JvmField var dataCommand = false
//@Name("Drowned")
//@Comment("Whether the Drowned is enabled.")
//@RequiresMcRestart
//@JvmField var drowned = false
@Name("Fish")
@Comment("Options for fish")
@JvmField
val fish = FishConfig()
@Name("New Water Color")
@Comment("Whether water uses its new color from 1.13+")
@RequiresMcRestart
@JvmField
var newWaterColor = true
@Name("Stripped Logs")
@Comment("Options for stripped logs")
@RequiresMcRestart
@JvmField
val strippedLogs = StrippedLogs()
@Name("Trident")
@Comment("Whether the Trident is enabled.")
@RequiresMcRestart
@JvmField
var trident = true
//@Name("Seagrass")
//@Comment("Whether Seagrass is enabled.")
//@RequiresMcRestart
//@JvmField var seagrass = false
@Name("Wood")
@Comment("Options for wood blocks")
@RequiresMcRestart
@JvmField
val wood = Wood()
class FishConfig {
@Name("Cod")
@Comment("Options for Cod")
@RequiresMcRestart
@JvmField
var cod = Fish(
Fish.SpawnEntry("minecraft", "frozen_ocean", 15,3, 6),
Fish.SpawnEntry("minecraft", "ocean", 10,3, 6),
Fish.SpawnEntry("minecraft", "deep_ocean", 10,3, 6)
)
@Name("Pufferfish")
@Comment("Options for Pufferfish")
@RequiresMcRestart
@JvmField
var pufferfish = Fish(Fish.SpawnEntry("minecraft", "deep_ocean", 5, 1, 3))
@Name("Salmon")
@Comment("Options for Salmon")
@RequiresMcRestart
@JvmField
var salmon = Fish(
Fish.SpawnEntry("minecraft", "frozen_ocean", 15, 1, 5),//"minecraft:frozen_ocean:15:1:5",
Fish.SpawnEntry("minecraft", "deep_ocean", 15, 1, 5),
Fish.SpawnEntry("minecraft", "river", 5, 1, 5),
Fish.SpawnEntry("minecraft", "frozen_river", 5, 1, 5)
)
@Name("Tropical Fish")
@Comment("Options for Tropical Fish")
@RequiresMcRestart
@JvmField
var tropicalFish = Fish(Fish.SpawnEntry("minecraft", "deep_ocean", 25, 8, 8))
@Name("Invalid Biome Messages")
@Comment("Whether missing biomes in a fish's Valid Biomes are logged to the console. Recommended for testing tweaked config options.")
@JvmField
var logMissingValidBiomes = false
class Fish(vararg defaultValidBiomes: SpawnEntry) {
@Name("Enabled")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var enabled = true
@Name("Valid Biomes")
@Comment("Which biomes this fish can spawn in.")
@RequiresMcRestart
@JvmField
@Suppress("UNCHECKED_CAST")
var validBiomes = defaultValidBiomes as Array<SpawnEntry>
class SpawnEntry(
@Name("Mod ID")
@Comment("The mod that this biome comes from")
@RequiresMcRestart
@JvmField
var modid: String,
@Name("Biome ID")
@RequiresMcRestart
@JvmField
var biome: String,
@Name("Weight")
@RequiresMcRestart
@JvmField
var weight: Int,
@Name("Minimum Group Count")
@RequiresMcRestart
@JvmField
var minGroupCount: Int,
@Name("Maximum Group Count")
@RequiresMcRestart
@JvmField
var maxGroupCount: Int
)
}
}
class StrippedLogs {
@Name("Acacia")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var acacia = true
@Name("Jungle")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var jungle = true
@Name("Birch")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var birch = true
@Name("Oak")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var oak = true
@Name("Spruce")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var spruce = true
@Name("Dark Oak")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var darkOak = true
@Name("Right click to strip")
@Comment("Whether right clicking with an axe will strip a log.")
@JvmField
var rightClickToStrip = true
}
class Wood {
@Name("Acacia")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var acacia = true
@Name("Stripped Acacia")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var strippedAcacia = true
@Name("Jungle")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var jungle = true
@Name("Stripped Jungle")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var strippedJungle = true
@Name("Birch")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var birch = true
@Name("Stripped Birch")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var strippedBirch = true
@Name("Oak")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var oak = true
@Name("Stripped Oak")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var strippedOak = true
@Name("Spruce")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var spruce = true
@Name("Stripped Spruce")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var strippedSpruce = true
@Name("Dark Oak")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var darkOak = true
@Name("Stripped Dark Oak")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var strippedDarkOak = true
}
}
class VillageAndPillage {
@Name("Bamboo")
@Comment("Options for Bamboo")
@JvmField
val bamboo = Bamboo()
@Name("Barrel")
@Comment("Whether the Barrel is enabled.")
@RequiresMcRestart
@JvmField
var barrel = true
@Name("Bell")
@Comment("Whether the Bell is enabled.")
@RequiresMcRestart
@JvmField
var bell = true
@Name("Blast Furnace")
@Comment("Whether the Blast Furnace is enabled.")
@RequiresMcRestart
@JvmField
var blastFurnace = true
@Name("Campfire")
@Comment("Options for Campfire")
@JvmField
val campfire = Campfire()
@Name("Cartography Table")
@Comment("Options for Cartography Table")
@RequiresMcRestart
@JvmField
val cartographyTable = SmithingTable()
@Name("Composter")
@Comment("Whether the Composter is enabled")
@RequiresMcRestart
@JvmField
var composter = true
@Name("Cornflower")
@Comment("Options for Cornflower")
@JvmField
val cornflower = Foliage()
@Name("Crossbow")
@Comment("Whether the Crossbow is enabled.")
@RequiresMcRestart
@JvmField
var crossbow = false
@Name("Dyes")
@Comment("Whether the new dyes are enabled.")
@RequiresMcRestart
@JvmField
var dyes = true
@Name("Fletching Table")
@Comment("Whether the Fletching Table is enabled.")
@RequiresMcRestart
@JvmField
var fletchingTable = true
@Name("Grindstone")
@Comment("Whether the Grindstone is enabled.")
@RequiresMcRestart
@JvmField
var grindstone = true
@Name("Lantern")
@Comment("Whether the Lantern is enabled.")
@RequiresMcRestart
@JvmField
var lantern = true
@Name("Lily of the Valley")
@Comment("Options for Lily of the Valley")
@JvmField
val lilyOfTheValley = Foliage()
@Name("Loom")
@Comment("Options for the Loom")
@RequiresMcRestart
@JvmField
val loom = Loom()
@Name("New Trapdoors")
@Comment("Enable/disable any of the new trapdoors from 1.14")
@JvmField
val newTrapdoors = NewTrapdoors()
@Name("New Walls")
@Comment("Enable/disable any of the new walls from 1.14")
@JvmField
val newWalls = NewWalls()
@Name("Panda")
@Comment("Whether the Panda is enabled.")
@RequiresMcRestart
@JvmField
var panda = true
@Name("Smithing Table")
@Comment("Options for Smithing Table")
@RequiresMcRestart
@JvmField
var smithingTable = SmithingTable()
@Name("Smoker")
@Comment("Whether the Smoker is enabled")
@RequiresMcRestart
@JvmField
var smoker = true
@Name("Smooth Stone")
@Comment("Whether Smooth Stone is enabled.")
@RequiresMcRestart
@JvmField
var smoothStone = true
@Name("Smooth Quartz")
@Comment("Whether Smooth Quartz is enabled.")
@RequiresMcRestart
@JvmField
var smoothQuartz = true
@Name("Stonecutter")
@Comment("Options for the Stonecutter")
@JvmField
var stonecutter = Stonecutter()
@Name("Suspicious Stew")
@Comment("")
@RequiresMcRestart
@JvmField
var suspiciousStew = true
@Name("Berry Bush")
@Comment("Options for Berry Bush")
@JvmField
val sweetBerryBush = SweetBerryBush()
@Name("Wither Rose")
@Comment("Options for the Wither Rose")
@JvmField
val witherRose = WitherRose()
class Bamboo {
@Name("Enabled")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var enabled = true
@Name("Tight Bounding Box")
@Comment("Whether the selection bounding box is tightened to the collision box.")
@JvmField
var tightBoundingBox = false
}
class Campfire {
@Name("Enabled")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var enabled = true
@Name("Functionality")
@Comment("Whether the Campfire can cook food.")
@RequiresMcRestart
@JvmField
var functionality = true
@Name("Does Damage")
@Comment("Whether the Campfire will hurt entities when walked on.")
@JvmField
var damage = true
}
class Foliage {
@Name("Enabled")
@Comment("Whether this flower is enabled.")
@RequiresMcRestart
@JvmField
var enabled = true
@Name("Spawn Rate")
@Comment("Lower means that less patches spawn. Set to 0 to disable generation.")
@Config.RangeDouble(min = 0.0, max = 1.0)
@SlidingOption
@JvmField
var spawnRate = 0.5
}
class Loom {
@Name("Enabled")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var enabled = true
@Name("Functionality")
@Comment("Whether the Loom can be used to make banners.")
@JvmField
var functionality = true
}
class NewTrapdoors {
@Name("Acacia")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var acacia = false
@Name("Jungle")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var jungle = false
@Name("Birch")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var birch = false
@Name("Spruce")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var spruce = false
@Name("Dark Oak")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var darkOak = false
}
class NewWalls {
@Name("Brick")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var brick = true
@Name("Granite")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var granite = true
@Name("Andesite")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var andesite = true
@Name("Diorite")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var diorite = true
@Name("Sandstone")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var sandstone = true
@Name("Red Sandstone")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var redSandstone = true
@Name("Stone Brick")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var stoneBrick = true
@Name("Mossy Stone")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var mossyStone = true
@Name("Nether Brick")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var netherBrick = true
@Name("Red Nether Brick")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var redNetherBrick = true
@Name("Brick")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var endStoneBrick = true
@Name("Brick")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var prismarine = true
}
class SmithingTable {
@Name("Enabled")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var enabled = true
@Name("Functionality")
@Comment("Whether this block's gui can be used.")
@JvmField
var functionality = true
}
class Stonecutter {
@Name("Enabled")
@Comment("Whether the Stonecutter is enabled.")
@RequiresMcRestart
@JvmField
var enabled = true
@Name("Functionality")
@Comment("Whether the Stonecutter can be used to cut blocks.")
@JvmField
var functionality = true
@Name("Recipe Button")
@Comment("When JEI is installed and this option is true, a recipes button is added to the Stonecutter gui.")
@JvmField
var recipeButton = true
}
class SweetBerryBush {
@Name("Enabled")
@Comment("Whether the Sweet Berry Bush is enabled. Disabling this also disables Sweet Berries.")
@RequiresMcRestart
@JvmField
var enabled = true
@Name("Spawn Rate")
@Comment("Lower means that less patches spawn. Set to 0 to disable generation.")
@Config.RangeDouble(min = 0.0, max = 1.0)
@SlidingOption
@JvmField
var spawnRate = 0.5
}
class WitherRose {
@Name("Enabled")
@Comment("Whether this flower is enabled.")
@RequiresMcRestart
@JvmField
var enabled = true
@Name("Does Damage")
@Comment("Whether the Wither Rose will deal damage when walked on.")
@JvmField
var damage = true
}
}
class BuzzyBees {
@Name("Bee")
@Comment("Whether the 1.15 creature and its related content should be enabled.")
@RequiresMcRestart
@JvmField
var bee = Bee()
@Name("Bee Nest Spawn Rate")
@Comment("The base chance a bee nest will spawn on a tree. Set to 0 to disable generation.")
@RangeDouble(min = 0.0, max = 1.0)
@SlidingOption
@JvmField
var beeNestChance = 0.05
@Name("Honey Block")
@Comment("Options for Honey Block")
@RequiresMcRestart
@JvmField
var honeyBlock = HoneyBlock()
@Name("Honeycomb Block")
@Comment("Whether the Honeycomb Block is enabled.")
@RequiresMcRestart
@JvmField
var honeycombBlock = true
@Name("Iron Golem")
@Comment("Options for Iron Golem")
@JvmField
val ironGolems = IronGolem()
@Name("Bee Nest Biome Whitelist")
@Comment(
"The list of biomes that the Bee Nests will spawn in." +
" Example: 'minecraft:taiga:2' allows bee nests to spawn in the Taiga biome and the nests have a 10% chance to spawn." +
" You should lower the chance multiplier in biomes where there are lots of trees."
)
@JvmField
var validBiomesForBeeNest =
arrayOf("minecraft:plains:1", "minecraft:sunflower_plains:1", "minecraft:mutated_forest:0.4")
class Bee {
@Name("Enabled")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var enabled = true
}
class HoneyBlock {
@Name("Enabled")
@Comment("Whether this feature is enabled.")
@RequiresMcRestart
@JvmField
var enabled = true
}
class IronGolem {
@Name("Crack")
@Comment("Whether Iron Golems \"crack\" as their health decreases.")
@RequiresMcRestart
@JvmField
var doCrack = true
@Name("Healing with Iron Ingots")
@Comment("Whether Iron Golems can be repaired and healed with Iron Ingots.")
@JvmField
var ironBarHealing = true
}
}
class NetherUpdate {
@Name("Soul Fire Lantern")
@Comment("Whether the Soul Fire Lantern is enabled.")
@RequiresMcRestart
@JvmField
var soulFireLantern = true
@Name("Soul Fire Torch")
@Comment("Whether the Soul Fire Torch is enabled.")
@RequiresMcRestart
var soulFireTorch = true
}
} | 1 | null | 1 | 1 | b343d2a134eab9575b1f9b45422862b2e964e74a | 21,583 | Future-MC | FSF All Permissive License |
Cours 5/replication-exercise/dummy/src/main/kotlin/com/example/dummy/DummyApplication.kt | SebStreb | 688,413,012 | false | {"Java": 99035, "Kotlin": 3457, "JavaScript": 800} | package com.example.dummy
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.cloud.client.discovery.EnableDiscoveryClient
@SpringBootApplication
@EnableDiscoveryClient
class DummyApplication
fun main(args: Array<String>) {
runApplication<DummyApplication>(*args)
}
| 1 | null | 1 | 1 | 9a81d273f804b370268ad3962c52b0f421fe6e13 | 363 | spring-examples | MIT License |
dsl/src/test/kotlin/Scratch.kt | prestongarno | 98,687,463 | false | {"Git Config": 1, "Gradle": 10, "XML": 1, "Shell": 2, "Ignore List": 1, "Batchfile": 1, "YAML": 2, "Text": 1, "Markdown": 8, "Kotlin": 130, "GraphQL": 3, "Java": 5, "ANTLR": 2, "Java Properties": 1, "INI": 1} | @file:Suppress("unused")
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.kotlinq.api.Fragment
import org.kotlinq.api.Kind
import org.kotlinq.api.Printer
import org.kotlinq.api.PrintingConfiguration
import org.kotlinq.api.PropertyInfo
import org.kotlinq.dsl.fragment
import org.kotlinq.dsl.query
fun greet(worldName: String = "Earth", message: Any = "Hello") =
query {
!"greet"("name" to worldName, "message" to message) on def("Response") {
"population"(integer)
"countries"("first" to 100) on def("Country") {
"name"(string)
!"coordinates" on coordinates()
!"subEntities"..{
on("State") {
"mayor"() on def("Person") {
"name"(string)
}
}
on("City") {
"name"(string)
}
}
}
}
}
fun coordinates() = fragment("Coordinate") {
"xValue"(float)
"yValue"(float)
}
enum class Measurement {
MILES,
KILOMETERS
}
class Scratch {
@Test fun `simple primitive field dsl coordinate type prints correctly`() {
assertThat(Printer
.fromConfiguration(PrintingConfiguration.PRETTY)
.toBuilder()
.metaStrategy(Printer.MetaStrategy.NONE)
.build()
.printFragmentToString(coordinates())
).isEqualTo("""
{
xValue
yValue
}
""".trimIndent())
assertThat(coordinates().toGraphQl(pretty = false))
.isEqualTo("{id,__typename,xValue,yValue}")
}
@Test fun simpleStarWars() {
val expect = """
|{
| search(text: "han solo") {
| ... on Human {
| name
| id
| height(unit: "METER")
| friendsConnection(first: 10) {
| totalCount
| friends {
| ... on Human {
| name
| id
| }
| }
| }
| }
| }
|}
""".trimMargin("|")
val printer = Printer.fromConfiguration(PrintingConfiguration.PRETTY)
.toBuilder()
.metaStrategy(Printer.MetaStrategy.NONE)
.build()
val starWarsQuery = query {
"search"("text" to "han solo")..{
on("Human") {
"name"(string)
"id"(string)
"height"(!float, "unit" to "METER")
"friendsConnection"("first" to 10) on def("FriendConnection") {
"totalCount"(integer)
"friends"..{
on("Human") {
"name"(!string)
"id"(string)
}
}
}
}
}
}.toGraphQl(printer)
assertThat(starWarsQuery)
.isEqualTo(expect)
}
@Test fun listStarWarsScratch() {
fun humanDef() = fragment("Human") {
"name"(string)
"nicknames" listOf !string
}
fun robotDef() = fragment("Robot") {
"modelNumber"(string)
"maker" on humanDef()
}
fun charactersQuery(fragments: List<Fragment>) = query {
"characters"("first" to 100)..listOf {
on..fragments
}
}
humanDef().graphQlInstance.properties.let { props ->
assertThat(props["nicknames"]?.propertyInfo)
.isEqualTo(
PropertyInfo.propertyNamed("nicknames")
.arguments(emptyMap())
.typeKind(Kind.string
.asNullable()
.asList())
.build())
assertThat(props["name"]?.propertyInfo)
.isEqualTo(PropertyInfo.propertyNamed("name")
.typeKind(Kind.string)
.build())
}
assertThat(charactersQuery(listOf(humanDef())).toGraphQl(pretty = true))
.isEqualTo("""
|{
| id
| __typename
| characters(first: 100) {
| ... on Human {
| id
| __typename
| name
| nicknames
| }
| }
|}
""".trimMargin("|"))
assertThat(charactersQuery(listOf(humanDef())).toGraphQl(pretty = false))
.isEqualTo(
"{id,__typename,characters(first: 100){...on Human{id,__typename,name,nicknames}}}")
assertThat(charactersQuery(listOf(humanDef(), robotDef())).toGraphQl(pretty = true))
.isEqualTo("""
|{
| id
| __typename
| characters(first: 100) {
| ... on Human {
| id
| __typename
| name
| nicknames
| }
| ... on Robot {
| id
| __typename
| modelNumber
| maker {
| id
| __typename
| name
| nicknames
| }
| }
| }
|}
""".trimMargin("|"))
val charactersQuery = query {
"characters"("first" to 100)..listOf {
on..humanDef()
on..robotDef()
}
}
val expect = """
|{
| id
| __typename
| characters(first: 100) {
| ... on Human {
| id
| __typename
| name
| nicknames
| }
| ... on Robot {
| id
| __typename
| modelNumber
| maker {
| id
| __typename
| name
| nicknames
| }
| }
| }
|}
""".trimMargin("|")
assertThat(charactersQuery.toGraphQl(pretty = true))
.isEqualTo(expect)
}
}
| 1 | null | 1 | 1 | a9e8dab66e2704aab1434f76cff7129d84494796 | 5,676 | kotlinq | Apache License 2.0 |
app/src/main/java/uk/co/richyhbm/coinbag/utils/WalletSummaryData.kt | RichyHBM | 63,550,566 | false | {"Gradle": 4, "Java Properties": 3, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Java": 4, "XML": 23, "Kotlin": 35} | package uk.co.richyhbm.coinbag.utils
import android.graphics.Color
import com.github.mikephil.charting.animation.Easing
import com.github.mikephil.charting.charts.PieChart
import com.github.mikephil.charting.data.PieData
import com.github.mikephil.charting.data.PieDataSet
import com.github.mikephil.charting.data.PieEntry
import com.github.mikephil.charting.formatter.PercentFormatter
import com.github.mikephil.charting.utils.ColorTemplate
import uk.co.richyhbm.coinbag.enums.Cryptocoins
import uk.co.richyhbm.coinbag.view_model.WalletSummaryViewModel
import java.util.concurrent.atomic.AtomicLong
import java.lang.Double.*
class WalletSummaryData {
val summaryVM = WalletSummaryViewModel()
val totalValue = AtomicLong(0)
val typeValues = MutableList(0, { Pair(Cryptocoins.Other, 0.0) })
val lock = Any()
fun reset() {
summaryVM.totalValue.set("Fetching")
totalValue.set(0)
synchronized(lock, {
typeValues.clear()
})
}
fun addToTotalValue(value:Double) {
totalValue.set(
doubleToLongBits(
longBitsToDouble(totalValue.get()) + value
)
)
}
fun addNewTypeValuePair(pair: Pair<Cryptocoins, Double>) {
synchronized(lock, {
typeValues.add(Pair(pair.first, pair.second))
})
}
fun getTotalValue(): Double {
return longBitsToDouble(totalValue.get())
}
fun buildChart(pieChart: PieChart):PieChart {
synchronized(lock, {
val entriesValue = typeValues.map { p ->
p.first to typeValues.filter { q -> q.first == p.first }.sumByDouble { it.second }
}.distinctBy { it.first }.map { PieEntry(it.second.toFloat(), it.first.symbol) }
val dataSet = PieDataSet(entriesValue.toMutableList(), "")
dataSet.sliceSpace = 3f
dataSet.selectionShift = 5f
dataSet.colors = ColorTemplate.MATERIAL_COLORS.toMutableList()
dataSet.valueFormatter = PercentFormatter()
dataSet.yValuePosition = PieDataSet.ValuePosition.OUTSIDE_SLICE
dataSet.valueTextColor = Color.BLACK
val data = PieData(dataSet)
pieChart.data = data
//pieChart.legend.verticalAlignment = Legend.LegendVerticalAlignment.TOP
//pieChart.legend.horizontalAlignment = Legend.LegendHorizontalAlignment.RIGHT
//pieChart.legend.orientation = Legend.LegendOrientation.VERTICAL
pieChart.legend.setDrawInside(false)
pieChart.legend.isEnabled = true
pieChart.description.isEnabled = false
pieChart.setUsePercentValues(true)
pieChart.isRotationEnabled = false
pieChart.animateY(400, Easing.EasingOption.Linear)
pieChart.setDrawEntryLabels(false)
pieChart.setEntryLabelColor(Color.BLACK)
return pieChart
})
}
} | 1 | null | 1 | 1 | db2e6dfce7b6d0230dbe8631a254dfba3dc1dd6f | 2,958 | CoinBag | Apache License 2.0 |
clients/kotlin/generated/src/main/kotlin/org/openapitools/client/models/AdGroupSummaryStatus.kt | oapicf | 489,369,143 | false | {"Markdown": 13009, "YAML": 64, "Text": 6, "Ignore List": 43, "JSON": 688, "Makefile": 2, "JavaScript": 2261, "F#": 1305, "XML": 1120, "Shell": 44, "Batchfile": 10, "Scala": 4677, "INI": 23, "Dockerfile": 14, "Maven POM": 22, "Java": 13384, "Emacs Lisp": 1, "Haskell": 75, "Swift": 551, "Ruby": 1149, "Cabal Config": 2, "OASv3-yaml": 16, "Go": 2224, "Go Checksums": 1, "Go Module": 4, "CMake": 9, "C++": 6688, "TOML": 3, "Rust": 556, "Nim": 541, "Perl": 540, "Microsoft Visual Studio Solution": 2, "C#": 1645, "HTML": 545, "Xojo": 1083, "Gradle": 20, "R": 1079, "JSON with Comments": 8, "QMake": 1, "Kotlin": 3280, "Python": 1, "Crystal": 1060, "ApacheConf": 2, "PHP": 3940, "Gradle Kotlin DSL": 1, "Protocol Buffer": 538, "C": 1598, "Ada": 16, "Objective-C": 1098, "Java Properties": 2, "Erlang": 1097, "PlantUML": 1, "robots.txt": 1, "HTML+ERB": 2, "Lua": 1077, "SQL": 512, "AsciiDoc": 1, "CSS": 3, "PowerShell": 1083, "Elixir": 5, "Apex": 1054, "Visual Basic 6.0": 3, "TeX": 1, "ObjectScript": 1, "OpenEdge ABL": 1, "Option List": 2, "Eiffel": 583, "Gherkin": 1, "Dart": 538, "Groovy": 539, "Elm": 31} | /**
*
* Please note:
* This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* Do not edit this file manually.
*
*/
@file:Suppress(
"ArrayInDataClass",
"EnumEntryName",
"RemoveRedundantQualifierName",
"UnusedImport"
)
package org.openapitools.client.models
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
/**
* Summary status for ad group
*
* Values: RUNNING,PAUSED,NOT_STARTED,COMPLETED,ADVERTISER_DISABLED,ARCHIVED,DRAFT,DELETED_DRAFT
*/
@JsonClass(generateAdapter = false)
enum class AdGroupSummaryStatus(val value: kotlin.String) {
@Json(name = "RUNNING")
RUNNING("RUNNING"),
@Json(name = "PAUSED")
PAUSED("PAUSED"),
@Json(name = "NOT_STARTED")
NOT_STARTED("NOT_STARTED"),
@Json(name = "COMPLETED")
COMPLETED("COMPLETED"),
@Json(name = "ADVERTISER_DISABLED")
ADVERTISER_DISABLED("ADVERTISER_DISABLED"),
@Json(name = "ARCHIVED")
ARCHIVED("ARCHIVED"),
@Json(name = "DRAFT")
DRAFT("DRAFT"),
@Json(name = "DELETED_DRAFT")
DELETED_DRAFT("DELETED_DRAFT");
/**
* Override [toString()] to avoid using the enum variable name as the value, and instead use
* the actual value defined in the API spec file.
*
* This solves a problem when the variable name and its value are different, and ensures that
* the client sends the correct enum values to the server always.
*/
override fun toString(): kotlin.String = value
companion object {
/**
* Converts the provided [data] to a [String] on success, null otherwise.
*/
fun encode(data: kotlin.Any?): kotlin.String? = if (data is AdGroupSummaryStatus) "$data" else null
/**
* Returns a valid [AdGroupSummaryStatus] for [data], null otherwise.
*/
fun decode(data: kotlin.Any?): AdGroupSummaryStatus? = data?.let {
val normalizedData = "$it".lowercase()
values().firstOrNull { value ->
it == value || normalizedData == "$value".lowercase()
}
}
}
}
| 0 | Java | 0 | 2 | dcd328f1e62119774fd8ddbb6e4bad6d7878e898 | 2,105 | pinterest-sdk | MIT License |
plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createClass/importDirective/annotationInPackage.kt | JetBrains | 2,489,216 | false | {"Text": 9788, "INI": 517, "YAML": 423, "Ant Build System": 11, "Batchfile": 34, "Dockerfile": 10, "Shell": 633, "Markdown": 750, "Ignore List": 141, "Git Revision List": 1, "Git Attributes": 11, "EditorConfig": 260, "XML": 7904, "SVG": 4537, "Kotlin": 60205, "Java": 84268, "HTML": 3803, "Java Properties": 217, "Gradle": 462, "Maven POM": 95, "JavaScript": 232, "CSS": 79, "JSON": 1436, "JFlex": 33, "Makefile": 5, "Diff": 137, "XSLT": 113, "Gradle Kotlin DSL": 735, "Groovy": 3102, "desktop": 1, "JAR Manifest": 17, "PHP": 47, "Microsoft Visual Studio Solution": 2, "C#": 33, "Smalltalk": 17, "Erlang": 1, "Perl": 9, "Jupyter Notebook": 13, "Rich Text Format": 2, "AspectJ": 2, "HLSL": 2, "Objective-C": 15, "CoffeeScript": 2, "HTTP": 2, "JSON with Comments": 73, "GraphQL": 127, "Nginx": 1, "HAProxy": 1, "OpenStep Property List": 47, "Python": 17095, "C": 110, "C++": 42, "Protocol Buffer": 3, "fish": 2, "PowerShell": 3, "Go": 36, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "TeX": 11, "HCL": 4, "F#": 1, "GLSL": 1, "Elixir": 2, "Ruby": 4, "XML Property List": 85, "E-mail": 18, "Roff": 289, "Roff Manpage": 40, "Swift": 3, "TOML": 196, "Checksums": 49, "Java Server Pages": 11, "Vue": 1, "Dotenv": 1, "reStructuredText": 67, "SQL": 1, "Vim Snippet": 8, "AMPL": 4, "Linux Kernel Module": 1, "CMake": 15, "Handlebars": 1, "Rust": 20, "Go Checksums": 1, "Go Module": 1, "NSIS": 8, "PlantUML": 6, "SCSS": 2, "Thrift": 3, "Cython": 13, "Regular Expression": 3, "JSON5": 4, "OASv3-json": 3, "OASv3-yaml": 1} | // "Create annotation 'A'" "true"
package p
import p.<caret>A
// FUS_QUICKFIX_NAME: org.jetbrains.kotlin.idea.quickfix.createFromUsage.createClass.CreateClassFromUsageFix$LowPriorityCreateClassFromUsageFix
// FUS_K2_QUICKFIX_NAME: org.jetbrains.kotlin.idea.k2.codeinsight.quickFixes.createFromUsage.CreateKotlinClassAction | 1 | null | 1 | 1 | 0d546ea6a419c7cb168bc3633937a826d4a91b7c | 323 | intellij-community | Apache License 2.0 |
app/src/main/java/com/MovieDb/app/core/data/source/local/entity/FavoriteEntity.kt | jeremy02 | 505,357,747 | false | {"Java": 221019, "Kotlin": 149653} | package com.MovieDb.app.core.data.source.local.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Ignore
import androidx.room.PrimaryKey
@Entity(tableName = "favoriteEntities")
class FavoriteEntity {
@PrimaryKey
@ColumnInfo(name = "uid")
val uid: String
@ColumnInfo(name = "id")
var id: Int
@ColumnInfo(name = "type")
var type: String
@ColumnInfo(name = "title")
var title: String
@ColumnInfo(name = "poster")
val poster: String
@ColumnInfo(name = "scoreAverage")
val scoreAverage: Double
@ColumnInfo(name = "startDate")
val startDate: String
@Ignore
var genres: List<GenreEntity>? = null
constructor(
uid: String,
id: Int,
type: String,
title: String,
poster: String,
scoreAverage: Double,
startDate: String
) {
this.uid = uid
this.id = id
this.type = type
this.title = title
this.poster = poster
this.scoreAverage = scoreAverage
this.startDate = startDate
}
@Ignore
constructor(
id: Int,
type: String,
title: String,
poster: String,
scoreAverage: Double,
startDate: String,
genres: List<GenreEntity>?
) {
uid = type + id
this.id = id
this.type = type
this.title = title
this.poster = poster
this.scoreAverage = scoreAverage
this.startDate = startDate
this.genres = genres
}
} | 1 | null | 1 | 1 | c09b98754b76b94fe69167a4a6569e4b204425e1 | 1,553 | MovieDb | MIT License |
clients/ktorm-schema/generated/src/main/kotlin/org/openapitools/database/models/CatalogsItemValidationWarnings.kt | oapicf | 489,369,143 | false | {"Markdown": 13009, "YAML": 64, "Text": 6, "Ignore List": 43, "JSON": 688, "Makefile": 2, "JavaScript": 2261, "F#": 1305, "XML": 1120, "Shell": 44, "Batchfile": 10, "Scala": 4677, "INI": 23, "Dockerfile": 14, "Maven POM": 22, "Java": 13384, "Emacs Lisp": 1, "Haskell": 75, "Swift": 551, "Ruby": 1149, "Cabal Config": 2, "OASv3-yaml": 16, "Go": 2224, "Go Checksums": 1, "Go Module": 4, "CMake": 9, "C++": 6688, "TOML": 3, "Rust": 556, "Nim": 541, "Perl": 540, "Microsoft Visual Studio Solution": 2, "C#": 1645, "HTML": 545, "Xojo": 1083, "Gradle": 20, "R": 1079, "JSON with Comments": 8, "QMake": 1, "Kotlin": 3280, "Python": 1, "Crystal": 1060, "ApacheConf": 2, "PHP": 3940, "Gradle Kotlin DSL": 1, "Protocol Buffer": 538, "C": 1598, "Ada": 16, "Objective-C": 1098, "Java Properties": 2, "Erlang": 1097, "PlantUML": 1, "robots.txt": 1, "HTML+ERB": 2, "Lua": 1077, "SQL": 512, "AsciiDoc": 1, "CSS": 3, "PowerShell": 1083, "Elixir": 5, "Apex": 1054, "Visual Basic 6.0": 3, "TeX": 1, "ObjectScript": 1, "OpenEdge ABL": 1, "Option List": 2, "Eiffel": 583, "Gherkin": 1, "Dart": 538, "Groovy": 539, "Elm": 31} | /**
* Pinterest REST API
* Pinterest's REST API
*
* The version of the OpenAPI document: 5.12.0
* Contact: <EMAIL>
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.database.models
import org.ktorm.dsl.*
import org.ktorm.schema.*
import org.ktorm.database.Database
import .*
/**
*
* @param AD_LINK_FORMAT_WARNING
* @param AD_LINK_SAME_AS_LINK
* @param ADDITIONAL_IMAGE_LINK_LENGTH_TOO_LONG
* @param ADDITIONAL_IMAGE_LINK_WARNING
* @param ADWORDS_FORMAT_WARNING
* @param ADWORDS_SAME_AS_LINK
* @param AGE_GROUP_INVALID
* @param SIZE_SYSTEM_INVALID
* @param ANDROID_DEEP_LINK_INVALID
* @param AVAILABILITY_DATE_INVALID
* @param COUNTRY_DOES_NOT_MAP_TO_CURRENCY
* @param CUSTOM_LABEL_LENGTH_TOO_LONG
* @param DESCRIPTION_LENGTH_TOO_LONG
* @param EXPIRATION_DATE_INVALID
* @param GENDER_INVALID
* @param GTIN_INVALID
* @param IMAGE_LINK_WARNING
* @param IOS_DEEP_LINK_INVALID
* @param IS_BUNDLE_INVALID
* @param ITEM_ADDITIONAL_IMAGE_DOWNLOAD_FAILURE
* @param LINK_FORMAT_WARNING
* @param MIN_AD_PRICE_INVALID
* @param MPN_INVALID
* @param MULTIPACK_INVALID
* @param OPTIONAL_CONDITION_INVALID
* @param OPTIONAL_CONDITION_MISSING
* @param OPTIONAL_PRODUCT_CATEGORY_INVALID
* @param OPTIONAL_PRODUCT_CATEGORY_MISSING
* @param PRODUCT_CATEGORY_DEPTH_WARNING
* @param PRODUCT_TYPE_LENGTH_TOO_LONG
* @param SALES_PRICE_INVALID
* @param SALES_PRICE_TOO_LOW
* @param SALES_PRICE_TOO_HIGH
* @param SALE_DATE_INVALID
* @param SHIPPING_INVALID
* @param SHIPPING_HEIGHT_INVALID
* @param SHIPPING_WEIGHT_INVALID
* @param SHIPPING_WIDTH_INVALID
* @param SIZE_TYPE_INVALID
* @param TAX_INVALID
* @param TITLE_LENGTH_TOO_LONG
* @param TOO_MANY_ADDITIONAL_IMAGE_LINKS
* @param UTM_SOURCE_AUTO_CORRECTED
* @param WEIGHT_UNIT_INVALID
*/
object CatalogsItemValidationWarningss : BaseTable<CatalogsItemValidationWarnings>("CatalogsItemValidationWarnings") {
val AD_LINK_FORMAT_WARNING = long("AD_LINK_FORMAT_WARNING") /* null */
val AD_LINK_SAME_AS_LINK = long("AD_LINK_SAME_AS_LINK") /* null */
val ADDITIONAL_IMAGE_LINK_LENGTH_TOO_LONG = long("ADDITIONAL_IMAGE_LINK_LENGTH_TOO_LONG") /* null */
val ADDITIONAL_IMAGE_LINK_WARNING = long("ADDITIONAL_IMAGE_LINK_WARNING") /* null */
val ADWORDS_FORMAT_WARNING = long("ADWORDS_FORMAT_WARNING") /* null */
val ADWORDS_SAME_AS_LINK = long("ADWORDS_SAME_AS_LINK") /* null */
val AGE_GROUP_INVALID = long("AGE_GROUP_INVALID") /* null */
val SIZE_SYSTEM_INVALID = long("SIZE_SYSTEM_INVALID") /* null */
val ANDROID_DEEP_LINK_INVALID = long("ANDROID_DEEP_LINK_INVALID") /* null */
val AVAILABILITY_DATE_INVALID = long("AVAILABILITY_DATE_INVALID") /* null */
val COUNTRY_DOES_NOT_MAP_TO_CURRENCY = long("COUNTRY_DOES_NOT_MAP_TO_CURRENCY") /* null */
val CUSTOM_LABEL_LENGTH_TOO_LONG = long("CUSTOM_LABEL_LENGTH_TOO_LONG") /* null */
val DESCRIPTION_LENGTH_TOO_LONG = long("DESCRIPTION_LENGTH_TOO_LONG") /* null */
val EXPIRATION_DATE_INVALID = long("EXPIRATION_DATE_INVALID") /* null */
val GENDER_INVALID = long("GENDER_INVALID") /* null */
val GTIN_INVALID = long("GTIN_INVALID") /* null */
val IMAGE_LINK_WARNING = long("IMAGE_LINK_WARNING") /* null */
val IOS_DEEP_LINK_INVALID = long("IOS_DEEP_LINK_INVALID") /* null */
val IS_BUNDLE_INVALID = long("IS_BUNDLE_INVALID") /* null */
val ITEM_ADDITIONAL_IMAGE_DOWNLOAD_FAILURE = long("ITEM_ADDITIONAL_IMAGE_DOWNLOAD_FAILURE") /* null */
val LINK_FORMAT_WARNING = long("LINK_FORMAT_WARNING") /* null */
val MIN_AD_PRICE_INVALID = long("MIN_AD_PRICE_INVALID") /* null */
val MPN_INVALID = long("MPN_INVALID") /* null */
val MULTIPACK_INVALID = long("MULTIPACK_INVALID") /* null */
val OPTIONAL_CONDITION_INVALID = long("OPTIONAL_CONDITION_INVALID") /* null */
val OPTIONAL_CONDITION_MISSING = long("OPTIONAL_CONDITION_MISSING") /* null */
val OPTIONAL_PRODUCT_CATEGORY_INVALID = long("OPTIONAL_PRODUCT_CATEGORY_INVALID") /* null */
val OPTIONAL_PRODUCT_CATEGORY_MISSING = long("OPTIONAL_PRODUCT_CATEGORY_MISSING") /* null */
val PRODUCT_CATEGORY_DEPTH_WARNING = long("PRODUCT_CATEGORY_DEPTH_WARNING") /* null */
val PRODUCT_TYPE_LENGTH_TOO_LONG = long("PRODUCT_TYPE_LENGTH_TOO_LONG") /* null */
val SALES_PRICE_INVALID = long("SALES_PRICE_INVALID") /* null */
val SALES_PRICE_TOO_LOW = long("SALES_PRICE_TOO_LOW") /* null */
val SALES_PRICE_TOO_HIGH = long("SALES_PRICE_TOO_HIGH") /* null */
val SALE_DATE_INVALID = long("SALE_DATE_INVALID") /* null */
val SHIPPING_INVALID = long("SHIPPING_INVALID") /* null */
val SHIPPING_HEIGHT_INVALID = long("SHIPPING_HEIGHT_INVALID") /* null */
val SHIPPING_WEIGHT_INVALID = long("SHIPPING_WEIGHT_INVALID") /* null */
val SHIPPING_WIDTH_INVALID = long("SHIPPING_WIDTH_INVALID") /* null */
val SIZE_TYPE_INVALID = long("SIZE_TYPE_INVALID") /* null */
val TAX_INVALID = long("TAX_INVALID") /* null */
val TITLE_LENGTH_TOO_LONG = long("TITLE_LENGTH_TOO_LONG") /* null */
val TOO_MANY_ADDITIONAL_IMAGE_LINKS = long("TOO_MANY_ADDITIONAL_IMAGE_LINKS") /* null */
val UTM_SOURCE_AUTO_CORRECTED = long("UTM_SOURCE_AUTO_CORRECTED") /* null */
val WEIGHT_UNIT_INVALID = long("WEIGHT_UNIT_INVALID") /* null */
/**
* Create an entity of type CatalogsItemValidationWarnings from the model
*/
override fun doCreateEntity(row: QueryRowSet, withReferences: Boolean) = CatalogsItemValidationWarnings(
AD_LINK_FORMAT_WARNING = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
AD_LINK_SAME_AS_LINK = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
ADDITIONAL_IMAGE_LINK_LENGTH_TOO_LONG = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
ADDITIONAL_IMAGE_LINK_WARNING = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
ADWORDS_FORMAT_WARNING = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
ADWORDS_SAME_AS_LINK = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
AGE_GROUP_INVALID = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
SIZE_SYSTEM_INVALID = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
ANDROID_DEEP_LINK_INVALID = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
AVAILABILITY_DATE_INVALID = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
COUNTRY_DOES_NOT_MAP_TO_CURRENCY = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
CUSTOM_LABEL_LENGTH_TOO_LONG = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
DESCRIPTION_LENGTH_TOO_LONG = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
EXPIRATION_DATE_INVALID = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
GENDER_INVALID = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
GTIN_INVALID = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
IMAGE_LINK_WARNING = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
IOS_DEEP_LINK_INVALID = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
IS_BUNDLE_INVALID = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
ITEM_ADDITIONAL_IMAGE_DOWNLOAD_FAILURE = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
LINK_FORMAT_WARNING = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
MIN_AD_PRICE_INVALID = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
MPN_INVALID = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
MULTIPACK_INVALID = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
OPTIONAL_CONDITION_INVALID = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
OPTIONAL_CONDITION_MISSING = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
OPTIONAL_PRODUCT_CATEGORY_INVALID = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
OPTIONAL_PRODUCT_CATEGORY_MISSING = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
PRODUCT_CATEGORY_DEPTH_WARNING = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
PRODUCT_TYPE_LENGTH_TOO_LONG = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
SALES_PRICE_INVALID = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
SALES_PRICE_TOO_LOW = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
SALES_PRICE_TOO_HIGH = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
SALE_DATE_INVALID = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
SHIPPING_INVALID = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
SHIPPING_HEIGHT_INVALID = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
SHIPPING_WEIGHT_INVALID = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
SHIPPING_WIDTH_INVALID = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
SIZE_TYPE_INVALID = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
TAX_INVALID = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
TITLE_LENGTH_TOO_LONG = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
TOO_MANY_ADDITIONAL_IMAGE_LINKS = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
UTM_SOURCE_AUTO_CORRECTED = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */,
WEIGHT_UNIT_INVALID = CatalogsItemValidationDetailss.createEntity(row, withReferences) /* CatalogsItemValidationDetails? */
)
/**
* Assign all the columns from the entity of type CatalogsItemValidationWarnings to the DML expression.
*
* Usage:
*
* ```kotlin
* let entity = CatalogsItemValidationWarnings()
* database.update(CatalogsItemValidationWarningss, {
* assignFrom(entity)
* })
* ```
* @return the builder with the columns for the update or insert.
*/
fun AssignmentsBuilder.assignFrom(entity: CatalogsItemValidationWarnings) {
this.apply {
set(CatalogsItemValidationWarningss.AD_LINK_FORMAT_WARNING, entity.AD_LINK_FORMAT_WARNING)
set(CatalogsItemValidationWarningss.AD_LINK_SAME_AS_LINK, entity.AD_LINK_SAME_AS_LINK)
set(CatalogsItemValidationWarningss.ADDITIONAL_IMAGE_LINK_LENGTH_TOO_LONG, entity.ADDITIONAL_IMAGE_LINK_LENGTH_TOO_LONG)
set(CatalogsItemValidationWarningss.ADDITIONAL_IMAGE_LINK_WARNING, entity.ADDITIONAL_IMAGE_LINK_WARNING)
set(CatalogsItemValidationWarningss.ADWORDS_FORMAT_WARNING, entity.ADWORDS_FORMAT_WARNING)
set(CatalogsItemValidationWarningss.ADWORDS_SAME_AS_LINK, entity.ADWORDS_SAME_AS_LINK)
set(CatalogsItemValidationWarningss.AGE_GROUP_INVALID, entity.AGE_GROUP_INVALID)
set(CatalogsItemValidationWarningss.SIZE_SYSTEM_INVALID, entity.SIZE_SYSTEM_INVALID)
set(CatalogsItemValidationWarningss.ANDROID_DEEP_LINK_INVALID, entity.ANDROID_DEEP_LINK_INVALID)
set(CatalogsItemValidationWarningss.AVAILABILITY_DATE_INVALID, entity.AVAILABILITY_DATE_INVALID)
set(CatalogsItemValidationWarningss.COUNTRY_DOES_NOT_MAP_TO_CURRENCY, entity.COUNTRY_DOES_NOT_MAP_TO_CURRENCY)
set(CatalogsItemValidationWarningss.CUSTOM_LABEL_LENGTH_TOO_LONG, entity.CUSTOM_LABEL_LENGTH_TOO_LONG)
set(CatalogsItemValidationWarningss.DESCRIPTION_LENGTH_TOO_LONG, entity.DESCRIPTION_LENGTH_TOO_LONG)
set(CatalogsItemValidationWarningss.EXPIRATION_DATE_INVALID, entity.EXPIRATION_DATE_INVALID)
set(CatalogsItemValidationWarningss.GENDER_INVALID, entity.GENDER_INVALID)
set(CatalogsItemValidationWarningss.GTIN_INVALID, entity.GTIN_INVALID)
set(CatalogsItemValidationWarningss.IMAGE_LINK_WARNING, entity.IMAGE_LINK_WARNING)
set(CatalogsItemValidationWarningss.IOS_DEEP_LINK_INVALID, entity.IOS_DEEP_LINK_INVALID)
set(CatalogsItemValidationWarningss.IS_BUNDLE_INVALID, entity.IS_BUNDLE_INVALID)
set(CatalogsItemValidationWarningss.ITEM_ADDITIONAL_IMAGE_DOWNLOAD_FAILURE, entity.ITEM_ADDITIONAL_IMAGE_DOWNLOAD_FAILURE)
set(CatalogsItemValidationWarningss.LINK_FORMAT_WARNING, entity.LINK_FORMAT_WARNING)
set(CatalogsItemValidationWarningss.MIN_AD_PRICE_INVALID, entity.MIN_AD_PRICE_INVALID)
set(CatalogsItemValidationWarningss.MPN_INVALID, entity.MPN_INVALID)
set(CatalogsItemValidationWarningss.MULTIPACK_INVALID, entity.MULTIPACK_INVALID)
set(CatalogsItemValidationWarningss.OPTIONAL_CONDITION_INVALID, entity.OPTIONAL_CONDITION_INVALID)
set(CatalogsItemValidationWarningss.OPTIONAL_CONDITION_MISSING, entity.OPTIONAL_CONDITION_MISSING)
set(CatalogsItemValidationWarningss.OPTIONAL_PRODUCT_CATEGORY_INVALID, entity.OPTIONAL_PRODUCT_CATEGORY_INVALID)
set(CatalogsItemValidationWarningss.OPTIONAL_PRODUCT_CATEGORY_MISSING, entity.OPTIONAL_PRODUCT_CATEGORY_MISSING)
set(CatalogsItemValidationWarningss.PRODUCT_CATEGORY_DEPTH_WARNING, entity.PRODUCT_CATEGORY_DEPTH_WARNING)
set(CatalogsItemValidationWarningss.PRODUCT_TYPE_LENGTH_TOO_LONG, entity.PRODUCT_TYPE_LENGTH_TOO_LONG)
set(CatalogsItemValidationWarningss.SALES_PRICE_INVALID, entity.SALES_PRICE_INVALID)
set(CatalogsItemValidationWarningss.SALES_PRICE_TOO_LOW, entity.SALES_PRICE_TOO_LOW)
set(CatalogsItemValidationWarningss.SALES_PRICE_TOO_HIGH, entity.SALES_PRICE_TOO_HIGH)
set(CatalogsItemValidationWarningss.SALE_DATE_INVALID, entity.SALE_DATE_INVALID)
set(CatalogsItemValidationWarningss.SHIPPING_INVALID, entity.SHIPPING_INVALID)
set(CatalogsItemValidationWarningss.SHIPPING_HEIGHT_INVALID, entity.SHIPPING_HEIGHT_INVALID)
set(CatalogsItemValidationWarningss.SHIPPING_WEIGHT_INVALID, entity.SHIPPING_WEIGHT_INVALID)
set(CatalogsItemValidationWarningss.SHIPPING_WIDTH_INVALID, entity.SHIPPING_WIDTH_INVALID)
set(CatalogsItemValidationWarningss.SIZE_TYPE_INVALID, entity.SIZE_TYPE_INVALID)
set(CatalogsItemValidationWarningss.TAX_INVALID, entity.TAX_INVALID)
set(CatalogsItemValidationWarningss.TITLE_LENGTH_TOO_LONG, entity.TITLE_LENGTH_TOO_LONG)
set(CatalogsItemValidationWarningss.TOO_MANY_ADDITIONAL_IMAGE_LINKS, entity.TOO_MANY_ADDITIONAL_IMAGE_LINKS)
set(CatalogsItemValidationWarningss.UTM_SOURCE_AUTO_CORRECTED, entity.UTM_SOURCE_AUTO_CORRECTED)
set(CatalogsItemValidationWarningss.WEIGHT_UNIT_INVALID, entity.WEIGHT_UNIT_INVALID)
}
}
}
| 0 | Java | 0 | 2 | dcd328f1e62119774fd8ddbb6e4bad6d7878e898 | 16,725 | pinterest-sdk | MIT License |
compiler/testData/codegen/boxInline/simple/classObject.2.kt | anothem | 32,282,897 | true | {"Markdown": 33, "XML": 646, "Ant Build System": 32, "Ignore List": 8, "Maven POM": 48, "Kotlin": 16461, "Java": 4172, "CSS": 10, "Shell": 7, "Batchfile": 7, "Java Properties": 9, "Gradle": 68, "HTML": 114, "INI": 7, "Groovy": 19, "JavaScript": 66, "Text": 3438, "JFlex": 3, "JAR Manifest": 2, "Roff": 30, "Roff Manpage": 10, "Protocol Buffer": 3} | package test
inline fun inline(s: () -> String): String {
return s()
}
class InlineAll {
inline fun inline(s: () -> String): String {
return s()
}
default object {
inline fun inline(s: () -> String): String {
return s()
}
}
} | 0 | Java | 0 | 0 | b44dbe6ca2e1519a4ccf548758714ce9726b77c7 | 285 | kotlin | Apache License 2.0 |
retrofit/src/main/java/retrofit2/OtherServiceMethod.kt | ltttttttttttt | 296,820,351 | true | {"Java Properties": 1, "Markdown": 25, "Text": 1, "Gradle": 24, "Shell": 2, "Batchfile": 1, "Ignore List": 1, "Java": 289, "YAML": 1, "HTML": 1, "JavaScript": 5, "CSS": 3, "INI": 19, "XML": 1, "Kotlin": 14, "Proguard": 1, "Protocol Buffer": 1} | package retrofit2
import okhttp3.HttpUrl
import java.lang.reflect.Method
/**
* creator: lt 2021/3/3 <EMAIL>
* effect : 给用户提供更方便的动态代理方法转对象的功能,可以自定义Call<T>的生成
* warning:
* [retrofit]Retrofit对象
* [method]需要生成的动态代理
*/
abstract class OtherServiceMethod<T>(
val retrofit: Retrofit,
val method: Method,
val requestFactory: RequestFactory,
) : ServiceMethod<T>() {
interface Factory<T> {
/**
* 创建OtherServiceMethod,如果自身可以处理就返回,否则可以返回null使用Retrofit默认的
*/
fun createServiceMethod(
retrofit: Retrofit,
method: Method,
requestFactory: RequestFactory,
): OtherServiceMethod<T>?
}
/**
* 用于创建Call
* [url]HttpUrl,可以通过调用toString来获取String类型的url
* [requestParameterMap]请求参数键值对
* [args]动态代理请求该方法是传入的参数
*
* [url]都会传入,但是[requestParameterMap]只有POST和GET才会传入,其他需要自己获取参数(其实是我没用到过,而且太懒...)
* 返回Retrofit.Call对象,用于替换掉原生的OkHttp的Call
*/
abstract fun createCall(
url: HttpUrl,
requestParameterMap: Map<String?, Any?>?,
args: Array<out Any>
): Call<T>
override fun invoke(args: Array<out Any>): T? {
val callAdapter = HttpServiceMethod.createCallAdapter<T, T?>(retrofit, method, method.genericReturnType, method.annotations)
val request = requestFactory.create(args)
val requestParameterMap = requestFactory.requestBuilder.getRequestParameterMap()
return callAdapter.adapt(createCall(request.url(), requestParameterMap, args))
}
} | 0 | Java | 0 | 2 | 732f88d0ca33d061eb26ac8a058f197fbe5d467e | 1,561 | retrofit | Apache License 2.0 |
DynamicKotlin/canConstructMain.kt | samyam81 | 791,205,035 | false | {"Markdown": 3, "Java": 8, "Go": 5, "Kotlin": 3} | fun main() {
println(canConstruct("abcdef", arrayOf("abc", "def")))
println(canConstruct("eeeeeeeeeeeeeeeeeeeeeeeeeeee", arrayOf("aaaa", "eee")))
}
fun canConstruct(target: String, alpha: Array<String>, samyam: MutableMap<String, Boolean> = mutableMapOf()): Boolean? {
if (target == "") return true
if (samyam.containsKey(target)) return samyam[target]
alpha.forEach { word ->
val suffix: String = target.substring(word.length)
if (canConstruct(suffix, alpha, samyam) == true) {
samyam[target] = true
return true
}
}
samyam[target] = false
return false
}
| 0 | Java | 0 | 2 | a30549ea25e0e489193d678857d34eae494afcf8 | 639 | DynamicProgramming | MIT License |
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Templates/OpModeTemplate.kt | 9880AfterShock | 751,564,175 | true | {"Batchfile": 1, "Shell": 1, "Markdown": 7, "Java Properties": 1, "Kotlin": 5, "Java": 53, "INI": 1} | package org.firstinspires.ftc.teamcode.Templates
import com.qualcomm.robotcore.eventloop.opmode.Disabled
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode
import com.qualcomm.robotcore.eventloop.opmode.TeleOp
import com.qualcomm.robotcore.util.ElapsedTime
import org.firstinspires.ftc.teamcode.LiftTemplate
import org.firstinspires.ftc.teamcode.PositionMotorTemplate
@TeleOp(name = "Template OpMode") //change string for display name
//Toggle Disabled to make appear in list or not.
//@Disabled
class OpmodeTemplate : LinearOpMode() {
private val runtime = ElapsedTime()
//Make Motor Vars
override fun runOpMode() {
//Add init msg
telemetry.addData("Status", "Initialized")
telemetry.update()
//Call Init Functions (make sure to add "this")
//LiftTemplate.initLift(this)
PositionMotorTemplate.initMotor(this)
//Wait for start
waitForStart()
runtime.reset()
//Running Loop
while (opModeIsActive()) {
//LiftTemplate.updateLift()
PositionMotorTemplate.updateMotor()
// Show the elapsed time (and other telemetry) on driver station
telemetry.addData("Status", "Run Time: $runtime")
telemetry.update()
}
}
} | 0 | Java | 0 | 0 | faa75615f17e1a3a54f2cf74d6cbded6e49aedde | 1,292 | 2024-OffSeason | BSD 3-Clause Clear License |
faculty-department-service/src/main/kotlin/kz/baltabayev/facultydepartmentservice/mapper/DepartmentMapper.kt | qaisar04 | 752,548,637 | false | {"YAML": 39, "Maven POM": 17, "Text": 1, "Ignore List": 11, "Markdown": 1, "Java": 158, "SQL": 3, "JSON": 1, "Dockerfile": 1, "XML": 5, "Fluent": 1, "Dotenv": 2, "Kotlin": 18} | package kz.baltabayev.facultydepartmentservice.mapper
import kz.baltabayev.facultydepartmentservice.model.dto.DepartmentDto
import kz.baltabayev.facultydepartmentservice.model.dto.DepartmentResponse
import kz.baltabayev.facultydepartmentservice.model.entity.Department
import kz.baltabayev.facultydepartmentservice.service.FacultyService
import org.springframework.stereotype.Component
@Component
class DepartmentMapper(
private val facultyService: FacultyService
) {
fun toEntity(departmentDto: DepartmentDto): Department {
val faculty = facultyService.findById(departmentDto.facultyId)
return Department(
name = departmentDto.name,
head = departmentDto.head,
faculty = faculty
)
}
fun toDto(department: Department?): DepartmentDto? {
return department?.let {
DepartmentDto(
it.name!!,
it.head!!,
it.faculty?.id!!
)
}
}
fun toResponse(department: Department): DepartmentResponse {
return DepartmentResponse(
id = department.id,
name = department.name,
head = department.head,
facultyId = department.faculty?.id
)
}
}
| 0 | Java | 0 | 1 | 636b33189da3c92fb0277b10ff23ec49c7a6f314 | 1,264 | university-portal | MIT License |
landscape/authorization/src/main/java/com/harera/hayat/authorization/util/ErrorMessage.kt | thucnh96dev | 741,747,383 | true | {"Shell": 13, "Dockerfile": 9, "Java": 296, "Kotlin": 11, "Markdown": 1} | package com.harera.hayat.framework.util
object ErrorMessage {
const val INCORRECT_USERNAME_PASSWORD_MESSAGE = "incorrect username or password"
} | 0 | null | 0 | 0 | 2d17baa49fefe0dbbaeb52a337487c66614eda8c | 150 | hayat-backend | Apache License 2.0 |
app/src/main/java/com/foreveross/atwork/modules/device/fragment/LoginDeviceAuthFragment.kt | AoEiuV020 | 421,650,297 | false | {"Java": 8618305, "Kotlin": 1733509, "JavaScript": 719597, "CSS": 277438, "HTML": 111559} | package com.foreveross.atwork.modules.device.fragment
import android.os.Build
import android.os.Bundle
import android.text.Editable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.foreveross.atwork.AtworkApplicationLike
import com.foreveross.atwork.R
import com.foreveross.atwork.api.sdk.BaseCallBackNetWorkListener
import com.foreveross.atwork.api.sdk.auth.model.LoginDeviceNeedAuthResult
import com.foreveross.atwork.api.sdk.auth.model.LoginWithMobileRequest
import com.foreveross.atwork.api.sdk.auth.model.PhoneSecureCodeRequestJson
import com.foreveross.atwork.component.ProgressDialogHelper
import com.foreveross.atwork.infrastructure.BaseApplicationLike
import com.foreveross.atwork.infrastructure.manager.DomainSettingsManager
import com.foreveross.atwork.infrastructure.support.AtworkConfig
import com.foreveross.atwork.infrastructure.utils.AppUtil
import com.foreveross.atwork.infrastructure.utils.CustomerHelper
import com.foreveross.atwork.infrastructure.utils.StringUtils
import com.foreveross.atwork.infrastructure.utils.rom.RomUtil
import com.foreveross.atwork.listener.TextWatcherAdapter
import com.foreveross.atwork.modules.device.activity.LoginDeviceAuthActivity
import com.foreveross.atwork.modules.login.listener.BasicLoginNetListener
import com.foreveross.atwork.modules.login.service.LoginService
import com.foreveross.atwork.modules.login.util.LoginHelper
import com.foreveross.atwork.support.BackHandledFragment
import com.foreveross.atwork.support.BaseActivity
import com.foreveross.atwork.utils.ErrorHandleUtil
import com.foreveross.atwork.utils.ViewHelper
import kotlinx.android.synthetic.main.fragment_login_device_auth.*
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.TimeUnit
class LoginDeviceAuthFragment:BackHandledFragment() {
private lateinit var tvTitle: TextView
private lateinit var ivBack: ImageView
private var loginDeviceNeedAuthResult: LoginDeviceNeedAuthResult? = null
private var timeLeft: Int = 0
private var timeCountDownScheduledFuture: ScheduledFuture<*>? = null
private val timeCountDownService = Executors.newScheduledThreadPool(1)
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_login_device_auth, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initData()
initUI()
registerListener()
}
override fun findViews(view: View) {
tvTitle = view.findViewById(R.id.title_bar_common_title)
ivBack = view.findViewById(R.id.title_bar_common_back)
}
private fun initUI() {
tvTitle.text = getStrings(R.string.title_login_device_auth)
loginDeviceNeedAuthResult?.let {
tvMobile.text = it.userPhone
}
onChangeAuthBtnStatus()
tvTip1.text = DomainSettingsManager.getInstance().loginDeviceUnAuthPrompt
tvTip2.text = DomainSettingsManager.getInstance().loginDeviceRefuseAuthPrompt
}
private fun initData() {
loginDeviceNeedAuthResult = arguments?.getParcelable(LoginDeviceAuthActivity.DATA_LOGIN_DEVICE_NEED_AUTH_RESULT)
}
private fun registerListener() {
ivBack.setOnClickListener { onBackPressed() }
etInputSecureCode.setOnFocusChangeListener { v, hasFocus -> ViewHelper.focusOnLine(vBottomLineSecureCode, hasFocus) }
etInputSecureCode.addTextChangedListener(object : TextWatcherAdapter() {
override fun afterTextChanged(content: Editable) {
onChangeAuthBtnStatus()
}
})
tvAuth.setOnClickListener {
handleLogin()
}
tvSendSecureCode.setOnClickListener {
if (null == loginDeviceNeedAuthResult) {
return@setOnClickListener
}
if(isSecureCodeResendTimeCountDowning()) {
return@setOnClickListener
}
val progressDialogHelper = ProgressDialogHelper(activity)
progressDialogHelper.show()
val phoneSecureCodeRequest = PhoneSecureCodeRequestJson().apply {
mDomainId = AtworkConfig.DOMAIN_ID
mBit = 4
mFrozenSeconds = 60
mSurvivalSeconds = 300
mType = "phone"
mAddresser = AtworkConfig.getDeviceId()
mSubsystem = AppUtil.getAppName(AtworkApplicationLike.baseContext)
mRecipient = loginDeviceNeedAuthResult!!.userPhone
if (CustomerHelper.isKwg(BaseApplicationLike.baseContext)) {
loginDeviceNeedAuthResult?.name?.let {
mTemplate = "尊敬的合景员工$it,现有新的设备尝试登陆到你的KK帐号,验证码为:%s,请使用该码验证登陆新设备。"
}
}
}
LoginService(AtworkApplicationLike.baseContext).requestPhoneSecureCode(phoneSecureCodeRequest, object : BaseCallBackNetWorkListener {
override fun onSuccess() {
progressDialogHelper.dismiss()
toast(R.string.secure_code_sent_successfully);
startTimeCountDown()
}
override fun networkFail(errorCode: Int, errorMsg: String?) {
progressDialogHelper.dismiss()
ErrorHandleUtil.handleError(errorCode, errorMsg)
}
})
}
}
private fun startTimeCountDown() {
timeLeft = 60
tvSendSecureCode.text = "${timeLeft}s"
tvSendSecureCode.alpha = 0.5f
tvSendSecureCode.isEnabled = false
timeCountDownScheduledFuture = timeCountDownService.scheduleAtFixedRate({
tvSendSecureCode.post {
timeLeft--
tvSendSecureCode.text = "${timeLeft}s"
if (0 == timeLeft) {
tvSendSecureCode.setText(R.string.re_send_secure_code)
tvSendSecureCode.alpha = 1f
tvSendSecureCode.isEnabled = true
timeCountDownScheduledFuture?.cancel(true)
timeCountDownScheduledFuture = null
}
}
}, 1000, 1000, TimeUnit.MILLISECONDS)
}
private fun isSecureCodeResendTimeCountDowning(): Boolean {
return null != timeCountDownScheduledFuture
}
private fun handleLogin() {
if (null == loginDeviceNeedAuthResult) {
return
}
val progressDialogHelper = ProgressDialogHelper(activity)
progressDialogHelper.show()
val loginWithMobileRequest = LoginWithMobileRequest().apply {
ip = AtworkConfig.getDeviceId()
clientId = loginDeviceNeedAuthResult!!.userPhone
clientPrincipal = loginDeviceNeedAuthResult!!.username
clientSecret = etInputSecureCode.text.toString()
val romChannel = RomUtil.getRomChannel()
if (!StringUtils.isEmpty(romChannel)) {
channelVendor = romChannel
channelId = AppUtil.getPackageName(context)
productVersion = AppUtil.getVersionName(context)
}
deviceName = systemModel
deviceSystemInfo = "Android " + Build.VERSION.RELEASE
}
LoginService(AtworkApplicationLike.baseContext).loginWithMobile(loginWithMobileRequest, loginDeviceNeedAuthResult!!.preInputPwd, object : BasicLoginNetListener {
override fun loginSuccess(clientId: String, needInitPwd: Boolean) {
progressDialogHelper.dismiss()
LoginHelper.handleFinishLogin(activity as BaseActivity, needInitPwd, loginDeviceNeedAuthResult!!.username, loginDeviceNeedAuthResult!!.preInputPwd)
}
override fun networkFail(errorCode: Int, errorMsg: String?) {
progressDialogHelper.dismiss()
if(202521 == errorCode || 202523 == errorCode) {
toast(R.string.WalletModifyPwd_202521)
return
}
ErrorHandleUtil.handleError(errorCode, errorMsg)
}
})
}
private fun onChangeAuthBtnStatus() {
refreshSendSecureCodeBtnStatus()
if (StringUtils.isEmpty(etInputSecureCode.text.toString())) {
tvAuth.setBackgroundResource(R.drawable.shape_login_rect_input_nothing)
tvAuth.isEnabled = false
return
}
tvAuth.setBackgroundResource(R.drawable.shape_login_rect_input_something)
tvAuth.isEnabled = true
}
private fun refreshSendSecureCodeBtnStatus() {
if (isSecureCodeResendTimeCountDowning()) {
tvSendSecureCode.alpha = 0.5f
tvSendSecureCode.isEnabled = false
} else {
tvSendSecureCode.alpha = 1f
tvSendSecureCode.isEnabled = true
}
}
override fun onBackPressed(): Boolean {
finish()
return false
}
} | 1 | null | 1 | 1 | 1c4ca5bdaea6d5230d851fb008cf2578a23b2ce5 | 9,249 | w6s_lite_android | MIT License |
app/src/main/java/com/foreveross/atwork/modules/device/fragment/LoginDeviceAuthFragment.kt | AoEiuV020 | 421,650,297 | false | {"Java": 8618305, "Kotlin": 1733509, "JavaScript": 719597, "CSS": 277438, "HTML": 111559} | package com.foreveross.atwork.modules.device.fragment
import android.os.Build
import android.os.Bundle
import android.text.Editable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.foreveross.atwork.AtworkApplicationLike
import com.foreveross.atwork.R
import com.foreveross.atwork.api.sdk.BaseCallBackNetWorkListener
import com.foreveross.atwork.api.sdk.auth.model.LoginDeviceNeedAuthResult
import com.foreveross.atwork.api.sdk.auth.model.LoginWithMobileRequest
import com.foreveross.atwork.api.sdk.auth.model.PhoneSecureCodeRequestJson
import com.foreveross.atwork.component.ProgressDialogHelper
import com.foreveross.atwork.infrastructure.BaseApplicationLike
import com.foreveross.atwork.infrastructure.manager.DomainSettingsManager
import com.foreveross.atwork.infrastructure.support.AtworkConfig
import com.foreveross.atwork.infrastructure.utils.AppUtil
import com.foreveross.atwork.infrastructure.utils.CustomerHelper
import com.foreveross.atwork.infrastructure.utils.StringUtils
import com.foreveross.atwork.infrastructure.utils.rom.RomUtil
import com.foreveross.atwork.listener.TextWatcherAdapter
import com.foreveross.atwork.modules.device.activity.LoginDeviceAuthActivity
import com.foreveross.atwork.modules.login.listener.BasicLoginNetListener
import com.foreveross.atwork.modules.login.service.LoginService
import com.foreveross.atwork.modules.login.util.LoginHelper
import com.foreveross.atwork.support.BackHandledFragment
import com.foreveross.atwork.support.BaseActivity
import com.foreveross.atwork.utils.ErrorHandleUtil
import com.foreveross.atwork.utils.ViewHelper
import kotlinx.android.synthetic.main.fragment_login_device_auth.*
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.TimeUnit
class LoginDeviceAuthFragment:BackHandledFragment() {
private lateinit var tvTitle: TextView
private lateinit var ivBack: ImageView
private var loginDeviceNeedAuthResult: LoginDeviceNeedAuthResult? = null
private var timeLeft: Int = 0
private var timeCountDownScheduledFuture: ScheduledFuture<*>? = null
private val timeCountDownService = Executors.newScheduledThreadPool(1)
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_login_device_auth, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initData()
initUI()
registerListener()
}
override fun findViews(view: View) {
tvTitle = view.findViewById(R.id.title_bar_common_title)
ivBack = view.findViewById(R.id.title_bar_common_back)
}
private fun initUI() {
tvTitle.text = getStrings(R.string.title_login_device_auth)
loginDeviceNeedAuthResult?.let {
tvMobile.text = it.userPhone
}
onChangeAuthBtnStatus()
tvTip1.text = DomainSettingsManager.getInstance().loginDeviceUnAuthPrompt
tvTip2.text = DomainSettingsManager.getInstance().loginDeviceRefuseAuthPrompt
}
private fun initData() {
loginDeviceNeedAuthResult = arguments?.getParcelable(LoginDeviceAuthActivity.DATA_LOGIN_DEVICE_NEED_AUTH_RESULT)
}
private fun registerListener() {
ivBack.setOnClickListener { onBackPressed() }
etInputSecureCode.setOnFocusChangeListener { v, hasFocus -> ViewHelper.focusOnLine(vBottomLineSecureCode, hasFocus) }
etInputSecureCode.addTextChangedListener(object : TextWatcherAdapter() {
override fun afterTextChanged(content: Editable) {
onChangeAuthBtnStatus()
}
})
tvAuth.setOnClickListener {
handleLogin()
}
tvSendSecureCode.setOnClickListener {
if (null == loginDeviceNeedAuthResult) {
return@setOnClickListener
}
if(isSecureCodeResendTimeCountDowning()) {
return@setOnClickListener
}
val progressDialogHelper = ProgressDialogHelper(activity)
progressDialogHelper.show()
val phoneSecureCodeRequest = PhoneSecureCodeRequestJson().apply {
mDomainId = AtworkConfig.DOMAIN_ID
mBit = 4
mFrozenSeconds = 60
mSurvivalSeconds = 300
mType = "phone"
mAddresser = AtworkConfig.getDeviceId()
mSubsystem = AppUtil.getAppName(AtworkApplicationLike.baseContext)
mRecipient = loginDeviceNeedAuthResult!!.userPhone
if (CustomerHelper.isKwg(BaseApplicationLike.baseContext)) {
loginDeviceNeedAuthResult?.name?.let {
mTemplate = "尊敬的合景员工$it,现有新的设备尝试登陆到你的KK帐号,验证码为:%s,请使用该码验证登陆新设备。"
}
}
}
LoginService(AtworkApplicationLike.baseContext).requestPhoneSecureCode(phoneSecureCodeRequest, object : BaseCallBackNetWorkListener {
override fun onSuccess() {
progressDialogHelper.dismiss()
toast(R.string.secure_code_sent_successfully);
startTimeCountDown()
}
override fun networkFail(errorCode: Int, errorMsg: String?) {
progressDialogHelper.dismiss()
ErrorHandleUtil.handleError(errorCode, errorMsg)
}
})
}
}
private fun startTimeCountDown() {
timeLeft = 60
tvSendSecureCode.text = "${timeLeft}s"
tvSendSecureCode.alpha = 0.5f
tvSendSecureCode.isEnabled = false
timeCountDownScheduledFuture = timeCountDownService.scheduleAtFixedRate({
tvSendSecureCode.post {
timeLeft--
tvSendSecureCode.text = "${timeLeft}s"
if (0 == timeLeft) {
tvSendSecureCode.setText(R.string.re_send_secure_code)
tvSendSecureCode.alpha = 1f
tvSendSecureCode.isEnabled = true
timeCountDownScheduledFuture?.cancel(true)
timeCountDownScheduledFuture = null
}
}
}, 1000, 1000, TimeUnit.MILLISECONDS)
}
private fun isSecureCodeResendTimeCountDowning(): Boolean {
return null != timeCountDownScheduledFuture
}
private fun handleLogin() {
if (null == loginDeviceNeedAuthResult) {
return
}
val progressDialogHelper = ProgressDialogHelper(activity)
progressDialogHelper.show()
val loginWithMobileRequest = LoginWithMobileRequest().apply {
ip = AtworkConfig.getDeviceId()
clientId = loginDeviceNeedAuthResult!!.userPhone
clientPrincipal = loginDeviceNeedAuthResult!!.username
clientSecret = etInputSecureCode.text.toString()
val romChannel = RomUtil.getRomChannel()
if (!StringUtils.isEmpty(romChannel)) {
channelVendor = romChannel
channelId = AppUtil.getPackageName(context)
productVersion = AppUtil.getVersionName(context)
}
deviceName = systemModel
deviceSystemInfo = "Android " + Build.VERSION.RELEASE
}
LoginService(AtworkApplicationLike.baseContext).loginWithMobile(loginWithMobileRequest, loginDeviceNeedAuthResult!!.preInputPwd, object : BasicLoginNetListener {
override fun loginSuccess(clientId: String, needInitPwd: Boolean) {
progressDialogHelper.dismiss()
LoginHelper.handleFinishLogin(activity as BaseActivity, needInitPwd, loginDeviceNeedAuthResult!!.username, loginDeviceNeedAuthResult!!.preInputPwd)
}
override fun networkFail(errorCode: Int, errorMsg: String?) {
progressDialogHelper.dismiss()
if(202521 == errorCode || 202523 == errorCode) {
toast(R.string.WalletModifyPwd_202521)
return
}
ErrorHandleUtil.handleError(errorCode, errorMsg)
}
})
}
private fun onChangeAuthBtnStatus() {
refreshSendSecureCodeBtnStatus()
if (StringUtils.isEmpty(etInputSecureCode.text.toString())) {
tvAuth.setBackgroundResource(R.drawable.shape_login_rect_input_nothing)
tvAuth.isEnabled = false
return
}
tvAuth.setBackgroundResource(R.drawable.shape_login_rect_input_something)
tvAuth.isEnabled = true
}
private fun refreshSendSecureCodeBtnStatus() {
if (isSecureCodeResendTimeCountDowning()) {
tvSendSecureCode.alpha = 0.5f
tvSendSecureCode.isEnabled = false
} else {
tvSendSecureCode.alpha = 1f
tvSendSecureCode.isEnabled = true
}
}
override fun onBackPressed(): Boolean {
finish()
return false
}
} | 1 | null | 1 | 1 | 1c4ca5bdaea6d5230d851fb008cf2578a23b2ce5 | 9,249 | w6s_lite_android | MIT License |
app/src/main/java/ro/alexmamo/optimizerealtimedatabase/navigation/Screen.kt | jiggery-pokery | 515,452,939 | true | {"Java Properties": 2, "Gradle": 3, "Shell": 1, "Markdown": 1, "Batchfile": 1, "Ignore List": 3, "XML": 14, "Proguard": 1, "Kotlin": 22, "Java": 21} | package ro.alexmamo.optimizerealtimedatabase.navigation
import ro.alexmamo.optimizerealtimedatabase.core.Constants.PRODUCT_DETAILS_SCREEN
import ro.alexmamo.optimizerealtimedatabase.core.Constants.PRODUCT_NAMES_SCREEN
sealed class Screen(val route: String) {
object ProductNamesScreen: Screen(PRODUCT_NAMES_SCREEN)
object ProductDetailsScreen: Screen(PRODUCT_DETAILS_SCREEN)
} | 0 | null | 0 | 0 | 4ec4b5fc92b4d08cd7d0c1b54907369e1930039b | 386 | Ex-OptimizeRealtimeDatabase | Apache License 2.0 |
app/src/main/java/com/passionpenguin/Alert.kt | Line3RenheStation | 337,653,441 | false | {"Java Properties": 2, "Gradle": 4, "Shell": 1, "Markdown": 2, "Batchfile": 1, "Text": 2, "Ignore List": 5, "XML": 268, "Proguard": 2, "Java": 133, "Makefile": 3, "C": 11, "SVG": 1, "HTML": 1, "Kotlin": 34, "JSON": 1} | /*
* ==================================================
* = PROJECT 地下铁的故事
* = MODULE 地下铁的故事.app
* = FILE NAME Alert.kt
* = LAST MODIFIED BY PASSIONPENGUIN [1/5/21, 9:25 PM]
* ==================================================
* Copyright 2021 PassionPenguin. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.passionpenguin
import android.app.Activity
import android.content.res.ColorStateList
import android.view.*
import android.widget.ImageView
import android.widget.PopupWindow
import android.widget.TextView
import com.ditiezu.android.R
import kotlin.properties.Delegates
class Alert(val activity: Activity, text: String) {
var view by Delegates.notNull<View>()
var popupWindow by Delegates.notNull<PopupWindow>()
var window by Delegates.notNull<Window>()
init {
activity.runOnUiThread {
window = activity.window
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
val target = window.decorView.findViewById<ViewGroup>(android.R.id.content)
view = LayoutInflater.from(activity).inflate(R.layout.fragment_tips, target, false)
popupWindow = PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true)
popupWindow.showAtLocation(target, Gravity.TOP, 0, 0)
view.alpha = 0F
view.animate().alpha(1F).setDuration(250).start()
view.postDelayed({
view.animate().alpha(0F).setDuration(250).start()
view.postDelayed({ popupWindow.dismiss() }, 250)
}, 1000)
view.findViewById<TextView>(R.id.text).text = text
}
}
fun success() {
view.findViewById<ImageView>(R.id.icon).setImageResource(R.drawable.ic_baseline_check_24)
view.findViewById<ImageView>(R.id.icon).backgroundTintList = ColorStateList.valueOf(activity.resources.getColor(R.color.success, null))
}
fun error() {
view.findViewById<ImageView>(R.id.icon).setImageResource(R.drawable.ic_baseline_close_24)
view.findViewById<ImageView>(R.id.icon).backgroundTintList = ColorStateList.valueOf(activity.resources.getColor(R.color.danger, null))
}
} | 1 | null | 1 | 1 | afd615412f0d0679a65faa327629fa8a80c78954 | 2,783 | Ditiezu | Apache License 2.0 |
packages/SystemUI/tests/src/com/android/systemui/shade/LargeScreenShadeHeaderControllerTest.kt | liu-wanshun | 595,904,109 | true | null | package com.android.systemui.shade
import android.animation.ValueAnimator
import android.app.StatusBarManager
import android.content.Context
import android.testing.AndroidTestingRunner
import android.view.View
import android.view.ViewPropertyAnimator
import android.widget.TextView
import androidx.test.filters.SmallTest
import com.android.systemui.R
import com.android.systemui.SysuiTestCase
import com.android.systemui.animation.Interpolators
import com.android.systemui.animation.ShadeInterpolation
import com.android.systemui.battery.BatteryMeterView
import com.android.systemui.battery.BatteryMeterViewController
import com.android.systemui.demomode.DemoMode
import com.android.systemui.demomode.DemoModeController
import com.android.systemui.dump.DumpManager
import com.android.systemui.flags.FeatureFlags
import com.android.systemui.flags.Flags
import com.android.systemui.qs.HeaderPrivacyIconsController
import com.android.systemui.qs.carrier.QSCarrierGroup
import com.android.systemui.qs.carrier.QSCarrierGroupController
import com.android.systemui.statusbar.phone.StatusBarContentInsetsProvider
import com.android.systemui.statusbar.phone.StatusBarIconController
import com.android.systemui.statusbar.phone.StatusIconContainer
import com.android.systemui.statusbar.policy.Clock
import com.android.systemui.statusbar.policy.FakeConfigurationController
import com.android.systemui.statusbar.policy.VariableDateViewController
import com.android.systemui.util.mockito.any
import com.android.systemui.util.mockito.argumentCaptor
import com.android.systemui.util.mockito.capture
import com.android.systemui.util.mockito.mock
import com.google.common.truth.Truth.assertThat
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Answers
import org.mockito.ArgumentMatchers.anyFloat
import org.mockito.ArgumentMatchers.anyInt
import org.mockito.Mock
import org.mockito.Mockito.mock
import org.mockito.Mockito.verify
import org.mockito.Mockito.verifyZeroInteractions
import org.mockito.Mockito.`when` as whenever
import org.mockito.junit.MockitoJUnit
@SmallTest
@RunWith(AndroidTestingRunner::class)
class LargeScreenShadeHeaderControllerTest : SysuiTestCase() {
@Mock private lateinit var view: View
@Mock private lateinit var statusIcons: StatusIconContainer
@Mock private lateinit var statusBarIconController: StatusBarIconController
@Mock private lateinit var iconManagerFactory: StatusBarIconController.TintedIconManager.Factory
@Mock private lateinit var iconManager: StatusBarIconController.TintedIconManager
@Mock private lateinit var qsCarrierGroupController: QSCarrierGroupController
@Mock private lateinit var qsCarrierGroupControllerBuilder: QSCarrierGroupController.Builder
@Mock private lateinit var featureFlags: FeatureFlags
@Mock private lateinit var clock: Clock
@Mock private lateinit var date: TextView
@Mock private lateinit var carrierGroup: QSCarrierGroup
@Mock private lateinit var batteryMeterView: BatteryMeterView
@Mock private lateinit var batteryMeterViewController: BatteryMeterViewController
@Mock private lateinit var privacyIconsController: HeaderPrivacyIconsController
@Mock private lateinit var insetsProvider: StatusBarContentInsetsProvider
@Mock private lateinit var variableDateViewControllerFactory: VariableDateViewController.Factory
@Mock private lateinit var variableDateViewController: VariableDateViewController
@Mock private lateinit var dumpManager: DumpManager
@Mock private lateinit var combinedShadeHeadersConstraintManager:
CombinedShadeHeadersConstraintManager
@Mock private lateinit var mockedContext: Context
@Mock private lateinit var demoModeController: DemoModeController
@JvmField @Rule val mockitoRule = MockitoJUnit.rule()
var viewVisibility = View.GONE
var viewAlpha = 1f
private lateinit var mLargeScreenShadeHeaderController: LargeScreenShadeHeaderController
private lateinit var carrierIconSlots: List<String>
private val configurationController = FakeConfigurationController()
@Before
fun setup() {
whenever<Clock>(view.findViewById(R.id.clock)).thenReturn(clock)
whenever(clock.context).thenReturn(mockedContext)
whenever<TextView>(view.findViewById(R.id.date)).thenReturn(date)
whenever(date.context).thenReturn(mockedContext)
whenever<QSCarrierGroup>(view.findViewById(R.id.carrier_group)).thenReturn(carrierGroup)
whenever<BatteryMeterView>(view.findViewById(R.id.batteryRemainingIcon))
.thenReturn(batteryMeterView)
whenever<StatusIconContainer>(view.findViewById(R.id.statusIcons)).thenReturn(statusIcons)
whenever(view.context).thenReturn(context)
whenever(view.resources).thenReturn(context.resources)
whenever(statusIcons.context).thenReturn(context)
whenever(qsCarrierGroupControllerBuilder.setQSCarrierGroup(any()))
.thenReturn(qsCarrierGroupControllerBuilder)
whenever(qsCarrierGroupControllerBuilder.build()).thenReturn(qsCarrierGroupController)
whenever(view.setVisibility(anyInt())).then {
viewVisibility = it.arguments[0] as Int
null
}
whenever(view.visibility).thenAnswer { _ -> viewVisibility }
whenever(view.setAlpha(anyFloat())).then {
viewAlpha = it.arguments[0] as Float
null
}
whenever(view.alpha).thenAnswer { _ -> viewAlpha }
whenever(variableDateViewControllerFactory.create(any()))
.thenReturn(variableDateViewController)
whenever(iconManagerFactory.create(any(), any())).thenReturn(iconManager)
whenever(featureFlags.isEnabled(Flags.COMBINED_QS_HEADERS)).thenReturn(false)
mLargeScreenShadeHeaderController = LargeScreenShadeHeaderController(
view,
statusBarIconController,
iconManagerFactory,
privacyIconsController,
insetsProvider,
configurationController,
variableDateViewControllerFactory,
batteryMeterViewController,
dumpManager,
featureFlags,
qsCarrierGroupControllerBuilder,
combinedShadeHeadersConstraintManager,
demoModeController
)
whenever(view.isAttachedToWindow).thenReturn(true)
mLargeScreenShadeHeaderController.init()
carrierIconSlots = listOf(
context.getString(com.android.internal.R.string.status_bar_mobile))
}
@After
fun verifyEveryTest() {
verifyZeroInteractions(combinedShadeHeadersConstraintManager)
}
@Test
fun setVisible_onlyWhenActive() {
makeShadeVisible()
assertThat(viewVisibility).isEqualTo(View.VISIBLE)
mLargeScreenShadeHeaderController.largeScreenActive = false
assertThat(viewVisibility).isEqualTo(View.GONE)
}
@Test
fun updateListeners_registersWhenVisible() {
makeShadeVisible()
verify(qsCarrierGroupController).setListening(true)
verify(statusBarIconController).addIconGroup(any())
}
@Test
fun shadeExpandedFraction_updatesAlpha() {
makeShadeVisible()
mLargeScreenShadeHeaderController.shadeExpandedFraction = 0.5f
verify(view).setAlpha(ShadeInterpolation.getContentAlpha(0.5f))
}
@Test
fun alphaChangesUpdateVisibility() {
makeShadeVisible()
mLargeScreenShadeHeaderController.shadeExpandedFraction = 0f
assertThat(viewVisibility).isEqualTo(View.INVISIBLE)
mLargeScreenShadeHeaderController.shadeExpandedFraction = 1f
assertThat(viewVisibility).isEqualTo(View.VISIBLE)
}
@Test
fun singleCarrier_enablesCarrierIconsInStatusIcons() {
whenever(qsCarrierGroupController.isSingleCarrier).thenReturn(true)
makeShadeVisible()
verify(statusIcons).removeIgnoredSlots(carrierIconSlots)
}
@Test
fun dualCarrier_disablesCarrierIconsInStatusIcons() {
whenever(qsCarrierGroupController.isSingleCarrier).thenReturn(false)
makeShadeVisible()
verify(statusIcons).addIgnoredSlots(carrierIconSlots)
}
@Test
fun disableQS_notDisabled_visible() {
makeShadeVisible()
mLargeScreenShadeHeaderController.disable(0, 0, false)
assertThat(viewVisibility).isEqualTo(View.VISIBLE)
}
@Test
fun disableQS_disabled_gone() {
makeShadeVisible()
mLargeScreenShadeHeaderController.disable(0, StatusBarManager.DISABLE2_QUICK_SETTINGS,
false)
assertThat(viewVisibility).isEqualTo(View.GONE)
}
private fun makeShadeVisible() {
mLargeScreenShadeHeaderController.largeScreenActive = true
mLargeScreenShadeHeaderController.qsVisible = true
}
@Test
fun updateConfig_changesFontStyle() {
configurationController.notifyDensityOrFontScaleChanged()
verify(clock).setTextAppearance(R.style.TextAppearance_QS_Status)
verify(date).setTextAppearance(R.style.TextAppearance_QS_Status)
verify(carrierGroup).updateTextAppearance(R.style.TextAppearance_QS_Status_Carriers)
}
@Test
fun alarmIconIgnored() {
verify(statusIcons).addIgnoredSlot(
context.getString(com.android.internal.R.string.status_bar_alarm_clock)
)
}
@Test
fun animateOutOnStartCustomizing() {
val animator = mock(ViewPropertyAnimator::class.java, Answers.RETURNS_SELF)
val duration = 1000L
whenever(view.animate()).thenReturn(animator)
mLargeScreenShadeHeaderController.startCustomizingAnimation(show = true, duration)
verify(animator).setDuration(duration)
verify(animator).alpha(0f)
verify(animator).setInterpolator(Interpolators.ALPHA_OUT)
verify(animator).start()
}
@Test
fun animateInOnEndCustomizing() {
val animator = mock(ViewPropertyAnimator::class.java, Answers.RETURNS_SELF)
val duration = 1000L
whenever(view.animate()).thenReturn(animator)
mLargeScreenShadeHeaderController.startCustomizingAnimation(show = false, duration)
verify(animator).setDuration(duration)
verify(animator).alpha(1f)
verify(animator).setInterpolator(Interpolators.ALPHA_IN)
verify(animator).start()
}
@Test
fun testShadeExpanded_true_alpha_zero_invisible() {
view.alpha = 0f
mLargeScreenShadeHeaderController.largeScreenActive = true
mLargeScreenShadeHeaderController.qsVisible = true
assertThat(viewVisibility).isEqualTo(View.INVISIBLE)
}
@Test
fun animatorCallsUpdateVisibilityOnUpdate() {
val animator = mock(ViewPropertyAnimator::class.java, Answers.RETURNS_SELF)
whenever(view.animate()).thenReturn(animator)
mLargeScreenShadeHeaderController.startCustomizingAnimation(show = false, 0L)
val updateCaptor = argumentCaptor<ValueAnimator.AnimatorUpdateListener>()
verify(animator).setUpdateListener(capture(updateCaptor))
mLargeScreenShadeHeaderController.largeScreenActive = true
mLargeScreenShadeHeaderController.qsVisible = true
view.alpha = 1f
updateCaptor.value.onAnimationUpdate(mock())
assertThat(viewVisibility).isEqualTo(View.VISIBLE)
view.alpha = 0f
updateCaptor.value.onAnimationUpdate(mock())
assertThat(viewVisibility).isEqualTo(View.INVISIBLE)
}
@Test
fun demoMode_attachDemoMode() {
val cb = argumentCaptor<DemoMode>()
verify(demoModeController).addCallback(capture(cb))
cb.value.onDemoModeStarted()
verify(clock).onDemoModeStarted()
}
@Test
fun demoMode_detachDemoMode() {
mLargeScreenShadeHeaderController.simulateViewDetached()
val cb = argumentCaptor<DemoMode>()
verify(demoModeController).removeCallback(capture(cb))
cb.value.onDemoModeFinished()
verify(clock).onDemoModeFinished()
}
}
| 0 | Java | 1 | 2 | e99201cd9b6a123b16c30cce427a2dc31bb2f501 | 12,196 | platform_frameworks_base | Apache License 2.0 |
core/src/main/java/com/star/wars/core/di/module/CoreErrorModule.kt | aldefy | 377,213,065 | false | {"Gradle": 11, "Java Properties": 2, "Shell": 1, "Ignore List": 8, "Batchfile": 1, "Markdown": 2, "INI": 6, "Proguard": 7, "XML": 91, "Kotlin": 158, "Java": 2, "JSON": 9} | package com.star.wars.core.di.module
import com.chuckerteam.chucker.api.ChuckerCollector
import com.star.wars.core.*
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
@Module
@InstallIn(SingletonComponent::class)
class CoreErrorModule {
@Provides
fun providerChuckerErrorCollector(collector: ChuckerCollector): ChuckerErrorCollectorImpl {
return ChuckerErrorCollectorImpl(collector)
}
@Provides
fun providerLogErrorCollector(): LogErrorCollectorImpl {
return LogErrorCollectorImpl()
}
@Provides
fun providerDebugErrorCollector(
chuckerErrorCollector: ChuckerErrorCollectorImpl,
logErrorCollector: LogErrorCollectorImpl,
): DebugErrorCollector {
return DebugErrorCollector(
chuckerErrorCollector,
logErrorCollector
)
}
@Provides
fun providerReleaseErrorCollector(
chuckerErrorCollector: ChuckerErrorCollectorImpl,
): ReleaseErrorCollector {
return ReleaseErrorCollector(
chuckerErrorCollector
)
}
@Provides
fun providerFeatureErrorCollector(
debugErrorCollector: DebugErrorCollector,
releaseErrorCollector: ReleaseErrorCollector
): FeatureErrorCollector {
return FeatureErrorCollector(
debugErrorCollector = debugErrorCollector,
releaseErrorCollector = releaseErrorCollector
)
}
}
| 1 | null | 1 | 1 | 581db6c4af7547f3adb960980bf9fa8d973b6962 | 1,495 | StarWarsApp | Apache License 2.0 |
src/main/java/de/fhg/ipa/ced/awx_jwt_authenticator/awx/model/CredentialTypeInputFieldItem.kt | FabOS-AI | 607,163,616 | false | {"Java": 40530, "Kotlin": 22036, "Shell": 2034, "Dockerfile": 912} | package de.fhg.ipa.ced.awx_jwt_authenticator.awx.model
data class CredentialTypeInputFieldItem(
val id: String,
val label: String,
val secret: Boolean,
val type: String
)
| 1 | null | 1 | 1 | 41d7dd5c63ced45fe62689e8c55a6bf69f60c5be | 188 | awx-jwt-authenticator | Apache License 2.0 |
editor/src/main/com/mbrlabs/mundus/editor/assets/FileHandleWithDependencies.kt | yuripourre-forks | 480,656,012 | false | {"INI": 1, "YAML": 2, "Gradle": 5, "Shell": 1, "XML": 2, "SVG": 1, "Markdown": 2, "Batchfile": 1, "Text": 1, "Ignore List": 1, "JSON": 2, "Java": 137, "Kotlin": 109, "GLSL": 8, "Wavefront Material": 2, "Wavefront Object": 1, "Java Properties": 1} | /*
* Copyright (c) 2021. See AUTHORS file.
*
* 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.mbrlabs.mundus.editor.assets
import com.badlogic.gdx.files.FileHandle
import com.badlogic.gdx.utils.Json
import com.mbrlabs.mundus.commons.utils.FileFormatUtils
import com.mbrlabs.mundus.editor.Mundus
import net.mgsx.gltf.data.GLTF
class FileHandleWithDependencies(val file: FileHandle, val dependencies: ArrayList<FileHandle> = ArrayList()) {
init {
if (FileFormatUtils.isGLTF(file)) {
loadGLTFDependencies()
}
}
fun exists(): Boolean = file.exists()
fun name(): String = file.name()
fun copyTo(dest: FileHandle) {
file.copyTo(dest);
dependencies.forEach { it.copyTo(dest) }
}
private fun loadGLTFDependencies() {
val json = Mundus.inject<Json>()
val dto = json.fromJson(GLTF::class.java, file)
dto.images?.forEach {
val depFile = FileHandle(file.parent().path() + '/' + it.uri)
if (depFile.exists()) {
dependencies.add(depFile)
}
}
dto.buffers.forEach {
val depFile = FileHandle(file.parent().path() + '/' + it.uri)
if (depFile.exists()) {
dependencies.add(depFile)
}
}
}
}
| 1 | null | 1 | 1 | 1cba8da346212dad2f185410c64a69e8f79d7a99 | 1,834 | Mundus | Apache License 2.0 |
migratedb-core/src/test/java/migratedb/v1/core/testing/MigrateDbDomain.kt | daniel-huss | 456,543,899 | false | {"Maven POM": 13, "Markdown": 1, "Text": 7, "Ignore List": 3, "Git Attributes": 1, "AsciiDoc": 3, "Kotlin": 140, "XML": 7, "Java": 473, "Gradle": 5, "Shell": 2, "Batchfile": 2, "INI": 1, "SQL": 1, "Groovy": 3, "Java Properties": 5, "YAML": 2} | /*
* Copyright 2022-2023 The MigrateDB contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package migratedb.v1.core.testing
import migratedb.v1.core.api.MigrationPattern
import migratedb.v1.core.api.TargetVersion
import migratedb.v1.core.api.configuration.DefaultConfiguration
import migratedb.v1.core.api.pattern.ValidatePattern
import net.jqwik.api.Arbitraries
import net.jqwik.api.Arbitrary
import net.jqwik.api.Combinators
import net.jqwik.api.Provide
import net.jqwik.api.domains.DomainContextBase
class MigrateDbDomain : DomainContextBase() {
@Provide
fun targetVersions(): Arbitrary<TargetVersion> = anyTargetVersion()
@Provide
fun migrationPatterns(): Arbitrary<MigrationPattern> = anyMigrationPattern()
@Provide
fun validatePatterns(): Arbitrary<ValidatePattern> = anyValidatePattern()
@Provide
fun configurations(): Arbitrary<DefaultConfiguration> {
return Arbitraries.subsetOf(ConfigSetters.all)
.edgeCases { it.add(ConfigSetters.all.toSet()) }
.flatMap { subsetOfSetters ->
Combinators.combine(subsetOfSetters.map { it.asAction }).`as` {
it.fold(DefaultConfiguration()) { config, setterAction ->
config.also {
if (setterAction.precondition(config)) {
setterAction.run(config)
}
}
}
}
}
}
}
| 0 | Java | 0 | 0 | 97ce486d14df4669846a53e5a046a9a87f77788d | 2,025 | migratedb | Apache License 2.0 |
clients/kotlin/generated/src/test/kotlin/org/openapitools/client/models/SSIOInsertionOrderCommonTest.kt | oapicf | 489,369,143 | false | {"Markdown": 13009, "YAML": 64, "Text": 6, "Ignore List": 43, "JSON": 688, "Makefile": 2, "JavaScript": 2261, "F#": 1305, "XML": 1120, "Shell": 44, "Batchfile": 10, "Scala": 4677, "INI": 23, "Dockerfile": 14, "Maven POM": 22, "Java": 13384, "Emacs Lisp": 1, "Haskell": 75, "Swift": 551, "Ruby": 1149, "Cabal Config": 2, "OASv3-yaml": 16, "Go": 2224, "Go Checksums": 1, "Go Module": 4, "CMake": 9, "C++": 6688, "TOML": 3, "Rust": 556, "Nim": 541, "Perl": 540, "Microsoft Visual Studio Solution": 2, "C#": 1645, "HTML": 545, "Xojo": 1083, "Gradle": 20, "R": 1079, "JSON with Comments": 8, "QMake": 1, "Kotlin": 3280, "Python": 1, "Crystal": 1060, "ApacheConf": 2, "PHP": 3940, "Gradle Kotlin DSL": 1, "Protocol Buffer": 538, "C": 1598, "Ada": 16, "Objective-C": 1098, "Java Properties": 2, "Erlang": 1097, "PlantUML": 1, "robots.txt": 1, "HTML+ERB": 2, "Lua": 1077, "SQL": 512, "AsciiDoc": 1, "CSS": 3, "PowerShell": 1083, "Elixir": 5, "Apex": 1054, "Visual Basic 6.0": 3, "TeX": 1, "ObjectScript": 1, "OpenEdge ABL": 1, "Option List": 2, "Eiffel": 583, "Gherkin": 1, "Dart": 538, "Groovy": 539, "Elm": 31} | /**
*
* Please note:
* This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* Do not edit this file manually.
*
*/
@file:Suppress(
"ArrayInDataClass",
"EnumEntryName",
"RemoveRedundantQualifierName",
"UnusedImport"
)
package org.openapitools.client.models
import io.kotlintest.shouldBe
import io.kotlintest.specs.ShouldSpec
import org.openapitools.client.models.SSIOInsertionOrderCommon
class SSIOInsertionOrderCommonTest : ShouldSpec() {
init {
// uncomment below to create an instance of SSIOInsertionOrderCommon
//val modelInstance = SSIOInsertionOrderCommon()
// to test the property `startDate` - Starting date of time period. Format: YYYY-MM-DD
should("test startDate") {
// uncomment below to test the property
//modelInstance.startDate shouldBe ("TODO")
}
// to test the property `endDate` - End date of time period. Format: YYYY-MM-DD
should("test endDate") {
// uncomment below to test the property
//modelInstance.endDate shouldBe ("TODO")
}
// to test the property `poNumber` - The po number
should("test poNumber") {
// uncomment below to test the property
//modelInstance.poNumber shouldBe ("TODO")
}
// to test the property `budgetAmount` - If Budget order line, the budget amount.
should("test budgetAmount") {
// uncomment below to test the property
//modelInstance.budgetAmount shouldBe ("TODO")
}
// to test the property `billingContactFirstname` - The billing contact first name
should("test billingContactFirstname") {
// uncomment below to test the property
//modelInstance.billingContactFirstname shouldBe ("TODO")
}
// to test the property `billingContactLastname` - The billing contact last name
should("test billingContactLastname") {
// uncomment below to test the property
//modelInstance.billingContactLastname shouldBe ("TODO")
}
// to test the property `billingContactEmail` - The billing contact email
should("test billingContactEmail") {
// uncomment below to test the property
//modelInstance.billingContactEmail shouldBe ("TODO")
}
// to test the property `mediaContactFirstname` - The media contact first name
should("test mediaContactFirstname") {
// uncomment below to test the property
//modelInstance.mediaContactFirstname shouldBe ("TODO")
}
// to test the property `mediaContactLastname` - The media contact last name
should("test mediaContactLastname") {
// uncomment below to test the property
//modelInstance.mediaContactLastname shouldBe ("TODO")
}
// to test the property `mediaContactEmail` - The media contact email
should("test mediaContactEmail") {
// uncomment below to test the property
//modelInstance.mediaContactEmail shouldBe ("TODO")
}
// to test the property `agencyLink` - URL link for agency
should("test agencyLink") {
// uncomment below to test the property
//modelInstance.agencyLink shouldBe ("TODO")
}
// to test the property `userEmail` - The email of user submitting the insertion order
should("test userEmail") {
// uncomment below to test the property
//modelInstance.userEmail shouldBe ("TODO")
}
}
}
| 0 | Java | 0 | 2 | dcd328f1e62119774fd8ddbb6e4bad6d7878e898 | 3,643 | pinterest-sdk | MIT License |
android-sdk/src/main/java/com/checkout/android_sdk/logging/FramesLoggingEventDataProvider.kt | isabella232 | 531,123,745 | true | {"Java Properties": 6, "YAML": 2, "Gradle": 12, "Shell": 3, "XML": 96, "Markdown": 10, "Batchfile": 3, "Text": 2, "Ignore List": 8, "CODEOWNERS": 1, "Proguard": 5, "Java": 42, "Kotlin": 80, "HTML": 649, "CSS": 11, "SVG": 8, "JavaScript": 17, "JSON": 1, "INI": 1} | package com.checkout.android_sdk.logging
import com.checkout.android_sdk.Utils.CheckoutTheme
import com.checkout.android_sdk.Utils.Environment
import com.checkout.android_sdk.Utils.filterNotNullValues
import com.checkout.eventlogger.domain.model.MonitoringLevel
import java.util.Locale
object FramesLoggingEventDataProvider {
internal fun logPaymentFormPresentedEvent(checkoutTheme: CheckoutTheme): FramesLoggingEvent {
val eventData = mapOf(
PaymentFormLanguageEventAttribute.locale to Locale.getDefault().toString(),
PaymentFormLanguageEventAttribute.theme to mapOf(
PaymentFormLanguageEventAttribute.colorPrimary to checkoutTheme.getColorPrimaryProperty(),
PaymentFormLanguageEventAttribute.colorAccent to checkoutTheme.getColorAccentProperty(),
PaymentFormLanguageEventAttribute.colorButtonNormal to checkoutTheme.getColorButtonNormalProperty(),
PaymentFormLanguageEventAttribute.colorControlNormal to checkoutTheme.getColorControlNormalProperty(),
PaymentFormLanguageEventAttribute.textColorPrimary to checkoutTheme.getTextColorPrimaryProperty(),
PaymentFormLanguageEventAttribute.colorControlActivated to checkoutTheme.getColorControlActivatedProperty())
)
return FramesLoggingEvent(
MonitoringLevel.INFO,
FramesLoggingEventType.PAYMENT_FORM_PRESENTED,
eventData.filterNotNullValues()
)
}
fun logCheckoutApiClientInitialisedEvent(environment: Environment): FramesLoggingEvent {
val eventData = mapOf(
CheckoutApiClientInitEventAttribute.environment to environment
)
return FramesLoggingEvent(
MonitoringLevel.INFO,
FramesLoggingEventType.CHECKOUT_API_CLIENT_INITIALISED,
eventData
)
}
fun logThreedsWebviewLoadedEvent(
success: Boolean,
): FramesLoggingEvent {
val eventData = mapOf(
WebviewEventAttribute.success to success,
)
return FramesLoggingEvent(
if (success) MonitoringLevel.INFO else MonitoringLevel.ERROR,
FramesLoggingEventType.THREEDS_WEBVIEW_LOADED,
eventData
)
}
fun logThreedsWebviewCompleteEvent(
tokenID: String?,
success: Boolean,
): FramesLoggingEvent {
val tokenId = tokenID ?: ""
val eventData = mapOf(
WebviewEventAttribute.tokenID to tokenId,
WebviewEventAttribute.success to success,
)
return FramesLoggingEvent(
if (success) MonitoringLevel.INFO else MonitoringLevel.ERROR,
FramesLoggingEventType.THREEDS_WEBVIEW_COMPLETE,
eventData
)
}
fun logThreedsWebviewPresentedEvent(
): FramesLoggingEvent {
return FramesLoggingEvent(
MonitoringLevel.INFO,
FramesLoggingEventType.THREEDS_WEBVIEW_PRESENTED
)
}
} | 0 | null | 0 | 0 | a5ac618b820129435bd05b9a701485a7e7defc3e | 3,006 | frames-android | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.