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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
kotlin-mui-icons/src/main/generated/mui/icons/material/PhotoLibraryRounded.kt
|
JetBrains
| 93,250,841
| false
| null |
// Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/PhotoLibraryRounded")
@file:JsNonModule
package mui.icons.material
@JsName("default")
external val PhotoLibraryRounded: SvgIconComponent
| 12
|
Kotlin
|
145
| 983
|
a99345a0160a80a7a90bf1adfbfdc83a31a18dd6
| 220
|
kotlin-wrappers
|
Apache License 2.0
|
src/main/kotlin/ogl_samples/tests/gl320/gl-320-caps.kt
|
jvm-graphics-labs
| 87,515,851
| false
|
{"GLSL": 367659, "Kotlin": 152172}
|
package ogl_samples.tests.gl320
import glm_.L
import ogl_samples.framework.TestA
import uno.caps.Caps
import uno.gln.glClearColorBuffer
import uno.gln.glViewport
fun main(args: Array<String>) {
gl_320_caps().loop()
}
private class gl_320_caps : TestA("es-320-caps", Caps.Profile.CORE, 3, 2) {
override fun begin(): Boolean {
var validated = true
validated = validated && caps.limits.MAX_VERTEX_UNIFORM_BLOCKS >= 12
validated = validated && caps.limits.MAX_GEOMETRY_UNIFORM_BLOCKS >= 12
validated = validated && caps.limits.MAX_FRAGMENT_UNIFORM_BLOCKS >= 12
validated = validated && caps.limits.MAX_VERTEX_UNIFORM_COMPONENTS >= 1024
validated = validated && caps.limits.MAX_GEOMETRY_UNIFORM_COMPONENTS >= 1024
validated = validated && caps.limits.MAX_FRAGMENT_UNIFORM_COMPONENTS >= 1024
validated = validated && caps.limits.MAX_COMBINED_UNIFORM_BLOCKS >= 36
validated = validated && caps.limits.MAX_UNIFORM_BUFFER_BINDINGS >= 36
validated = validated && caps.limits.MAX_UNIFORM_BLOCK_SIZE >= 16384
val combinedVertUniformCount = caps.limits.MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS.L
val combinedGeomUniformCount = caps.limits.MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS.L
val combinedFragUniformCount = caps.limits.MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS.L
val vertUniformCount = caps.limits.MAX_VERTEX_UNIFORM_BLOCKS.L * caps.limits.MAX_UNIFORM_BLOCK_SIZE.L / 4 +
caps.limits.MAX_VERTEX_UNIFORM_COMPONENTS.L
val geomUniformCount = caps.limits.MAX_GEOMETRY_UNIFORM_BLOCKS.L * caps.limits.MAX_UNIFORM_BLOCK_SIZE.L / 4 +
caps.limits.MAX_GEOMETRY_UNIFORM_COMPONENTS.L
val fragUniformCount = caps.limits.MAX_FRAGMENT_UNIFORM_BLOCKS.L * caps.limits.MAX_UNIFORM_BLOCK_SIZE.L / 4 +
caps.limits.MAX_FRAGMENT_UNIFORM_COMPONENTS.L
println("combinedVertUniformCount: $combinedVertUniformCount")
println("combinedGeomUniformCount: $combinedGeomUniformCount")
println("combinedFragUniformCount: $combinedFragUniformCount")
println("vertUniformCount: $vertUniformCount")
println("geomUniformCount: $geomUniformCount")
println("fragUniformCount: $fragUniformCount")
validated = validated && combinedVertUniformCount <= vertUniformCount
validated = validated && combinedGeomUniformCount <= geomUniformCount
validated = validated && combinedFragUniformCount <= fragUniformCount
return validated
}
override fun render(): Boolean {
glViewport(windowSize)
glClearColorBuffer(1f, 0.5f, 0f, 1f)
return true
}
}
| 0
|
GLSL
|
1
| 0
|
d028e032d6b35f2661a39e8ecf0192d6fcb26a9e
| 2,702
|
ogl-samples
|
MIT License
|
naveditor/testSrc/com/android/tools/idea/naveditor/scene/draw/TestDrawNavScreen.kt
|
zakharchanka
| 314,699,321
| true
|
{"Java": 39917608, "Kotlin": 17687377, "HTML": 1204348, "Starlark": 501007, "C": 62588, "NSIS": 58512, "Lex": 50354, "JavaScript": 18437, "CMake": 17952, "Shell": 8736, "Smali": 7580, "RenderScript": 4411, "C++": 4407, "Python": 2727, "Makefile": 2290, "FreeMarker": 247, "Prolog": 231}
|
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.naveditor.scene.draw
import com.android.tools.adtui.common.SwingRectangle
import com.android.tools.idea.common.scene.SceneContext
import com.android.tools.idea.naveditor.scene.NavColors.PLACEHOLDER_BACKGROUND
import com.android.tools.idea.naveditor.scene.NavColors.PLACEHOLDER_TEXT
import com.android.tools.idea.naveditor.scene.RefinableImage
import org.junit.Test
import org.mockito.Mockito.`when`
import org.mockito.Mockito.anyFloat
import org.mockito.Mockito.eq
import org.mockito.Mockito.mock
import org.mockito.Mockito.verify
import java.awt.Dimension
import java.awt.FontMetrics
import java.awt.Graphics2D
import java.awt.geom.Rectangle2D
import java.awt.image.BufferedImage
import java.util.concurrent.CompletableFuture
var IMAGE_DIMENSION = Dimension(5, 5)
var DRAW_COMMAND_RECTANGLE = SwingRectangle(Rectangle2D.Float(1f, 2f, 3f, 4f))
class TestDrawNavScreen {
@Test
fun testPaint() {
var graphics = createGraphics()
val context = mock(SceneContext::class.java)
var drawCommand = DrawNavScreen(createRectangle(), RefinableImage())
drawCommand.paint(graphics, context)
verify(graphics).setColor(eq(PLACEHOLDER_BACKGROUND))
verify(graphics).setColor(eq(PLACEHOLDER_TEXT))
verify(graphics).drawString(eq("Preview"), anyFloat(), anyFloat())
verify(graphics).drawString(eq("Unavailable"), anyFloat(), anyFloat())
graphics = createGraphics()
drawCommand = DrawNavScreen(createRectangle(), RefinableImage(null, CompletableFuture()))
drawCommand.paint(graphics, context)
verify(graphics).setColor(eq(PLACEHOLDER_BACKGROUND))
verify(graphics).setColor(eq(PLACEHOLDER_TEXT))
verify(graphics).drawString(eq("Loading..."), anyFloat(), anyFloat())
graphics = createGraphics()
val image = createImage()
drawCommand = DrawNavScreen(createRectangle(), RefinableImage(null, CompletableFuture.completedFuture(RefinableImage(image))))
drawCommand.paint(graphics, context)
verify(graphics).drawImage(image, 1, 2, 0, 0, null)
graphics = createGraphics()
val oldImage = createImage()
drawCommand = DrawNavScreen(createRectangle(), RefinableImage(oldImage, CompletableFuture.completedFuture(RefinableImage(image))))
drawCommand.paint(graphics, context)
verify(graphics).drawImage(image, 1, 2, 0, 0, null)
graphics = createGraphics()
drawCommand = DrawNavScreen(createRectangle(), RefinableImage(oldImage, CompletableFuture()))
drawCommand.paint(graphics, context)
verify(graphics).drawImage(oldImage, 1, 2, 0, 0, null)
}
private fun createGraphics(): Graphics2D {
val graphics = mock(Graphics2D::class.java)
`when`(graphics.create()).thenReturn(graphics)
val metrics = mock(FontMetrics::class.java)
`when`(graphics.fontMetrics).thenReturn(metrics)
return graphics
}
private fun createRectangle() : SwingRectangle {
return SwingRectangle(DRAW_COMMAND_RECTANGLE.x, DRAW_COMMAND_RECTANGLE.y,
DRAW_COMMAND_RECTANGLE.width, DRAW_COMMAND_RECTANGLE.height)
}
private fun createImage() : BufferedImage {
val image = mock(BufferedImage::class.java)
`when`(image.width).thenReturn(IMAGE_DIMENSION.width)
`when`(image.height).thenReturn(IMAGE_DIMENSION.height)
return image
}
}
| 0
| null |
0
| 0
|
cd393da1a11d2dfe572f4baa6eef882256e95d6a
| 3,923
|
android-1
|
Apache License 2.0
|
app/src/test/kotlin/com/example/valorantandroid/agent/ui/viewmodel/AgentDetailsViewModelTest.kt
|
jamesdpli
| 680,617,148
| false
|
{"Kotlin": 57532}
|
package com.example.valorantandroid.agent.ui.viewmodel
import androidx.lifecycle.SavedStateHandle
import com.example.valorantandroid.core.utils.constants.Constants
import com.example.valorantandroid.utils.MainDispatcherRule
import com.example.valorantandroid.utils.TestUtils
import com.example.valorantandroid.utils.fake.FakeAgentsRepository
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
@OptIn(ExperimentalCoroutinesApi::class)
class AgentDetailsViewModelTest {
@get:Rule
val mainDispatcherRule = MainDispatcherRule()
private val savedStateHandle = SavedStateHandle(
mapOf(Constants.AGENT_UUID to TestUtils.fakeDomainAgentOne.uuid)
)
private val fakeAgentsRepository = FakeAgentsRepository()
private val agentDetailsViewModel by lazy {
AgentDetailsViewModel(
savedStateHandle = savedStateHandle,
repository = fakeAgentsRepository
)
}
@Test
fun `WHEN viewModel init THEN expect first state to be Loading`() = runTest {
val values = mutableListOf<AgentDetailsUiState>()
backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) {
agentDetailsViewModel.agentDetailsUiState.toList(values)
}
assertEquals(
AgentDetailsUiState.Loading,
values.first()
)
}
@Test
fun `GIVEN no api errorWHEN viewModel init THEN expect last state to be Success with agent`() =
runTest {
val values = mutableListOf<AgentDetailsUiState>()
backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) {
agentDetailsViewModel.agentDetailsUiState.toList(values)
}
assertEquals(
AgentDetailsUiState.Success(agent = TestUtils.fakeDomainAgentDetailOne),
values.last()
)
}
@Test
fun `GIVEN an api error WHEN viewModel init Then assert last state is Error with message`() =
runTest {
fakeAgentsRepository.setIsApiErrorTrue()
val values = mutableListOf<AgentDetailsUiState>()
backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) {
agentDetailsViewModel.agentDetailsUiState.toList(values)
}
assertEquals(
AgentDetailsUiState.Error(message = FakeAgentsRepository.EXCEPTION),
values.last()
)
}
}
| 0
|
Kotlin
|
0
| 0
|
9015c2b1ee9b324bfb5b9f60b1d7562e12797b81
| 2,681
|
ValorantAndroid
|
Apache License 2.0
|
app/src/main/java/com/example/takeofflabstinder/profiles/ProfilesViewModel.kt
|
MarcBrout
| 410,886,256
| false
|
{"Kotlin": 19018}
|
package com.example.takeofflabstinder.profiles
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.takeofflabstinder.data.datasource.local.LocalDataSource
import com.example.takeofflabstinder.data.datasource.local.ProfileEntity
import com.example.takeofflabstinder.data.repository.ProfilesRepository
import kotlinx.coroutines.launch
class ProfilesViewModel : ViewModel() {
// refactor to real repository using DI such as Hilt or Koin
private val repository = ProfilesRepository(LocalDataSource())
private val _profiles = MutableLiveData<List<ProfileEntity>>()
val profiles: LiveData<List<ProfileEntity>>
get() = _profiles
private val _matchCount = MutableLiveData<Int>()
val matchCount: LiveData<Int>
get() = _matchCount
private var index = 0
fun getProfiles() {
viewModelScope.launch {
val resource = repository.getProfiles()
_profiles.postValue(resource)
_matchCount.postValue(resource.count { it.isMatch })
}
}
fun like() {
_profiles.value?.let {
it[index].isMatch = true
_matchCount.postValue(it.count { profile -> profile.isMatch })
index++
}
}
fun dislike() {
_profiles.value?.let {
it[index].isMatch = false
_matchCount.postValue(it.count { profile -> profile.isMatch })
index++
}
}
}
| 0
|
Kotlin
|
0
| 0
|
09e364661a5d873572bdc7117fab626bc9bdb207
| 1,544
|
takeoff_lab_tinder_copycat
|
Apache License 2.0
|
storiesview/src/main/java/com/adalpari/storiesview/view/StoriesView.kt
|
adalpari
| 306,628,815
| false
|
{"Kotlin": 19807}
|
package com.adalpari.storiesview.view
import android.app.Activity
import android.content.Context
import android.util.AttributeSet
import android.widget.LinearLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.adalpari.storiesview.R
import com.adalpari.storiesview.adapter.ThumbnailsAdapter
import com.adalpari.storiesview.model.StoriesSet
class StoriesView(context: Context, attrs: AttributeSet) : LinearLayout(context, attrs) {
init {
inflate(context, R.layout.view_stories, this)
}
fun showStories(entries: List<StoriesSet>, activity: Activity) {
val recyclerView: RecyclerView = findViewById(R.id.thumbnails_recycler_view)
val adapter = ThumbnailsAdapter(entries, activity)
recyclerView.layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
recyclerView.setHasFixedSize(true)
recyclerView.adapter = adapter
}
}
| 0
|
Kotlin
|
4
| 2
|
b83e11eb08549c3e3d940cd412b8311592be2f71
| 984
|
stories-MVVM-Coroutines-example
|
Apache License 2.0
|
app/src/androidTest/java/com/example/android/architecture/blueprints/todoapp/test/espresso/example/tests/BaseTest.kt
|
jakubcekala
| 332,780,090
| false
| null |
package com.example.android.architecture.blueprints.todoapp.test.espresso.example.tests
import android.Manifest
import android.support.test.rule.ActivityTestRule
import android.support.test.rule.GrantPermissionRule
import android.support.test.runner.AndroidJUnit4
import com.example.android.architecture.blueprints.todoapp.tasks.TasksActivity
import org.junit.Rule
import org.junit.rules.RuleChain
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
open class BaseTest {
@get:Rule
var activityTestRule = ActivityTestRule(TasksActivity::class.java)
@get:Rule
var ruleChain: RuleChain = RuleChain
.outerRule(GrantPermissionRule.grant(
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.CAMERA))
}
| 1
| null |
1
| 1
|
ff41c65223797875371707e492739b9ebbaccdee
| 855
|
espresso-example-todoapp
|
Apache License 2.0
|
src/main/kotlin/eu/fizzystuff/krog/scenes/visibility/RaycastingVisibilityStrategy.kt
|
noseblowhorn
| 53,980,499
| false
| null |
package eu.fizzystuff.krog.scenes.visibility
import eu.fizzystuff.krog.model.DungeonLevel
/**
* Hey, let's be sloppy and inefficient! Here, we can calculate a path between the origin point and each and every
* tile at the edges of the level. And see if something sticks between.
*/
class RaycastingVisibilityStrategy : VisibilityStrategy {
override fun calculateVisibility(dungeonLevel: DungeonLevel, originX: Int, originY: Int, maxDistance: Int): Array<Array<Boolean>> {
val edgePointSet = buildEdgePointSet(dungeonLevel)
val visible = Array(dungeonLevel.width, {i -> Array(dungeonLevel.height, {j -> false}) })
visible[originX][originY] = true
for (edgePoint in edgePointSet) {
var radius = 0.0;
val angle = Math.atan2((edgePoint.second - originY).toDouble(), (edgePoint.first - originX).toDouble())
do {
radius += 1.0
val x = (radius * Math.cos(angle)).toInt() + originX
val y = (radius * Math.sin(angle)).toInt() + originY
if (!pointWithinBounds(dungeonLevel, x, y)) {
break
}
val tile = dungeonLevel.getTileAt(x, y)
if (tile.translucent) {
visible[x][y] = true
} else {
// mark this tile as seen and bail - we can't see anything beyond it
visible[x][y] = true
break
}
} while (radius.toInt() <= maxDistance)
}
return visible
}
private fun pointWithinBounds(dungeonLevel: DungeonLevel, x: Int, y: Int): Boolean {
return x >= 0 && y >= 0 && x < dungeonLevel.width && y < dungeonLevel.height
}
private fun buildEdgePointSet(dungeonLevel: DungeonLevel): Set<Pair<Int, Int>> =
setOf((0..dungeonLevel.width - 1).map({x -> Pair(x, 0)}),
(0..dungeonLevel.width - 1).map({x -> Pair(x, dungeonLevel.height - 1)}),
(0..dungeonLevel.height - 1).map({x -> Pair(0, x)}),
(0..dungeonLevel.height - 1).map({x -> Pair(dungeonLevel.width - 1, x)}))
.flatten().toSet()
}
| 9
|
Kotlin
|
0
| 0
|
07bd6389b0bb20a60a5ab2e4cc7f31b8c867949c
| 2,194
|
krog
|
Apache License 2.0
|
harness/tests/src/main/kotlin/godot/tests/inheritance/ClassInheritanceParent.kt
|
utopia-rise
| 289,462,532
| false
| null |
package godot.tests.inheritance
import godot.Node
import godot.annotation.RegisterClass
import godot.annotation.RegisterFunction
import godot.annotation.RegisterProperty
import godot.annotation.RegisterSignal
import godot.core.GodotNotification
import godot.global.GD
import godot.signals.signal
@RegisterClass
open class ClassInheritanceParent : Node() {
@RegisterSignal
val testNotOverridden by signal<String>("blubb")
@RegisterSignal
open val testOverridden by signal<String, Int>("blubb", "habbalubb")
//---------------- Here to check ------------------
@RegisterProperty
var closedFunctionHasBeenCalled = false
@RegisterProperty
var parentOpenFunctionHasBeenCalled = false
//-------------------------------------------------
@RegisterProperty
var closedVar = 0
@RegisterProperty
open var openVar = 0
@RegisterFunction
fun closedFunction() {
closedFunctionHasBeenCalled = true
}
@RegisterFunction
open fun openFunction() {
parentOpenFunctionHasBeenCalled = true
}
@RegisterProperty
var notificationCallBitFlag = 0
@RegisterFunction
override fun _notification(): GodotNotification = godotNotification {
GD.print("Called ClassInheritanceParent::_notification on $this with $it")
notificationCallBitFlag = notificationCallBitFlag or 1
GD.print(notificationCallBitFlag)
}
}
| 63
| null |
44
| 634
|
ac2a1bd5ea931725e2ed19eb5093dea171962e3f
| 1,428
|
godot-kotlin-jvm
|
MIT License
|
commerce-services-sample/src/main/java/com/godaddy/commerce/services/sample/catalog/product/ProductFragment.kt
|
poynt
| 26,389,506
| false
|
{"Gradle": 9, "Java Properties": 2, "Shell": 1, "Text": 4, "Ignore List": 8, "Batchfile": 1, "XML": 129, "Markdown": 1, "TOML": 1, "Proguard": 6, "Java": 48, "Kotlin": 70, "INI": 1}
|
package com.godaddy.commerce.services.sample.catalog.product
import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import com.godaddy.commerce.services.sample.R
import com.godaddy.commerce.services.sample.common.extensions.bindTo
import com.godaddy.commerce.services.sample.common.extensions.launch
import com.godaddy.commerce.services.sample.common.view.CommonFragment
import com.godaddy.commerce.services.sample.common.view.bindOnCommonViewModelUpdates
import com.godaddy.commerce.services.sample.common.view.doOnToolbarSearchQueryChanged
import com.godaddy.commerce.services.sample.databinding.ProductFragmentBinding
import timber.log.Timber
class ProductFragment : CommonFragment<ProductFragmentBinding>(R.layout.product_fragment) {
private val viewModel: ProductViewModel by viewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
bindOnCommonViewModelUpdates(viewModel)
doOnToolbarSearchQueryChanged { viewModel.searchProduct(it) }
launch {
viewModel.stateFlow.bindTo({
Timber.d("Items : $items")
items
}) { dataBinding.items = it }
}
}
}
| 6
|
Java
|
43
| 17
|
dc4d5f02a15673667cce596a268401ae8f13a9a6
| 1,266
|
PoyntSamples
|
MIT License
|
src/main/kotlin/com/amazon/opendistroforelasticsearch/indexstatemanagement/resthandler/RestIndexPolicyAction.kt
|
qreshi
| 266,040,612
| true
|
{"Kotlin": 751808}
|
/*
* Copyright 2019 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://www.apache.org/licenses/LICENSE-2.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 com.amazon.opendistroforelasticsearch.indexstatemanagement.resthandler
import com.amazon.opendistroforelasticsearch.indexstatemanagement.IndexStateManagementIndices
import com.amazon.opendistroforelasticsearch.indexstatemanagement.IndexStateManagementPlugin.Companion.INDEX_STATE_MANAGEMENT_INDEX
import com.amazon.opendistroforelasticsearch.indexstatemanagement.IndexStateManagementPlugin.Companion.POLICY_BASE_URI
import com.amazon.opendistroforelasticsearch.indexstatemanagement.model.Policy
import com.amazon.opendistroforelasticsearch.indexstatemanagement.model.Policy.Companion.POLICY_TYPE
import com.amazon.opendistroforelasticsearch.indexstatemanagement.settings.ManagedIndexSettings.Companion.ALLOW_LIST
import com.amazon.opendistroforelasticsearch.indexstatemanagement.util.IF_PRIMARY_TERM
import com.amazon.opendistroforelasticsearch.indexstatemanagement.util.IF_SEQ_NO
import com.amazon.opendistroforelasticsearch.indexstatemanagement.util.REFRESH
import com.amazon.opendistroforelasticsearch.indexstatemanagement.util._ID
import com.amazon.opendistroforelasticsearch.indexstatemanagement.util._PRIMARY_TERM
import com.amazon.opendistroforelasticsearch.indexstatemanagement.util._SEQ_NO
import com.amazon.opendistroforelasticsearch.indexstatemanagement.util._VERSION
import com.amazon.opendistroforelasticsearch.indexstatemanagement.util.getDisallowedActions
import org.apache.logging.log4j.LogManager
import org.elasticsearch.action.ActionListener
import org.elasticsearch.action.DocWriteRequest
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse
import org.elasticsearch.action.index.IndexRequest
import org.elasticsearch.action.index.IndexResponse
import org.elasticsearch.action.support.WriteRequest
import org.elasticsearch.client.node.NodeClient
import org.elasticsearch.cluster.service.ClusterService
import org.elasticsearch.common.settings.Settings
import org.elasticsearch.common.xcontent.ToXContent
import org.elasticsearch.index.seqno.SequenceNumbers
import org.elasticsearch.rest.BaseRestHandler
import org.elasticsearch.rest.BaseRestHandler.RestChannelConsumer
import org.elasticsearch.rest.BytesRestResponse
import org.elasticsearch.rest.RestChannel
import org.elasticsearch.rest.RestController
import org.elasticsearch.rest.RestRequest
import org.elasticsearch.rest.RestRequest.Method.PUT
import org.elasticsearch.rest.RestResponse
import org.elasticsearch.rest.RestStatus
import org.elasticsearch.rest.action.RestResponseListener
import java.io.IOException
import java.time.Instant
class RestIndexPolicyAction(
settings: Settings,
controller: RestController,
val clusterService: ClusterService,
indexStateManagementIndices: IndexStateManagementIndices
) : BaseRestHandler(settings) {
private val log = LogManager.getLogger(javaClass)
private var ismIndices = indexStateManagementIndices
@Volatile private var allowList = ALLOW_LIST.get(settings)
init {
clusterService.clusterSettings.addSettingsUpdateConsumer(ALLOW_LIST) { allowList = it }
controller.registerHandler(PUT, POLICY_BASE_URI, this)
controller.registerHandler(PUT, "$POLICY_BASE_URI/{policyID}", this)
}
override fun getName(): String {
return "index_policy_action"
}
@Throws(IOException::class)
override fun prepareRequest(request: RestRequest, client: NodeClient): RestChannelConsumer {
val id = request.param("policyID", Policy.NO_ID)
if (Policy.NO_ID == id) {
throw IllegalArgumentException("Missing policy ID")
}
val xcp = request.contentParser()
val policy = Policy.parseWithType(xcp = xcp, id = id).copy(lastUpdatedTime = Instant.now())
val seqNo = request.paramAsLong(IF_SEQ_NO, SequenceNumbers.UNASSIGNED_SEQ_NO)
val primaryTerm = request.paramAsLong(IF_PRIMARY_TERM, SequenceNumbers.UNASSIGNED_PRIMARY_TERM)
val refreshPolicy = if (request.hasParam(REFRESH)) {
WriteRequest.RefreshPolicy.parse(request.param(REFRESH))
} else {
WriteRequest.RefreshPolicy.IMMEDIATE
}
val disallowedActions = policy.getDisallowedActions(allowList)
if (disallowedActions.isNotEmpty()) {
return RestChannelConsumer { channel ->
channel.sendResponse(
BytesRestResponse(
RestStatus.FORBIDDEN,
"You have actions that are not allowed in your policy $disallowedActions"
)
)
}
}
return RestChannelConsumer { channel ->
IndexPolicyHandler(client, channel, id, seqNo, primaryTerm, refreshPolicy, policy).start()
}
}
inner class IndexPolicyHandler(
client: NodeClient,
channel: RestChannel,
private val policyId: String,
private val seqNo: Long,
private val primaryTerm: Long,
private val refreshPolicy: WriteRequest.RefreshPolicy,
private var newPolicy: Policy
) : AsyncActionHandler(client, channel) {
fun start() {
if (!ismIndices.indexStateManagementIndexExists()) {
ismIndices.initIndexStateManagementIndex(ActionListener.wrap(::onCreateMappingsResponse, ::onFailure))
} else {
putPolicy()
}
}
private fun onCreateMappingsResponse(response: CreateIndexResponse) {
if (response.isAcknowledged) {
log.info("Created $INDEX_STATE_MANAGEMENT_INDEX with mappings.")
putPolicy()
} else {
log.error("Create $INDEX_STATE_MANAGEMENT_INDEX mappings call not acknowledged.")
channel.sendResponse(
BytesRestResponse(
RestStatus.INTERNAL_SERVER_ERROR,
response.toXContent(channel.newErrorBuilder(), ToXContent.EMPTY_PARAMS))
)
}
}
private fun putPolicy() {
val indexRequest = IndexRequest(INDEX_STATE_MANAGEMENT_INDEX)
.setRefreshPolicy(refreshPolicy)
.source(newPolicy.toXContent(channel.newBuilder()))
.id(policyId)
.timeout(IndexRequest.DEFAULT_TIMEOUT)
if (seqNo == SequenceNumbers.UNASSIGNED_SEQ_NO || primaryTerm == SequenceNumbers.UNASSIGNED_PRIMARY_TERM) {
indexRequest.opType(DocWriteRequest.OpType.CREATE)
} else {
indexRequest.setIfSeqNo(seqNo)
.setIfPrimaryTerm(primaryTerm)
}
client.index(indexRequest, indexPolicyResponse())
}
private fun indexPolicyResponse(): RestResponseListener<IndexResponse> {
return object : RestResponseListener<IndexResponse>(channel) {
@Throws(Exception::class)
override fun buildResponse(response: IndexResponse): RestResponse {
if (response.shardInfo.successful < 1) {
return BytesRestResponse(response.status(), response.toXContent(channel.newErrorBuilder(),
ToXContent.EMPTY_PARAMS))
}
val builder = channel.newBuilder()
.startObject()
.field(_ID, response.id)
.field(_VERSION, response.version)
.field(_PRIMARY_TERM, response.primaryTerm)
.field(_SEQ_NO, response.seqNo)
.field(POLICY_TYPE, newPolicy)
.endObject()
val restResponse = BytesRestResponse(response.status(), builder)
if (response.status() == RestStatus.CREATED) {
val location = "$POLICY_BASE_URI/${response.id}"
restResponse.addHeader("Location", location)
}
return restResponse
}
}
}
}
}
| 2
|
Kotlin
|
0
| 0
|
b59492568dda712499c53ecbc018a9e1e9131dcf
| 8,709
|
index-management
|
Apache License 2.0
|
app/src/main/java/com/nicoapps/cooktime/ui/screens/recipe/execute/dialogs/SaveExecutionDialog.kt
|
andremn
| 758,641,451
| false
|
{"Kotlin": 185045}
|
package com.nicoapps.cooktime.ui.screens.recipe.execute.dialogs
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
import com.nicoapps.cooktime.R
@Composable
fun SaveExecutionDialog(
onDismissRequest: () -> Unit,
onConfirmed: () -> Unit,
onRejected: () -> Unit
) {
AlertDialog(
onDismissRequest = { onDismissRequest() },
title = {
Text(
text = stringResource(
id = R.string.execute_recipe_save_execution_dialog_title
)
)
},
text = {
Text(
text = stringResource(
id = R.string.execute_recipe_save_execution_dialog_description
)
)
},
confirmButton = {
TextButton(
onClick = { onConfirmed() }
) {
Text(
text = stringResource(
id = R.string.execute_recipe_save_execution_dialog_confirm
)
)
}
},
dismissButton = {
TextButton(onClick = { onRejected() }) {
Text(
text = stringResource(
id = R.string.execute_recipe_save_execution_dialog_cancel
)
)
}
}
)
}
| 0
|
Kotlin
|
0
| 0
|
389af6b6dffccd88ddbf4a434a090fa7c1a65e6a
| 1,530
|
cooktime
|
MIT License
|
app/src/main/java/com/example/marvelclient/di/AppModules.kt
|
Prathamesh010
| 284,286,786
| false
| null |
package com.example.marvelclient.di
val appComponent = listOf(
databaseModule,
networkModule,
repoModule,
viewModelModule
)
| 0
|
Kotlin
|
0
| 0
|
a71aade97fe5e52a8d2dfb832a239986bd75dc76
| 140
|
Marvel
|
MIT License
|
library/src/main/java/com/afollestad/aesthetic/States.kt
|
reyadrahman
| 153,971,139
| true
|
{"Kotlin": 158524}
|
/*
* Licensed under Apache-2.0
*
* Designed and developed by Aidan Follestad (@afollestad)
*/
package com.afollestad.aesthetic
import android.R.attr
import android.content.res.ColorStateList
import androidx.annotation.ColorInt
/** @author Aidan Follestad (afollestad) */
data class ActiveInactiveColors(
@field:ColorInt val activeColor: Int,
@field:ColorInt val inactiveColor: Int
) {
fun toEnabledSl(): ColorStateList {
return ColorStateList(
arrayOf(
intArrayOf(attr.state_enabled), intArrayOf(-attr.state_enabled)
),
intArrayOf(activeColor, inactiveColor)
)
}
}
/** @author Aidan Follestad (afollestad) */
internal data class ColorIsDarkState(
@field:ColorInt val color: Int,
val isDark: Boolean
)
| 0
|
Kotlin
|
0
| 0
|
22fa19081f23c37ccf1e140e551c85a8efba805b
| 764
|
aesthetic
|
Apache License 2.0
|
app/src/androidTest/java/com/example/traveltogether/MyPostTest.kt
|
sw21-tug
| 351,004,544
| false
| null |
package com.example.traveltogether
import androidx.test.espresso.Espresso
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.ext.junit.rules.ActivityScenarioRule
import com.google.android.gms.tasks.Tasks
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import org.hamcrest.CoreMatchers.allOf
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import java.text.SimpleDateFormat
import java.util.*
@RunWith(androidx.test.ext.junit.runners.AndroidJUnit4::class)
class MyPostTest {
private lateinit var loginUser: LoginUser
private lateinit var firebaseDb: FirebaseDatabase
private lateinit var firebaseRef: DatabaseReference
private val postTitle = "Weit weg"
private val postDestination = "Weg"
private val postDescription = "...."
private val postStartEndDate = 1621209800000L
private val postNPeople = 3L
private lateinit var pid : String
private lateinit var userPost : UserPost
private val myFormat = "dd/MM/yyyy"
@get:Rule
var activityRule = ActivityScenarioRule(MainActivity::class.java)
@Before
fun checkLogin () {
loginUser = LoginUser("mypoststests@gmail.com", "mypoststests", "mypoststests", "mypoststests")
loginUser.signIn()
firebaseDb = FirebaseDatabase.getInstance()
firebaseRef = firebaseDb.reference
val list : MutableList<Comment> = mutableListOf()
var messages : MutableList<Message> = mutableListOf()
var ids : MutableList<String> = mutableListOf()
firebaseRef.child("posts").push().
setValue(UserPost(
FirebaseAuth.getInstance().currentUser?.uid.toString(), "2", System.currentTimeMillis(),
postTitle, postDestination, postStartEndDate, postStartEndDate,
postNPeople, postDescription, list, messages, ids))
val data = Tasks.await(firebaseRef.child("posts").get())
for (item in data.children) {
assert(item.hasChild("title"))
if (item.child("title").value.toString() == postTitle &&
item.child("uid").value.toString() ==
FirebaseAuth.getInstance().currentUser?.uid
) {
pid = item.key.toString()
break
}
}
assert(pid != "")
val dataNew = Tasks.await(firebaseRef.child("posts").child(pid).get())
userPost = UserPost(dataNew.child("uid").value.toString(),
dataNew.key, dataNew.child("timePosted").value as Long, dataNew.child("title").value.toString(),
dataNew.child("destination").value.toString(),
dataNew.child("startDate").value as Long,
dataNew.child("endDate").value as Long,
dataNew.child("numOfPeople").value as Long,
dataNew.child("description").value.toString(), list, messages, ids)
}
@After
fun cleanup () {
var activityRule = ActivityScenarioRule(MainActivity::class.java)
userPost.delete()
}
@Test
fun checkDisplayContainer() {
onView(withId(R.id.my_posts_fragment)).perform(click())
onView(withId(R.id.recycler_view_my_post)).check(matches(isDisplayed()))
}
@Test
fun checkIfPostIsDisplayed() {
onView(withId(R.id.my_posts_fragment)).perform(click())
onView(withText(postTitle)).check(matches(isDisplayed()))
onView(withText(postDestination)).check(matches(isDisplayed()))
onView(withText(postDescription)).check(matches(isDisplayed()))
onView(withText("Group size: $postNPeople")).check(matches(isDisplayed()))
val date = getDate(postStartEndDate)
onView(withText("From $date")).check(matches(isDisplayed()))
onView(withText("To $date")).check(matches(isDisplayed()))
}
@Test
fun checkIfPostEditButtonClickable() {
onView(withId(R.id.my_posts_fragment)).perform(click())
onView(withId(R.id.Button_delete_my_posts)).perform(click())
}
@Test
fun checkIfPostCommentButtonClickable() {
onView(withId(R.id.my_posts_fragment)).perform(click())
onView(withText("Comments")).perform(click())
}
@Test
fun checkIfPostJoinButtonClickable() {
onView(withId(R.id.my_posts_fragment)).perform(click())
onView(withText("Join Group Chat"))
.perform(click())
}
private fun getDate(l: Long): String? {
return try {
val sdf = SimpleDateFormat(myFormat)
val netDate = Date(l)
sdf.format(netDate)
} catch (e: Exception) {
e.toString()
}
}
}
| 2
|
Kotlin
|
7
| 0
|
6f5519f4fd1d000e87c69531b071cbe611384738
| 4,952
|
Team-04
|
MIT License
|
app/src/main/java/me/zsj/pretty_girl_kotlin/model/GirlData.kt
|
jijicanyu
| 113,018,883
| false
| null |
package me.zsj.pretty_girl_kotlin.model
/**
* @author zsj
*/
data class GirlData(val error: Boolean,
val results: List<PrettyGirl>)
| 0
|
Kotlin
|
0
| 0
|
410e9b05dbef817660fb6dc4f9c59db8e999a53a
| 154
|
pretty-girl-kotlin
|
Apache License 2.0
|
clara-app/src/main/kotlin/de/unistuttgart/iste/sqa/clara/export/graphviz/GraphVizExporter.kt
|
SteveBinary
| 724,727,375
| false
|
{"Kotlin": 89820}
|
package de.unistuttgart.iste.sqa.clara.export.graphviz
import arrow.core.Either
import arrow.core.Option
import arrow.core.Some
import arrow.core.getOrElse
import de.unistuttgart.iste.sqa.clara.api.export.ExportFailure
import de.unistuttgart.iste.sqa.clara.api.export.Exporter
import de.unistuttgart.iste.sqa.clara.api.model.Communication
import de.unistuttgart.iste.sqa.clara.api.model.Component
import de.unistuttgart.iste.sqa.clara.config.ExportConfig.Exporters.GraphViz
import de.unistuttgart.iste.sqa.clara.utils.process.readError
import de.unistuttgart.iste.sqa.clara.utils.process.startChecked
import de.unistuttgart.iste.sqa.clara.utils.process.writeOutput
import io.github.oshai.kotlinlogging.KotlinLogging
import java.io.IOException
import kotlin.io.path.Path
import kotlin.io.path.createParentDirectories
import kotlin.time.Duration.Companion.seconds
class GraphVizExporter(private val config: Config) : Exporter {
data class Config(
val outputType: String,
val outputFile: String,
)
private val log = KotlinLogging.logger {}
override fun export(components: Set<Component>, communications: Set<Communication>): Option<ExportFailure> {
log.info { "Export to GraphViz ..." }
if (config.outputType !in GraphViz.ALLOWED_TYPES) {
return Some(ExportFailure("GraphViz: Cannot export with GraphViz because the type '${config.outputType}' is not supported! Supported types are: ${GraphViz.ALLOWED_TYPES}"))
}
val graphVizVersion = getGraphVizVersion().getOrElse { return Some(it) }
log.info { "Using GraphViz version: $graphVizVersion" }
val graphvizCode = GraphVizCodeGenerator.generateDotCode(components, communications)
log.trace { "Generated GraphViz code:\n$graphvizCode" }
try {
Path(config.outputFile).normalize().createParentDirectories()
} catch (ex: IOException) {
return Some(ExportFailure("GraphViz: Cannot create parent directories of output file '${config.outputFile}': ${ex.message}"))
} catch (ex: FileSystemException) {
return Some(ExportFailure("GraphViz: Cannot create parent directories of output file '${config.outputFile}': ${ex.message}"))
}
val maybeExportFailure = executeExportProcess(graphvizCode)
log.info { "Done exporting to GraphViz" }
return maybeExportFailure
}
private fun getGraphVizVersion(): Either<ExportFailure, String> {
val versionAskProcess = ProcessBuilder("dot", "--version").startChecked()
return versionAskProcess
// for some reason the correct output is sent over the error stream
.readError(timeout = 5.seconds)
.mapLeft { ExportFailure("GraphViz: Cannot get GraphViz version: ${it.description}") }
.map { it.substringAfter("version").trim() }
}
private fun executeExportProcess(code: String): Option<ExportFailure> {
val exportProcess = ProcessBuilder("dot", "-T${config.outputType}", "-o", config.outputFile).startChecked()
return exportProcess
.writeOutput(timeout = 30.seconds) {
write(code)
write(System.lineSeparator())
flush()
}
.map { ExportFailure("GraphViz: Cannot export: ${it.description}") }
}
}
| 0
|
Kotlin
|
0
| 0
|
bce6976ec77ecd2301f68ca7eb1dfce7216c810e
| 3,352
|
clara
|
MIT License
|
buildSrc/src/Info.kt
|
Ricky12Awesome
| 282,574,304
| false
| null |
object Info {
const val modid = "template_mod"
const val name = "Template Mod"
const val description = "Template Mod"
const val version = "1.0"
const val group = "com.template"
}
| 0
|
Kotlin
|
0
| 1
|
99309d74839a9470e7940e6edc9c80087bb5abad
| 188
|
fabric-kotlin-mod-template
|
MIT License
|
src/main/kotlin/no/nav/syfo/api/v3/domain/Kontaktinfo.kt
|
navikt
| 164,875,446
| false
|
{"Gradle": 1, "Markdown": 2, "CODEOWNERS": 1, "Gradle Kotlin DSL": 1, "Dockerfile": 1, "Shell": 2, "Ignore List": 1, "Batchfile": 1, "YAML": 13, "INI": 1, "Java": 166, "XML": 11, "SQL": 37, "Kotlin": 160, "XSLT": 2, "GraphQL": 2, "PLSQL": 1}
|
package no.nav.syfo.api.v3.domain
data class Kontaktinfo(
val fnr: String,
val epost: String? = null,
val tlf: String? = null,
val skalHaVarsel: Boolean,
val feilAarsak: FeilAarsak? = null
)
enum class FeilAarsak {
RESERVERT, UTGAATT, KONTAKTINFO_IKKE_FUNNET, SIKKERHETSBEGRENSNING, PERSON_IKKE_FUNNET
}
| 7
|
Java
|
0
| 0
|
383a9d2c6256c2a8a014293d37f7f42962be6972
| 330
|
syfooppfolgingsplanservice
|
MIT License
|
src/main/kotlin/cn/soldat/jutils/web/response/ResponseResult.kt
|
jacob-du
| 743,856,862
| false
|
{"Kotlin": 33233}
|
package cn.soldat.jutils.web.response
/**
* 统一响应数据类
*/
data class ResponseResult<T> (
/**
* 响应码
*/
val code: Int,
/**
* 响应信息
*/
val msg: String,
/**
* 响应数据
*/
val data: T? = null
){
companion object{
/**
* 成功响应
*/
fun success() = ResponseResult<Nothing>(ResponseCode.SUCCESS.code, ResponseCode.SUCCESS.msg)
fun success(code: Int) = ResponseResult<Nothing>(code, ResponseCode.SUCCESS.msg)
fun success(msg: String) = ResponseResult<Nothing>(ResponseCode.SUCCESS.code, msg)
fun success(code: Int, msg: String) = ResponseResult<Nothing>(code, msg)
fun success(respCode: ResponseCode) = ResponseResult<Nothing>(respCode.code, respCode.msg)
inline fun <reified T> success(data: T) = ResponseResult(ResponseCode.SUCCESS.code, ResponseCode.SUCCESS.msg, data)
inline fun <reified T> success(code: Int, data: T) = ResponseResult(code, ResponseCode.SUCCESS.msg, data)
inline fun <reified T> success(msg: String, data: T) = ResponseResult(ResponseCode.SUCCESS.code, msg, data)
inline fun <reified T> success(code: Int, msg: String, data: T) = ResponseResult(code, msg, data)
inline fun <reified T> success(respCode: ResponseCode, data: T) = ResponseResult(respCode.code, respCode.msg, data)
/**
* 失败响应
*/
fun error() = ResponseResult<Nothing>(ResponseCode.ERROR.code, ResponseCode.ERROR.msg)
fun error(code: Int) = ResponseResult<Nothing>(code, ResponseCode.ERROR.msg)
fun error(msg: String) = ResponseResult<Nothing>(ResponseCode.ERROR.code, msg)
fun error(code: Int, msg: String) = ResponseResult<Nothing>(code, msg)
fun error(respCode: ResponseCode) = ResponseResult<Nothing>(respCode.code, respCode.msg)
inline fun <reified T> error(data: T) = ResponseResult(ResponseCode.ERROR.code, ResponseCode.ERROR.msg, data)
inline fun <reified T> error(code: Int, data: T) = ResponseResult(code, ResponseCode.ERROR.msg, data)
inline fun <reified T> error(msg: String, data: T) = ResponseResult(ResponseCode.ERROR.code, msg, data)
inline fun <reified T> error(respCode: ResponseCode, data: T) = ResponseResult(respCode.code, respCode.msg, data)
}
}
| 0
|
Kotlin
|
0
| 0
|
b74fb635f37d7c633d504c50297c4926632c62ab
| 2,301
|
jutils-kt
|
MIT License
|
agora.core/src/commonMain/kotlin/org/agorahq/agora/core/api/shared/templates/DefaultLoginPage.kt
|
agorahq
| 228,175,670
| false
| null |
package org.agorahq.agora.core.api.shared.templates
import kotlinx.html.*
import org.agorahq.agora.core.api.operation.context.OperationContext
import org.agorahq.agora.core.api.shared.layouts.withDefaultLayout
fun HTML.renderDefaultLoginPage(ctx: OperationContext<out Any>) = withDefaultLayout(ctx, "Log In") {
div("card mt-3") {
div("card-header") {
h3 { +"Log In" }
}
div("card-body") {
ul("list-group") {
li("list-group-item") {
a("/login/google") { +"Google" }
}
li("list-group-item") {
a("/login/facebook") { +"Facebook" }
}
}
}
}
}
| 28
|
Kotlin
|
0
| 0
|
a7aeabc25d31e11090f37733de2b8ec138d1de3b
| 720
|
agora
|
Apache License 2.0
|
runtime/src/commonMain/kotlin/land/sungbin/composeinvestigator/runtime/ComposableScope.kt
|
jisungbin
| 703,660,716
| false
|
{"Kotlin": 257855, "Shell": 447}
|
// Copyright 2024 <NAME>
// SPDX-License-Identifier: Apache-2.0
package land.sungbin.composeinvestigator.runtime
/** APIs annotated with this should only be used within Composable functions. */
@MustBeDocumented
@Retention(AnnotationRetention.SOURCE)
@Target(
AnnotationTarget.FUNCTION,
AnnotationTarget.PROPERTY,
AnnotationTarget.PROPERTY_GETTER,
AnnotationTarget.PROPERTY_SETTER,
)
public annotation class ComposableScope
| 7
|
Kotlin
|
7
| 283
|
4c668b87e4b0bf72fdfa6f7d62317b5767741e8f
| 433
|
ComposeInvestigator
|
Apache License 2.0
|
api/src/main/kotlin/com/wnsgml972/strada/api/v1/ordering/service/OrderingResponse.kt
|
Coffee-Street
| 289,485,814
| false
|
{"Kotlin": 267923, "Shell": 2546, "Dockerfile": 174}
|
package com.wnsgml972.strada.api.v1.ordering.service
import com.wnsgml972.strada.api.base.AbstractValueObject
data class OrderingResponse(
val orderingDTO: OrderingDTO,
val orderingDetailDTOs: List<OrderingDetailDTO>
) : AbstractValueObject() {
override fun equalProperties(other: Any): Boolean {
return other is OrderingResponse &&
orderingDTO == other.orderingDTO &&
orderingDetailDTOs == other.orderingDetailDTOs
}
}
| 2
|
Kotlin
|
2
| 2
|
24422867afe6c7f547a93f98083f655ecb80c0ed
| 479
|
strada
|
MIT License
|
src/main/kotlin/br/com/zup/pix/registra/ValidPixKey.kt
|
paullogoncalves
| 388,871,641
| true
|
{"Kotlin": 82362}
|
package br.com.zup.pix.registra
import javax.inject.Singleton
import javax.validation.*
import kotlin.annotation.AnnotationRetention.RUNTIME
import kotlin.annotation.AnnotationTarget.CLASS
import kotlin.annotation.AnnotationTarget.TYPE
import kotlin.reflect.KClass
@MustBeDocumented
@Target(CLASS, TYPE)
@Retention(RUNTIME)
@Constraint(validatedBy = [ValidPixKeyValidator::class])
annotation class ValidPixKey(
val message: String = "chave Pix inválida '\${validatedValue.tipo}'",
val groups: Array<KClass<Any>> = [],
val payload: Array<KClass<Payload>> = [],
)
/**
* Using Bean Validation API because we wanted to use Custom property paths
* https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-custom-property-paths
*/
@Singleton
class ValidPixKeyValidator: ConstraintValidator<ValidPixKey, NovaChavePix> {
override fun isValid(value: NovaChavePix?, context: ConstraintValidatorContext): Boolean {
// must be validated with @NotNull
if (value?.tipo == null) {
return true
}
val valid = value.tipo.valida(value.chave, context)
if (!valid) {
// https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-custom-property-paths
context.disableDefaultConstraintViolation()
context
.buildConstraintViolationWithTemplate(context.defaultConstraintMessageTemplate) // or "chave Pix inválida (${value.tipo})"
.addPropertyNode("chave").addConstraintViolation()
}
return valid
}
}
/**
* IT'S NOT USED HERE
*
* It seems like Micronaut does NOT support Custom property paths, so we have to use Bean Validation API
* directly instead
*
* - https://docs.micronaut.io/latest/guide/index.html#beanValidation
* - https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-custom-property-paths
*/
class ValidPixKeyValidatorUsingMicronautSupport: ConstraintValidator<ValidPixKey, NovaChavePix> {
override fun isValid(
value: NovaChavePix?,
context: ConstraintValidatorContext,
): Boolean {
// must be validated with @NotNull
if (value?.tipo == null) {
return true
}
return value.tipo.valida(value.chave, context)
}
}
| 0
|
Kotlin
|
0
| 0
|
fbfcb5d00ce859673c305239961caad5a8b9994f
| 2,339
|
orange-talents-05-template-pix-keymanager-grpc
|
Apache License 2.0
|
kotlin/kotlin-feature/src/main/kotlin/top/spencercjh/chapter3/notNull.kt
|
spencercjh
| 175,650,453
| false
|
{"Java": 512838, "Kotlin": 99897, "Python": 16109, "HTML": 13016, "JavaScript": 11973, "CSS": 3821, "Scala": 3218}
|
package top.spencercjh.chapter3
import kotlin.properties.Delegates
/**
* @author SpencerCJH
* @date 2019/10/26 14:22
*/
var testNotNull: String by Delegates.notNull()
fun main() {
// assert exception:Property testNotNull should be initialized before get.
// println(testNotNull)
testNotNull = "123"
println(testNotNull)
}
| 9
|
Java
|
1
| 7
|
be27d99380c0a1bdf4bea9a86b0d436deb7e2d2d
| 341
|
codeLife
|
Apache License 2.0
|
plugin-dotnet-server/src/main/kotlin/jetbrains/buildServer/dotCover/DotCoverToolTypeAdapter.kt
|
JetBrains
| 49,584,664
| false
| null |
package jetbrains.buildServer.dotCover
import jetbrains.buildServer.dotnet.CoverageConstants
import jetbrains.buildServer.tools.ToolTypeAdapter
class DotCoverToolTypeAdapter : ToolTypeAdapter() {
override fun getType() = CoverageConstants.DOTCOVER_PACKAGE_ID
override fun getDisplayName() = CoverageConstants.DOT_COVER_TOOL_TYPE_NAME
override fun getDescription(): String = "Is used in JetBrains dotCover-specific build steps to get code coverage."
override fun getShortDisplayName() = CoverageConstants.DOT_COVER_SHORT_TOOL_TYPE_NAME
override fun getTargetFileDisplayName() = CoverageConstants.DOT_COVER_TARGET_FILE_DISPLAY_NAME
override fun isSupportDownload() = true
override fun getToolSiteUrl() = "https://www.jetbrains.com/dotcover/download/#section=commandline"
override fun getToolLicenseUrl() = "https://www.jetbrains.com/legal/docs/dotcover/dotcover_clt_license"
override fun getTeamCityHelpFile() = "JetBrains+dotCover"
override fun getValidPackageDescription() = "Specify the path to a " + displayName + " (.zip or .nupkg).\n" +
"<br/><br/>Supported tools:" +
"<br/><a href=\"https://www.jetbrains.com/dotcover/download/#section=commandline\" target=\"_blank\" rel=\"noreferrer\">JetBrains.dotCover.CommandLineTools.<VERSION>.zip</a>" +
"<br/><a href=\"https://www.nuget.org/packages/JetBrains.dotCover.CommandLineTools/\" target=\"_blank\" rel=\"noreferrer\">JetBrains.dotCover.CommandLineTools.<VERSION>.nupkg</a>"
}
| 3
| null |
25
| 94
|
5f444c22b3354955d1060e08478d543d2b0b99b0
| 1,533
|
teamcity-dotnet-plugin
|
Apache License 2.0
|
app/src/main/java/com/santansarah/blescanner/presentation/BleObserver.kt
|
santansarah
| 588,753,371
| false
| null |
package com.santansarah.blescanner.presentation
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.activity.ComponentActivity
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.ActivityResultRegistry
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import org.koin.core.component.KoinComponent
import org.koin.core.component.get
class BleObserver(
private val activity: ComponentActivity
) : DefaultLifecycleObserver, KoinComponent {
val bleManager = get<BleManager>()
val btAdapter = get<BluetoothAdapter>()
private val registry: ActivityResultRegistry = activity.activityResultRegistry
lateinit var btEnableResultLauncher: ActivityResultLauncher<Intent>
private lateinit var broadcastReceiver: BroadcastReceiver
override fun onCreate(owner: LifecycleOwner) {
super.onCreate(owner)
createBroadcastReceiver()
btEnableResultLauncher = registerHandler(owner, "EnableBLE")
ContextCompat.registerReceiver(activity, broadcastReceiver,
IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED),
ContextCompat.RECEIVER_EXPORTED)
}
private fun createBroadcastReceiver() {
broadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent) {
val action = intent.action
// It means the user has changed their bluetooth state.
if (action == BluetoothAdapter.ACTION_STATE_CHANGED) {
if (btAdapter.state == BluetoothAdapter.STATE_OFF) {
bleManager.stopScan()
val btEnableIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
btEnableResultLauncher.launch(btEnableIntent)
return
}
if (btAdapter.state == BluetoothAdapter.STATE_ON) {
bleManager.scan()
return
}
}
}
}
}
private fun registerHandler(owner: LifecycleOwner, key: String) = registry.register(
key,
owner,
ActivityResultContracts.StartActivityForResult()
) { result ->
if (result.resultCode == Activity.RESULT_OK) {
// There are no request codes
val data: Intent? = result.data
bleManager.scan()
}
}
}
| 1
|
Kotlin
|
1
| 7
|
25cf4144258357bcd16a2b4bb708db92f2f7cbcf
| 2,765
|
ble-scanner
|
MIT License
|
paris/src/testDebug/java/com/airbnb/paris/views/kotlin/WithStyleableChildPropertyDelegateViewStyleExtensionsTest.kt
|
airbnb
| 114,683,464
| false
| null |
package com.airbnb.paris.views.kotlin
import android.content.Context
import android.view.View
import com.airbnb.paris.R
import com.airbnb.paris.extensions.addDefault
import com.airbnb.paris.extensions.style
import com.airbnb.paris.extensions.testArbitraryStyle
import com.airbnb.paris.extensions.viewStyle
import com.airbnb.paris.extensions.visibility
import com.airbnb.paris.extensions.withStyleableChildKotlinViewStyle
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
@RunWith(RobolectricTestRunner::class)
class WithStyleableChildPropertyDelegateViewStyleExtensionsTest {
private lateinit var context: Context
private lateinit var withStyleableChildPropertyDelegateView: WithStyleableChildPropertyDelegateView
@Before
fun setup() {
context = RuntimeEnvironment.application
withStyleableChildPropertyDelegateView = WithStyleableChildPropertyDelegateView(context)
}
@Test
fun style_builderDefault() {
// Tests that the extension to set a default style exists
withStyleableChildPropertyDelegateView.style { addDefault() }
}
@Test
fun style_builderSubStyleStyle() {
// Tests that the extension to build and set a sub-style exist and work with an arbitrary
// attribute
withStyleableChildPropertyDelegateView.style {
testArbitraryStyle(viewStyle {
visibility(View.INVISIBLE)
})
}
assertEquals(withStyleableChildPropertyDelegateView.arbitrarySubView.visibility, View.INVISIBLE)
}
@Test
fun style_builderSubStyleStyleRes() {
// Tests that the extension to build and set a sub-style exist and work with an arbitrary
// attribute
withStyleableChildPropertyDelegateView.style {
testArbitraryStyle(R.style.Test_WithStyleableChildPropertyDelegateViewStyleExtensions_Style_BuilderSubStyleStyle_Invisible)
}
assertEquals(withStyleableChildPropertyDelegateView.arbitrarySubView.visibility, View.INVISIBLE)
}
@Test
fun style_builderSubStyleStyleBuilder() {
// Tests that the extension to build and set a sub-style exist and work with an arbitrary
// attribute
withStyleableChildPropertyDelegateView.style {
testArbitraryStyle {
visibility(View.INVISIBLE)
}
}
assertEquals(withStyleableChildPropertyDelegateView.arbitrarySubView.visibility, View.INVISIBLE)
}
@Test
fun withStyleableChildPropertyDelegateViewStyle() {
// Tests that the extension to build and set a style exists and works with an arbitrary attribute.
withStyleableChildPropertyDelegateView.arbitrarySubView.visibility = View.VISIBLE
withStyleableChildPropertyDelegateView.style(withStyleableChildKotlinViewStyle {
testArbitraryStyle {
visibility(View.INVISIBLE)
}
})
assertEquals(withStyleableChildPropertyDelegateView.arbitrarySubView.visibility, View.INVISIBLE)
}
}
| 56
| null |
91
| 1,897
|
d8b5edbc56253bcdd0d0c57930d2e91113dd0f37
| 3,185
|
paris
|
Apache License 2.0
|
plume/src/main/kotlin/io/github/plume/oss/domain/model/DeltaGraph.kt
|
plume-oss
| 285,804,384
| false
| null |
/*
* Copyright 2021 Plume Authors
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.plume.oss.domain.model
import io.github.plume.oss.drivers.IDriver
import io.github.plume.oss.drivers.TigerGraphDriver
import io.shiftleft.codepropertygraph.generated.nodes.NewNodeBuilder
import org.apache.logging.log4j.LogManager
import overflowdb.Graph
import overflowdb.Node
/**
* This is based off of [io.shiftleft.passes.DiffGraph]. Where DiffGraphs do not propagate ID changes, this one does by
* making use of [NewNodeBuilder] objects. These get assigned an ID when passed to [IDriver.addVertex] so no duplication
* occurs.
*/
class DeltaGraph private constructor(val changes: List<Delta>) {
private val logger = LogManager.getLogger(DeltaGraph::class.java)
private constructor(builder: Builder) : this(builder.getChanges())
/**
* Applies the delta graph to an OverflowDB instance. To have valid IDs this must be passed into the driver with
* the [DeltaGraph.apply] method first.
*
* @param existingG optionally one can write the deltas to the given OverflowDB graph.
* @return An OverflowDB graph with the changes from this [DeltaGraph] applied to it.
*/
fun toOverflowDb(existingG: Graph): Graph {
fun exists(g: Graph, id: Long): Boolean {
val maybeNode = g.node(id)
return if (maybeNode == null) false
else (maybeNode.id() == id)
}
fun d2g(g: Graph) {
fun addNode(n: NewNodeBuilder): Node {
val b = n.build()
val v = g.addNode(n.id(), b.label())
b.properties().foreachEntry { key, value -> v.setProperty(key, value) }
return v
}
changes.filterIsInstance<VertexAdd>().forEach { d -> if (!exists(g, d.n.id())) addNode(d.n) }
changes.filterIsInstance<EdgeAdd>().forEach { d ->
val src = if (exists(g, d.src.id())) g.node(d.src.id()) else addNode(d.src)
val dst = if (exists(g, d.dst.id())) g.node(d.dst.id()) else g.node(d.dst.id()) ?: addNode(d.dst)
try {
src.addEdge(d.e, dst)
} catch (e: Exception) {
logger.error("Exception while adding edge between ${d.src} ($src) and ${d.dst} ($dst)", e)
}
}
changes.filterIsInstance<VertexDelete>().forEach { d -> g.node(d.id)?.remove() }
changes.filterIsInstance<EdgeDelete>().forEach { d ->
val src = g.node(d.src.id())
g.node(d.dst.id())?.let { dst ->
src.outE(d.e).asSequence().firstOrNull { it.inNode() == dst }?.remove()
}
}
}
return existingG.apply { d2g(this) }
}
/**
* Builds an [DeltaGraph] instance by accumulating changes.
*/
class Builder {
private val changes = mutableListOf<Delta>()
/**
* Returns a list of the accumulated changes.
*/
fun getChanges() = changes.toList()
fun addVertex(n: NewNodeBuilder) = apply { changes.add(VertexAdd(n)) }
fun deleteVertex(n: NewNodeBuilder) = apply { changes.add(VertexDelete(n.id(), n.build().label())) }
fun deleteVertex(id: Long, label: String) = apply { changes.add(VertexDelete(id, label)) }
fun addEdge(src: NewNodeBuilder, tgt: NewNodeBuilder, e: String) = apply {
changes.add(VertexAdd(src))
changes.add(VertexAdd(tgt))
changes.add(EdgeAdd(src, tgt, e))
}
fun deleteEdge(src: NewNodeBuilder, tgt: NewNodeBuilder, e: String) =
apply { changes.add(EdgeDelete(src, tgt, e)) }
fun addAll(otherChanges: List<Delta>) = apply { changes.addAll(otherChanges) }
fun build() = DeltaGraph(this)
}
abstract class Delta
data class VertexAdd(val n: NewNodeBuilder) : Delta()
data class VertexDelete(val id: Long, val label: String) : Delta()
data class EdgeAdd(val src: NewNodeBuilder, val dst: NewNodeBuilder, val e: String) : Delta()
data class EdgeDelete(val src: NewNodeBuilder, val dst: NewNodeBuilder, val e: String) : Delta()
}
| 6
| null |
7
| 24
|
ff0d35bf6986aa56952762bd7c456cad7a44954e
| 4,742
|
plume
|
Apache License 2.0
|
app/src/main/java/com/coinninja/coinkeeper/db/migrations/Migrate_V34_to_V35.kt
|
coinninjadev
| 175,276,289
| false
| null |
package com.coinninja.coinkeeper.db.migrations
import com.coinninja.coinkeeper.db.AbstractMigration
import com.coinninja.coinkeeper.db.Migration
import org.greenrobot.greendao.database.Database
class Migrate_V34_to_V35 : AbstractMigration() {
override val migratedVersion: Int = 35
override val targetVersion: Int = 34
override val previousMigration: Migration = Migrate_V33_to_V34()
override fun applyMigration(db: Database, currentVersion: Int) {
dropFeeColumnFromWallet(db)
}
private fun dropFeeColumnFromWallet(db: Database) {
db.execSQL("ALTER TABLE WALLET RENAME TO TEMP_WALLET")
db.execSQL("CREATE TABLE \"WALLET\" (\"_id\" INTEGER PRIMARY KEY AUTOINCREMENT ," +
"\"HD_INDEX\" INTEGER NOT NULL ,\"USER_ID\" INTEGER,\"LAST_SYNC\" INTEGER NOT NULL ," +
"\"INTERNAL_INDEX\" INTEGER NOT NULL ,\"EXTERNAL_INDEX\" INTEGER NOT NULL ," +
"\"BALANCE\" INTEGER NOT NULL ,\"SPENDABLE_BALANCE\" INTEGER NOT NULL ," +
"\"BLOCK_TIP\" INTEGER NOT NULL ,\"LAST_USDPRICE\" INTEGER NOT NULL)")
db.execSQL("INSERT INTO \"WALLET\" \n" +
"(" +
" \"_id\", " +
" \"HD_INDEX\", " +
" \"USER_ID\", " +
" \"LAST_SYNC\", " +
" \"INTERNAL_INDEX\", " +
" \"EXTERNAL_INDEX\", " +
" \"BALANCE\", " +
" \"SPENDABLE_BALANCE\", " +
" \"BLOCK_TIP\", " +
" \"LAST_USDPRICE\"" +
") \n" +
"SELECT " +
" \"_id\", " +
" \"HD_INDEX\", " +
" \"USER_ID\", " +
" \"LAST_SYNC\", " +
" \"INTERNAL_INDEX\", " +
" \"EXTERNAL_INDEX\", " +
" \"BALANCE\", " +
" \"SPENDABLE_BALANCE\", " +
" \"BLOCK_TIP\", " +
" \"LAST_USDPRICE\"" +
"FROM TEMP_WALLET;")
db.execSQL("drop table TEMP_WALLET")
}
}
| 2
| null |
0
| 6
|
d67d7c0b9cad27db94470231073c5d6cdda83cd0
| 2,095
|
dropbit-android
|
MIT License
|
modules/android/src/main/kotlin/com/waicool20/cvauto/android/AndroidDevice.kt
|
waicool20
| 219,472,930
| false
|
{"Kotlin": 147842}
|
/*
* The MIT License (MIT)
*
* Copyright (c) waicool20
*
* 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.waicool20.cvauto.android
import com.waicool20.cvauto.android.input.AndroidInput
import com.waicool20.cvauto.core.IDevice
import java.nio.file.Path
import java.util.concurrent.TimeUnit
import kotlin.io.path.absolutePathString
import kotlin.io.path.createTempDirectory
import kotlin.io.path.deleteExisting
import kotlin.io.path.outputStream
/**
* Represents an android device
*/
class AndroidDevice internal constructor(val serial: String) :
IDevice<AndroidDevice, AndroidDisplay, AndroidRegion> {
class UnexpectedDisconnectException(device: AndroidDevice) :
Exception("Device ${device.serial} disconnected unexpectedly")
/**
* Wrapper class containing the basic properties of an android device
*/
data class Properties(
val androidVersion: String,
val brand: String,
val manufacturer: String,
val model: String,
val name: String
)
enum class Orientation {
NORMAL, ROTATED
}
/**
* Properties of this android device
*/
val properties: Properties
/**
* Orientation of the device
*/
val orientation: Orientation
get() {
val txt = execute("dumpsys window | grep init=").readText()
val (w0, h0, w1, h1) = Regex("init=(\\d+)x(\\d+) \\d+?dpi cur=(\\d+)x(\\d+)")
.find(txt)?.destructured ?: error("Could not read orientation from device")
return when {
w0 == w1 && h0 == h1 -> Orientation.NORMAL
w0 == h1 && h0 == w1 -> Orientation.ROTATED
else -> error("Could not determine orientation from device $serial")
}
}
init {
val props = execute("getprop").readLines().mapNotNull { str ->
Regex("\\[(.*?)]: \\[(.*?)]").matchEntire(str)?.groupValues?.let { it[1] to it[2] }
}.toMap()
properties = Properties(
androidVersion = props["ro.build.version.release"] ?: "Unknown",
brand = props["ro.product.brand"] ?: "Unknown",
model = props["ro.product.model"] ?: "Unknown",
manufacturer = props["ro.product.manufacturer"] ?: "Unknown",
name = props["ro.product.name"] ?: "Unknown"
)
}
/**
* Reference to [Scrcpy] object tied to this device, providing services such as video and input
*/
var scrcpy = Scrcpy.getForDevice(this)
private set
enum class CaptureMethod {
SCREENCAP, SCRCPY
}
/**
* Capture method to use
*
* - [CaptureMethod.SCREENCAP]: Uses `screencap` command, a bit slower but reliable
* - [CaptureMethod.SCRCPY]: Uses custom scrcpy capture method
*/
var captureMethod: CaptureMethod = CaptureMethod.SCRCPY
enum class CompressionMode {
NONE, GZIP, LZ4
}
/**
* Compression of the captured image can reduce the amount of time it takes to copy it
* from the emulator to pc memory, therefore reducing latency. Only applicable when
* [captureMethod] is [CaptureMethod.SCREENCAP]
*
* - [CompressionMode.LZ4]: Best latency, default
* - [CompressionMode.GZIP]: Slower than LZ4
* - [CompressionMode.NONE]: No compression
*/
var compressionMode = CompressionMode.LZ4
override val input = AndroidInput(this)
override val displays: List<AndroidDisplay>
init {
// Push lz4 binary
var arch = execute("uname -m").readText().trim()
if (arch == "armv8l") arch = "aarch64"
try {
val inStream = AndroidDevice::class.java
.getResourceAsStream("/com/waicool20/cvauto/android/libs/$arch/lz4")
?: error("$arch not supported")
val tmp = createTempDirectory().resolve("lz4")
val outStream = tmp.outputStream()
inStream.copyTo(outStream)
inStream.close()
outStream.close()
push(tmp, "/data/local/tmp")
executeShell("chmod +x /data/local/tmp/lz4")
tmp.deleteExisting()
tmp.parent.deleteExisting()
} catch (e: Exception) {
// Fallback to None
compressionMode = CompressionMode.NONE
}
displays = scrcpy.getDisplayInfo().mapIndexed { i, dimension ->
AndroidDisplay(this, dimension.width, dimension.height, i)
}
}
/**
* Checks if device is showing pointer information
*
* @returns True if pointer info is on screen
*/
fun isShowingPointerInfo(): Boolean {
return executeShell("settings get system pointer_location").readText().contains("1")
}
/**
* Controls whether or not to show the pointer info on screen
*
* @param display Displays pointer info if True
*/
fun displayPointerInfo(display: Boolean) {
executeShell("settings put system pointer_location ${if (display) "1" else "0"}")
}
/**
* Toggles pointer info
*/
fun togglePointerInfo() {
executeShell("settings put system pointer_location ${if (isShowingPointerInfo()) "0" else "1"}")
}
/**
* Checks if device is showing touches
*
* @returns True if touches are shown on screen
*/
fun isShowingTouches(): Boolean {
return executeShell("settings get system show_touches").readText().contains("1")
}
/**
* Controls whether or not to show touches on screen
*
* @param display Displays touches if True
*/
fun showTouches(display: Boolean) {
executeShell("settings put system show_touches ${if (display) "1" else "0"}")
}
/**
* Toggles show touches
*/
fun toggleTouches() {
executeShell("settings put system show_touches ${if (isShowingTouches()) "0" else "1"}")
}
/**
* Runs a command specifically on this device using "exec-out"
*
* @param args command or arguments passed onto adb
* @return [Process] instance of the command
*/
fun execute(vararg args: String): Process {
return ADB.execute("-s", serial, "exec-out", *args)
}
/**
* Same as [execute] but uses "shell" instead of "exec-out",
* use this if there are input/output issues with [execute]
*
* @param args command or arguments passed onto adb
* @return [Process] instance of the command
*/
fun executeShell(vararg args: String): Process {
return ADB.execute("-s", serial, "shell", *args)
}
/**
* Transfer a file to this device
*
* @param local Path to file to push
* @param remote Remote path to push file to
*
* @return true if pushed successfully
*/
fun push(local: Path, remote: String): Boolean {
return ADB.execute("-s", serial, "push", local.absolutePathString(), remote).run {
waitFor()
exitValue() == 0
}
}
/**
* This will close the current scrcpy process tied to this device and start a new instance
*/
fun resetScrcpy() {
scrcpy.close()
TimeUnit.MILLISECONDS.sleep(200)
try {
scrcpy = Scrcpy.getForDevice(this)
scrcpy.waitInitialized()
} catch (e: Exception) {
assertConnected()
throw e
}
}
/**
* Checks if this device is still reachable by ADB
*/
fun isConnected(): Boolean {
return ADB.getDevices().contains(this)
}
internal fun assertConnected() {
if (!isConnected()) throw UnexpectedDisconnectException(this)
}
override fun toString(): String {
return "AndroidDevice(serial = $serial)"
}
}
| 0
|
Kotlin
|
3
| 4
|
7d3b2577066a5c15a1af09405c53a3d03412b23c
| 8,809
|
CVAuto
|
MIT License
|
src/test/kotlin/br/com/zup/ot5/grpc/GlobalGrpcEndpointInterceptorTest.kt
|
DaviLevi
| 383,277,033
| true
|
{"Kotlin": 84053, "Smarty": 2172}
|
package br.com.zup.ot5.grpc
import br.com.zup.ot5.compartilhado.interceptors.GlobalGrpcEndpointInterceptor
import br.com.zup.ot5.compartilhado.interceptors.GrpcExceptionResolver
import io.grpc.BindableService
import io.grpc.stub.StreamObserver
import io.micronaut.aop.MethodInvocationContext
import io.micronaut.test.extensions.junit5.annotation.MicronautTest
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.mockito.Mockito.verify
import org.mockito.Mockito.notNull
import org.mockito.junit.jupiter.MockitoExtension
@ExtendWith(MockitoExtension::class)
class ExceptionHandlerInterceptorTest {
@Mock
lateinit var context: MethodInvocationContext<BindableService, Any?>
val interceptor = GlobalGrpcEndpointInterceptor(resolver = GrpcExceptionResolver(handlers = emptyList()))
@Test
fun `deve capturar a excecao lancada pelo execucao do metodo, e gerar um erro na resposta gRPC`(@Mock streamObserver: StreamObserver<*>) {
with (context) {
`when`(proceed()).thenThrow(RuntimeException("argh!"))
`when`(parameterValues).thenReturn(arrayOf(null, streamObserver))
}
interceptor.intercept(context)
verify(streamObserver).onError(notNull())
}
@Test
fun `se o metodo nao gerar nenhuma excecao, deve apenas retornar a mesma resposta`() {
val expected = "whatever"
`when`(context.proceed()).thenReturn(expected)
Assertions.assertEquals(expected, interceptor.intercept(context))
}
}
| 0
|
Kotlin
|
0
| 0
|
f00bfecba37e7f78e18c4d89e617d90c6fb13ea3
| 1,643
|
orange-talents-05-template-pix-keymanager-grpc
|
Apache License 2.0
|
components/app/src/main/java/com/notable/ui/MainActivity.kt
|
fabricethilaw
| 576,792,746
| false
|
{"Kotlin": 63079, "Shell": 8899}
|
/*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.notable.ui
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.scrollable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.material.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.notable.ui.demos.responsivetext.DemoAutoScalingDownText
import com.notable.ui.demos.responsivetext.DemoDisableAutoTextSizing
import com.notable.ui.demos.responsivetext.DemoEnableAutoTextSizing
import com.notable.ui.demos.responsivetext.DemoOptimalTextOverflow
import com.notable.ui.theme.MyApplicationTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyApplicationTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = Color(0xFFF1F1F1)
) {
DefaultPreview()
}
}
}
}
}
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
MyApplicationTheme {
Column(
Modifier
.padding(16.dp)
.scrollable(
rememberScrollState(), orientation = Orientation.Vertical
)
) {
DemoDisableAutoTextSizing()
Spacer(modifier = Modifier.height(16.dp))
DemoEnableAutoTextSizing()
Spacer(modifier = Modifier.height(16.dp))
DemoAutoScalingDownText()
Spacer(modifier = Modifier.height(16.dp))
DemoOptimalTextOverflow()
}
}
}
| 1
|
Kotlin
|
3
| 20
|
0e3523e289ba0f5a4478e55883b4e900433807a1
| 2,464
|
notable-ui-compose
|
Apache License 2.0
|
testscript/test/org/partiql/testscript/parser/ParserMacroTests.kt
|
partiql
| 186,474,394
| false
| null |
package org.partiql.testscript.parser
import com.amazon.ion.IonSexp
import com.amazon.ion.IonStruct
import org.junit.jupiter.api.Test
import org.partiql.testscript.parser.ast.TestNode
class ParserForTests : BaseParseTests() {
@Test
fun forWithSingleTestAndVariable() = assertParse(
"""
|for::{
| template: [
| test::{
| id: testTemplate,
| statement: "1 + #value",
| expected: #expected
| }
| ],
|
| variable_sets: [
| { value: 1, expected: (success 2) }
| ]
|}""".trimMargin(),
expected = singleModulesList(
TestNode(
id = "testTemplate\$\${value:1,expected:(success 2)}",
description = null,
statement = "1 + 1",
environment = null,
expected = BaseParseTests.ion.singleValue("(success 2)") as IonSexp,
scriptLocation = ScriptLocation("$inputBasePath/input[0].sqlts", 11)
)
)
)
@Test
fun forWithMultipleTestsAndMultipleVariables() = assertParse(
"""
|for::{
| template: [
|
| test::{
| id: testTemplate1,
| description: "test: #description",
| statement: "1 + #value",
| environment: {myTable:#table},
| expected: (success #result)
| },
|
| test::{
| id: testTemplate2,
| description: #description,
| statement: "#value",
| environment: #environment,
| expected: #expected
| }
| ],
|
| variable_sets: [
| { description: "description 1", value: 1, table: [1], result: 1, environment: {foo: "1"}, expected: (success 10) },
| { description: "description 2", value: 2, table: [2], result: 2, environment: {foo: "2"}, expected: (success 20) }
| ]
|}""".trimMargin(),
expected = singleModulesList(
TestNode(
id = "testTemplate1\$\${description:\"description 1\",value:1,table:[1],result:1,environment:{foo:\"1\"},expected:(success 10)}",
description = "test: description 1",
statement = "1 + 1",
environment = ion.singleValue("{myTable: [1]}") as IonStruct,
expected = ion.singleValue("(success 1)") as IonSexp,
scriptLocation = ScriptLocation("$inputBasePath/input[0].sqlts", 22)
),
TestNode(
id = "testTemplate1\$\${description:\"description 2\",value:2,table:[2],result:2,environment:{foo:\"2\"},expected:(success 20)}",
description = "test: description 2",
statement = "1 + 2",
environment = ion.singleValue("{myTable: [2]}") as IonStruct,
expected = ion.singleValue("(success 2)") as IonSexp,
scriptLocation = ScriptLocation("$inputBasePath/input[0].sqlts", 23)
),
TestNode(
id = "testTemplate2\$\${description:\"description 1\",value:1,table:[1],result:1,environment:{foo:\"1\"},expected:(success 10)}",
description = "description 1",
statement = "1",
environment = ion.singleValue("{foo: \"1\"}") as IonStruct,
expected = ion.singleValue("(success 10)") as IonSexp,
scriptLocation = ScriptLocation("$inputBasePath/input[0].sqlts", 22)
),
TestNode(
id = "testTemplate2\$\${description:\"description 2\",value:2,table:[2],result:2,environment:{foo:\"2\"},expected:(success 20)}",
description = "description 2",
statement = "2",
environment = ion.singleValue("{foo: \"2\"}") as IonStruct,
expected = ion.singleValue("(success 20)") as IonSexp,
scriptLocation = ScriptLocation("$inputBasePath/input[0].sqlts", 23)
)
)
)
@Test
fun forWrongType() = assertParseError(
input = """ for::"should be a struct" """,
expectedErrorMessage = """
|Errors found when parsing test scripts:
| $inputBasePath/input[0].sqlts:1 - Wrong type for for. Expected [STRUCT], got STRING
""".trimMargin()
)
@Test
fun forWrongTemplateType() = assertParseError(
input = """
|for::{
| template: "should be a list",
|
| variable_sets: [
| { value: 1, expected: (success 2) }
| ]
|}
|""".trimMargin(),
expectedErrorMessage = """
|Errors found when parsing test scripts:
| $inputBasePath/input[0].sqlts:2 - Wrong type for for.template. Expected [LIST], got STRING
""".trimMargin()
)
@Test
fun forEmptyTemplate() = assertParseError(
input = """
|for::{
| template: [],
|
| variable_sets: [
| { value: 1, expected: (success 2) }
| ]
|} """.trimMargin(),
expectedErrorMessage = """
|Errors found when parsing test scripts:
| $inputBasePath/input[0].sqlts:1 - Field must have at least one element: for.template
""".trimMargin()
)
@Test
fun forTestTemplateWrongType() = assertParseError(
input = """
|for::{
| template: [
| test::"should be a struct"
| ],
|
| variable_sets: [
| { value: 1, expected: (success 2) }
| ]
|}
|""".trimMargin(),
expectedErrorMessage = """
|Errors found when parsing test scripts:
| $inputBasePath/input[0].sqlts:3 - Wrong type for for.template[0]. Expected [STRUCT], got STRING
""".trimMargin()
)
@Test
fun forTestTemplateWrongIdType() = assertParseError(
input = """
|for::{
| template: [
| test::{
| id: "should be a symbol",
| statement: "1 + #value",
| expected: #expected
| }
| ],
|
| variable_sets: [
| { value: 1, expected: (success 2) }
| ]
|}
|""".trimMargin(),
expectedErrorMessage = """
|Errors found when parsing test scripts:
| $inputBasePath/input[0].sqlts:4 - Wrong type for for.template[0].id. Expected [SYMBOL], got STRING
""".trimMargin()
)
@Test
fun forTestTemplateMissingId() = assertParseError(
input = """
|for::{
| template: [
| test::{
| statement: "1 + #value",
| expected: #expected
| }
| ],
|
| variable_sets: [
| { value: 1, expected: (success 2) }
| ]
|}
|""".trimMargin(),
expectedErrorMessage = """
|Errors found when parsing test scripts:
| $inputBasePath/input[0].sqlts:3 - Missing required field: for.template[0].id
""".trimMargin()
)
@Test
fun forTestTemplateWrongDescriptionType() = assertParseError(
input = """
|for::{
| template: [
| test::{
| id: test,
| description: 'should be a string',
| statement: "1 + #value",
| expected: #expected
| }
| ],
|
| variable_sets: [
| { value: 1, expected: (success 2) }
| ]
|}
|""".trimMargin(),
expectedErrorMessage = """
|Errors found when parsing test scripts:
| $inputBasePath/input[0].sqlts:5 - Invalid template value for field: for.template[0].description. Must start with '${'$'}' when it's a SYMBOL
""".trimMargin()
)
@Test
fun forTestTemplateWrongStatementType() = assertParseError(
input = """
|for::{
| template: [
| test::{
| id: test,
| statement: 'should be a string',
| expected: #expected
| }
| ],
|
| variable_sets: [
| { value: 1, expected: (success 2) }
| ]
|}
|""".trimMargin(),
expectedErrorMessage = """
|Errors found when parsing test scripts:
| $inputBasePath/input[0].sqlts:5 - Invalid template value for field: for.template[0].statement. Must start with '${'$'}' when it's a SYMBOL
""".trimMargin()
)
@Test
fun forTestTemplateMissingStatement() = assertParseError(
input = """
|for::{
| template: [
| test::{
| id: test,
| expected: #expected
| }
| ],
|
| variable_sets: [
| { value: 1, expected: (success 2) }
| ]
|}
|""".trimMargin(),
expectedErrorMessage = """
|Errors found when parsing test scripts:
| $inputBasePath/input[0].sqlts:3 - Missing required field: for.template[0].statement
""".trimMargin()
)
@Test
fun forTestTemplateWrongEnvironmentType() = assertParseError(
input = """
|for::{
| template: [
| test::{
| id: test,
| statement: "1 + #value",
| environment: "should be a struct",
| expected: #expected
| }
| ],
|
| variable_sets: [
| { value: 1, expected: (success 2) }
| ]
|}""".trimMargin(),
expectedErrorMessage = """
|Errors found when parsing test scripts:
| $inputBasePath/input[0].sqlts:6 - Wrong type for for.template[0].environment. Expected [STRUCT], got STRING
""".trimMargin()
)
@Test
fun forTestTemplateWrongExpectedType() = assertParseError(
input = """
|for::{
| template: [
| test::{
| id: test,
| statement: "1 + #value",
| expected: 'should be a SEXP'
| }
| ],
|
| variable_sets: [
| { value: 1, expected: (success 2) }
| ]
|}""".trimMargin(),
expectedErrorMessage = """
|Errors found when parsing test scripts:
| $inputBasePath/input[0].sqlts:7 - Invalid template value for field: for.template[0].expected. Must start with '${'$'}' when it's a SYMBOL
""".trimMargin()
)
@Test
fun forTestTemplateMissingExpected() = assertParseError(
input = """
|for::{
| template: [
| test::{
| id: test,
| statement: "1 + #value"
| }
| ],
|
| variable_sets: [
| { value: 1, expected: (success 2) }
| ]
|}
|""".trimMargin(),
expectedErrorMessage = """
|Errors found when parsing test scripts:
| $inputBasePath/input[0].sqlts:3 - Missing required field: for.template[0].expected
""".trimMargin()
)
@Test
fun forMissingTemplate() = assertParseError(
input = """
|for::{
| variable_sets: [
| { value: 1, expected: (success 2) }
| ]
|}
|""".trimMargin(),
expectedErrorMessage = """
|Errors found when parsing test scripts:
| $inputBasePath/input[0].sqlts:1 - Missing required field: for.template
""".trimMargin()
)
@Test
fun forWrongVariableSetType() = assertParseError(
input = """
|for::{
| template: [
| test::{
| id: test,
| statement: "1 + #value",
| expected: #expected
| }
| ],
|
| variable_sets: "should be a list"
|}
|""".trimMargin(),
expectedErrorMessage = """
|Errors found when parsing test scripts:
| $inputBasePath/input[0].sqlts:10 - Wrong type for for.variable_sets. Expected [LIST], got STRING
""".trimMargin()
)
@Test
fun forMissingVariableSet() = assertParseError(
input = """
|for::{
| template: [
| test::{
| id: test,
| statement: "1 + #value",
| expected: #expected
| }
| ]
|}
|""".trimMargin(),
expectedErrorMessage = """
|Errors found when parsing test scripts:
| $inputBasePath/input[0].sqlts:1 - Missing required field: for.variable_sets
""".trimMargin()
)
@Test
fun forWrongVariableSetElementType() = assertParseError(
input = """
|for::{
| template: [
| test::{
| id: test,
| statement: "1 + #value",
| expected: #expected
| }
| ],
|
| variable_sets: [
| "should be a struct"
| ]
|}
|""".trimMargin(),
expectedErrorMessage = """
|Errors found when parsing test scripts:
| $inputBasePath/input[0].sqlts:11 - Wrong type for variable_sets[0]. Expected [STRUCT], got STRING
""".trimMargin()
)
@Test
fun forEmptyVariableSet() = assertParseError(
input = """
|for::{
| template: [
| test::{
| id: test,
| statement: "1 + #value",
| expected: #expected
| }
| ],
|
| variable_sets: []
|}
|""".trimMargin(),
expectedErrorMessage = """
|Errors found when parsing test scripts:
| $inputBasePath/input[0].sqlts:1 - Field must have at least one element: for.variable_sets
""".trimMargin()
)
@Test
fun forUnknownField() = assertParseError(
input = """
|for::{
| template: [
| test::{
| id: test,
| statement: "1 + #value",
| expected: #expected
| }
| ],
|
| shouldNotBeHere: 1,
|
| variable_sets: [
| { value: 1, expected: (success 2) }
| ]
|}
|""".trimMargin(),
expectedErrorMessage = """
|Errors found when parsing test scripts:
| $inputBasePath/input[0].sqlts:10 - Unexpected field: for.shouldNotBeHere
""".trimMargin()
)
@Test
fun forUnknownVariable() = assertParseError(
input = """
|for::{
| template: [
| test::{
| id: test,
| statement: "1 + #unknown",
| expected: #expected
| }
| ],
|
| variable_sets: [
| { expected: (success 2) }
| ]
|}
|""".trimMargin(),
expectedErrorMessage = """
|Errors found when parsing test scripts:
| $inputBasePath/input[0].sqlts:11 - Missing template variable: unknown
""".trimMargin()
)
@Test
fun forInvalidExpectedVariable() = assertParseError(
input = """
|for::{
| template: [
| test::{
| id: test,
| statement: "1 + 1",
| expected: #expected
| }
| ],
|
| variable_sets: [
| { expected: (success) }
| ]
|}
|""".trimMargin(),
expectedErrorMessage = """
|Errors found when parsing test scripts:
| $inputBasePath/input[0].sqlts:11 - for.template.expected success must have two elements, e.g. (success (bag {a: 1}))
""".trimMargin()
)
}
| 188
| null |
55
| 519
|
ff041b28c6db53853c3b370690246bc01913a400
| 18,478
|
partiql-lang-kotlin
|
Apache License 2.0
|
src/main/kotlin/de/tweerlei/plumber/pipeline/steps/dynamodb/DynamoDBPutStep.kt
|
tweerlei
| 450,150,451
| false
| null |
/*
* Copyright 2022 <NAME> + Buchmeier GbR - http://www.tweerlei.de/
*
* 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 de.tweerlei.plumber.pipeline.steps.dynamodb
import com.fasterxml.jackson.databind.ObjectMapper
import de.tweerlei.plumber.pipeline.PipelineParams
import de.tweerlei.plumber.pipeline.steps.ProcessingStep
import de.tweerlei.plumber.pipeline.steps.toWorkItemStringAccessor
import de.tweerlei.plumber.worker.Worker
import de.tweerlei.plumber.worker.impl.dynamodb.DynamoDBClientFactory
import de.tweerlei.plumber.worker.impl.dynamodb.DynamoDBPutWorker
import org.springframework.stereotype.Service
@Service("dynamodb-writeWorker")
class DynamoDBPutStep(
private val dynamoDBClientFactory: DynamoDBClientFactory,
private val objectMapper: ObjectMapper
): ProcessingStep {
override val group = "AWS DynamoDB"
override val name = "Put DynamoDB item"
override val description = "Write an element to the given DynamoDB table"
override val help = """
This will write the current record, if any. Otherwise the current value will be used.
If the argument is omitted, the table name will be taken from a previously read DynamoDB item.
""".trimIndent()
override val options = ""
override val example = """
value:123
record-set:ItemID
value:foo
record-set:Name
value:true
record-set:InStock
dynamodb-write:myTable
""".trimIndent()
override val argDescription = "<table>"
override val argInterpolated = true
override fun createWorker(
arg: String,
w: Worker,
predecessorName: String,
params: PipelineParams,
parallelDegree: Int
) =
dynamoDBClientFactory.createAmazonDynamoDBClient(parallelDegree, params.assumeRoleArn)
.let { client ->
DynamoDBPutWorker(
arg.toWorkItemStringAccessor(),
client,
objectMapper,
w
)
}
}
| 0
|
Kotlin
|
0
| 2
|
ea5ec4d291f6a4a17dc507378e368d6216605926
| 2,555
|
plumber
|
Apache License 2.0
|
src/main/kotlin/io/github/gciatto/kt/mpp/DefaultProperties.kt
|
gciatto
| 611,832,186
| false
| null |
package org.spectralpowered.speck.plugin
interface DefaultProperties {
val disableJavadocTask: PropertyDescriptor
get() = PropertyDescriptor(
name = "disableJavadocTask",
description = "If true, default javadoc task will be disabled",
mandatory = false,
defaultValue = true,
)
val allWarningsAsErrors: PropertyDescriptor
get() = PropertyDescriptor(
name = "allWarningsAsErrors",
description = "If true, the Kotlin compiler will consider all warnings as errors",
mandatory = false,
defaultValue = true,
)
val developerIdEmail: PropertyDescriptor
get() = PropertyDescriptor(
name = "developer<ID>Email",
description = "The email of developer <ID> (useful for Maven/NPM publications)",
mandatory = false,
defaultValue = null,
)
val developerIdName: PropertyDescriptor
get() = PropertyDescriptor(
name = "developerIdName",
description = "The full name of developer <ID> (useful for Maven/NPM publications)",
mandatory = false,
defaultValue = null,
)
val developerIdOrg: PropertyDescriptor
get() = PropertyDescriptor(
name = "developerIdOrg",
description = "Reference to the organization <ORG> of developer <ID> (useful for Maven/NPM publications)",
mandatory = false,
defaultValue = null,
)
val developerIdUrl: PropertyDescriptor
get() = PropertyDescriptor(
name = "developerIdUrl",
description = "The homepage URL of developer <ID> (useful for Maven/NPM publications)",
mandatory = false,
defaultValue = null,
)
val issuesEmail: PropertyDescriptor
get() = PropertyDescriptor(
name = "issuesEmail",
description = "Issue tracking email (useful for Maven/NPM publications)",
mandatory = false,
defaultValue = null,
)
val issuesUrl: PropertyDescriptor
get() = PropertyDescriptor(
name = "issuesUrl",
description = "Issue tracking web page URL (useful for Maven/NPM publications)",
mandatory = false,
defaultValue = null,
)
val ktCompilerArgs: PropertyDescriptor
get() = PropertyDescriptor(
name = "ktCompilerArgs",
description = "Free compiler arguments to be passed to the Kotlin compiler, for all platforms",
mandatory = true,
defaultValue = "",
)
val ktCompilerArgsJs: PropertyDescriptor
get() = PropertyDescriptor(
name = "ktCompilerArgsJs",
description = "Free compiler arguments to be passed to the Kotlin compiler when compiling JS sources",
mandatory = true,
defaultValue = "",
)
val ktCompilerArgsJvm: PropertyDescriptor
get() = PropertyDescriptor(
name = "ktCompilerArgsJvm",
description = "Free compiler arguments to be passed to the Kotlin compiler when compiling JVM sources",
mandatory = true,
defaultValue = "",
)
val ktTargetJsDisable: PropertyDescriptor
get() = PropertyDescriptor(
name = "ktTargetJsDisable",
description = "If true, disables the JS target on a multi-platform project",
mandatory = false,
defaultValue = false,
)
val ktTargetJvmDisable: PropertyDescriptor
get() = PropertyDescriptor(
name = "ktTargetJvmDisable",
description = "If true, disables the JVM target on a multi-platform project",
mandatory = false,
defaultValue = false,
)
val repoOwner: PropertyDescriptor
get() = PropertyDescriptor(
name = "repoOwner",
description = "Name of the GitHub user/organization owning the repository of this project. " +
"Setting this property will assign default values to the following properties in case they " +
"are unset/blank: <projectHomepage>, <scmUrl>, and <scmConnection>",
mandatory = false,
defaultValue = null,
)
val mavenCentralPassword: PropertyDescriptor
get() = PropertyDescriptor(
name = "mavenCentralPassword",
description = "The password of the user willing to release Maven publications on Maven Central",
mandatory = false,
defaultValue = null,
)
val mavenCentralUsername: PropertyDescriptor
get() = PropertyDescriptor(
name = "mavenCentralUsername",
description = "The username of the user willing to release Maven publications on Maven Central",
mandatory = false,
defaultValue = null,
)
val otherMavenRepo: PropertyDescriptor
get() = PropertyDescriptor(
name = "otherMavenRepo",
description = "The URL of Maven repository upon which Maven publications will be released",
mandatory = false,
defaultValue = "https://oss.sonatype.org/service/local/staging/deploy/maven2/",
)
val otherMavenPassword: PropertyDescriptor
get() = PropertyDescriptor(
name = "otherMavenPassword",
description = "The password of the user willing to release Maven publications on <mavenRepo>",
mandatory = false,
defaultValue = null,
)
val otherMavenUsername: PropertyDescriptor
get() = PropertyDescriptor(
name = "otherMavenUsername",
description = "The username of the user willing to release Maven publications on <mavenRepo>",
mandatory = false,
defaultValue = null,
)
val mochaTimeout: PropertyDescriptor
get() = PropertyDescriptor(
name = "mochaTimeout",
description = "The amount of time to be ",
mandatory = true,
defaultValue = "180s",
)
val npmDryRun: PropertyDescriptor
get() = PropertyDescriptor(
name = "npmDryRun",
description = "If true, release of NPM packages will simply be simulated (i.e., no actual release)",
mandatory = false,
defaultValue = false,
)
val npmOrganization: PropertyDescriptor
get() = PropertyDescriptor(
name = "npmOrganization",
description = "If non-blank, Kotlin JS projects will be released as NPM packages named " +
"@<npmOrganization>/<rootProject.name>-<project.name>, otherwise the package name will simply " +
"be <rootProject.name>-<project.name>",
mandatory = false,
defaultValue = "",
)
val npmRepo: PropertyDescriptor
get() = PropertyDescriptor(
name = "npmRepo",
description = "The URL of NPM registry upon which NPM publications will be released." +
"If missing or blank, https://registry.npmjs.org will be used",
mandatory = false,
defaultValue = "https://registry.npmjs.org",
)
val npmToken: PropertyDescriptor
get() = PropertyDescriptor(
name = "npmToken",
description = "The authentication token of the user willing to release NPM publications on <npmRepo>",
mandatory = false,
defaultValue = null,
)
val orgName: PropertyDescriptor
get() = PropertyDescriptor(
name = "<ORG>Name",
description = "The full name of organization <ORG> (useful for Maven/NPM publications)",
mandatory = false,
defaultValue = null,
)
val orgUrl: PropertyDescriptor
get() = PropertyDescriptor(
name = "<ORG>Url",
description = "The URL of the homepage of organization <ORG> (useful for Maven/NPM publications)",
mandatory = false,
defaultValue = null,
)
val projectDescription: PropertyDescriptor
get() = PropertyDescriptor(
name = "projectDescription",
description = "Full project description (useful for Maven/NPM publications)",
mandatory = false,
defaultValue = null,
)
val projectHomepage: PropertyDescriptor
get() = PropertyDescriptor(
name = "projectHomepage",
description = "The URL of the project homepage (useful for Maven/NPM publications)",
mandatory = false,
defaultValue = null,
)
val projectLicense: PropertyDescriptor
get() = PropertyDescriptor(
name = "projectLicense",
description = "Acronym of the license of this project (useful for Maven/NPM publications)",
mandatory = false,
defaultValue = "Apache-2.0",
)
val projectLicenseUrl: PropertyDescriptor
get() = PropertyDescriptor(
name = "projectLicenseUrl",
description = "URL of the license of this project (useful for Maven/NPM publications)",
mandatory = false,
defaultValue = "https://www.apache.org/licenses/LICENSE-2.0",
)
val projectLongName: PropertyDescriptor
get() = PropertyDescriptor(
name = "projectLongName",
description = "Non-necessarily path-compliant project name (to be used in place of project.name for " +
"Maven/NPM publications)",
mandatory = false,
defaultValue = null,
)
val scmConnection: PropertyDescriptor
get() = PropertyDescriptor(
name = "scmConnection",
description = "The connection string for the DVCS repository hosting the code of this project" +
"(useful for Maven/NPM publications)",
mandatory = false,
defaultValue = null,
)
val scmUrl: PropertyDescriptor
get() = PropertyDescriptor(
name = "scmUrl",
description = "The URL of the DVCS repository hosting the code of this project " +
"(useful for Maven/NPM publications)",
mandatory = false,
defaultValue = null,
)
val signingKey: PropertyDescriptor
get() = PropertyDescriptor(
name = "signingKey",
description = "The ASCII-armored value of the private key to be used for signing Maven publications. " +
"It should be provided along with <signingPassword>. " +
"If missing or blank, publication artifact signing will be disabled",
mandatory = false,
defaultValue = "",
)
val signingPassword: PropertyDescriptor
get() = PropertyDescriptor(
name = "signingPassword",
description = "The passphrase of the private key to be used for signing Maven publications. " +
"It should be provided along with <signingPassword>. " +
"If missing or blank, publication artifact signing will be disabled",
mandatory = false,
defaultValue = "",
)
val useKotlinBom: PropertyDescriptor
get() = PropertyDescriptor(
name = "useKotlinBom",
description = "If true, the kotlin-bom dependency will be added to all kotlin projects",
mandatory = false,
defaultValue = false,
)
val versionsFromCatalog: PropertyDescriptor
get() = PropertyDescriptor(
name = "versionsFromCatalog",
description = "The name of the catalog from which Kotlin, JVM, and Node versions should be taken. " +
"Leave empty in case all declared catalogs should be considered, as well as if no one should",
mandatory = false,
defaultValue = "",
)
val nodeVersion: PropertyDescriptor
get() = PropertyDescriptor(
name = "nodeVersion",
description = "The version of NodeJS to use for running Kotlin JS scripts",
mandatory = false,
defaultValue = "",
)
val docStyle: PropertyDescriptor
get() = PropertyDescriptor(
name = "docStyle",
description = "The Dokka style to be used for Maven publications" +
" (one of {'html', 'gfm', 'javadoc', 'jekyll'})",
mandatory = false,
defaultValue = "html",
)
}
| 9
| null |
1
| 1
|
91176dd73b89c7ac59d39c82cebdc59680680687
| 12,711
|
kt-mpp
|
Apache License 2.0
|
app/src/main/java/com/words/storageapp/ui/main/di/MainModule.kt
|
emmasonn
| 451,215,073
| false
|
{"Kotlin": 311218}
|
package com.words.storageapp.ui.main.di
import android.app.Activity
import android.content.Context
import android.net.ConnectivityManager
import androidx.core.content.getSystemService
import com.words.storageapp.database.AppDatabase
import com.words.storageapp.di.SharedPreference
import com.words.storageapp.di.Storage
import com.words.storageapp.ui.main.MainActivity
import com.words.storageapp.util.utilities.ConnectivityChecker
import dagger.Binds
import dagger.Module
import dagger.Provides
@Module
abstract class MainModule {
@Binds
abstract fun context(activity: MainActivity): Context
@Module
companion object {
@JvmStatic
@Provides
fun provideAppDatabase(context: Context): AppDatabase = AppDatabase.getInstance(context)
@JvmStatic
@Provides
fun connectivityChecker(activity: Activity): ConnectivityChecker? {
val connectivityManager = activity.getSystemService<ConnectivityManager>()
return if (connectivityManager != null) {
ConnectivityChecker(connectivityManager)
} else {
null
}
}
}
}
| 0
|
Kotlin
|
0
| 1
|
84e4a537e3f45c21cf4ba121c78006f9fab889de
| 1,161
|
SkillHub
|
Apache License 2.0
|
mediator/src/test/kotlin/no/nav/dagpenger/mottak/behov/saksbehandling/arena/ArenaBehovLøserTest.kt
|
navikt
| 351,793,236
| false
|
{"Kotlin": 450030, "Dockerfile": 205}
|
package no.nav.dagpenger.mottak.behov.saksbehandling.arena
import com.github.navikt.tbd_libs.rapids_and_rivers.test_support.TestRapid
import io.mockk.coEvery
import io.mockk.mockk
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertDoesNotThrow
import java.time.LocalDateTime
import java.util.UUID
private const val JOURNALPOST_ID = "2345678"
internal class ArenaBehovLøserTest {
private val testRapid = TestRapid()
private val arenaOppslagMock =
mockk<ArenaOppslag>().also {
coEvery { it.opprettStartVedtakOppgave(any(), any()) } returns
OpprettVedtakOppgaveResponse(
fagsakId = "123",
oppgaveId = "123",
)
coEvery { it.opprettVurderHenvendelsOppgave(any(), any()) } returns
OpprettVedtakOppgaveResponse(
fagsakId = null,
oppgaveId = "123",
)
}
init {
ArenaBehovLøser(
arenaOppslag = arenaOppslagMock,
rapidsConnection = testRapid,
)
}
@BeforeEach
fun `clear rapid`() {
testRapid.reset()
}
@Test
fun `Løser OpprettStartVedtakOppgave behov`() {
testRapid.sendTestMessage(opprettStartVedtakBehov())
with(testRapid.inspektør) {
assertEquals(1, size)
assertDoesNotThrow { field(0, "@løsning") }
assertEquals("123", field(0, "@løsning")["OpprettStartVedtakOppgave"]["fagsakId"].asText())
assertEquals("123", field(0, "@løsning")["OpprettStartVedtakOppgave"]["oppgaveId"].asText())
assertEquals(JOURNALPOST_ID, field(0, "@løsning")["OpprettStartVedtakOppgave"]["journalpostId"].asText())
}
}
@Test
fun `Løser 0pprettVurderhenvendelseOppgave behov`() {
testRapid.sendTestMessage(opprettVurderhenvendelseOppgaveBehov())
with(testRapid.inspektør) {
assertEquals(1, size)
assertDoesNotThrow { field(0, "@løsning") }
assertEquals(null, field(0, "@løsning")["OpprettVurderhenvendelseOppgave"]["fagsakId"].textValue())
assertEquals("123", field(0, "@løsning")["OpprettVurderhenvendelseOppgave"]["oppgaveId"].asText())
assertEquals(JOURNALPOST_ID, field(0, "@løsning")["OpprettVurderhenvendelseOppgave"]["journalpostId"].asText())
}
}
@Test
fun `Løser OpprettStartVedtakOppgave ved feil (null response)`() {
coEvery { arenaOppslagMock.opprettStartVedtakOppgave(any(), any()) } returns null
testRapid.sendTestMessage(opprettStartVedtakBehov())
with(testRapid.inspektør) {
assertEquals(1, size)
assertDoesNotThrow { field(0, "@løsning") }
assertEquals("Kunne ikke opprettet Arena oppgave", field(0, "@løsning")["OpprettStartVedtakOppgave"]["@feil"].asText())
}
}
@Test
fun `Løser 0pprettVurderhenvendelseOppgave ved feil (null response)`() {
coEvery { arenaOppslagMock.opprettVurderHenvendelsOppgave(any(), any()) } returns null
testRapid.sendTestMessage(opprettVurderhenvendelseOppgaveBehov())
with(testRapid.inspektør) {
assertEquals(1, size)
assertDoesNotThrow { field(0, "@løsning") }
assertEquals("Kunne ikke opprettet Arena oppgave", field(0, "@løsning")["OpprettVurderhenvendelseOppgave"]["@feil"].asText())
}
}
//language=JSON
private fun opprettStartVedtakBehov(): String =
"""
{
"@event_name": "behov",
"@id": "${UUID.randomUUID()}",
"@behovId": "${UUID.randomUUID()}",
"@behov": [
"OpprettStartVedtakOppgave"
],
"@opprettet" : "${LocalDateTime.now()}",
"journalpostId": "$JOURNALPOST_ID",
"fødselsnummer": "12345678910",
"behandlendeEnhetId": "1235",
"oppgavebeskrivelse": "beskrivende beskrivelse",
"registrertDato": "${LocalDateTime.now()}",
"tilleggsinformasjon": "I tillegg til informasjonen kommer det noen ganger tileggsinformasjon"
}
""".trimIndent()
//language=JSON
private fun opprettVurderhenvendelseOppgaveBehov(): String =
"""
{
"@event_name": "behov",
"@id": "${UUID.randomUUID()}",
"@behovId": "${UUID.randomUUID()}",
"@behov": [
"OpprettVurderhenvendelseOppgave"
],
"@opprettet" : "${LocalDateTime.now()}",
"journalpostId": "$JOURNALPOST_ID",
"fødselsnummer": "12345678910",
"behandlendeEnhetId": "1235",
"oppgavebeskrivelse": "beskrivende beskrivelse",
"registrertDato": "${LocalDateTime.now()}",
"tilleggsinformasjon": "I tillegg til informasjonen kommer det noen ganger tileggsinformasjon"
}
""".trimIndent()
}
| 3
|
Kotlin
|
0
| 0
|
df1f48afdb1439a192432ac547b6b985cda2c414
| 5,003
|
dp-mottak
|
MIT License
|
domain/src/commonMain/kotlin/uk/co/sentinelweb/cuer/app/db/repository/file/JsonFileInteractor.kt
|
sentinelweb
| 220,796,368
| false
|
{"Kotlin": 2627352, "CSS": 205156, "Java": 98919, "Swift": 85812, "HTML": 19322, "JavaScript": 12105, "Ruby": 2170}
|
package uk.co.sentinelweb.cuer.app.db.repository.file
class FileInteractor(
private val file: AFile,
private val operation: PlatformFileOperation
) {
fun loadJson(): String? = try {
operation.readBytes(file).decodeToString()
} catch (e: Exception) {
null
}
fun saveJson(data: String) {
operation.writeBytes(file, data.encodeToByteArray())
}
fun exists() =
operation.exists(file)
}
| 94
|
Kotlin
|
0
| 2
|
f74e211570fe3985ba45848b228e91a3a8593788
| 448
|
cuer
|
Apache License 2.0
|
fluxo-kmp-conf/src/main/kotlin/fluxo/conf/feat/SetupAndroidLint.kt
|
fluxo-kt
| 705,309,218
| false
|
{"Kotlin": 416263}
|
package fluxo.conf.feat
import com.android.build.api.dsl.CommonExtension
import com.android.build.gradle.internal.lint.AndroidLintAnalysisTask
import com.android.build.gradle.internal.lint.AndroidLintTask
import com.android.build.gradle.internal.lint.AndroidLintTextOutputTask
import com.android.build.gradle.internal.tasks.AndroidVariantTask
import fluxo.conf.FluxoKmpConfContext
import fluxo.conf.dsl.container.impl.KmpTargetCode
import fluxo.conf.dsl.impl.FluxoConfigurationExtensionImpl
import fluxo.conf.impl.configureExtension
import fluxo.conf.impl.disableTask
import fluxo.conf.impl.ifNotEmpty
import fluxo.conf.impl.withType
import io.gitlab.arturbosch.detekt.report.ReportMergeTask
import org.gradle.api.Project
import org.gradle.api.tasks.TaskProvider
import org.gradle.language.base.plugins.LifecycleBasePlugin.CHECK_TASK_NAME
private const val MERGE_LINT_TASK_NAME = "mergeLintSarif"
internal fun FluxoKmpConfContext.registerLintMergeRootTask(): TaskProvider<ReportMergeTask>? =
registerReportMergeTask(
name = MERGE_LINT_TASK_NAME,
description = "Merges all Lint reports from all modules to the root one",
filePrefix = "lint",
)
internal fun Project.setupAndroidLint(
conf: FluxoConfigurationExtensionImpl,
ignoredBuildTypes: List<String>,
ignoredFlavors: List<String>,
) {
val context = conf.context
val disableLint = context.testsDisabled || !context.isTargetEnabled(KmpTargetCode.ANDROID)
configureExtension("android", CommonExtension::class) {
lint {
sarifReport = !disableLint
htmlReport = !disableLint
textReport = !disableLint
xmlReport = false
// Use baseline only for CI checks, show all problems in local development.
// Don't use if file doesn't exist, and we're running the `check` task.
if (context.isCI || context.isRelease) {
val file = file("lint-baseline.xml")
if (file.exists() || CHECK_TASK_NAME !in context.startTaskNames) {
baseline = file
}
}
abortOnError = false
absolutePaths = false
checkAllWarnings = !disableLint
checkDependencies = false
checkReleaseBuilds = !disableLint
explainIssues = false
noLines = true
warningsAsErrors = !disableLint
}
}
if (!disableLint) {
context.mergeLintTask?.let { mergeLint ->
tasks.withType<AndroidLintTask> {
val lintTask = this
if (name.startsWith("lintReport")) {
mergeLint.configure {
input.from(lintTask.sarifReportOutputFile)
dependsOn(lintTask)
}
}
}
}
}
val variants = (ignoredBuildTypes + ignoredFlavors)
.ifNotEmpty { toHashSet().toTypedArray() }
if (variants.isNullOrEmpty()) {
return
}
val disableIgnoredVariants: AndroidVariantTask.() -> Unit = {
if (enabled) {
for (v in variants) {
if (name.contains(v, ignoreCase = true)) {
disableTask()
break
}
}
}
}
tasks.withType<AndroidLintTextOutputTask>(disableIgnoredVariants)
tasks.withType<AndroidLintAnalysisTask>(disableIgnoredVariants)
tasks.withType<AndroidLintTask>(disableIgnoredVariants)
}
| 5
|
Kotlin
|
0
| 1
|
8521cd7e0a0d02453603f8e6f736308ff06e1d01
| 3,517
|
fluxo-kmp-conf
|
Apache License 2.0
|
app/src/main/java/com/fafadiatech/newscout/activity/SourceActivity.kt
|
Vicky-Vicky27
| 484,837,384
| true
|
{"Kotlin": 430654}
|
package com.fafadiatech.newscout.activity
import android.content.Context
import android.content.SharedPreferences
import android.content.res.Configuration
import android.content.res.Resources
import android.os.Bundle
import android.util.DisplayMetrics
import android.view.View
import android.view.WindowManager
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import androidx.paging.LivePagedListBuilder
import androidx.paging.PageKeyedDataSource
import androidx.paging.PagedList
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.fafadiatech.newscout.R
import com.fafadiatech.newscout.adapter.NewsAdapter
import com.fafadiatech.newscout.api.ApiClient
import com.fafadiatech.newscout.api.ApiInterface
import com.fafadiatech.newscout.appconstants.AppConstant
import com.fafadiatech.newscout.appconstants.NEWSPAGESIZE
import com.fafadiatech.newscout.db.NewsEntity
import com.fafadiatech.newscout.interfaces.PlaceHolderImageListener
import com.fafadiatech.newscout.model.ArticlesData
import com.fafadiatech.newscout.paging.SourceDataSourceFactory
import com.fafadiatech.newscout.paging.SourceItemDataSource
class SourceActivity : AppCompatActivity(), PlaceHolderImageListener {
lateinit var interfaceObj: ApiInterface
var list = ArrayList<ArticlesData>()
var newsList = ArrayList<NewsEntity>()
lateinit var adapter: NewsAdapter
lateinit var itemPagedList: LiveData<PagedList<NewsEntity>>
lateinit var liveDataSource: LiveData<PageKeyedDataSource<Int, NewsEntity>>
var source: String = ""
var deviceWidthDp: Float = 0f
lateinit var layoutManager: RecyclerView.LayoutManager
lateinit var placeHolderListener: PlaceHolderImageListener
lateinit var themePreference: SharedPreferences
lateinit var fabReturnTop: com.github.clans.fab.FloatingActionButton
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
placeHolderListener = this
if (resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {
val displayMetrics = DisplayMetrics()
val windowmanager = this.getSystemService(Context.WINDOW_SERVICE) as WindowManager
windowmanager.defaultDisplay.getMetrics(displayMetrics)
val deviceWidth = displayMetrics.widthPixels
deviceWidthDp = deviceWidth / Resources.getSystem().getDisplayMetrics().density
if (deviceWidthDp < 600) {
}
}
themePreference = this.getSharedPreferences(AppConstant.APPPREF, Context.MODE_PRIVATE)
var themes: Int = themePreference.getInt("theme", R.style.DefaultMedium)
var isNightModeEnable = themePreference.getBoolean("night mode enable", false)
this.setTheme(themes)
setContentView(R.layout.activity_source)
var rvSource = findViewById<RecyclerView>(R.id.rv_source)
var emptyView = findViewById<TextView>(R.id.empty_view)
var toolbarTitle = findViewById<TextView>(R.id.toolbar_title)
emptyView.visibility = View.GONE
interfaceObj = ApiClient.getClient().create(ApiInterface::class.java)
var adapterObj = NewsAdapter(this, "Source")
fabReturnTop = findViewById(R.id.fab_return_top)
val itemDecorator = DividerItemDecoration(this, DividerItemDecoration.VERTICAL)
if (deviceWidthDp < 600) {
layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
} else {
itemDecorator.setDrawable(ContextCompat.getDrawable(this, R.drawable.news_item_divider_tab_horizontal)!!)
layoutManager = GridLayoutManager(this, 3, RecyclerView.VERTICAL, false)
val hDivider = DividerItemDecoration(this, DividerItemDecoration.HORIZONTAL)
hDivider.setDrawable(ContextCompat.getDrawable(this, R.drawable.news_item_divider_verticle)!!)
}
rvSource.layoutManager = layoutManager
rvSource.adapter = adapterObj
var intent = intent
var source = intent.getStringExtra("source_from_detail")
val itemDataSourceFactory = SourceDataSourceFactory(this.application, source)
toolbarTitle.text = source
liveDataSource = itemDataSourceFactory.itemLiveDataSource
val pagedListConfig = PagedList.Config.Builder()
.setEnablePlaceholders(false)
.setPageSize(NEWSPAGESIZE).build()
itemPagedList = LivePagedListBuilder(itemDataSourceFactory, pagedListConfig)
.build()
itemPagedList.observe(this, Observer<PagedList<NewsEntity>> {
adapterObj.submitList(it)
})
fabReturnTop.setOnClickListener {
rvSource.smoothScrollToPosition(0)
}
}
override fun onResume() {
super.onResume()
}
override fun onStop() {
super.onStop()
}
}
| 0
| null |
0
| 0
|
aa136721998e6c1fa0ab1e2fa1215584a1384b84
| 5,150
|
newscout_android
|
Apache License 2.0
|
src/main/kotlin/vec/useCase/service/PrincipalService.kt
|
tmyksj
| 374,243,992
| false
| null |
package vec.useCase.service
import org.springframework.web.server.ServerWebExchange
import reactor.core.publisher.Mono
import vec.domain.entity.User
/**
* Principal に関するサービスです。
*/
interface PrincipalService {
/**
* Principal を clear します。
* @param serverWebExchange serverWebExchange
* @return clear されたユーザ
*/
fun clear(serverWebExchange: ServerWebExchange): Mono<User>
/**
* Principal を reload します。
* @param serverWebExchange serverWebExchange
* @return reload されたユーザ
*/
fun reload(serverWebExchange: ServerWebExchange): Mono<User>
}
| 13
|
Kotlin
|
0
| 1
|
751465126e6ee9b2c75989e9b437540009ac9a6b
| 597
|
vec
|
Apache License 2.0
|
src/main/kotlin/mingle/chang/api/entities/AppEntity.kt
|
MingleChang
| 217,474,426
| false
| null |
package mingle.chang.api.entities
import mingle.chang.api.utils.AppUtils
import org.hibernate.annotations.GenericGenerator
import org.springframework.beans.factory.annotation.Value
import java.util.*
import javax.persistence.*
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@Entity
@Table(name = "app")
@EntityListeners(AuditingEntityListener::class)
data class App (
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid")
@Column(name = "id", length = 34)
var id: String = "",
@Column(name = "name")
var name: String = "",
@Column(name = "display_name")
var displayName : String = "",
@Column(name = "package_id")
var packageId: String = "",
@Column(name = "version")
var version: String = "",
@Column(name = "build_version")
var buildVersion: String = "",
@Column(name = "platform")
var platform: String = "",
@Column(name = "environment")
var environment: String = "",
@Column(name = "file_name")
var fileName: String = UUID.randomUUID().toString(),
@Column(name = "download_count")
var downloadCount: Long = 0,
@Column(name = "created_date")
@CreatedDate
var createdDate: Date? = null,
@Column(name = "modified_date")
@LastModifiedDate
var modifiedDate: Date? = null
){
fun fileAddress(host: String): String {
return host + "/app/download/" + this.id
}
}
| 0
|
Kotlin
|
0
| 0
|
35744998e64c9d2dd6fb88842d47fc7e53542910
| 1,718
|
api_kotlin
|
MIT License
|
VPAwesomeWidgets/src/main/java/awesome/vrund/vpawesomewidgets/VPBackTextView.kt
|
VrUnd14
| 288,725,242
| false
| null |
package awesome.vrund.vpawesomewidgets
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
class VPBackTextView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = android.R.attr.textViewStyle) : AppCompatTextView(context, attrs, defStyleAttr) {
private val mContext = context
var backColor = Color.TRANSPARENT
set(value) {
field = value
val dg = this.background as GradientDrawable
dg.setColor(backColor)
}
var isCapsule = false
set(value) {
field = value
setCorners()
}
var cornerRadiusTopLeft = 0F
set(value) {
field = value
setCorners()
}
var cornerRadiusBottomLeft = 0F
set(value) {
field = value
setCorners()
}
var cornerRadiusTopRight = 0F
set(value) {
field = value
setCorners()
}
var cornerRadiusBottomRight = 0F
set(value) {
field = value
setCorners()
}
var borderColor = Color.BLACK
set(value) {
field = value
val dg = this.background as GradientDrawable
dg.setStroke(borderWidth.takeIf { hasBorder } ?: 0, borderColor)
}
var borderWidth = 0
set(value) {
field = value
val dg = this.background as GradientDrawable
dg.setStroke(borderWidth.takeIf { hasBorder } ?: 0, borderColor)
}
var hasBorder = true
set(value) {
field = value
val dg = this.background as GradientDrawable
dg.setStroke(borderWidth.takeIf { hasBorder } ?: 0, borderColor)
}
init {
val shape = GradientDrawable()
shape.shape = GradientDrawable.RECTANGLE
this.background = shape
val parent = mContext.obtainStyledAttributes(attrs, R.styleable.VPBackTextView)
backColor = parent.getColor(R.styleable.VPBackTextView_backColor, backColor)
isCapsule = parent.getBoolean(R.styleable.VPBackTextView_isCapsule, isCapsule)
cornerRadiusTopLeft = parent.getDimensionPixelSize(R.styleable.VPBackTextView_cornerRadiusTopLeft, 0).toFloat()
cornerRadiusTopRight = parent.getDimensionPixelSize(R.styleable.VPBackTextView_cornerRadiusTopRight, 0).toFloat()
cornerRadiusBottomLeft = parent.getDimensionPixelSize(R.styleable.VPBackTextView_cornerRadiusBottomLeft, 0).toFloat()
cornerRadiusBottomRight = parent.getDimensionPixelSize(R.styleable.VPBackTextView_cornerRadiusBottomRight, 0).toFloat()
borderColor = parent.getColor(R.styleable.VPBackTextView_borderColor, borderColor)
borderWidth = parent.getDimensionPixelSize(R.styleable.VPBackTextView_borderWidth, borderWidth)
hasBorder = parent.getBoolean(R.styleable.VPBackTextView_hasBorder, hasBorder)
parent.recycle()
}
private fun setCorners() {
val dg = this.background as GradientDrawable
if (isCapsule)
dg.cornerRadii = floatArrayOf(200F, 200F, 200F, 200F, 200F, 200F, 200F, 200F)
else
dg.cornerRadii = floatArrayOf(cornerRadiusTopLeft, cornerRadiusTopLeft, cornerRadiusTopRight, cornerRadiusTopRight, cornerRadiusBottomRight, cornerRadiusBottomRight, cornerRadiusBottomLeft, cornerRadiusBottomLeft)
}
}
| 0
|
Kotlin
|
0
| 1
|
d2c861dd557f4f78f35cf5bc8b646a5eacc1f20a
| 3,543
|
VPAwesomeWidgets
|
Apache License 2.0
|
library/src/main/java/com/speshiou/android/common/ui/ads/AdUtils.kt
|
speshiou
| 116,790,796
| false
| null |
package com.speshiou.android.common.ui.ads
class AdUtils {
companion object {
var AD_ENABLED = true
fun setAdEnabled(enabled: Boolean) {
AD_ENABLED = enabled
}
fun insertAdData(adViewRecycler: AdViewRecycler, data: Array<Any>, adPositions: Array<Int>, adType: String, adId: String): Array<Any> {
if (AD_ENABLED && data.isNotEmpty() && AdType.allTypes.contains(adType) && adPositions.isNotEmpty() && adType.isNotBlank() && adId.isNotBlank()) {
var updatedData = arrayListOf<Any>()
updatedData.addAll(data)
var admobTask: LoadAdTask? = null
val admobNumInBundle = 2
adPositions.forEachIndexed { index, i ->
if (i > -1) {
var insertToIndex = -1
if (i <= data.size) {
insertToIndex = i + index
} else if (updatedData[updatedData.lastIndex] !is LoadAdTask) {
// insertToIndex = updatedData.lastIndex + 1
}
if (adType == AdType.AD_ADMOB_NATIVE && index % admobNumInBundle == 0) {
admobTask = getAdData(adViewRecycler, adType, adId, -1, admobNumInBundle)
}
if (insertToIndex > -1) {
var adTask: LoadAdTask? = null
if (admobTask != null) {
if (admobTask is LoadAdTaskAdapter) {
adTask = admobTask
} else {
admobTask?.apply {
adTask = LoadAdTaskAdapter(this, index % admobNumInBundle)
}
}
} else {
adTask = getAdData(adViewRecycler, adType, adId, index, adPositions.size)
}
adTask?.apply {
updatedData.add(insertToIndex, this)
}
}
}
}
return updatedData.toTypedArray()
} else {
return data
}
}
private fun getAdData(adViewRecycler: AdViewRecycler, adType: String, adId: String, index: Int, totalAds: Int): LoadAdTask? {
val adTask = adViewRecycler.obtainAdTask(adType, adId, -1)
if (adTask != null) {
if (adTask is LoadCSATask) {
adTask.page = index + 1
} else if (adTask is LoadGoogleAdsNativeAdTask) {
adTask.adCount = totalAds
}
}
return adTask
}
}
}
| 0
|
Kotlin
|
0
| 0
|
42520c587bd583e1397d80002405332cbc52aba8
| 2,916
|
android-common
|
MIT License
|
ton-kotlin-contract/src/commonMain/kotlin/org/ton/contract/wallet/WalletV4R2Contract.kt
|
andreypfau
| 448,983,229
| false
| null |
package org.ton.contract.wallet
import kotlinx.coroutines.coroutineScope
import kotlinx.datetime.Clock
import kotlinx.datetime.Instant
import org.ton.api.pk.PrivateKeyEd25519
import org.ton.api.pub.PublicKeyEd25519
import org.ton.api.tonnode.TonNodeBlockIdExt
import org.ton.bitstring.BitString
import org.ton.block.*
import org.ton.boc.BagOfCells
import org.ton.cell.Cell
import org.ton.cell.CellBuilder
import org.ton.contract.SmartContract
import org.ton.contract.wallet.WalletContract.Companion.DEFAULT_WALLET_ID
import org.ton.crypto.base64
import org.ton.lite.api.LiteApi
import org.ton.lite.client.LiteClient
import org.ton.tlb.CellRef
import org.ton.tlb.constructor.AnyTlbConstructor
import org.ton.tlb.storeRef
import kotlin.jvm.JvmField
import kotlin.jvm.JvmStatic
import kotlin.time.Duration.Companion.seconds
public class WalletV4R2Contract private constructor(
override val address: MsgAddressInt,
public override val state: AccountState
) : WalletContract<Cell> {
public constructor(
workchain: Int,
init: StateInit
) : this(SmartContract.address(workchain, init), AccountUninit)
public constructor(
workchain: Int,
publicKey: PublicKeyEd25519,
) : this(workchain, createStateInit(publicKey, DEFAULT_WALLET_ID + workchain))
public constructor(
accountInfo: AccountInfo
) : this(accountInfo.addr, accountInfo.storage.state)
override fun loadData(): Cell? = data
public fun getSeqno(): Int = requireNotNull(data).beginParse().run {
preloadInt(32).toInt()
}
public fun getSubWalletId(): Int = requireNotNull(data).beginParse().run {
skipBits(32)
preloadInt(32).toInt()
}
public fun getPublicKey(): PublicKeyEd25519 = requireNotNull(data).beginParse().run {
skipBits(64)
PublicKeyEd25519(loadBits(256).toByteArray())
}
public suspend fun transfer(
liteApi: LiteApi,
privateKey: PrivateKeyEd25519,
vararg transfers: WalletTransfer
): Unit = transfer(liteApi, privateKey, Clock.System.now() + 60.seconds, *transfers)
public suspend fun transfer(
liteApi: LiteApi,
privateKey: PrivateKeyEd25519,
validUntil: Instant,
vararg transfers: WalletTransfer
): Unit = coroutineScope {
val seqno = if (state !is AccountActive) 0 else getSeqno()
val walletId = if (state !is AccountActive) DEFAULT_WALLET_ID else getSubWalletId()
val message = createTransferMessage(
address = address,
stateInit = if (state !is AccountActive) createStateInit(privateKey.publicKey(), walletId) else null,
privateKey = privateKey,
validUntil = validUntil.epochSeconds.toInt(),
walletId = walletId,
seqno = seqno,
transfers = transfers
)
sendExternalMessage(liteApi, AnyTlbConstructor, message)
}
private companion object {
@JvmField
val CODE =
BagOfCells(base64("<KEY>)).first()
@JvmField
val OP_TRANSFER = 0
@JvmStatic
suspend fun loadContract(liteClient: LiteClient, address: AddrStd): WalletV4R2Contract? {
val blockId = liteClient.getLastBlockId()
return loadContract(liteClient, blockId, address)
}
@JvmStatic
suspend fun loadContract(
liteClient: LiteClient,
blockId: TonNodeBlockIdExt,
address: AddrStd
): WalletV4R2Contract? {
val accountInfo = liteClient.getAccountState(address, blockId)
return WalletV4R2Contract(accountInfo.account.value as? AccountInfo ?: return null)
}
@JvmStatic
fun createTransferMessage(
address: MsgAddressInt,
stateInit: StateInit?,
privateKey: PrivateKeyEd25519,
walletId: Int,
validUntil: Int,
seqno: Int,
vararg transfers: WalletTransfer
): Message<Cell> {
val info = ExtInMsgInfo(
src = AddrNone,
dest = address,
importFee = Coins()
)
val maybeStateInit =
Maybe.of(stateInit?.let { Either.of<StateInit, CellRef<StateInit>>(null, CellRef(it)) })
val transferBody = createTransferMessageBody(
privateKey,
walletId,
validUntil,
seqno,
*transfers
)
val body = Either.of<Cell, CellRef<Cell>>(null, CellRef(transferBody))
return Message(
info = info,
init = maybeStateInit,
body = body
)
}
@JvmStatic
fun createStateInit(
publicKey: PublicKeyEd25519,
walletId: Int,
): StateInit {
val data = CellBuilder.createCell {
storeUInt(0, 32) // seqno
storeUInt(walletId, 32)
storeBytes(publicKey.key.toByteArray())
storeBit(false) // plugins
}
return StateInit(
code = CODE,
data = data
)
}
private fun createTransferMessageBody(
privateKey: PrivateKeyEd25519,
walletId: Int,
validUntil: Int,
seqno: Int,
vararg gifts: WalletTransfer
): Cell {
val unsignedBody = CellBuilder.createCell {
storeUInt(walletId, 32)
storeUInt(validUntil, 32)
storeUInt(seqno, 32)
storeUInt(OP_TRANSFER, 8) // op
for (gift in gifts) {
var sendMode = 3
if (gift.sendMode > -1) {
sendMode = gift.sendMode
}
val intMsg = CellRef(createIntMsg(gift))
storeUInt(sendMode, 8)
storeRef(MessageRelaxed.tlbCodec(AnyTlbConstructor), intMsg)
}
}
val signature = BitString(privateKey.sign(unsignedBody.hash().toByteArray()))
return CellBuilder.createCell {
storeBits(signature)
storeBits(unsignedBody.bits)
storeRefs(unsignedBody.refs)
}
}
private fun createIntMsg(gift: WalletTransfer): MessageRelaxed<Cell> {
val info = CommonMsgInfoRelaxed.IntMsgInfoRelaxed(
ihrDisabled = true,
bounce = gift.bounceable,
bounced = false,
src = AddrNone,
dest = gift.destination,
value = gift.coins,
ihrFee = Coins(),
fwdFee = Coins(),
createdLt = 0u,
createdAt = 0u
)
val init = Maybe.of(gift.stateInit?.let {
Either.of<StateInit, CellRef<StateInit>>(null, CellRef(it))
})
val body = if (gift.body == null) {
Either.of<Cell, CellRef<Cell>>(Cell.empty(), null)
} else {
Either.of<Cell, CellRef<Cell>>(null, CellRef(gift.body))
}
return MessageRelaxed(
info = info,
init = init,
body = body,
)
}
}
}
| 15
|
Kotlin
|
15
| 55
|
2aef7c4dbd494d262aef2bcdc8669d5b3cc41879
| 7,424
|
ton-kotlin
|
Apache License 2.0
|
shared/src/commonMain/kotlin/com/rvcoding/imhere/domain/model/Subscription.kt
|
revs87
| 842,125,970
| false
|
{"Kotlin": 125290, "Swift": 621, "HTML": 332, "CSS": 102}
|
package com.rvcoding.imhere.domain.model
import com.rvcoding.imhere.util.currentTimeMillis
import kotlinx.serialization.Serializable
@Serializable
data class Subscription(
val userId: String = "",
val userSubscribedId: String = "",
val timestamp: Long = currentTimeMillis()
)
| 0
|
Kotlin
|
0
| 0
|
44297ef69d09c9a85e55fc0e6ef4ad8baaea680b
| 290
|
imhere-cmp
|
Apache License 2.0
|
.teamcity/settings.kts
|
KsenX
| 162,048,145
| true
|
{"Python": 33067, "Java": 10973, "Objective-C": 4941, "Shell": 4094, "Kotlin": 3141, "C++": 2305, "C": 87, "HTML": 36}
|
import jetbrains.buildServer.configs.kotlin.v2018_1.*
import jetbrains.buildServer.configs.kotlin.v2018_1.buildSteps.BazelStep
import jetbrains.buildServer.configs.kotlin.v2018_1.buildSteps.bazel
import jetbrains.buildServer.configs.kotlin.v2018_1.triggers.vcs
/*
The settings script is an entry point for defining a TeamCity
project hierarchy. The script should contain a single call to the
project() function with a Project instance or an init function as
an argument.
VcsRoots, BuildTypes, Templates, and subprojects can be
registered inside the project using the vcsRoot(), buildType(),
template(), and subProject() methods respectively.
To debug settings scripts in command-line, run the
mvnDebug org.jetbrains.teamcity:teamcity-configs-maven-plugin:generate
command and attach your debugger to the port 8000.
To debug in IntelliJ Idea, open the 'Maven Projects' tool window (View
-> Tool Windows -> Maven Projects), find the generate task node
(Plugins -> teamcity-configs -> teamcity-configs:generate), the
'Debug' option is available in the context menu for the task.
*/
version = "2018.1"
project {
buildType(Build)
template(id11_1)
subProject(id11)
}
object Build : BuildType({
name = "Build"
artifactRules = """
java-maven\bazel-out\x64_windows-fastbuild\bin\java-maven.exe
java-maven\bazel-out\x64_windows-fastbuild\bin\tests.exe
""".trimIndent()
vcs {
root(DslContext.settingsRoot)
}
steps {
bazel {
workingDir = "java-maven"
command = "clean"
arguments = "--announce_rc"
}
bazel {
workingDir = "java-maven"
command = "build"
targets = ":java-maven"
arguments = "--announce_rc"
}
bazel {
workingDir = "java-maven"
command = "build"
targets = ":java-maven-lib"
param("verbosity", "Verbose")
}
bazel {
workingDir = "java-maven"
command = "test"
targets = ":tests2"
param("verbosity", "Verbose")
}
bazel {
workingDir = "java-maven"
command = "run"
targets = ":java-maven"
logging = BazelStep.Verbosity.Diagnostic
}
}
triggers {
vcs {
}
}
})
object id11_1 : Template({
id("11")
name = "11"
steps {
bazel {
name = "11"
id = "RUNNER_18"
command = "build"
targets = ":target"
arguments = "--lalalalalala"
startupOptions = "-lalalala"
}
}
})
object id11 : Project({
id("11")
name = "11"
buildType(id11_11)
})
object id11_11 : BuildType({
templates(id11_1)
id("11_11")
name = "11"
steps {
bazel {
name = "11"
id = "RUNNER_18"
command = "build"
targets = ":target"
arguments = "--lalalalalala"
startupOptions = "-lalalala"
logging = BazelStep.Verbosity.Diagnostic
}
}
})
| 0
|
Python
|
0
| 0
|
d8e1cf2996299688f1151636432c9992df320c62
| 3,141
|
examples
|
Apache License 2.0
|
src/main/kotlin/org/fenrirs/stored/Environment.kt
|
rushmi0
| 713,799,628
| false
|
{"Kotlin": 117851, "HTML": 326}
|
package org.fenrirs.stored
import io.github.cdimascio.dotenv.Dotenv
import io.github.cdimascio.dotenv.dotenv
object Environment {
private val dotenv: Dotenv = dotenv {
directory = "." // root path
filename = ".env"
}
val DATABASE_NAME: String by lazy { dotenv["DATABASE_NAME"] }
val DATABASE_URL: String by lazy { dotenv["DATABASE_URL"] }
val DATABASE_USERNAME: String by lazy { dotenv["DATABASE_USERNAME"] }
val DATABASE_PASSWORD : String by lazy { dotenv["DATABASE_PASSWORD"] }
}
| 0
|
Kotlin
|
1
| 8
|
ac4e1b9bbf7ddf9c826e79ae50513781caa2e480
| 527
|
Fenrir-s
|
MIT License
|
common/designsystem/src/main/java/com/cmc/curtaincall/common/designsystem/component/buttons/common/ButtonsPreview.kt
|
CurtainCall-App
| 659,971,351
| false
|
{"Kotlin": 1298142}
|
package com.cmc.curtaincall.common.designsystem.component.buttons.common
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.cmc.curtaincall.common.designsystem.theme.CurtainCallTheme
@Preview
@Composable
fun CurtainCallFilledButtonPreview() {
CurtainCallTheme {
CurtainCallFilledButton(
modifier = Modifier.fillMaxWidth(),
text = "텍스트",
containerColor = CurtainCallTheme.colors.secondary
)
}
}
@Preview
@Composable
fun CurtainCallOutlinedButtonPreview() {
CurtainCallTheme {
CurtainCallOutlinedButton(
modifier = Modifier.fillMaxWidth(),
text = "텍스트"
)
}
}
| 4
|
Kotlin
|
1
| 5
|
c9f51916e3acbb292f364b3a3191991506d76580
| 813
|
CurtainCall-AOS
|
Apache License 2.0
|
src/main/kotlin/com/moqi/kotlin/ch02/2.3.2_3_WhenEnums2.kt
|
HiAwesome
| 317,410,821
| false
| null |
package com.moqi.kotlin.ch02
import com.moqi.kotlin.ch02.Color4.*
/**
* 使用 When 处理枚举类型
*
* @author moqi On 12/2/20 16:02
*/
fun getWarmth2(color: Color4) = when (color) {
RED, ORANGE, YELLOW -> "warm"
GREEN -> "neutral"
BLUE, INDIGO, VIOLET -> "cold"
}
fun main() {
println("getWarmth2(INDIGO) = ${getWarmth2(VIOLET)}")
}
| 0
|
Kotlin
|
0
| 0
|
2228e08f304f06020917b7bea98f32b83ec22f69
| 345
|
kotlin-demo
|
Apache License 2.0
|
src/main/kotlin/com/moqi/kotlin/ch02/2.3.2_3_WhenEnums2.kt
|
HiAwesome
| 317,410,821
| false
| null |
package com.moqi.kotlin.ch02
import com.moqi.kotlin.ch02.Color4.*
/**
* 使用 When 处理枚举类型
*
* @author moqi On 12/2/20 16:02
*/
fun getWarmth2(color: Color4) = when (color) {
RED, ORANGE, YELLOW -> "warm"
GREEN -> "neutral"
BLUE, INDIGO, VIOLET -> "cold"
}
fun main() {
println("getWarmth2(INDIGO) = ${getWarmth2(VIOLET)}")
}
| 0
|
Kotlin
|
0
| 0
|
2228e08f304f06020917b7bea98f32b83ec22f69
| 345
|
kotlin-demo
|
Apache License 2.0
|
app/src/main/java/io/horizontalsystems/bankwallet/modules/swap/confirmation/oneinch/OneInchConfirmationModule.kt
|
horizontalsystems
| 142,825,178
| false
| null |
package io.horizontalsystems.bankwallet.modules.swap.confirmation.oneinch
import android.os.Bundle
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.NavOptions
import io.horizontalsystems.bankwallet.core.App
import io.horizontalsystems.bankwallet.core.ethereum.EthereumFeeViewModel
import io.horizontalsystems.bankwallet.core.ethereum.EvmCoinServiceFactory
import io.horizontalsystems.bankwallet.core.factories.FeeRateProviderFactory
import io.horizontalsystems.bankwallet.modules.sendevmtransaction.SendEvmTransactionViewModel
import io.horizontalsystems.bankwallet.modules.swap.SwapMainModule
import io.horizontalsystems.bankwallet.modules.swap.oneinch.OneInchKitHelper
import io.horizontalsystems.core.findNavController
object OneInchConfirmationModule {
private const val oneInchSwapParametersKey = "oneInchSwapParametersKey"
class Factory(
private val blockchain: SwapMainModule.Blockchain,
private val arguments: Bundle
) : ViewModelProvider.Factory {
private val oneInchSwapParameters by lazy { arguments.getParcelable<OneInchSwapParameters>(oneInchSwapParametersKey)!! }
private val evmKit by lazy { blockchain.evmKit!! }
private val oneInchKitHelper by lazy { OneInchKitHelper(evmKit) }
private val coin by lazy { blockchain.coin!! }
private val transactionService by lazy {
val feeRateProvider = FeeRateProviderFactory.provider(coin)!!
OneInchTransactionFeeService(oneInchKitHelper, oneInchSwapParameters, feeRateProvider)
}
private val coinServiceFactory by lazy { EvmCoinServiceFactory(coin, App.coinKit, App.currencyManager, App.xRateManager) }
private val sendService by lazy { OneInchSendEvmTransactionService(evmKit, transactionService, App.activateCoinManager) }
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return when (modelClass) {
SendEvmTransactionViewModel::class.java -> {
SendEvmTransactionViewModel(sendService, coinServiceFactory) as T
}
EthereumFeeViewModel::class.java -> {
EthereumFeeViewModel(transactionService, coinServiceFactory.baseCoinService) as T
}
else -> throw IllegalArgumentException()
}
}
}
fun start(fragment: Fragment, navigateTo: Int, navOptions: NavOptions, oneInchSwapParameters: OneInchSwapParameters) {
fragment.findNavController().navigate(navigateTo, bundleOf(oneInchSwapParametersKey to oneInchSwapParameters), navOptions)
}
}
| 163
| null |
170
| 320
|
a520b87e9553e69c76d9d48a0adb0268a53e65b2
| 2,774
|
unstoppable-wallet-android
|
MIT License
|
app/src/main/java/com/ramzmania/tubefy/data/dto/home/youtubei/YoutubeiHomeResponse.kt
|
rameshvoltella
| 834,415,700
| false
|
{"Kotlin": 517818, "Java": 2426}
|
package com.ramzmania.tubefy.data.dto.home.youtubei
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class YoutubeiMusicHomeApiResponse(
@Json(name = "responseContext") val responseContext: ResponseContext? = null,
@Json(name = "contents") val contents: Contents? = null
)
@JsonClass(generateAdapter = true)
data class ResponseContext(
@Json(name = "visitorData") val visitorData: String? = null
)
@JsonClass(generateAdapter = true)
data class Contents(
@Json(name = "singleColumnBrowseResultsRenderer") val singleColumnBrowseResultsRenderer: SingleColumnBrowseResultsRenderer? = null
)
@JsonClass(generateAdapter = true)
data class SingleColumnBrowseResultsRenderer(
@Json(name = "tabs") val tabs: List<TabRendererWrapper>? = null
)
@JsonClass(generateAdapter = true)
data class TabRendererWrapper(
@Json(name = "tabRenderer") val tabRenderer: TabRenderer? = null
)
@JsonClass(generateAdapter = true)
data class TabRenderer(
@Json(name = "content") val content: Content? = null
)
@JsonClass(generateAdapter = true)
data class Content(
@Json(name = "sectionListRenderer") val sectionListRenderer: SectionListRenderer? = null
)
@JsonClass(generateAdapter = true)
data class SectionListRenderer(
@Json(name = "contents") val contents: List<MusicCarouselShelfRendererWrapper>? = null,
@Json(name = "continuations") val continuations: List<NextContinuationDataWrapper>? = null
)
@JsonClass(generateAdapter = true)
data class MusicCarouselShelfRendererWrapper(
@Json(name = "musicCarouselShelfRenderer") val musicCarouselShelfRenderer: MusicCarouselShelfRenderer? = null
)
@JsonClass(generateAdapter = true)
data class MusicCarouselShelfRenderer(
@Json(name = "header") val header: MusicCarouselShelfBasicHeaderRendererWrapper? = null,
@Json(name = "contents") val contents: List<MusicResponsiveListItemRendererWrapper>? = null
)
@JsonClass(generateAdapter = true)
data class MusicCarouselShelfBasicHeaderRendererWrapper(
@Json(name = "musicCarouselShelfBasicHeaderRenderer") val musicCarouselShelfBasicHeaderRenderer: MusicCarouselShelfBasicHeaderRenderer? = null
)
@JsonClass(generateAdapter = true)
data class MusicCarouselShelfBasicHeaderRenderer(
@Json(name = "accessibilityData") val accessibilityData: AccessibilityDataWrapper? = null
)
@JsonClass(generateAdapter = true)
data class AccessibilityDataWrapper(
@Json(name = "accessibilityData") val accessibilityData: AccessibilityData? = null
)
@JsonClass(generateAdapter = true)
data class AccessibilityData(
@Json(name = "label") val label: String? = null
)
@JsonClass(generateAdapter = true)
data class MusicResponsiveListItemRendererWrapper(
@Json(name = "musicResponsiveListItemRenderer") val musicResponsiveListItemRenderer: MusicResponsiveListItemRenderer? = null,
@Json(name = "musicTwoRowItemRenderer") val musicTwoRowItemRenderer: MusicTwoRowItemRenderer? = null
)
@JsonClass(generateAdapter = true)
data class MusicResponsiveListItemRenderer(
@Json(name = "thumbnail") val thumbnail: MusicThumbnailRendererWrapper? = null,
@Json(name = "flexColumns") val flexColumns: List<MusicResponsiveListItemFlexColumnRendererWrapper>? = null
)
@JsonClass(generateAdapter = true)
data class MusicTwoRowItemRenderer(
@Json(name = "thumbnailRenderer") val thumbnailRenderer: MusicThumbnailRendererWrapper? = null,
@Json(name = "title") val title: TitleWrapper? = null,
@Json(name = "thumbnailOverlay") val thumbnailOverlay: MusicItemThumbnailOverlayRenderer? = null
)
@JsonClass(generateAdapter = true)
data class MusicResponsiveListItemFlexColumnRendererWrapper(
@Json(name = "musicResponsiveListItemFlexColumnRenderer") val musicResponsiveListItemFlexColumnRenderer: MusicResponsiveListItemFlexColumnRenderer? = null
)
@JsonClass(generateAdapter = true)
data class MusicResponsiveListItemFlexColumnRenderer(
@Json(name = "text") val text: TextWrapper? = null,
@Json(name = "displayPriority") val displayPriority: String? = null
)
@JsonClass(generateAdapter = true)
data class TextWrapper(
@Json(name = "runs") val runs: List<Run>? = null
)
@JsonClass(generateAdapter = true)
data class Run(
@Json(name = "text") val text: String? = null,
@Json(name = "navigationEndpoint") val navigationEndpoint: NavigationEndpoint? = null
)
@JsonClass(generateAdapter = true)
data class NavigationEndpoint(
@Json(name = "clickTrackingParams") val clickTrackingParams: String? = null,
@Json(name = "watchEndpoint") val watchEndpoint: WatchEndpoint? = null,
@Json(name = "browseEndpoint") val browseEndpoint: BrowseEndpoint? = null
)
@JsonClass(generateAdapter = true)
data class WatchEndpoint(
@Json(name = "videoId") val videoId: String? = null,
@Json(name = "playlistId") val playlistId: String? = null,
@Json(name = "params") val params: String? = null,
@Json(name = "loggingContext") val loggingContext: LoggingContext? = null,
@Json(name = "watchEndpointMusicSupportedConfigs") val watchEndpointMusicSupportedConfigs: WatchEndpointMusicSupportedConfigs? = null
)
@JsonClass(generateAdapter = true)
data class WatchEndpointMusicSupportedConfigs(
@Json(name = "watchEndpointMusicConfig") val watchEndpointMusicConfig: WatchEndpointMusicConfig? = null
)
@JsonClass(generateAdapter = true)
data class WatchEndpointMusicConfig(
@Json(name = "musicVideoType") val musicVideoType: String? = null
)
@JsonClass(generateAdapter = true)
data class LoggingContext(
@Json(name = "vssLoggingContext") val vssLoggingContext: VssLoggingContext? = null
)
@JsonClass(generateAdapter = true)
data class VssLoggingContext(
@Json(name = "serializedContextData") val serializedContextData: String? = null
)
@JsonClass(generateAdapter = true)
data class BrowseEndpoint(
@Json(name = "browseId") val browseId: String? = null,
@Json(name = "params") val params: String? = null,
@Json(name = "browseEndpointContextSupportedConfigs") val browseEndpointContextSupportedConfigs: BrowseEndpointContextSupportedConfigs? = null
)
@JsonClass(generateAdapter = true)
data class BrowseEndpointContextSupportedConfigs(
@Json(name = "browseEndpointContextMusicConfig") val browseEndpointContextMusicConfig: BrowseEndpointContextMusicConfig? = null
)
@JsonClass(generateAdapter = true)
data class BrowseEndpointContextMusicConfig(
@Json(name = "pageType") val pageType: String? = null
)
@JsonClass(generateAdapter = true)
data class MusicThumbnailRendererWrapper(
@Json(name = "musicThumbnailRenderer") val musicThumbnailRenderer: MusicThumbnailRenderer? = null
)
@JsonClass(generateAdapter = true)
data class MusicThumbnailRenderer(
@Json(name = "thumbnail") val thumbnail: Thumbnail? = null,
@Json(name = "thumbnailCrop") val thumbnailCrop: String? = null,
@Json(name = "thumbnailScale") val thumbnailScale: String? = null,
@Json(name = "trackingParams") val trackingParams: String? = null
)
@JsonClass(generateAdapter = true)
data class Thumbnail(
@Json(name = "thumbnails") val thumbnails: List<ThumbnailDetail>? = null
)
@JsonClass(generateAdapter = true)
data class ThumbnailDetail(
@Json(name = "url") val url: String? = null,
@Json(name = "width") val width: Int? = null,
@Json(name = "height") val height: Int? = null
)
@JsonClass(generateAdapter = true)
data class TitleWrapper(
@Json(name = "runs") val runs: List<Run>? = null
)
@JsonClass(generateAdapter = true)
data class MusicItemThumbnailOverlayRenderer(
@Json(name = "musicItemThumbnailOverlayRenderer") val musicItemThumbnailOverlayRenderer: MusicItemThumbnailOverlayRendererContent? = null
)
@JsonClass(generateAdapter = true)
data class MusicItemThumbnailOverlayRendererContent(
@Json(name = "background") val background: VerticalGradientWrapper? = null,
@Json(name = "content") val content: MusicPlayButtonRendererWrapper? = null,
@Json(name = "contentPosition") val contentPosition: String? = null,
@Json(name = "displayStyle") val displayStyle: String? = null
)
@JsonClass(generateAdapter = true)
data class VerticalGradientWrapper(
@Json(name = "verticalGradient") val verticalGradient: VerticalGradient? = null
)
@JsonClass(generateAdapter = true)
data class VerticalGradient(
@Json(name = "gradientLayerColors") val gradientLayerColors: List<String>? = null
)
@JsonClass(generateAdapter = true)
data class MusicPlayButtonRendererWrapper(
@Json(name = "musicPlayButtonRenderer") val musicPlayButtonRenderer: MusicPlayButtonRenderer? = null
)
@JsonClass(generateAdapter = true)
data class MusicPlayButtonRenderer(
@Json(name = "playNavigationEndpoint") val playNavigationEndpoint: PlayNavigationEndpoint? = null
)
@JsonClass(generateAdapter = true)
data class PlayNavigationEndpoint(
@Json(name = "clickTrackingParams") val clickTrackingParams: String? = null,
@Json(name = "watchPlaylistEndpoint") val watchPlaylistEndpoint: WatchPlaylistEndpoint? = null
)
@JsonClass(generateAdapter = true)
data class WatchPlaylistEndpoint(
@Json(name = "playlistId") val playlistId: String? = null,
@Json(name = "params") val params: String? = null,
@Json(name = "loggingContext") val loggingContext: LoggingContext? = null
)
@JsonClass(generateAdapter = true)
data class NextContinuationDataWrapper(
@Json(name = "nextContinuationData") val nextContinuationData: NextContinuationData? = null
)
@JsonClass(generateAdapter = true)
data class NextContinuationData(
@Json(name = "continuation") val continuation: String? = null,
@Json(name = "clickTrackingParams") val clickTrackingParams: String? = null
)
| 0
|
Kotlin
|
0
| 1
|
2adb4336e4c9c736e241d39bf0773589e72cf897
| 9,667
|
TubeFy
|
MIT License
|
faker/edu/src/main/kotlin/io/github/serpro69/kfaker/edu/provider/University.kt
|
serpro69
| 174,969,439
| false
|
{"Kotlin": 741942, "Shell": 6192, "Makefile": 4515, "Java": 3978, "Groovy": 1144}
|
package io.github.serpro69.kfaker.edu.provider
import io.github.serpro69.kfaker.FakerService
import io.github.serpro69.kfaker.dictionary.YamlCategory
import io.github.serpro69.kfaker.provider.FakeDataProvider
import io.github.serpro69.kfaker.provider.YamlFakeDataProvider
import io.github.serpro69.kfaker.provider.unique.LocalUniqueDataProvider
import io.github.serpro69.kfaker.provider.unique.UniqueProviderDelegate
/**
* [FakeDataProvider] implementation for [YamlCategory.UNIVERSITY] category.
*/
@Suppress("unused")
class University internal constructor(fakerService: FakerService) : YamlFakeDataProvider<University>(fakerService) {
override val yamlCategory = YamlCategory.UNIVERSITY
override val localUniqueDataProvider = LocalUniqueDataProvider<University>()
override val unique by UniqueProviderDelegate(localUniqueDataProvider, fakerService)
init {
fakerService.load(yamlCategory)
}
// Prefix and suffix are needed because they are used as expressions, i.e. `#{University.prefix}`
fun prefix() = resolve("prefix")
fun suffix() = resolve("suffix")
fun name() = resolve("name")
}
| 33
|
Kotlin
|
42
| 462
|
22b0f971c9f699045b30d913c6cbca02060ed9b3
| 1,138
|
kotlin-faker
|
MIT License
|
plugin-locationcomponent/src/main/java/com/mapbox/maps/plugin/locationcomponent/generated/LocationComponentAttributeParser.kt
|
willgan916
| 408,637,684
| true
|
{"Kotlin": 1873962, "Java": 53692, "Shell": 16849, "Python": 11569, "C++": 10129, "JavaScript": 4344, "Makefile": 3644, "CMake": 1201, "EJS": 1194}
|
// This file is generated.
package com.mapbox.maps.plugin.locationcomponent.generated
import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import androidx.core.content.res.ResourcesCompat
import com.mapbox.maps.plugin.LocationPuck2D
import com.mapbox.maps.plugin.LocationPuck3D
import com.mapbox.maps.plugin.locationcomponent.R
/**
* Utility class for parsing [AttributeSet] to [LocationComponentSettings].
*/
internal object LocationComponentAttributeParser {
/**
* Parse [AttributeSet] to [LocationComponentSettings].
*
* @param context Context
* @param attrs AttributionSet
*/
fun parseLocationComponentSettings(context: Context, attrs: AttributeSet?, pixelRatio: Float = 1.0f): LocationComponentSettings {
val typedArray = context.obtainStyledAttributes(attrs, R.styleable.mapbox_MapView, 0, 0)
try {
return LocationComponentSettings(
enabled = typedArray.getBoolean(R.styleable.mapbox_MapView_mapbox_locationComponentEnabled, false),
pulsingEnabled = typedArray.getBoolean(R.styleable.mapbox_MapView_mapbox_locationComponentPulsingEnabled, false),
pulsingColor = typedArray.getColor(R.styleable.mapbox_MapView_mapbox_locationComponentPulsingColor, Color.parseColor("#4A90E2")),
pulsingMaxRadius = typedArray.getDimension(R.styleable.mapbox_MapView_mapbox_locationComponentPulsingMaxRadius, 10f * pixelRatio),
layerAbove = typedArray.getString(R.styleable.mapbox_MapView_mapbox_locationComponentLayerAbove),
layerBelow = typedArray.getString(R.styleable.mapbox_MapView_mapbox_locationComponentLayerBelow),
locationPuck = when (typedArray.getInt(R.styleable.mapbox_MapView_mapbox_locationComponentLocationPuck, -1)) {
0 -> LocationPuck2D(
topImage = typedArray.getDrawable(R.styleable.mapbox_MapView_mapbox_locationComponentLocationPuckLocationPuck2DTopImage),
bearingImage = typedArray.getDrawable(R.styleable.mapbox_MapView_mapbox_locationComponentLocationPuckLocationPuck2DBearingImage),
shadowImage = typedArray.getDrawable(R.styleable.mapbox_MapView_mapbox_locationComponentLocationPuckLocationPuck2DShadowImage),
scaleExpression = typedArray.getString(R.styleable.mapbox_MapView_mapbox_locationComponentLocationPuckLocationPuck2DScaleExpression),
)
1 -> LocationPuck3D(
modelUri = typedArray.getString(R.styleable.mapbox_MapView_mapbox_locationComponentLocationPuckLocationPuck3DModelUri)
?: throw RuntimeException("model-uri must be specified in order to use 3d location puck."),
position = listOf(
typedArray.getFloat(R.styleable.mapbox_MapView_mapbox_locationComponentLocationPuckLocationPuck3DPosition_lon, 0.0f),
typedArray.getFloat(R.styleable.mapbox_MapView_mapbox_locationComponentLocationPuckLocationPuck3DPosition_lat, 0.0f),
),
modelOpacity = typedArray.getFloat(R.styleable.mapbox_MapView_mapbox_locationComponentLocationPuckLocationPuck3DModelOpacity, 1f),
modelScale = listOf(
typedArray.getFloat(R.styleable.mapbox_MapView_mapbox_locationComponentLocationPuckLocationPuck3DModelScale_x, 1.0f),
typedArray.getFloat(R.styleable.mapbox_MapView_mapbox_locationComponentLocationPuckLocationPuck3DModelScale_y, 1.0f),
typedArray.getFloat(R.styleable.mapbox_MapView_mapbox_locationComponentLocationPuckLocationPuck3DModelScale_z, 1.0f),
),
modelScaleExpression = typedArray.getString(R.styleable.mapbox_MapView_mapbox_locationComponentLocationPuckLocationPuck3DModelScaleExpression),
modelRotation = listOf(
typedArray.getFloat(R.styleable.mapbox_MapView_mapbox_locationComponentLocationPuckLocationPuck3DModelRotation_x, 0.0f),
typedArray.getFloat(R.styleable.mapbox_MapView_mapbox_locationComponentLocationPuckLocationPuck3DModelRotation_y, 0.0f),
typedArray.getFloat(R.styleable.mapbox_MapView_mapbox_locationComponentLocationPuckLocationPuck3DModelRotation_z, 90.0f),
),
)
else -> LocationPuck2D(
topImage = ResourcesCompat.getDrawable(context.resources, R.drawable.mapbox_user_icon, null),
bearingImage = ResourcesCompat.getDrawable(context.resources, R.drawable.mapbox_user_stroke_icon, null),
shadowImage = ResourcesCompat.getDrawable(context.resources, R.drawable.mapbox_user_icon_shadow, null),
)
},
)
} finally {
typedArray.recycle()
}
}
}
// End of generated file.
| 1
| null |
1
| 0
|
e4d2553af0c994ca8ba6897ed3a5d6c6dbc4681b
| 4,636
|
mapbox-maps-android
|
Apache License 2.0
|
shared/src/commonMain/kotlin/view/ViewConfig.kt
|
CherryLover
| 685,290,933
| false
|
{"Kotlin": 15811, "Swift": 592, "Shell": 228}
|
package view
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
/**
* @description
* @author: Created jiangjiwei in 2023/12/8 13:31
*/
val marginMax = 20.dp
val marginMiddle = 10.dp
val marginMin = 4.dp
val lineHeight = 1.dp
val actionHeight = 48.dp
val textSizePrimary = 14.sp
val textSizeSecondary = 12.sp
val textColorPrimary = Color(0xFF333333)
val textColorSecondary = Color(0xFF999999)
val billOutColor = Color(0xFFEA595E)
val billInColor = Color(0xFF4DBF83)
val cardBgColor = Color(0xFFFFFFFF)
val surfaceBgColor = Color(0xFFF5F5F5)
val corner = 8.dp
val roundCornerShape = RoundedCornerShape(corner)
| 1
|
Kotlin
|
0
| 0
|
5c5b8c9410269906dc35f6d94c8a44a3b98eab0e
| 737
|
Compose-multiplatform-bill-record
|
Apache License 2.0
|
intellijPlugin/src/main/kotlin/pw/binom/SimpleMaterial.kt
|
caffeine-mgn
| 223,796,620
| false
| null |
package pw.binom
import mogot.gl.GL
import mogot.gl.MaterialGLSL
import mogot.gl.Shader
import mogot.math.Matrix4fc
import mogot.math.Vector4f
import mogot.rendering.Display
import pw.binom.material.EmptyModuleResolver
import pw.binom.material.SourceModule
import pw.binom.material.compiler.Compiler
import pw.binom.material.generator.gles300.GLES300Generator
import pw.binom.material.lex.Parser
import java.io.StringReader
private val shaderText = """
@vertex
vec3 vertexPos
@normal
vec3 normalList
@uv
vec2 vertexUV
@projection
mat4 projection
@modelView
mat4 modelView
vec3 normal
vec4 vertex(){
return vec4(projection * modelView * vec4(vertexPos, 1f))
}
vec4 fragment(vec4 color2){
return vec4(0.7f,0.7f,0.7f,1f)
}
"""
internal class SimpleMaterial(gl: GL) : MaterialGLSL(gl) {
override fun dispose() {
shader.close()
super.dispose()
}
val diffuseColor = Vector4f(1f, 1f, 1f, 1f)
override val shader: Shader = run {
val module = SourceModule("")
val gen = Parser(module, StringReader(shaderText))
.let { Compiler(it, module, EmptyModuleResolver) }
.let { GLES300Generator.mix(listOf(module)) }
Shader(gl, gen.vp, gen.fp)
}
/*
override val shader: Shader = Shader(engile.gl,
vertex = """#version 440 core
layout(location = 0) in vec3 vertexPos;
layout(location = 1) in vec3 normalList;
layout(location = 2) in vec2 vertexUV;
uniform mat4 projection;
uniform mat4 model;
uniform mat4 gl_ModelViewMatrix;
uniform mat4 gl_ProjectionMatrix;
uniform mat3 gl_NormalMatrix;
out vec2 UV;
out vec3 normal;
out vec3 vVertex;
void main() {
mat3 normalMatrix = mat3(transpose(inverse(model)));
normal = vec3(normalMatrix * normalList);
gl_Position = projection * model * vec4(vertexPos, 1.0);
//norm=normalize(vec3(gl_NormalMatrix * normalList));
vVertex = vec3(model * vec4(vertexPos, 1.0));
UV = vertexUV;
}""",
fragment = """#version 440 core
uniform sampler2D tex;
uniform vec4 diffuseColor;
in vec2 UV;
in vec3 normal;
out vec4 color;
uniform mat4 projection;
uniform mat4 model;
uniform mat4 model_projection;
in vec3 vVertex;
struct Light {
vec3 position;
vec3 diffuse;
float specular;
};
uniform Light lights[10];
uniform int lights_len;
uniform vec4 FrontMaterial_specular;
uniform float FrontMaterial_shininess;
void main() {
// color = texture(tex, UV).rgba + diffuseColor;
// color = vec4(texture(tex, UV).rgb,0.5f);
// color = texture(tex, UV).rgba * diffuseColor;
// vec4 cc = texture(tex, UV).rgba * diffuseColor;
vec4 cc = vec4(0.5,0.5,0.5,1);
for (int i = 0; i<lights_len; i++){
vec3 lightDir = vec3(lights[i].position.xyz - vVertex);
vec3 N = normalize(normal);
vec3 L = normalize(lightDir);
float lambertTerm = dot(N,L);
float cosTheta = dot( N,L );
float distation = length(lightDir);
// if(lambertTerm > 0.0){
vec3 E = normalize(-vVertex);
vec3 R = normalize(-reflect(L, N));
float LightPower = 1000;
//calculate Diffuse Term:
cc += vec4(lights[i].diffuse, 1f) * LightPower * cosTheta / (distation*distation);
//calculate Specular Term
// float specular = pow( max(dot(R, E), 0.0), FrontMaterial_shininess );
// cc += lights[i].specular * FrontMaterial_specular * specular;
vec4 Ispec = FrontMaterial_specular * pow( max(dot(R,E),0.0), 0.3*FrontMaterial_shininess);
Ispec = clamp(Ispec, 0.0, 1.0);
cc += Ispec;
// }
}
color = cc;
//color=vec4(normalize(normal),1);
}
"""
)
*/
override fun use(model: Matrix4fc, modelView: Matrix4fc, projection: Matrix4fc, context: Display.Context) {
super.use(model, modelView, projection, context)
// image?.bind()
shader.uniform("diffuseColor", diffuseColor.x, diffuseColor.y, diffuseColor.z, diffuseColor.w)
}
}
| 6
|
Kotlin
|
0
| 4
|
e673acfcb20e2d62d8e68c43d395731bd9d9d882
| 4,021
|
mogot
|
Apache License 2.0
|
uxmobile/src/main/java/sk/uxtweak/uxmobile/study/study_flow/questionnaire_option/QuestionnaireOptionsRadioButton.kt
|
macro39
| 389,744,953
| false
| null |
package sk.uxtweak.uxmobile.study.study_flow.questionnaire_option
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.RadioButton
import kotlinx.android.synthetic.main.fragment_questionnaire_radio_button.*
import sk.uxtweak.uxmobile.R
/**
* Created by Kamil Macek on 21.2.2020.
*/
class QuestionnaireOptionsRadioButton : QuestionnaireOptionsBaseFragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_questionnaire_radio_button, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
configure()
radioGroup_questionnaire.setOnCheckedChangeListener { group, checkedId ->
setAnswer(checkedId)
}
}
override fun addOptions() {
for (i in question.questionOptions.indices) {
val radioButton = RadioButton(activity)
radioButton.id = i
radioButton.setTextColor(Color.BLACK)
if (i == 0) {
radioButton.isChecked = true
setAnswer(i)
}
radioButton.text = question.questionOptions[i].option
radioGroup_questionnaire.addView(radioButton)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
9dc1d26c95c42f739c7aa9610da815a01ea7f5d2
| 1,490
|
UxMobile
|
Apache License 2.0
|
bookcase-core/src/test/kotlin/com/github/vhromada/bookcase/facade/ItemFacadeIntegrationTest.kt
|
vhromada
| 127,519,826
| false
| null |
package com.github.vhromada.bookcase.facade
import com.github.vhromada.bookcase.BookcaseTestConfiguration
import com.github.vhromada.bookcase.utils.AuditUtils
import com.github.vhromada.bookcase.utils.BookUtils
import com.github.vhromada.bookcase.utils.ItemUtils
import com.github.vhromada.bookcase.utils.fillAudit
import com.github.vhromada.common.entity.Language
import com.github.vhromada.common.result.Event
import com.github.vhromada.common.result.Severity
import com.github.vhromada.common.result.Status
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.SoftAssertions.assertSoftly
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.test.annotation.DirtiesContext
import org.springframework.test.annotation.Rollback
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.context.junit.jupiter.SpringExtension
import org.springframework.transaction.annotation.Transactional
import javax.persistence.EntityManager
import javax.persistence.PersistenceContext
/**
* A class represents integration test for class [ItemFacade].
*
* @author <NAME>
*/
@ExtendWith(SpringExtension::class)
@ContextConfiguration(classes = [BookcaseTestConfiguration::class])
@Transactional
@Rollback
class ItemFacadeIntegrationTest {
/**
* Instance of [EntityManager]
*/
@PersistenceContext
private lateinit var entityManager: EntityManager
/**
* Instance of [ItemFacade]
*/
@Autowired
private lateinit var facade: ItemFacade
/**
* Test method for [ItemFacade.get].
*/
@Test
fun get() {
for (i in 1..ItemUtils.ITEMS_COUNT) {
val result = facade.get(id = i)
assertSoftly {
it.assertThat(result.status).isEqualTo(Status.OK)
it.assertThat(result.data).isNotNull
it.assertThat(result.events()).isEmpty()
}
ItemUtils.assertItemDeepEquals(expected = ItemUtils.getItemDomain(index = i), actual = result.data!!)
}
assertSoftly {
it.assertThat(ItemUtils.getItemsCount(entityManager = entityManager)).isEqualTo(ItemUtils.ITEMS_COUNT)
it.assertThat(BookUtils.getBooksCount(entityManager = entityManager)).isEqualTo(BookUtils.BOOKS_COUNT)
}
}
/**
* Test method for [ItemFacade.get] with bad ID.
*/
@Test
fun getBadId() {
val result = facade.get(id = Int.MAX_VALUE)
assertSoftly {
it.assertThat(result.status).isEqualTo(Status.ERROR)
it.assertThat(result.events()).isEqualTo(listOf(ITEM_NOT_EXIST_EVENT))
}
assertSoftly {
it.assertThat(ItemUtils.getItemsCount(entityManager = entityManager)).isEqualTo(ItemUtils.ITEMS_COUNT)
it.assertThat(BookUtils.getBooksCount(entityManager = entityManager)).isEqualTo(BookUtils.BOOKS_COUNT)
}
}
/**
* Test method for [ItemFacade.update].
*/
@Test
fun update() {
val item = ItemUtils.newItem(id = 1)
val expectedItem = ItemUtils.newItemDomain(id = 1)
.fillAudit(audit = AuditUtils.updatedAudit())
expectedItem.book = BookUtils.getBook(entityManager = entityManager, id = 1)
val result = facade.update(data = item)
entityManager.flush()
assertSoftly {
it.assertThat(result.status).isEqualTo(Status.OK)
it.assertThat(result.events()).isEmpty()
}
ItemUtils.assertItemDeepEquals(expected = expectedItem, actual = ItemUtils.getItem(entityManager = entityManager, id = 1)!!)
assertSoftly {
it.assertThat(ItemUtils.getItemsCount(entityManager = entityManager)).isEqualTo(ItemUtils.ITEMS_COUNT)
it.assertThat(BookUtils.getBooksCount(entityManager = entityManager)).isEqualTo(BookUtils.BOOKS_COUNT)
}
}
/**
* Test method for [ItemFacade.update] with item with null ID.
*/
@Test
fun updateNullId() {
val item = ItemUtils.newItem(id = 1)
.copy(id = null)
val result = facade.update(data = item)
assertSoftly {
it.assertThat(result.status).isEqualTo(Status.ERROR)
it.assertThat(result.events()).isEqualTo(listOf(Event(severity = Severity.ERROR, key = "ITEM_ID_NULL", message = "ID mustn't be null.")))
}
assertSoftly {
it.assertThat(ItemUtils.getItemsCount(entityManager = entityManager)).isEqualTo(ItemUtils.ITEMS_COUNT)
it.assertThat(BookUtils.getBooksCount(entityManager = entityManager)).isEqualTo(BookUtils.BOOKS_COUNT)
}
}
/**
* Test method for [ItemFacade.update] with item with null position.
*/
@Test
fun updateNullPosition() {
val item = ItemUtils.newItem(id = 1)
.copy(position = null)
val result = facade.update(data = item)
assertSoftly {
it.assertThat(result.status).isEqualTo(Status.ERROR)
it.assertThat(result.events()).isEqualTo(listOf(Event(severity = Severity.ERROR, key = "ITEM_POSITION_NULL", message = "Position mustn't be null.")))
}
assertSoftly {
it.assertThat(ItemUtils.getItemsCount(entityManager = entityManager)).isEqualTo(ItemUtils.ITEMS_COUNT)
it.assertThat(BookUtils.getBooksCount(entityManager = entityManager)).isEqualTo(BookUtils.BOOKS_COUNT)
}
}
/**
* Test method for [ItemFacade.update] with item with null languages.
*/
@Test
fun updateNullLanguages() {
val item = ItemUtils.newItem(id = 1)
.copy(languages = null)
val result = facade.update(data = item)
assertSoftly {
it.assertThat(result.status).isEqualTo(Status.ERROR)
it.assertThat(result.events()).isEqualTo(listOf(Event(severity = Severity.ERROR, key = "ITEM_LANGUAGES_NULL", message = "Languages mustn't be null.")))
}
assertSoftly {
it.assertThat(ItemUtils.getItemsCount(entityManager = entityManager)).isEqualTo(ItemUtils.ITEMS_COUNT)
it.assertThat(BookUtils.getBooksCount(entityManager = entityManager)).isEqualTo(BookUtils.BOOKS_COUNT)
}
}
/**
* Test method for [ItemFacade.update] with item with empty empty languages.
*/
@Test
fun updateEmptyLanguages() {
val item = ItemUtils.newItem(id = 1)
.copy(languages = emptyList())
val result = facade.update(data = item)
assertSoftly {
it.assertThat(result.status).isEqualTo(Status.ERROR)
it.assertThat(result.events()).isEqualTo(listOf(Event(severity = Severity.ERROR, key = "ITEM_LANGUAGES_EMPTY", message = "Languages mustn't be empty.")))
}
assertSoftly {
it.assertThat(ItemUtils.getItemsCount(entityManager = entityManager)).isEqualTo(ItemUtils.ITEMS_COUNT)
it.assertThat(BookUtils.getBooksCount(entityManager = entityManager)).isEqualTo(BookUtils.BOOKS_COUNT)
}
}
/**
* Test method for [ItemFacade.update] with item with languages with null value.
*/
@Test
fun updateBadLanguages() {
val item = ItemUtils.newItem(id = 1)
.copy(languages = listOf(Language.CZ, null))
val result = facade.update(data = item)
assertSoftly {
it.assertThat(result.status).isEqualTo(Status.ERROR)
it.assertThat(result.events()).isEqualTo(listOf(Event(severity = Severity.ERROR, key = "ITEM_LANGUAGES_CONTAIN_NULL", message = "Languages mustn't contain null value.")))
}
assertSoftly {
it.assertThat(ItemUtils.getItemsCount(entityManager = entityManager)).isEqualTo(ItemUtils.ITEMS_COUNT)
it.assertThat(BookUtils.getBooksCount(entityManager = entityManager)).isEqualTo(BookUtils.BOOKS_COUNT)
}
}
/**
* Test method for [ItemFacade.update] with item with null format.
*/
@Test
fun updateNullFormat() {
val item = ItemUtils.newItem(id = 1)
.copy(format = null)
val result = facade.update(data = item)
assertSoftly {
it.assertThat(result.status).isEqualTo(Status.ERROR)
it.assertThat(result.events()).isEqualTo(listOf(Event(severity = Severity.ERROR, key = "ITEM_FORMAT_NULL", message = "Format mustn't be null.")))
}
assertSoftly {
it.assertThat(ItemUtils.getItemsCount(entityManager = entityManager)).isEqualTo(ItemUtils.ITEMS_COUNT)
it.assertThat(BookUtils.getBooksCount(entityManager = entityManager)).isEqualTo(BookUtils.BOOKS_COUNT)
}
}
/**
* Test method for [ItemFacade.update] with item with null note.
*/
@Test
fun updateNullNote() {
val item = ItemUtils.newItem(id = 1)
.copy(note = null)
val result = facade.update(data = item)
assertSoftly {
it.assertThat(result.status).isEqualTo(Status.ERROR)
it.assertThat(result.events()).isEqualTo(listOf(Event(severity = Severity.ERROR, key = "ITEM_NOTE_NULL", message = "Note mustn't be null.")))
}
assertSoftly {
it.assertThat(ItemUtils.getItemsCount(entityManager = entityManager)).isEqualTo(ItemUtils.ITEMS_COUNT)
it.assertThat(BookUtils.getBooksCount(entityManager = entityManager)).isEqualTo(BookUtils.BOOKS_COUNT)
}
}
/**
* Test method for [ItemFacade.update] with item with bad ID.
*/
@Test
fun updateBadId() {
val result = facade.update(data = ItemUtils.newItem(id = Int.MAX_VALUE))
assertSoftly {
it.assertThat(result.status).isEqualTo(Status.ERROR)
it.assertThat(result.events()).isEqualTo(listOf(ITEM_NOT_EXIST_EVENT))
}
assertSoftly {
it.assertThat(ItemUtils.getItemsCount(entityManager = entityManager)).isEqualTo(ItemUtils.ITEMS_COUNT)
it.assertThat(BookUtils.getBooksCount(entityManager = entityManager)).isEqualTo(BookUtils.BOOKS_COUNT)
}
}
/**
* Test method for [ItemFacade.remove].
*/
@Test
fun remove() {
val result = facade.remove(id = 1)
entityManager.flush()
assertSoftly {
it.assertThat(result.status).isEqualTo(Status.OK)
it.assertThat(result.events()).isEmpty()
}
assertThat(ItemUtils.getItem(entityManager = entityManager, id = 1)).isNull()
assertSoftly {
it.assertThat(ItemUtils.getItemsCount(entityManager = entityManager)).isEqualTo(ItemUtils.ITEMS_COUNT - 1)
it.assertThat(BookUtils.getBooksCount(entityManager = entityManager)).isEqualTo(BookUtils.BOOKS_COUNT)
}
}
/**
* Test method for [ItemFacade.remove] with item with bad ID.
*/
@Test
fun removeBadId() {
val result = facade.remove(id = Int.MAX_VALUE)
assertSoftly {
it.assertThat(result.status).isEqualTo(Status.ERROR)
it.assertThat(result.events()).isEqualTo(listOf(ITEM_NOT_EXIST_EVENT))
}
assertSoftly {
it.assertThat(ItemUtils.getItemsCount(entityManager = entityManager)).isEqualTo(ItemUtils.ITEMS_COUNT)
it.assertThat(BookUtils.getBooksCount(entityManager = entityManager)).isEqualTo(BookUtils.BOOKS_COUNT)
}
}
/**
* Test method for [ItemFacade.duplicate].
*/
@Test
@DirtiesContext
fun duplicate() {
val expectedItem = ItemUtils.getItemDomain(index = ItemUtils.ITEMS_COUNT)
.copy(id = ItemUtils.ITEMS_COUNT + 1)
.fillAudit(audit = AuditUtils.newAudit())
expectedItem.book = BookUtils.getBook(entityManager = entityManager, id = BookUtils.BOOKS_COUNT)
val result = facade.duplicate(id = ItemUtils.ITEMS_COUNT)
entityManager.flush()
assertSoftly {
it.assertThat(result.status).isEqualTo(Status.OK)
it.assertThat(result.events()).isEmpty()
}
ItemUtils.assertItemDeepEquals(expected = expectedItem, actual = ItemUtils.getItem(entityManager = entityManager, id = ItemUtils.ITEMS_COUNT + 1)!!)
assertSoftly {
it.assertThat(ItemUtils.getItemsCount(entityManager = entityManager)).isEqualTo(ItemUtils.ITEMS_COUNT + 1)
it.assertThat(BookUtils.getBooksCount(entityManager = entityManager)).isEqualTo(BookUtils.BOOKS_COUNT)
}
}
/**
* Test method for [ItemFacade.duplicate] with item with bad ID.
*/
@Test
fun duplicateBadId() {
val result = facade.duplicate(id = Int.MAX_VALUE)
assertSoftly {
it.assertThat(result.status).isEqualTo(Status.ERROR)
it.assertThat(result.events()).isEqualTo(listOf(ITEM_NOT_EXIST_EVENT))
}
assertSoftly {
it.assertThat(ItemUtils.getItemsCount(entityManager = entityManager)).isEqualTo(ItemUtils.ITEMS_COUNT)
it.assertThat(BookUtils.getBooksCount(entityManager = entityManager)).isEqualTo(BookUtils.BOOKS_COUNT)
}
}
/**
* Test method for [ItemFacade.moveUp].
*/
@Test
fun moveUp() {
val result = facade.moveUp(id = 2)
entityManager.flush()
assertSoftly {
it.assertThat(result.status).isEqualTo(Status.OK)
it.assertThat(result.events()).isEmpty()
}
val item1 = ItemUtils.getItemDomain(index = 1)
.copy(position = 11)
.fillAudit(audit = AuditUtils.updatedAudit())
val item2 = ItemUtils.getItemDomain(index = 2)
.copy(position = 10)
.fillAudit(audit = AuditUtils.updatedAudit())
ItemUtils.assertItemDeepEquals(expected = item1, actual = ItemUtils.getItem(entityManager = entityManager, id = 1)!!)
ItemUtils.assertItemDeepEquals(expected = item2, actual = ItemUtils.getItem(entityManager = entityManager, id = 2)!!)
for (i in 3..ItemUtils.ITEMS_COUNT) {
ItemUtils.assertItemDeepEquals(expected = ItemUtils.getItemDomain(i), actual = ItemUtils.getItem(entityManager = entityManager, id = i)!!)
}
assertSoftly {
it.assertThat(ItemUtils.getItemsCount(entityManager = entityManager)).isEqualTo(ItemUtils.ITEMS_COUNT)
it.assertThat(BookUtils.getBooksCount(entityManager = entityManager)).isEqualTo(BookUtils.BOOKS_COUNT)
}
}
/**
* Test method for [ItemFacade.moveUp] with not movable item.
*/
@Test
fun moveUpNotMovable() {
val result = facade.moveUp(id = 1)
assertSoftly {
it.assertThat(result.status).isEqualTo(Status.ERROR)
it.assertThat(result.events()).isEqualTo(listOf(Event(severity = Severity.ERROR, key = "ITEM_NOT_MOVABLE", message = "Item can't be moved up.")))
}
assertSoftly {
it.assertThat(ItemUtils.getItemsCount(entityManager = entityManager)).isEqualTo(ItemUtils.ITEMS_COUNT)
it.assertThat(BookUtils.getBooksCount(entityManager = entityManager)).isEqualTo(BookUtils.BOOKS_COUNT)
}
}
/**
* Test method for [ItemFacade.moveUp] with item with bad ID.
*/
@Test
fun moveUpBadId() {
val result = facade.moveUp(id = Int.MAX_VALUE)
assertSoftly {
it.assertThat(result.status).isEqualTo(Status.ERROR)
it.assertThat(result.events()).isEqualTo(listOf(ITEM_NOT_EXIST_EVENT))
}
assertSoftly {
it.assertThat(ItemUtils.getItemsCount(entityManager = entityManager)).isEqualTo(ItemUtils.ITEMS_COUNT)
it.assertThat(BookUtils.getBooksCount(entityManager = entityManager)).isEqualTo(BookUtils.BOOKS_COUNT)
}
}
/**
* Test method for [ItemFacade.moveDown].
*/
@Test
fun moveDown() {
val result = facade.moveDown(id = 1)
entityManager.flush()
assertSoftly {
it.assertThat(result.status).isEqualTo(Status.OK)
it.assertThat(result.events()).isEmpty()
}
val item1 = ItemUtils.getItemDomain(index = 1)
.copy(position = 11)
.fillAudit(audit = AuditUtils.updatedAudit())
val item2 = ItemUtils.getItemDomain(index = 2)
.copy(position = 10)
.fillAudit(audit = AuditUtils.updatedAudit())
ItemUtils.assertItemDeepEquals(expected = item1, actual = ItemUtils.getItem(entityManager = entityManager, id = 1)!!)
ItemUtils.assertItemDeepEquals(expected = item2, actual = ItemUtils.getItem(entityManager = entityManager, id = 2)!!)
for (i in 3..ItemUtils.ITEMS_COUNT) {
ItemUtils.assertItemDeepEquals(expected = ItemUtils.getItemDomain(i), actual = ItemUtils.getItem(entityManager = entityManager, id = i)!!)
}
assertSoftly {
it.assertThat(ItemUtils.getItemsCount(entityManager = entityManager)).isEqualTo(ItemUtils.ITEMS_COUNT)
it.assertThat(BookUtils.getBooksCount(entityManager = entityManager)).isEqualTo(BookUtils.BOOKS_COUNT)
}
}
/**
* Test method for [ItemFacade.moveDown] with not movable item.
*/
@Test
fun moveDownNotMovable() {
val result = facade.moveDown(id = ItemUtils.ITEMS_COUNT)
assertSoftly {
it.assertThat(result.status).isEqualTo(Status.ERROR)
it.assertThat(result.events()).isEqualTo(listOf(Event(severity = Severity.ERROR, key = "ITEM_NOT_MOVABLE", message = "Item can't be moved down.")))
}
assertSoftly {
it.assertThat(ItemUtils.getItemsCount(entityManager = entityManager)).isEqualTo(ItemUtils.ITEMS_COUNT)
it.assertThat(BookUtils.getBooksCount(entityManager = entityManager)).isEqualTo(BookUtils.BOOKS_COUNT)
}
}
/**
* Test method for [ItemFacade.moveDown] with item with bad ID.
*/
@Test
fun moveDownBadId() {
val result = facade.moveDown(id = Int.MAX_VALUE)
assertSoftly {
it.assertThat(result.status).isEqualTo(Status.ERROR)
it.assertThat(result.events()).isEqualTo(listOf(ITEM_NOT_EXIST_EVENT))
}
assertSoftly {
it.assertThat(ItemUtils.getItemsCount(entityManager = entityManager)).isEqualTo(ItemUtils.ITEMS_COUNT)
it.assertThat(BookUtils.getBooksCount(entityManager = entityManager)).isEqualTo(BookUtils.BOOKS_COUNT)
}
}
/**
* Test method for [ItemFacade.add].
*/
@Test
@DirtiesContext
fun add() {
val expectedItem = ItemUtils.newItemDomain(id = ItemUtils.ITEMS_COUNT + 1)
.fillAudit(audit = AuditUtils.newAudit())
expectedItem.book = BookUtils.getBook(entityManager = entityManager, id = 1)
val result = facade.add(parent = 1, data = ItemUtils.newItem(id = null))
entityManager.flush()
assertSoftly {
it.assertThat(result.status).isEqualTo(Status.OK)
it.assertThat(result.events()).isEmpty()
}
ItemUtils.assertItemDeepEquals(expected = expectedItem, actual = ItemUtils.getItem(entityManager = entityManager, id = ItemUtils.ITEMS_COUNT + 1)!!)
assertSoftly {
it.assertThat(ItemUtils.getItemsCount(entityManager = entityManager)).isEqualTo(ItemUtils.ITEMS_COUNT + 1)
it.assertThat(BookUtils.getBooksCount(entityManager = entityManager)).isEqualTo(BookUtils.BOOKS_COUNT)
}
}
/**
* Test method for [ItemFacade.add] with bad book ID.
*/
@Test
fun addBadBookId() {
val result = facade.add(parent = Int.MAX_VALUE, data = ItemUtils.newItem(id = null))
assertSoftly {
it.assertThat(result.status).isEqualTo(Status.ERROR)
it.assertThat(result.events()).isEqualTo(listOf(BOOK_NOT_EXIST_EVENT))
}
assertSoftly {
it.assertThat(ItemUtils.getItemsCount(entityManager = entityManager)).isEqualTo(ItemUtils.ITEMS_COUNT)
it.assertThat(BookUtils.getBooksCount(entityManager = entityManager)).isEqualTo(BookUtils.BOOKS_COUNT)
}
}
/**
* Test method for [ItemFacade.add] with item with not null ID.
*/
@Test
fun addNotNullId() {
val item = ItemUtils.newItem(id = null)
.copy(id = Int.MAX_VALUE)
val result = facade.add(parent = 1, data = item)
assertSoftly {
it.assertThat(result.status).isEqualTo(Status.ERROR)
it.assertThat(result.events()).isEqualTo(listOf(Event(severity = Severity.ERROR, key = "ITEM_ID_NOT_NULL", message = "ID must be null.")))
}
assertSoftly {
it.assertThat(ItemUtils.getItemsCount(entityManager = entityManager)).isEqualTo(ItemUtils.ITEMS_COUNT)
it.assertThat(BookUtils.getBooksCount(entityManager = entityManager)).isEqualTo(BookUtils.BOOKS_COUNT)
}
}
/**
* Test method for [ItemFacade.add] with item with not null position.
*/
@Test
fun addNotNullPosition() {
val item = ItemUtils.newItem(id = null)
.copy(position = Int.MAX_VALUE)
val result = facade.add(parent = 1, data = item)
assertSoftly {
it.assertThat(result.status).isEqualTo(Status.ERROR)
it.assertThat(result.events()).isEqualTo(listOf(Event(severity = Severity.ERROR, key = "ITEM_POSITION_NOT_NULL", message = "Position must be null.")))
}
assertSoftly {
it.assertThat(ItemUtils.getItemsCount(entityManager = entityManager)).isEqualTo(ItemUtils.ITEMS_COUNT)
it.assertThat(BookUtils.getBooksCount(entityManager = entityManager)).isEqualTo(BookUtils.BOOKS_COUNT)
}
}
/**
* Test method for [ItemFacade.add] with item with null languages.
*/
@Test
fun addNullLanguages() {
val item = ItemUtils.newItem(id = null)
.copy(languages = null)
val result = facade.add(parent = 1, data = item)
assertSoftly {
it.assertThat(result.status).isEqualTo(Status.ERROR)
it.assertThat(result.events()).isEqualTo(listOf(Event(severity = Severity.ERROR, key = "ITEM_LANGUAGES_NULL", message = "Languages mustn't be null.")))
}
assertSoftly {
it.assertThat(ItemUtils.getItemsCount(entityManager = entityManager)).isEqualTo(ItemUtils.ITEMS_COUNT)
it.assertThat(BookUtils.getBooksCount(entityManager = entityManager)).isEqualTo(BookUtils.BOOKS_COUNT)
}
}
/**
* Test method for [ItemFacade.add] with item with empty empty languages.
*/
@Test
fun addEmptyLanguages() {
val item = ItemUtils.newItem(id = null)
.copy(languages = emptyList())
val result = facade.add(parent = 1, data = item)
assertSoftly {
it.assertThat(result.status).isEqualTo(Status.ERROR)
it.assertThat(result.events()).isEqualTo(listOf(Event(severity = Severity.ERROR, key = "ITEM_LANGUAGES_EMPTY", message = "Languages mustn't be empty.")))
}
assertSoftly {
it.assertThat(ItemUtils.getItemsCount(entityManager = entityManager)).isEqualTo(ItemUtils.ITEMS_COUNT)
it.assertThat(BookUtils.getBooksCount(entityManager = entityManager)).isEqualTo(BookUtils.BOOKS_COUNT)
}
}
/**
* Test method for [ItemFacade.add] with item with languages with null value.
*/
@Test
fun addBadLanguages() {
val item = ItemUtils.newItem(id = null)
.copy(languages = listOf(Language.CZ, null))
val result = facade.add(parent = 1, data = item)
assertSoftly {
it.assertThat(result.status).isEqualTo(Status.ERROR)
it.assertThat(result.events()).isEqualTo(listOf(Event(severity = Severity.ERROR, key = "ITEM_LANGUAGES_CONTAIN_NULL", message = "Languages mustn't contain null value.")))
}
assertSoftly {
it.assertThat(ItemUtils.getItemsCount(entityManager = entityManager)).isEqualTo(ItemUtils.ITEMS_COUNT)
it.assertThat(BookUtils.getBooksCount(entityManager = entityManager)).isEqualTo(BookUtils.BOOKS_COUNT)
}
}
/**
* Test method for [ItemFacade.add] with item with null format.
*/
@Test
fun addNullFormat() {
val item = ItemUtils.newItem(id = null)
.copy(format = null)
val result = facade.add(parent = 1, data = item)
assertSoftly {
it.assertThat(result.status).isEqualTo(Status.ERROR)
it.assertThat(result.events()).isEqualTo(listOf(Event(severity = Severity.ERROR, key = "ITEM_FORMAT_NULL", message = "Format mustn't be null.")))
}
assertSoftly {
it.assertThat(ItemUtils.getItemsCount(entityManager = entityManager)).isEqualTo(ItemUtils.ITEMS_COUNT)
it.assertThat(BookUtils.getBooksCount(entityManager = entityManager)).isEqualTo(BookUtils.BOOKS_COUNT)
}
}
/**
* Test method for [ItemFacade.add] with item with null note.
*/
@Test
fun addNullNote() {
val item = ItemUtils.newItem(id = null)
.copy(note = null)
val result = facade.add(parent = 1, data = item)
assertSoftly {
it.assertThat(result.status).isEqualTo(Status.ERROR)
it.assertThat(result.events()).isEqualTo(listOf(Event(severity = Severity.ERROR, key = "ITEM_NOTE_NULL", message = "Note mustn't be null.")))
}
assertSoftly {
it.assertThat(ItemUtils.getItemsCount(entityManager = entityManager)).isEqualTo(ItemUtils.ITEMS_COUNT)
it.assertThat(BookUtils.getBooksCount(entityManager = entityManager)).isEqualTo(BookUtils.BOOKS_COUNT)
}
}
/**
* Test method for [ItemFacade.find].
*/
@Test
fun find() {
for (i in 1..BookUtils.BOOKS_COUNT) {
val result = facade.find(parent = i)
assertSoftly {
it.assertThat(result.status).isEqualTo(Status.OK)
it.assertThat(result.data).isNotNull
it.assertThat(result.events()).isEmpty()
}
ItemUtils.assertItemListDeepEquals(expected = ItemUtils.getItems(book = i), actual = result.data!!)
}
assertSoftly {
it.assertThat(ItemUtils.getItemsCount(entityManager = entityManager)).isEqualTo(ItemUtils.ITEMS_COUNT)
it.assertThat(BookUtils.getBooksCount(entityManager = entityManager)).isEqualTo(BookUtils.BOOKS_COUNT)
}
}
/**
* Test method for [ItemFacade.find] with bad music ID.
*/
@Test
fun findBadBookId() {
val result = facade.find(parent = Int.MAX_VALUE)
assertSoftly {
it.assertThat(result.status).isEqualTo(Status.ERROR)
it.assertThat(result.events()).isEqualTo(listOf(BOOK_NOT_EXIST_EVENT))
}
assertSoftly {
it.assertThat(ItemUtils.getItemsCount(entityManager = entityManager)).isEqualTo(ItemUtils.ITEMS_COUNT)
it.assertThat(BookUtils.getBooksCount(entityManager = entityManager)).isEqualTo(BookUtils.BOOKS_COUNT)
}
}
companion object {
/**
* Event for not existing item
*/
private val ITEM_NOT_EXIST_EVENT = Event(severity = Severity.ERROR, key = "ITEM_NOT_EXIST", message = "Item doesn't exist.")
/**
* Event for not existing music
*/
private val BOOK_NOT_EXIST_EVENT = Event(severity = Severity.ERROR, key = "BOOK_NOT_EXIST", message = "Book doesn't exist.")
}
}
| 0
|
Kotlin
|
0
| 0
|
c3b6da21b0be7cdc5a13ceb3f04937316207bf77
| 27,720
|
Bookcase
|
MIT License
|
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/lower/CallableReferenceLowering.kt
|
damalmax
| 91,635,300
| true
|
{"Markdown": 14, "Git Config": 1, "Gradle": 22, "Java Properties": 5, "Shell": 13, "Ignore List": 1, "Batchfile": 1, "XML": 12, "Kotlin": 4177, "C": 24, "Makefile": 1, "Text": 69, "Java": 2, "Protocol Buffer": 2, "C++": 25, "Groovy": 6, "INI": 6, "OpenStep Property List": 1}
|
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.backend.konan.lower
import org.jetbrains.kotlin.backend.common.DeclarationContainerLoweringPass
import org.jetbrains.kotlin.backend.common.descriptors.explicitParameters
import org.jetbrains.kotlin.backend.common.lower.createIrBuilder
import org.jetbrains.kotlin.backend.konan.KonanBackendContext
import org.jetbrains.kotlin.backend.konan.descriptors.getKonanInternalClass
import org.jetbrains.kotlin.backend.konan.descriptors.isFunctionOrKFunctionType
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.descriptors.impl.SimpleFunctionDescriptorImpl
import org.jetbrains.kotlin.descriptors.impl.ValueParameterDescriptorImpl
import org.jetbrains.kotlin.ir.IrElement
import org.jetbrains.kotlin.ir.IrStatement
import org.jetbrains.kotlin.ir.builders.*
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.declarations.impl.IrFunctionImpl
import org.jetbrains.kotlin.ir.expressions.IrCallableReference
import org.jetbrains.kotlin.ir.expressions.IrExpression
import org.jetbrains.kotlin.ir.expressions.impl.IrCallImpl
import org.jetbrains.kotlin.ir.expressions.impl.IrCallableReferenceImpl
import org.jetbrains.kotlin.ir.expressions.impl.IrVarargImpl
import org.jetbrains.kotlin.ir.util.addArguments
import org.jetbrains.kotlin.ir.util.getArguments
import org.jetbrains.kotlin.ir.util.transformFlat
import org.jetbrains.kotlin.ir.visitors.IrElementTransformerVoid
import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid
import org.jetbrains.kotlin.name.Name
/**
* This lowering pass lowers all [IrCallableReference]s to unbound ones.
*/
internal class CallableReferenceLowering(val context: KonanBackendContext) : DeclarationContainerLoweringPass {
var callableReferenceCount = 0
override fun lower(irDeclarationContainer: IrDeclarationContainer) {
irDeclarationContainer.declarations.transformFlat { declaration ->
if (declaration !is IrDeclarationContainer)
lowerCallableReferences(this, irDeclarationContainer, declaration)
else
null
}
}
}
/**
* Replaces all callable references in the function body to unbound ones.
* Returns the list of this function and all created ones.
*/
private fun lowerCallableReferences(lower: CallableReferenceLowering,
irDeclarationContainer: IrDeclarationContainer,
declaration: IrDeclaration): List<IrDeclaration> {
val containingDeclaration = when (irDeclarationContainer) {
is IrClass -> irDeclarationContainer.descriptor
is IrFile -> irDeclarationContainer.packageFragmentDescriptor
else -> throw AssertionError("Unexpected declaration container: $irDeclarationContainer")
}
val transformer = CallableReferencesUnbinder(lower, containingDeclaration)
declaration.transformChildrenVoid(transformer)
return listOf(declaration) + transformer.createdFunctions
}
private object DECLARATION_ORIGIN_FUNCTION_FOR_CALLABLE_REFERENCE :
IrDeclarationOriginImpl("FUNCTION_FOR_CALLABLE_REFERENCE")
/**
* Replaces all callable references in the function body to unbound ones.
* Adds all created functions to [createdFunctions].
*/
private class CallableReferencesUnbinder(val lower: CallableReferenceLowering,
val containingDeclaration: DeclarationDescriptor) : IrElementTransformerVoid() {
val createdFunctions = mutableListOf<IrFunction>()
private val builtIns = lower.context.builtIns
override fun visitElement(element: IrElement): IrElement {
return super.visitElement(element)
}
private val unboundCallableReferenceType by lazy {
builtIns.getKonanInternalClass("UnboundCallableReference").defaultType
}
private val simpleFunctionImplClass by lazy {
builtIns.getKonanInternalClass("SimpleFunctionImpl")
}
private val simpleFunctionImplBoundArgsGetter by lazy {
simpleFunctionImplClass.defaultType.memberScope.getContributedDescriptors()
.filterIsInstance<PropertyDescriptor>()
.single { it.name.asString() == "boundArgs" }
.getter!!
}
override fun visitClass(declaration: IrClass): IrStatement {
// Class is a declaration container - it will be visited by the main visitor (CallableReferenceLowering).
return declaration
}
override fun visitCallableReference(expression: IrCallableReference): IrExpression {
expression.transformChildrenVoid(this)
if (!expression.type.isFunctionOrKFunctionType) {
// Not a subject of this lowering.
return expression
}
val descriptor = expression.descriptor
val boundArgs = expression.getArguments()
val boundParams = boundArgs.map { it.first }
val allParams = descriptor.explicitParameters
val unboundParams = allParams - boundParams
val startOffset = expression.startOffset
val endOffset = expression.endOffset
// The code below creates a call to `SimpleFunctionImpl` constructor which creates the object implementing
// the function type.
// Create the function to be used as `unboundRef` of `SimpleFunctionImpl`:
val newFunction = createSimpleFunctionImplTarget(descriptor, unboundParams, boundParams, startOffset, endOffset)
createdFunctions.add(newFunction)
// Create the call to constructor and its arguments:
val unboundRef = IrCallableReferenceImpl(startOffset, endOffset,
unboundCallableReferenceType, newFunction.descriptor, null)
val simpleFunctionImplClassConstructor = simpleFunctionImplClass.unsubstitutedPrimaryConstructor!!
val boundArgsVarargParam = simpleFunctionImplClassConstructor.valueParameters[1]
val boundArgsVararg = IrVarargImpl(
startOffset, endOffset,
boundArgsVarargParam.type,
boundArgsVarargParam.varargElementType!!,
boundArgs.map { it.second }
)
return IrCallImpl(startOffset, endOffset, simpleFunctionImplClassConstructor).apply {
putValueArgument(0, unboundRef)
putValueArgument(1, boundArgsVararg)
}
}
/**
* For given function [descriptor] creates the function which calls [descriptor] but
* takes all [boundParams] packed into `SimpleFunctionImpl` (and all [unboundParams] as is).
*/
private fun createSimpleFunctionImplTarget(descriptor: CallableDescriptor,
unboundParams: List<ParameterDescriptor>,
boundParams: List<ParameterDescriptor>,
startOffset: Int, endOffset: Int): IrFunctionImpl {
// Create new function descriptor:
val newDescriptor = createSimpleFunctionImplTargetDescriptor(descriptor, unboundParams)
val builder = lower.context.createIrBuilder(newDescriptor)
val blockBody = builder.irBlockBody(startOffset, endOffset) {
val boundArgsGet = irCall(simpleFunctionImplBoundArgsGetter).apply {
dispatchReceiver = irGet(newDescriptor.valueParameters[0])
}
+irLet(boundArgsGet) { boundArgs ->
val arrayGet = boundArgs.type.memberScope.getContributedDescriptors()
.filterIsInstance<FunctionDescriptor>().single { it.name.asString() == "get" }
// TODO: some handling for type parameters is probably required here.
// Call to old function from new function:
val call = irCall(descriptor).apply {
// unboundParams are received as all new function parameters except first:
val newUnboundParams = newDescriptor.valueParameters.drop(1)
assert (unboundParams.size == newUnboundParams.size)
addArguments(unboundParams.mapIndexed { index, param ->
param to irGet(newUnboundParams[index])
})
// boundParams are received in `SimpleFunctionImpl.boundArgs`:
addArguments(boundParams.mapIndexed { index, param ->
param to irCall(arrayGet).apply {
dispatchReceiver = irGet(boundArgs)
putValueArgument(0, irInt(index))
}
})
}
irReturn(call)
}
}
val newFunction = IrFunctionImpl(
startOffset, endOffset, DECLARATION_ORIGIN_FUNCTION_FOR_CALLABLE_REFERENCE,
newDescriptor,
blockBody
)
return newFunction
}
/**
* Creates descriptor for [createSimpleFunctionImplTarget].
*/
private fun createSimpleFunctionImplTargetDescriptor(descriptor: CallableDescriptor,
unboundParams: List<ParameterDescriptor>): FunctionDescriptor {
val newName = Name.identifier("${descriptor.name}\$bound-${lower.callableReferenceCount++}")
val newDescriptor = SimpleFunctionDescriptorImpl.create(
containingDeclaration, Annotations.EMPTY,
newName, CallableMemberDescriptor.Kind.SYNTHESIZED, SourceElement.NO_SOURCE)
val simpleFunctionImplType = simpleFunctionImplClass.defaultType
// Map each unbound param of original function to parameter of new function.
val newUnboundParams = unboundParams.mapIndexed { index, param ->
ValueParameterDescriptorImpl(
containingDeclaration = newDescriptor,
original = null,
index = index + 1,
annotations = Annotations.EMPTY,
name = param.name,
outType = builtIns.nullableAnyType, // Use erased type.
declaresDefaultValue = false,
isCrossinline = false, isNoinline = false,
varargElementType = null,
source = SourceElement.NO_SOURCE)
}
// `<func>: SimpleFunctionImpl`
val functionParameter = ValueParameterDescriptorImpl(
containingDeclaration = newDescriptor,
original = null,
index = 0,
annotations = Annotations.EMPTY,
name = Name.special("<func>"),
outType = simpleFunctionImplType,
declaresDefaultValue = false,
isCrossinline = false, isNoinline = false,
varargElementType = null,
source = SourceElement.NO_SOURCE)
val newValueParameters = listOf(functionParameter) + newUnboundParams
val newReturnType = builtIns.nullableAnyType // Use erased type.
newDescriptor.initialize(null, null, descriptor.typeParameters, newValueParameters,
newReturnType, Modality.FINAL, Visibilities.PRIVATE)
return newDescriptor
}
}
| 0
|
Kotlin
|
0
| 0
|
dc80ba34929c47de2933af02f3d0a57ad59e88c3
| 11,868
|
kotlin-native
|
Apache License 2.0
|
app/src/main/java/com/febers/iuestc/lifecycle/IActivity.kt
|
Febers
| 136,202,080
| false
| null |
package com.febers.iuestc.lifecycle
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
abstract class IActivity: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(contentLayout())
}
private var activityCreated = false
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (!activityCreated && hasFocus) {
activityCreated = true
afterResume()
}
}
open fun afterResume(){ }
abstract fun contentLayout(): Int
}
| 3
|
Java
|
3
| 31
|
c83c21f28a78fe6bac6e6359494acec8b8d16799
| 644
|
iUESTC
|
Apache License 2.0
|
ok-marketplace-be-repo-test/src/main/kotlin/ru/otus/otuskotlin/marketplace/backend/repo/test/RepoAdUpdateTest.kt
|
otuskotlin
| 375,767,209
| false
| null |
package ru.otus.otuskotlin.marketplace.backend.repo.test
import kotlinx.coroutines.runBlocking
import org.junit.Test
import ru.otus.otuskotlin.marketplace.backend.common.models.*
import ru.otus.otuskotlin.marketplace.backend.repo.common.DbAdModelRequest
import ru.otus.otuskotlin.marketplace.backend.repo.common.IRepoAd
import java.util.*
import kotlin.test.assertEquals
abstract class RepoAdUpdateTest {
abstract val repo: IRepoAd
@Test
fun updateSuccess() {
val result = runBlocking { repo.update(DbAdModelRequest(updateObj)) }
assertEquals(true, result.isSuccess)
assertEquals(updateObj, result.result)
assertEquals(emptyList(), result.errors)
}
@Test
fun updateNotFound() {
val result = runBlocking { repo.update(DbAdModelRequest(updateObjNotFound)) }
assertEquals(false, result.isSuccess)
assertEquals(null, result.result)
assertEquals(listOf(CommonErrorModel(field = "id", message = "Not Found")), result.errors)
}
companion object: BaseInitAds() {
override val initObjects: List<AdModel> = listOf(
createInitTestModel("update")
)
private val updateId = initObjects.first().id
private val updateIdNotFound = AdIdModel(UUID.randomUUID())
private val updateObj = AdModel(
id = updateId,
title = "update object",
description = "update object description",
ownerId = OwnerIdModel(UUID.randomUUID()),
visibility = AdVisibilityModel.REGISTERED_ONLY,
dealSide = DealSideModel.PROPOSAL,
)
private val updateObjNotFound = AdModel(
id = updateIdNotFound,
title = "update object not found",
description = "update object not found description",
ownerId = OwnerIdModel(UUID.randomUUID()),
visibility = AdVisibilityModel.REGISTERED_ONLY,
dealSide = DealSideModel.PROPOSAL,
)
}
}
| 0
|
Kotlin
|
5
| 9
|
f7b000e861fb35b5e0a641782fb7fe746814da31
| 1,999
|
202105-otuskotlin-marketplace
|
MIT License
|
app/src/main/java/com/torchdragon/gish/api/GitHubApi.kt
|
torchdragon
| 262,654,301
| false
| null |
package com.torchdragon.gish.api
import com.torchdragon.gish.model.issues.GitHubIssue
import com.torchdragon.gish.model.repositories.GitHubRepository
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Query
import retrofit2.http.Url
interface GitHubApi {
companion object {
const val BASE_URL = "https://api.github.com/"
const val ORG_REPOSITORIES_PATH = "orgs/{org}/repos"
const val ITEMS_PER_PAGE = 100
}
@GET
suspend fun repositories(@Url pagingUrl: String, @Query("per_page") itemsPerPage: Int? = null): Response<List<GitHubRepository>>
@GET
suspend fun issues(@Url pagingUrl: String, @Query("state") state: String? = null, @Query("per_page") itemsPerPage: Int? = null): Response<List<GitHubIssue>>
}
| 0
|
Kotlin
|
0
| 0
|
ae950c83ed1848a34c89fa7022c4794d9682fdcd
| 782
|
gish
|
MIT License
|
test-annotations/src/main/kotlin/com/avito/android/test/annotations/Regression.kt
|
mduisenov
| 237,274,875
| true
|
{"Kotlin": 2360982, "Python": 14063, "Shell": 13206, "Dockerfile": 7097, "Makefile": 35}
|
package com.avito.android.test.annotations
/**
* Identifies case as part of Regression suite
*/
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.CLASS)
annotation class Regression
| 0
|
Kotlin
|
0
| 0
|
b0513404cc36196fb87ddadd1894b9015beac952
| 226
|
avito-android
|
Apache License 2.0
|
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/EyeDropper.kt
|
localhostov
| 808,861,591
| false
|
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.rounded.bold
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Bold.EyeDropper: ImageVector
get() {
if (_eyeDropper != null) {
return _eyeDropper!!
}
_eyeDropper = Builder(name = "EyeDropper", defaultWidth = 512.0.dp, defaultHeight =
512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(22.965f, 6.019f)
arcToRelative(3.525f, 3.525f, 0.0f, false, false, 0.0f, -4.987f)
arcToRelative(3.608f, 3.608f, 0.0f, false, false, -4.982f, 0.0f)
lineToRelative(-1.436f, 1.438f)
curveToRelative(-0.834f, 0.835f, -2.718f, 0.6f, -3.984f, -0.1f)
arcToRelative(3.1f, 3.1f, 0.0f, false, false, -3.653f, 4.938f)
lineToRelative(1.077f, 1.077f)
lineToRelative(-7.815f, 8.054f)
arcToRelative(3.942f, 3.942f, 0.0f, false, false, -0.921f, 4.189f)
lineToRelative(-0.812f, 0.811f)
arcToRelative(1.5f, 1.5f, 0.0f, false, false, 2.122f, 2.122f)
lineToRelative(0.706f, -0.707f)
arcToRelative(3.957f, 3.957f, 0.0f, false, false, 4.577f, -0.774f)
lineToRelative(7.8f, -8.038f)
lineToRelative(1.048f, 1.048f)
arcToRelative(3.1f, 3.1f, 0.0f, false, false, 4.935f, -3.652f)
curveToRelative(-0.7f, -1.267f, -0.932f, -3.15f, -0.1f, -3.985f)
close()
moveTo(5.707f, 19.975f)
arcToRelative(1.0f, 1.0f, 0.0f, true, true, -1.4f, -1.431f)
lineToRelative(7.8f, -8.038f)
lineToRelative(1.413f, 1.414f)
close()
moveTo(20.846f, 3.9f)
lineTo(19.409f, 5.332f)
curveToRelative(-1.934f, 1.933f, -1.67f, 5.262f, -0.445f, 7.637f)
arcToRelative(0.108f, 0.108f, 0.0f, false, true, -0.151f, 0.0f)
lineToRelative(-7.782f, -7.782f)
curveToRelative(-0.031f, -0.036f, -0.031f, -0.116f, 0.085f, -0.187f)
curveToRelative(2.289f, 1.26f, 5.619f, 1.524f, 7.552f, -0.409f)
lineToRelative(1.439f, -1.439f)
arcToRelative(0.524f, 0.524f, 0.0f, false, true, 0.739f, 0.742f)
close()
}
}
.build()
return _eyeDropper!!
}
private var _eyeDropper: ImageVector? = null
| 1
|
Kotlin
|
0
| 5
|
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 3,187
|
icons
|
MIT License
|
core-db/src/main/java/io/novafoundation/nova/core_db/model/chain/account/ProxyAccountLocal.kt
|
novasamatech
| 415,834,480
| false
|
{"Kotlin": 11121812, "Rust": 25308, "Java": 17664, "JavaScript": 425}
|
package io.novafoundation.nova.core_db.model.chain.account
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Ignore
import io.novafoundation.nova.common.utils.Identifiable
import io.novafoundation.nova.core_db.model.chain.ChainLocal
import io.novasama.substrate_sdk_android.extensions.toHexString
@Entity(
tableName = "proxy_accounts",
foreignKeys = [
ForeignKey(
parentColumns = ["id"],
childColumns = ["proxiedMetaId"],
entity = MetaAccountLocal::class,
onDelete = ForeignKey.CASCADE
),
ForeignKey(
parentColumns = ["id"],
childColumns = ["proxyMetaId"],
entity = MetaAccountLocal::class,
onDelete = ForeignKey.CASCADE
),
ForeignKey(
parentColumns = ["id"],
childColumns = ["chainId"],
entity = ChainLocal::class,
onDelete = ForeignKey.CASCADE
),
],
primaryKeys = ["proxyMetaId", "proxiedAccountId", "chainId", "proxyType"]
)
data class ProxyAccountLocal(
val proxiedMetaId: Long,
val proxyMetaId: Long,
val chainId: String,
val proxiedAccountId: ByteArray,
val proxyType: String
) : Identifiable {
@Ignore
override val identifier: String = makeIdentifier(proxyMetaId, chainId, proxiedAccountId, proxyType)
companion object {
fun makeIdentifier(
proxyMetaId: Long,
chainId: String,
proxiedAccountId: ByteArray,
proxyType: String
): String {
return "$proxyMetaId:$chainId:${proxiedAccountId.toHexString()}:$proxyType"
}
}
}
| 14
|
Kotlin
|
6
| 50
|
166755d1c3388a7afd9b592402489ea5ca26fdb8
| 1,688
|
nova-wallet-android
|
Apache License 2.0
|
app/src/main/java/com/holydev/biocheck/ImageAnalyzer.kt
|
PovarIsSFEDU
| 717,582,038
| false
|
{"Kotlin": 26255}
|
package com.holydev.biocheck
import android.content.ContentValues
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Matrix
import android.graphics.Paint
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import androidx.annotation.OptIn
import androidx.annotation.RequiresApi
import androidx.camera.core.ExperimentalGetImage
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageProxy
import com.google.mlkit.vision.common.InputImage
import com.google.mlkit.vision.facemesh.FaceMeshDetection
import com.google.mlkit.vision.facemesh.FaceMeshDetectorOptions
import java.io.File
import java.io.FileOutputStream
import java.io.OutputStream
import kotlin.system.measureTimeMillis
class ImageAnalyzer(mainActivity: MainActivity) : ImageAnalysis.Analyzer {
val ctx = mainActivity
@RequiresApi(Build.VERSION_CODES.Q)
@OptIn(ExperimentalGetImage::class)
override fun analyze(imageProxy: ImageProxy) {
val time = measureTimeMillis {
val mediaImage = imageProxy.image
if (mediaImage != null) {
val buffer = mediaImage.planes!![0].buffer
val bytes = ByteArray(buffer.capacity())
buffer.position(0);
buffer.get(bytes)
val bitmapImage =
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, null)
// val new_bitmap = BITMAP_RESIZER(bitmapImage, 720, 1280)
val mutableBitmap: Bitmap =
bitmapImage.copy(Bitmap.Config.ARGB_8888, true)
val image = InputImage.fromBitmap(mutableBitmap, 0)
// Pass image to an ML Kit Vision API
val defaultDetector = FaceMeshDetection.getClient(
FaceMeshDetectorOptions.Builder()
.setUseCase(FaceMeshDetectorOptions.FACE_MESH)
.build()
)
val result = defaultDetector.process(image)
.addOnSuccessListener { result ->
val canvas = Canvas(mutableBitmap)
val p = Paint()
p.style = Paint.Style.FILL_AND_STROKE
p.isAntiAlias = true
p.isFilterBitmap = true
p.isDither = true
p.color = Color.GREEN
for (faceMesh in result) {
// val bounds: Rect = faceMesh.boundingBox
// Gets all points
for (faceMeshpoint in faceMesh.allPoints) {
val position = faceMeshpoint.position
canvas.drawCircle(position.x, position.y, 3f, p)
}
// Gets triangle info
/*val triangles: List<Triangle<FaceMeshPoint>> = faceMesh.allTriangles
for (triangle in triangles) {
// 3 Points connecting to each other and representing a triangle area.
val connectedPoints = triangle.allPoints
}*/
}
canvas.drawBitmap(mutableBitmap, 0f, 0f, p)
saveMediaToStorage(mutableBitmap)
}
.addOnFailureListener { e ->
e.message?.let { Log.e("mesh-1", it) }
}
}
}
Log.d("timer", time.toString())
}
fun saveMediaToStorage(bitmap: Bitmap) {
//Generating a file name
val filename = "${System.currentTimeMillis()}.jpg"
//Output stream
var fos: OutputStream? = null
//For devices running android >= Q
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
//getting the contentResolver
ctx.contentResolver?.also { resolver ->
//Content resolver will process the contentvalues
val contentValues = ContentValues().apply {
//putting file information in content values
put(MediaStore.MediaColumns.DISPLAY_NAME, filename)
put(MediaStore.MediaColumns.MIME_TYPE, "image/jpg")
put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES)
}
//Inserting the contentValues to contentResolver and getting the Uri
val imageUri: Uri? =
resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
//Opening an outputstream with the Uri that we got
fos = imageUri?.let { resolver.openOutputStream(it) }
}
} else {
//These for devices running on android < Q
//So I don't think an explanation is needed here
val imagesDir =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
val image = File(imagesDir, filename)
fos = FileOutputStream(image)
}
fos?.use {
//Finally writing the bitmap to the output stream that we opened
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, it)
// ctx?.toast("Saved to Photos")
}
}
fun BITMAP_RESIZER(bitmap: Bitmap, newWidth: Int, newHeight: Int): Bitmap {
val scaledBitmap = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888)
val ratioX = newWidth / bitmap.width.toFloat()
val ratioY = newHeight / bitmap.height.toFloat()
val middleX = newWidth / 2.0f
val middleY = newHeight / 2.0f
val scaleMatrix = Matrix()
scaleMatrix.setScale(ratioX, ratioY, middleX, middleY)
val canvas = Canvas(scaledBitmap)
canvas.setMatrix(scaleMatrix)
canvas.drawBitmap(
bitmap,
middleX - bitmap.width / 2,
middleY - bitmap.height / 2,
Paint(Paint.FILTER_BITMAP_FLAG)
)
return scaledBitmap
}
}
| 0
|
Kotlin
|
0
| 0
|
bd6f1a713dd327a7714a181313fb143b1a5c1d43
| 6,332
|
BioCheck
|
MIT License
|
app/src/main/java/io/freshdroid/mediapickerinstagram/lib/utils/TransitionUtils.kt
|
gm4s
| 126,516,097
| false
| null |
package io.freshdroid.mymonzo.core.ui
import android.app.Activity
import android.content.Context
import androidx.fragment.app.Fragment
import io.freshdroid.mymonzo.core.R
object TransitionUtils {
/**
* Explicitly set a transition after starting an activity.
*
* @param context The activity that started the new intent.
* @param transition A pair of animation ids, first is the enter animation, second is the exit animation.
*/
@JvmStatic
fun transition(context: Context, transition: Pair<Int, Int>) {
if (context !is Activity) {
return
}
context.overridePendingTransition(transition.first, transition.second)
}
@JvmStatic
fun transition(fragment: Fragment, transition: Pair<Int, Int>) {
if (fragment.activity !is Activity) {
return
}
fragment.activity?.overridePendingTransition(transition.first, transition.second)
}
@JvmStatic
fun slideInRight(): Pair<Int, Int> {
return Pair(R.anim.slide_in_right, R.anim.zoom_out)
}
@JvmStatic
fun slideOutRight(): Pair<Int, Int> {
return Pair(R.anim.zoom_in, R.anim.slide_out_right)
}
@JvmStatic
fun slideInUp(): Pair<Int, Int> {
return Pair(R.anim.slide_in_up, R.anim.stay)
}
@JvmStatic
fun slideOutDown(): Pair<Int, Int> {
return Pair(R.anim.stay, R.anim.slide_out_down)
}
@JvmStatic
fun fadeIn(): Pair<Int, Int> {
return Pair(R.anim.fade_in_full, R.anim.stay)
}
@JvmStatic
fun fadeOut(): Pair<Int, Int> {
return Pair(R.anim.stay, R.anim.fade_out_full)
}
}
| 2
|
Kotlin
|
24
| 61
|
ceaade4ae51ac3dab228d9e04af9653e8ff14e3f
| 1,652
|
MediaPickerInstagram
|
Apache License 2.0
|
app/src/main/java/com/jiangkang/ktools/effect/fragment/ShapePathViewFragment.kt
|
mingrq
| 248,896,835
| false
|
{"Gradle": 29, "Java Properties": 2, "Shell": 4, "Text": 2, "Ignore List": 21, "Batchfile": 1, "Git Attributes": 1, "Markdown": 3, "Proguard": 17, "Java": 174, "XML": 199, "Kotlin": 109, "JSON": 3, "YAML": 2, "CMake": 2, "AIDL": 1, "C++": 1, "JavaScript": 6, "HTML": 4, "CSS": 2, "Dart": 1}
|
package com.jiangkang.ktools.effect.fragment
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.jiangkang.ktools.R
import com.jiangkang.tools.extend.widget.addOnChangeListener
import kotlinx.android.synthetic.main.fragment_shape_path_view.*
/**
* 利用Path 绘图
*/
class ShapePathViewFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_shape_path_view, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
seekBarSides.addOnChangeListener(
onProgressChanged = { _, progress, _ ->
shapePathView.post {
shapePathView.updateSides(sides = progress)
}
}
)
seekBarProgress.addOnChangeListener(
onProgressChanged = { _, progress, _ ->
shapePathView.post {
shapePathView.updateProgress(progress = progress.toFloat())
}
}
)
}
}
| 1
| null |
1
| 1
|
3eb2b95e7fc7332173c6cebffac781a8f1547b8d
| 1,386
|
KTools
|
MIT License
|
src/module/ContentNegotiationModule.kt
|
alessandroToninelli
| 266,056,845
| false
| null |
package module
import io.ktor.application.Application
import io.ktor.application.install
import io.ktor.features.ContentNegotiation
import io.ktor.gson.gson
class ContentNegotiationModule : AppModule{
override fun install(application: Application) {
application.install(ContentNegotiation){
gson { }
}
}
}
| 0
|
Kotlin
|
0
| 0
|
105159069bee4a97715f61165b683c741b01820e
| 345
|
videostore
|
Apache License 2.0
|
app/src/main/java/com/samiu/wangank/ui/nav/adapter/NavigationAdapter.kt
|
SamiuZhong
| 244,276,691
| false
| null |
package com.samiu.wangank.ui.nav.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.ListAdapter
import com.samiu.wangank.databinding.NavMenuItemLayoutBinding
/**
* [BottomNavDrawerFragment]的adapter
*
* @author Samiu 2020/3/31
* @github https://github.com/SamiuZhong
* @blog samiu.top
*/
class NavigationAdapter(
private val listener: NavigationAdapterListener
) : ListAdapter<NavigationModelItem, NavigationViewHolder<NavigationModelItem>>(
NavigationModelItem.NavModelItemDiff
) {
interface NavigationAdapterListener {
fun onNavMenuItemClicked(item: NavigationModelItem.NavMenuItem)
}
@Suppress("UNCHECKED_CAST")
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): NavigationViewHolder<NavigationModelItem> {
return NavigationViewHolder.NavMenuItemViewHolder(
NavMenuItemLayoutBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
),
listener
) as NavigationViewHolder<NavigationModelItem>
}
override fun onBindViewHolder(
holder: NavigationViewHolder<NavigationModelItem>,
position: Int
) {
holder.bind(getItem(position))
}
}
| 0
|
Kotlin
|
3
| 12
|
fb5ae9d14ab442c95e0210125f53aef9f060a3a9
| 1,320
|
WanAndroid_Gank
|
MIT License
|
Feed/src/main/java/com/j/jface/action/InformUserAction.kt
|
jeanchalard
| 32,686,314
| false
|
{"Gradle": 6, "INI": 2, "Shell": 1, "Text": 1, "Ignore List": 4, "Java Properties": 1, "Java": 66, "JSON": 1, "XML": 49, "Kotlin": 43, "Proguard": 1}
|
package com.j.jface.action
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.text.SpannableStringBuilder
import android.view.View
import androidx.core.text.bold
import com.google.android.material.snackbar.Snackbar
import com.j.jface.R
import com.j.jface.feed.LocalLog
import com.j.jface.feed.views.SnackbarRegistry
import com.j.jface.nextNotifId
const val CHANNEL_ID = "jorg_general"
const val CHANNEL_NAME = "Jormungand : General"
const val LAST_NOTIF_ID = "general_lastId"
class NotificationAction(private val context : Context, private val text : String, private val details : String? = null, private val pendingIntent : PendingIntent? = null) : () -> Unit
{
companion object
{
private fun getChannel(context : Context, notificationManager : NotificationManager) : NotificationChannel
{
val existing = notificationManager.getNotificationChannel(CHANNEL_ID)
if (null != existing) return existing
val channel = NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT)
// Configure the notification channel.
channel.description = "Jormungand : debug and misc notifications"
channel.enableLights(true)
channel.lightColor = context.getColor(R.color.jormungand_color)
channel.enableVibration(false)
notificationManager.createNotificationChannel(channel)
return notificationManager.getNotificationChannel(CHANNEL_ID)
}
fun postNotification(context : Context, text : String, details : String?, pendingIntent : PendingIntent?)
{
val notificationManager = context.getSystemService(NotificationManager::class.java) as NotificationManager
val channel = getChannel(context, notificationManager)
val notif = Notification.Builder(context, channel.id)
.setSmallIcon(R.drawable.jormungand)
.setColor(context.getColor(R.color.jormungand_color))
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setTimeoutAfter(10_000)
if (null != pendingIntent) notif.setContentIntent(pendingIntent)
if (null != details) {
notif.setContentTitle(text)
notif.setContentText(details)
} else {
val index = text.indexOf('\n')
if (index < 0)
notif.setContentText(text)
else {
notif.setContentTitle(text.subSequence(0, index))
notif.style = Notification.BigTextStyle().bigText(text.subSequence(index, text.length))
}
}
val notifId = context.nextNotifId(LAST_NOTIF_ID)
notificationManager.notify(notifId, notif.build())
}
}
override fun invoke() = postNotification(context, text, details, pendingIntent)
}
class SnackbarAction(private val text : String, private val details : String? = null, private val actionMessage : String? = null, private val callback : View.OnClickListener? = null) : () -> Unit
{
companion object
{
fun showSnackbar(text : String, details : String? = null, actionMessage : String? = null, callback : View.OnClickListener? = null)
{
val message = if (null != details) SpannableStringBuilder().bold { append(text) }.append("\n").append(details) else text
val snackbarParent = SnackbarRegistry.getSnackbarParent() ?: return
val sb = Snackbar.make(snackbarParent, message, Snackbar.LENGTH_LONG)
if (null != actionMessage && null != callback)
sb.setAction(actionMessage, callback)
snackbarParent.post { sb.show() }
}
}
override fun invoke() = showSnackbar(text, details, actionMessage, callback)
}
class InformUserAction(private val context : Context, private val text : String, private val details : String? = null, private val actionMessage : String? = null, private val callback : View.OnClickListener? = null, private val pendingIntent : PendingIntent? = null) : () -> Unit
{
override fun invoke()
{
LocalLog.log(context, if (null == details) text else "${text}\n${details}")
val snackbarParent = SnackbarRegistry.getSnackbarParent()
if (null == snackbarParent) { NotificationAction.postNotification(context, text, details, pendingIntent); return }
SnackbarAction.showSnackbar(text, details, actionMessage, callback)
pendingIntent?.send()
}
}
| 0
|
Java
|
0
| 0
|
f0d651246ea90a81d598603b733cd24f28d44df5
| 4,337
|
jface
|
Apache License 2.0
|
src/main/kotlin/org/alfalfa/fx/core/WindowStub.kt
|
dicolar
| 49,516,149
| false
|
{"Kotlin": 9301}
|
package org.alfalfa.fx.core
import javafx.scene.Parent
import javafx.scene.image.Image
import javafx.stage.Modality
import javafx.stage.StageStyle
import javafx.stage.Window
open class WindowStub<T : AbstractController>(@JvmField val controller: T) {
fun <R : Parent?> getRoot(): R {
return controller.stage.scene.root as R
}
fun size(width: Int, height: Int): WindowStub<T> {
return width(width).height(height)
}
fun modal(): WindowStub<T> {
controller.stage.initModality(Modality.APPLICATION_MODAL)
return this
}
fun wmodal(): WindowStub<T> {
controller.stage.initModality(Modality.WINDOW_MODAL)
return this
}
fun width(width: Int): WindowStub<T> {
controller.stage.width = width.toDouble()
return this
}
fun height(height: Int): WindowStub<T> {
controller.stage.height = height.toDouble()
return this
}
fun owner(window: Window?): WindowStub<T> {
controller.stage.initOwner(window)
return this
}
fun windowTitle(title: String?): WindowStub<T> {
controller.stage.title = title
return this
}
fun icon(image: Image?): WindowStub<T> {
controller.stage.icons.add(image)
return this
}
fun show() {
controller.stage.show()
}
fun showAndWait() {
controller.stage.showAndWait()
}
fun style(style: StageStyle?): WindowStub<T> {
controller.stage.initStyle(style)
return this
}
fun resizable(resizable: Boolean): WindowStub<T> {
controller.stage.isResizable = resizable
return this
}
fun close() {
controller.stage.close()
}
}
| 1
|
Kotlin
|
122
| 302
|
30c49f1a542a6537744b08cd40a38c84ec881f0f
| 1,729
|
jbootx
|
Apache License 2.0
|
zowe-cli/src/jsMain/kotlin/zowe/cli/zosfiles/strings/Temp127.kt
|
lppedd
| 761,812,661
| false
|
{"Kotlin": 1887051}
|
package zowe.cli.zosfiles.strings
external interface Temp127 {
var USSDIRNAME: String
}
| 0
|
Kotlin
|
0
| 3
|
0f493d3051afa3de2016e5425a708c7a9ed6699a
| 91
|
kotlin-externals
|
MIT License
|
core/src/jvmMain/kotlin/kotlinx/fs/core/IOException.kt
|
cy6erGn0m
| 168,707,260
| true
|
{"Kotlin": 63013}
|
package kotlinx.fs.core
import java.io.Closeable as JvmCloseable
actual typealias IOException = java.io.IOException
| 0
|
Kotlin
|
0
| 0
|
a5f427bf11d781696595c23e03fc7c8bf9558cba
| 117
|
kotlinx-fs
|
Apache License 2.0
|
locallydynamic-android-lib/integration-tests/installtimefeature/src/main/java/com/jeppeman/locallydynamic/integration_tests/installtimefeature/IntegrationTestsInstallTimeFeatureImpl.kt
|
poovarasanvasudevan
| 239,129,218
| true
|
{"Kotlin": 319796, "Java": 302260, "Shell": 7767}
|
package com.jeppeman.locallydynamic.integration_tests.installtimefeature
import android.content.Context
import android.content.Intent
import androidx.fragment.app.Fragment
import com.google.auto.service.AutoService
import com.jeppeman.locallydynamic.integration_tests.InstallTimeFeature
@AutoService(InstallTimeFeature::class)
class IntegrationTestsInstallTimeFeatureImpl : InstallTimeFeature {
override fun getMainScreen(): Fragment = IntegrationTestsInstallTimeFragment()
override fun getLaunchIntent(context: Context): Intent =
Intent(context, IntegrationTestsInstallTimeActivity::class.java)
override fun inject(dependencies: InstallTimeFeature.Dependencies) {
}
}
| 0
| null |
0
| 0
|
9e52f801e8afdb88b245600dbfd4d6691fd22d95
| 696
|
LocallyDynamic
|
Apache License 2.0
|
src/test/kotlin/br/com/zupacademy/gabrielamartins/endpoint/lista/ListaChavesPixEndpointTest.kt
|
gabrielamartinszup
| 409,667,340
| true
|
{"Kotlin": 82274}
|
package br.com.zupacademy.gabrielamartins.endpoint.lista
import br.com.zupacademy.gabrielamartins.KeyManagerListaServiceGrpc
import br.com.zupacademy.gabrielamartins.ListarChavesPixRequest
import br.com.zupacademy.gabrielamartins.model.ChavePix
import br.com.zupacademy.gabrielamartins.model.Conta
import br.com.zupacademy.gabrielamartins.model.enums.TipoChave
import br.com.zupacademy.gabrielamartins.model.enums.TipoConta
import br.com.zupacademy.gabrielamartins.repository.ChavePixRepository
import io.grpc.ManagedChannel
import io.grpc.Status
import io.grpc.StatusRuntimeException
import io.micronaut.context.annotation.Bean
import io.micronaut.context.annotation.Factory
import io.micronaut.grpc.annotation.GrpcChannel
import io.micronaut.grpc.server.GrpcServerChannel
import io.micronaut.test.extensions.junit5.annotation.MicronautTest
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.containsInAnyOrder
import org.hamcrest.Matchers.hasSize
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import java.util.*
import javax.transaction.Transactional
@MicronautTest(transactional = false)
internal class ListaChavesPixEndpointTest(val repository: ChavePixRepository, val grpcClient: KeyManagerListaServiceGrpc.KeyManagerListaServiceBlockingStub){
companion object {
val CLIENTE_ID = UUID.randomUUID()
}
/**
* TIP: por padrão roda numa transação isolada
*/
@BeforeEach
fun setup() {
repository.save(chave(tipo = TipoChave.EMAIL, chave = "rafael.ponte@zup.com.br", clienteId = CLIENTE_ID))
repository.save(chave(tipo = TipoChave.ALEATORIA, chave = "randomkey-2", clienteId = UUID.randomUUID()))
repository.save(chave(tipo = TipoChave.ALEATORIA, chave = "randomkey-3", clienteId = CLIENTE_ID))
}
/**
* TIP: por padrão roda numa transação isolada
*/
@AfterEach
fun cleanUp() {
repository.deleteAll()
}
@Test
fun `deve listar todas as chaves do cliente`() {
// cenário
val clienteId = CLIENTE_ID.toString()
// ação
val response = grpcClient.listarChavesPix(
ListarChavesPixRequest.newBuilder()
.setClienteId(clienteId)
.build())
// validação
with (response.chavesList) {
assertThat(this, hasSize(2))
assertThat(
this.map { Pair(it.tipoChave, it.chave) }.toList(),
containsInAnyOrder(
Pair(TipoChave.ALEATORIA, "randomkey-3"),
Pair(TipoChave.EMAIL, "rafael.ponte@zup.com.br")
)
)
}
}
@Test
fun `nao deve listar as chaves do cliente quando cliente nao possuir chaves`() {
// cenário
val clienteSemChaves = UUID.randomUUID().toString()
// ação
val response = grpcClient.listarChavesPix(ListarChavesPixRequest.newBuilder()
.setClienteId(clienteSemChaves)
.build())
// validação
assertEquals(0, response.chavesCount)
}
@Test
fun `nao deve listar todas as chaves do cliente quando clienteId for invalido`() {
// cenário
val clienteIdInvalido = ""
// ação
val thrown = assertThrows<StatusRuntimeException> {
grpcClient.listarChavesPix(ListarChavesPixRequest.newBuilder()
.setClienteId(clienteIdInvalido)
.build())
}
// validação
with(thrown) {
assertEquals(Status.INVALID_ARGUMENT.code, status.code)
assertEquals("Cliente ID não pode ser nulo ou vazio", status.description)
}
}
@Factory
class Clients {
@Bean
fun blockingStub(@GrpcChannel(GrpcServerChannel.NAME) channel: ManagedChannel): KeyManagerListaServiceGrpc.KeyManagerListaServiceBlockingStub? {
return KeyManagerListaServiceGrpc.newBlockingStub(channel)
}
}
private fun chave(
tipo: TipoChave,
chave: String = UUID.randomUUID().toString(),
clienteId: UUID = UUID.randomUUID(),
): ChavePix {
return ChavePix(
clienteId = clienteId,
tipoChave = tipo,
chave = chave,
tipoConta = TipoConta.CONTA_CORRENTE,
conta = Conta(
instituicao = "UNIBANCO ITAU",
nomeTitular = "Rafael Ponte",
cpfTitular = "12345678900",
agencia = "1218",
numeroConta = "123456"
)
)
}
}
| 0
|
Kotlin
|
0
| 0
|
1b007c351604cbf3a576fb0ed22d2e3751f333cb
| 4,705
|
orange-talents-07-template-pix-keymanager-grpc
|
Apache License 2.0
|
clef-workflow-api/clef-workflow-api-adapter/clef-workflow-api-adapter-element/src/main/java/io/arkitik/clef/workflow/api/adapter/element/repository/ElementFlowRepository.kt
|
arkitik
| 443,436,455
| false
|
{"Kotlin": 433170, "Shell": 268, "Dockerfile": 244}
|
package io.arkitik.clef.workflow.api.adapter.element.repository
import io.arkitik.radix.adapter.shared.repository.RadixRepository
import io.arkitik.clef.workflow.api.entity.element.ElementFlow
import org.springframework.stereotype.Repository
/**
* Created By [**Ibrahim Al-Tamimi **](https://www.linkedin.com/in/iloom/)<br></br>
* Created At **20**, **Fri Mar, 2020**
* Project **clef-workflow** [arkitik.IO](https://arkitik.io/)<br></br>
*/
@Repository
interface ElementFlowRepository : RadixRepository<String, ElementFlow>
| 0
|
Kotlin
|
0
| 0
|
785e1b4ee583b6a6e3ea01e656eecd8365f171ef
| 531
|
clef-workflow
|
Apache License 2.0
|
app/src/main/java/com/garan/wearwind/screens/Loading.kt
|
garanj
| 338,176,338
| false
| null |
package com.garan.wearwind.screens
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.wear.compose.material.ExperimentalWearMaterialApi
import com.garan.wearwind.FanControlService
import com.garan.wearwind.R
import com.garan.wearwind.Screen
import com.garan.wearwind.UiState
import com.garan.wearwind.rememberUiState
@OptIn(ExperimentalWearMaterialApi::class)
@Composable
fun WearwindLoadingMessage(
uiState: UiState,
service: FanControlService?
) {
LaunchedEffect(service) {
service?.let {
uiState.navHostController.popBackStack(Screen.LOADING.route, true)
uiState.navHostController.navigate(Screen.CONNECT.route)
}
}
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
val context = LocalContext.current
Image(
painter = painterResource(
id = R.drawable.ic_logo
),
contentDescription = context.getString(R.string.loading_message)
)
}
}
@Preview(
widthDp = WEAR_PREVIEW_DEVICE_WIDTH_DP,
heightDp = WEAR_PREVIEW_DEVICE_HEIGHT_DP,
apiLevel = WEAR_PREVIEW_API_LEVEL,
uiMode = WEAR_PREVIEW_UI_MODE,
backgroundColor = WEAR_PREVIEW_BACKGROUND_COLOR_BLACK,
showBackground = WEAR_PREVIEW_SHOW_BACKGROUND
)
@Composable
fun LoadingScreenPreview() {
val uiState = rememberUiState()
WearwindLoadingMessage(
uiState = uiState,
service = null
)
}
| 0
| null |
2
| 2
|
7a3b9c39f5a02b05d830167840916ed43fdb209d
| 1,893
|
wearwind
|
Apache License 2.0
|
app/src/main/java/com/github/colinjeremie/willyoufindit/adapters/GenreAdapter.kt
|
colinjeremie
| 53,530,048
| false
| null |
package com.github.colinjeremie.willyoufindit.adapters
import android.support.annotation.VisibleForTesting
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.deezer.sdk.model.Genre
import com.deezer.sdk.network.request.event.JsonRequestListener
import com.deezer.sdk.network.request.event.RequestListener
import com.github.colinjeremie.willyoufindit.MyApplication
import com.github.colinjeremie.willyoufindit.R
import com.github.colinjeremie.willyoufindit.utils.normalize
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.util.*
class GenreAdapter(private val onGenreClickListener: ((Genre) -> Unit), private val loadingCallback: (Boolean) -> Unit) : RecyclerView.Adapter<GenreAdapter.GenresViewHolder>() {
private var dataSet: MutableList<Genre> = ArrayList()
private var originalDataSet: List<Genre> = mutableListOf()
@VisibleForTesting
val listener: RequestListener = object : JsonRequestListener() {
override fun onResult(o: Any, o1: Any) {
originalDataSet = o as List<Genre>
clearFilter()
loadingCallback.invoke(false)
}
override fun onUnparsedResult(s: String, o: Any) {
loadingCallback.invoke(false)
}
override fun onException(e: Exception, o: Any) {
loadingCallback.invoke(false)
}
}
fun fetchGenres() {
loadingCallback.invoke(true)
MyApplication.instance.deezerApi.getGenres(listener)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GenresViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.genre_item, parent, false)
return GenresViewHolder(view)
}
override fun onBindViewHolder(holder: GenresViewHolder, position: Int) {
val model = dataSet[position]
holder.name.text = model.name
holder.itemView.setOnClickListener {
onGenreClickListener.invoke(model)
}
}
override fun getItemCount() = dataSet.size
fun clearFilter() {
dataSet.clear()
dataSet.addAll(originalDataSet)
notifyDataSetChanged()
}
fun filter(search: String) {
getFilterObservable(search, originalDataSet)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { result ->
dataSet = result
notifyDataSetChanged()
}
}
fun getFilterObservable(search: String, list: List<Genre>): Single<MutableList<Genre>> =
Observable
.fromIterable(list)
.filter { it.name.normalize().contains(search.normalize(), ignoreCase = true) }
.toList()
inner class GenresViewHolder(itemView: View,
val name: TextView = itemView.findViewById(R.id.genre_name)) : RecyclerView.ViewHolder(itemView)
}
| 0
|
Kotlin
|
0
| 0
|
12f336815f65bf7b675010913564f133f0b955b8
| 3,178
|
WillYouFindIt
|
Apache License 2.0
|
app/src/main/java/com/thejuki/kformmasterexample/custom/helper/FormBuilderExtensions.kt
|
7u4
| 156,162,862
| true
|
{"Kotlin": 355656, "Java": 12877}
|
package com.thejuki.kformmasterexample.custom.helper
import com.thejuki.kformmaster.helper.BaseElementBuilder
import com.thejuki.kformmaster.helper.FormBuildHelper
import com.thejuki.kformmasterexample.custom.model.FormCustomElement
/**
* Form Builder Extensions
*
* Used for Kotlin DSL to create the FormBuildHelper
*
* @author **TheJuki** ([GitHub](https://github.com/TheJuki))
* @version 1.0
*/
/** Builder method to add a CustomElement */
class CustomElementBuilder(tag: Int = -1) : BaseElementBuilder<String>(tag) {
override fun build() =
FormCustomElement(tag).apply {
this@CustomElementBuilder.let {
title = it.title.orEmpty()
value = it.value
hint = it.hint
rightToLeft = it.rightToLeft
maxLines = it.maxLines
error = it.error
required = it.required
enabled = it.enabled
visible = it.visible
valueObservers.addAll(it.valueObservers)
// Colors
backgroundColor = it.backgroundColor
hintTextColor = it.hintTextColor
titleTextColor = it.titleTextColor
titleFocusedTextColor = it.titleFocusedTextColor
valueTextColor = it.valueTextColor
errorTextColor = it.errorTextColor
}
}
}
/** FormBuildHelper extension to add a CustomElement */
fun FormBuildHelper.customEx(tag: Int = -1, init: CustomElementBuilder.() -> Unit): FormCustomElement {
return addFormElement(CustomElementBuilder(tag).apply(init).build())
}
| 0
|
Kotlin
|
0
| 0
|
80328b007b7455f0bddbcff838e1bce7b3d28170
| 1,727
|
KFormMaster
|
Apache License 2.0
|
support-refs_heads_androidx-master-dev-ui.tar/ui-foundation/src/main/java/androidx/ui/foundation/Image.kt
|
cpinan
| 215,833,397
| false
| null |
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.ui.foundation
import androidx.compose.Composable
import androidx.compose.memo
import androidx.compose.unaryPlus
import androidx.ui.core.Draw
import androidx.ui.core.WithDensity
import androidx.ui.engine.geometry.Rect
import androidx.ui.graphics.Color
import androidx.ui.layout.Container
import androidx.ui.graphics.BlendMode
import androidx.ui.graphics.ColorFilter
import androidx.ui.graphics.FilterQuality
import androidx.ui.graphics.Image
import androidx.ui.graphics.Paint
// TODO(Andrey) Temporary. Should be replaced with our proper Image component when it available
@Composable
fun SimpleImage(
image: Image,
tint: Color? = null
) {
// TODO b/132071873: WithDensity should be able to use the DSL syntax
WithDensity(block = {
Container(width = image.width.toDp(), height = image.height.toDp()) {
DrawImage(image, tint)
}
})
}
/**
* Fits an image into the parent container while maintaining the image aspect ratio.
* The image will be clipped if the aspect ratios of the image and the parent don't match.
*
* This component has the same behavior as ImageView.ScaleType.CENTER_CROP currently.
*
* @param image The image to draw.
* @param tint The tint color to apply for the image.
*/
// TODO(Andrey, Matvei, Nader): Support other scale types b/141741141
@Composable
fun DrawImage(image: Image, tint: Color? = null) {
val paint = +memo { Paint().apply {
filterQuality = FilterQuality.low // we only support low currently
} }
paint.colorFilter = tint?.let { ColorFilter(it, BlendMode.srcIn) }
Draw { canvas, parentSize ->
val inputWidth = image.width.toFloat()
val inputHeight = image.height.toFloat()
val inputAspectRatio = inputWidth / inputHeight
val outputWidth = parentSize.width.value
val outputHeight = parentSize.height.value
val outputAspectRatio = outputWidth / outputHeight
val fittedWidth = if (outputAspectRatio > inputAspectRatio) {
inputWidth
} else {
inputHeight * outputAspectRatio
}
val fittedHeight = if (outputAspectRatio > inputAspectRatio) {
inputWidth / outputAspectRatio
} else {
inputHeight
}
val srcRect = Rect(
left = (inputWidth - fittedWidth) / 2,
top = (inputHeight - fittedHeight) / 2,
right = (inputWidth + fittedWidth) / 2,
bottom = (inputHeight + fittedHeight) / 2
)
val dstRect = Rect(
left = 0f,
top = 0f,
right = outputWidth,
bottom = outputHeight
)
canvas.drawImageRect(image, srcRect, dstRect, paint)
}
}
| 1
|
Kotlin
|
1
| 3
|
a4298de63f0cb4848269a9fe5b6a5ab59d68a4e5
| 3,350
|
Android-Jetpack-Composer
|
Apache License 2.0
|
dbinspector/src/test/kotlin/com/infinum/dbinspector/domain/settings/usecases/SaveIgnoredTableNameUseCaseTest.kt
|
infinum
| 17,116,181
| false
| null |
package com.infinum.dbinspector.domain.settings.usecases
import com.infinum.dbinspector.domain.Repositories
import com.infinum.dbinspector.shared.BaseTest
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.mockk
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.koin.core.module.Module
import org.koin.dsl.module
import org.koin.test.get
import org.mockito.kotlin.any
@DisplayName("SaveIgnoredTableNameUseCase tests")
internal class SaveIgnoredTableNameUseCaseTest : BaseTest() {
override fun modules(): List<Module> = listOf(
module {
factory { mockk<Repositories.Settings>() }
}
)
@Test
fun `Invoking use case saves ignored table name in settings`() {
val repository: Repositories.Settings = get()
val useCase = SaveIgnoredTableNameUseCase(repository)
coEvery { repository.saveIgnoredTableName(any()) } returns mockk()
test {
useCase.invoke(any())
}
coVerify(exactly = 1) { repository.saveIgnoredTableName(any()) }
}
}
| 0
|
Kotlin
|
93
| 936
|
10b9ac5013ca01e602976a615e754dff7001f11d
| 1,086
|
android_dbinspector
|
Apache License 2.0
|
src/main/kotlin/tech/aaregall/lab/functions/question/service/openai/OpenAiDTOs.kt
|
ArnauAregall
| 648,974,932
| false
| null |
package tech.aaregall.lab.functions.question.service.openai
data class OpenAiChatCompletionRequest(
val model: String,
val messages: List<OpenAiMessage>
)
data class OpenAiChatCompletionResponse(
val choices: List<OpenAiChatAnswerChoice>
)
data class OpenAiChatAnswerChoice(
val index: Int,
val message: OpenAiMessage
)
data class OpenAiMessage (
val role: String,
val content: String
)
| 0
|
Kotlin
|
0
| 1
|
29279e0d32d8ead56b31463a515529901774d397
| 418
|
aws-lambda-spring-cloud-function
|
Apache License 2.0
|
app/src/main/java/ru/otus/android/finish/services/UploadService.kt
|
vic-android
| 840,340,266
| false
|
{"Kotlin": 21454}
|
package ru.otus.android.finish.services
import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import ru.otus.android.domain.FileUploader
import ru.otus.android.domain.FileUploader.ProgressCallback
import ru.otus.android.finish.MainActivity
import ru.otus.android.utils.NotificationFactory
import ru.otus.android.utils.getPendingIntent
import java.util.concurrent.Executors
class UploadService : Service() {
private val fileUploader = FileUploader()
private var onProgress: ((Int) -> Unit)? = null
inner class UploadBinder : Binder() {
fun subscribeToProgress(onProgress: (Int) -> Unit) {
this@UploadService.onProgress = onProgress
}
}
override fun onCreate() {
super.onCreate()
println("UploadService::onCreate")
}
override fun onBind(intent: Intent): IBinder {
return UploadBinder()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
println("UploadService::onStartCommand")
val notificationFactory = NotificationFactory(
context = this,
pendingIntent = getPendingIntent(MainActivity::class.java),
)
startForeground(
1,
notificationFactory.create(title = "Uploading", text = "Starting...")
)
Executors.newSingleThreadExecutor().execute {
fileUploader.upload(object : ProgressCallback {
override fun onProgress(progress: Int) {
println("UploadService progress $progress%")
onProgress?.invoke(progress)
// val notificationManager =
// getSystemService(NOTIFICATION_SERVICE) as NotificationManager
// notificationManager.notify(
// 1,
// notificationFactory.create(text = "progress $progress%"),
// )
}
})
stopSelf()
}
return START_STICKY
}
}
| 0
|
Kotlin
|
1
| 0
|
a9266e0e24543a1150e67d192bf23079ce192d59
| 2,076
|
otus-service-lesson
|
Apache License 2.0
|
buildSrc/src/main/kotlin/SpotlessConfiguration.kt
|
wilksy
| 213,588,424
| true
|
{"Git Config": 1, "Gradle Kotlin DSL": 6, "YAML": 4, "Text": 1, "Markdown": 5, "Java Properties": 1, "Shell": 3, "Ignore List": 5, "INI": 1, "CODEOWNERS": 1, "Proguard": 1, "XML": 78, "Kotlin": 76, "Java": 8, "CMake": 1, "C": 3, "Go Checksums": 1, "Go": 1, "Diff": 1, "Makefile": 1, "Go Module": 1}
|
/*
* Copyright © 2017-2019 WireGuard LLC.
* Copyright © 2018-2019 Harsh Shandilya <msfjarvis@gmail.com>. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
import com.diffplug.gradle.spotless.SpotlessExtension
import com.diffplug.gradle.spotless.SpotlessPlugin
import org.gradle.api.Project
import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.configure
val kotlinLicenseHeader = """/*
* Copyright © 2017-2019 WireGuard LLC.
* Copyright © 2018-2019 Harsh Shandilya <msfjarvis@gmail.com>. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
""".trimIndent()
fun Project.configureSpotless() {
apply<SpotlessPlugin>()
configure<SpotlessExtension> {
format("misc") {
target(
fileTree(
mapOf(
"dir" to ".",
"include" to listOf("**/*.md", "**/.gitignore", "**/*.yaml", "**/*.yml"),
"exclude" to listOf(".gradle/**", ".gradle-cache/**", "**/tools/**", "**/build/**")
)
)
)
trimTrailingWhitespace()
indentWithSpaces()
endWithNewline()
}
format("xml") {
target("**/res/**/*.xml")
indentWithSpaces(4)
trimTrailingWhitespace()
endWithNewline()
}
java {
target(
"app/src/main/java/com/wireguard/android/util/ObservableSortedKeyedArrayList.java",
"app/src/main/java/com/wireguard/android/util/ObservableKeyedArrayList.java",
"app/src/main/java/com/wireguard/android/util/KotlinCompanions.java"
)
trimTrailingWhitespace()
@Suppress("INACCESSIBLE_TYPE")
licenseHeader(kotlinLicenseHeader)
removeUnusedImports()
googleJavaFormat().aosp()
endWithNewline()
}
kotlinGradle {
target("**/*.gradle.kts", "*.gradle.kts")
ktlint("0.33.0").userData(mapOf("indent_size" to "4", "continuation_indent_size" to "4"))
@Suppress("INACCESSIBLE_TYPE")
licenseHeader(kotlinLicenseHeader, "import|tasks|apply|plugins|include|buildscript")
trimTrailingWhitespace()
indentWithSpaces()
endWithNewline()
}
kotlin {
target("**/src/**/*.kt", "buildSrc/**/*.kt")
ktlint("0.33.0").userData(mapOf("indent_size" to "4", "continuation_indent_size" to "8"))
@Suppress("INACCESSIBLE_TYPE")
licenseHeader(kotlinLicenseHeader, "import|package|class|object|@file")
trimTrailingWhitespace()
indentWithSpaces()
endWithNewline()
}
}
}
| 0
|
Kotlin
|
0
| 0
|
a57a384fe6b9da5b204ee2439bf78fbd17356b71
| 2,784
|
viscerion
|
Apache License 2.0
|
api/src/main/java/dev/doubledot/doki/api/tasks/DokiApiCallback.kt
|
doubledotlabs
| 174,850,580
| false
| null |
package dev.doubledot.doki.api.tasks
import dev.doubledot.doki.api.models.DokiManufacturer
interface DokiApiCallback {
fun onStart() {}
fun onSuccess(response: DokiManufacturer?)
fun onError(e: Throwable?) {
e?.printStackTrace()
}
}
| 11
| null |
15
| 161
|
4bed979c7db295af263f0f97f75d0d3a429513ff
| 260
|
doki
|
MIT License
|
src/main/kotlin/AdbFinder.kt
|
parshav
| 174,736,199
| false
| null |
import com.intellij.openapi.project.Project
import org.jetbrains.android.sdk.AndroidSdkUtils
object AdbFinder {
fun isAdbInstalled() = AndroidSdkUtils.isAndroidSdkAvailable()
fun adbPath(project: Project): String {
var adbPath = ""
val adbFile = AndroidSdkUtils.getAdb(project)
if (adbFile != null) {
adbPath = adbFile.absolutePath
}
return adbPath
}
}
| 0
|
Kotlin
|
0
| 1
|
93b14358ab7471807cd4e0ad76ded18e5b32515c
| 419
|
kwick-activity
|
MIT License
|
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/connect/CfnContactFlowModuleProps.kt
|
cloudshiftinc
| 667,063,030
| false
|
{"Kotlin": 149148378}
|
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package io.cloudshiftdev.awscdk.services.connect
import io.cloudshiftdev.awscdk.CfnTag
import io.cloudshiftdev.awscdk.common.CdkDslMarker
import io.cloudshiftdev.awscdk.common.CdkObject
import io.cloudshiftdev.awscdk.common.CdkObjectWrappers
import kotlin.String
import kotlin.Unit
import kotlin.collections.List
/**
* Properties for defining a `CfnContactFlowModule`.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import io.cloudshiftdev.awscdk.services.connect.*;
* CfnContactFlowModuleProps cfnContactFlowModuleProps = CfnContactFlowModuleProps.builder()
* .content("content")
* .instanceArn("instanceArn")
* .name("name")
* // the properties below are optional
* .description("description")
* .state("state")
* .tags(List.of(CfnTag.builder()
* .key("key")
* .value("value")
* .build()))
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-connect-contactflowmodule.html)
*/
public interface CfnContactFlowModuleProps {
/**
* The content of the flow module.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-connect-contactflowmodule.html#cfn-connect-contactflowmodule-content)
*/
public fun content(): String
/**
* The description of the flow module.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-connect-contactflowmodule.html#cfn-connect-contactflowmodule-description)
*/
public fun description(): String? = unwrap(this).getDescription()
/**
* The Amazon Resource Name (ARN) of the Amazon Connect instance.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-connect-contactflowmodule.html#cfn-connect-contactflowmodule-instancearn)
*/
public fun instanceArn(): String
/**
* The name of the flow module.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-connect-contactflowmodule.html#cfn-connect-contactflowmodule-name)
*/
public fun name(): String
/**
* The state of the flow module.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-connect-contactflowmodule.html#cfn-connect-contactflowmodule-state)
*/
public fun state(): String? = unwrap(this).getState()
/**
* An array of key-value pairs to apply to this resource.
*
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-connect-contactflowmodule.html#cfn-connect-contactflowmodule-tags)
*/
public fun tags(): List<CfnTag> = unwrap(this).getTags()?.map(CfnTag::wrap) ?: emptyList()
/**
* A builder for [CfnContactFlowModuleProps]
*/
@CdkDslMarker
public interface Builder {
/**
* @param content The content of the flow module.
*/
public fun content(content: String)
/**
* @param description The description of the flow module.
*/
public fun description(description: String)
/**
* @param instanceArn The Amazon Resource Name (ARN) of the Amazon Connect instance.
*/
public fun instanceArn(instanceArn: String)
/**
* @param name The name of the flow module.
*/
public fun name(name: String)
/**
* @param state The state of the flow module.
*/
public fun state(state: String)
/**
* @param tags An array of key-value pairs to apply to this resource.
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*/
public fun tags(tags: List<CfnTag>)
/**
* @param tags An array of key-value pairs to apply to this resource.
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*/
public fun tags(vararg tags: CfnTag)
}
private class BuilderImpl : Builder {
private val cdkBuilder:
software.amazon.awscdk.services.connect.CfnContactFlowModuleProps.Builder =
software.amazon.awscdk.services.connect.CfnContactFlowModuleProps.builder()
/**
* @param content The content of the flow module.
*/
override fun content(content: String) {
cdkBuilder.content(content)
}
/**
* @param description The description of the flow module.
*/
override fun description(description: String) {
cdkBuilder.description(description)
}
/**
* @param instanceArn The Amazon Resource Name (ARN) of the Amazon Connect instance.
*/
override fun instanceArn(instanceArn: String) {
cdkBuilder.instanceArn(instanceArn)
}
/**
* @param name The name of the flow module.
*/
override fun name(name: String) {
cdkBuilder.name(name)
}
/**
* @param state The state of the flow module.
*/
override fun state(state: String) {
cdkBuilder.state(state)
}
/**
* @param tags An array of key-value pairs to apply to this resource.
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*/
override fun tags(tags: List<CfnTag>) {
cdkBuilder.tags(tags.map(CfnTag.Companion::unwrap))
}
/**
* @param tags An array of key-value pairs to apply to this resource.
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*/
override fun tags(vararg tags: CfnTag): Unit = tags(tags.toList())
public fun build(): software.amazon.awscdk.services.connect.CfnContactFlowModuleProps =
cdkBuilder.build()
}
private class Wrapper(
cdkObject: software.amazon.awscdk.services.connect.CfnContactFlowModuleProps,
) : CdkObject(cdkObject), CfnContactFlowModuleProps {
/**
* The content of the flow module.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-connect-contactflowmodule.html#cfn-connect-contactflowmodule-content)
*/
override fun content(): String = unwrap(this).getContent()
/**
* The description of the flow module.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-connect-contactflowmodule.html#cfn-connect-contactflowmodule-description)
*/
override fun description(): String? = unwrap(this).getDescription()
/**
* The Amazon Resource Name (ARN) of the Amazon Connect instance.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-connect-contactflowmodule.html#cfn-connect-contactflowmodule-instancearn)
*/
override fun instanceArn(): String = unwrap(this).getInstanceArn()
/**
* The name of the flow module.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-connect-contactflowmodule.html#cfn-connect-contactflowmodule-name)
*/
override fun name(): String = unwrap(this).getName()
/**
* The state of the flow module.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-connect-contactflowmodule.html#cfn-connect-contactflowmodule-state)
*/
override fun state(): String? = unwrap(this).getState()
/**
* An array of key-value pairs to apply to this resource.
*
* For more information, see
* [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
* .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-connect-contactflowmodule.html#cfn-connect-contactflowmodule-tags)
*/
override fun tags(): List<CfnTag> = unwrap(this).getTags()?.map(CfnTag::wrap) ?: emptyList()
}
public companion object {
public operator fun invoke(block: Builder.() -> Unit = {}): CfnContactFlowModuleProps {
val builderImpl = BuilderImpl()
return Wrapper(builderImpl.apply(block).build())
}
internal fun wrap(cdkObject: software.amazon.awscdk.services.connect.CfnContactFlowModuleProps):
CfnContactFlowModuleProps = CdkObjectWrappers.wrap(cdkObject) as? CfnContactFlowModuleProps
?: Wrapper(cdkObject)
internal fun unwrap(wrapped: CfnContactFlowModuleProps):
software.amazon.awscdk.services.connect.CfnContactFlowModuleProps = (wrapped as
CdkObject).cdkObject as software.amazon.awscdk.services.connect.CfnContactFlowModuleProps
}
}
| 1
|
Kotlin
|
0
| 4
|
eb3eef728b34da593a3e55dc423d4f5fa3668e9c
| 9,144
|
kotlin-cdk-wrapper
|
Apache License 2.0
|
app/src/main/java/com/example/androiddevchallenge/model/Bunny.kt
|
tobibo
| 342,403,379
| false
| null |
/*
* Copyright 2021 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge.model
import java.io.Serializable
data class Bunny(
val name: String,
val dob: String,
val breed: String,
val sex: String,
val description: String,
val imageUrl: String
) : Serializable
fun getBunnies() = listOf<Bunny>(
Bunny(
"<NAME>",
"2/12/2020",
"giants",
"females",
"These girls are very sweet and friendly and love pats.",
"https://static.wixstatic.com/media/df8370_38925f62a6704474b57a6fd9d1721080~mv2.jpg"
),
Bunny(
"Gigi",
"1/12/2020",
"giants",
"male",
"Gigi is a giant bun and she has 2 babies waiting for homes.",
"https://static.wixstatic.com/media/df8370_38925f62a6704474b57a6fd9d1721080~mv2.jpg"
),
Bunny(
"Ginger & Wilder (vib)",
"Ginger 1/7/2020 Wilder 1/8/2020",
"giants",
"male/female",
"Ginger is very friendly once he gets to know you. Wilder is a native bush bunny. And yes... you can keep a bush bunny in Victoria. See link below for more information.",
"https://static.wixstatic.com/media/df8370_29ab6117f9ec40419a9c4004e9afb22e~mv2.jpg"
),
Bunny(
"Dapple",
"unknown",
"Dwarf x",
"female",
"Ginger is very friendly once he gets to know you. Wilder is a native bush bunny. And yes... you can keep a bush bunny in Victoria. See link below for more information.",
"https://static.wixstatic.com/media/df8370_4e24de34c57243b5afb70d7b7c6acbba~mv2.jpg"
),
Bunny(
"Elisa (vib)",
"18/10/2019",
"Dwarf x",
"female",
"Elsa is an active and inquisitive bun. Not suitable for families with children as small humans make her nervous.",
"https://static.wixstatic.com/media/df8370_451e688f4c80445b9ce07c223535c5dd~mv2.jpg"
),
Bunny(
"Kisses",
"27/5/2017",
"Standard sating",
"female",
"Kisses was left with a friend after her owners returned to NZ, and they were not to return. Kisses is a little shy to start but is litter trained and has been a free range house bun.\n" +
"\n" +
"Kisses is recovering from trauma from a bite",
"https://static.wixstatic.com/media/df8370_aaf082dbef1049f5bbca4db8c7adf3eb~mv2.jpg"
),
Bunny(
"Flur",
"23/10/2020",
"Dwarf",
"female",
"nethie dwarf/dutch colours",
"https://static.wixstatic.com/media/df8370_9a95addaf7b2473da5c660072960249d~mv2.jpg"
),
Bunny(
"Carrot",
"27/11/2018",
"Ginger lop",
"male",
"",
"https://static.wixstatic.com/media/df8370_0a1a5d1da09645ca86f57810bbcbf2f4~mv2.jpg"
),
Bunny(
"Mercury",
"06/08/2020",
"lop",
"male",
"",
"https://static.wixstatic.com/media/df8370_e33bab2f10b94e8196faaaacc09844b8~mv2.jpg"
)
)
| 0
|
Kotlin
|
0
| 0
|
4ca067d51d01fd9ed1a4aacedc67385bf90979d2
| 3,595
|
AdoptABunny
|
Apache License 2.0
|
game/plugins/src/main/kotlin/gg/rsmod/plugins/content/npcs/definitions/critters/giant_bat_level_27.plugin.kts
|
2011Scape
| 578,880,245
| false
| null |
package gg.rsmod.plugins.content.npcs.definitions.critters
import gg.rsmod.game.model.combat.SlayerAssignment
import gg.rsmod.plugins.content.drops.DropTableFactory
val ids = intArrayOf(Npcs.GIANT_BAT)
val table = DropTableFactory
val giantBat = table.build {
guaranteed {
obj(Items.BAT_BONES)
}
}
table.register(giantBat, *ids)
on_npc_death(*ids) {
table.getDrop(world, npc.damageMap.getMostDamage()!! as Player, npc.id, npc.tile)
}
ids.forEach {
set_combat_def(it) {
configs {
attackSpeed = 4
respawnDelay = 35
}
stats {
hitpoints = 320
attack = 22
strength = 22
defence = 22
}
bonuses {
defenceStab = 10
defenceSlash = 10
defenceCrush = 12
defenceMagic = 10
defenceRanged = 8
}
anims {
attack = 4915
death = 4917
block = 4916
}
aggro {
radius = 4
}
slayerData {
slayerAssignment = SlayerAssignment.BAT
levelRequirement = 1
xp = 32.0
}
}
}
| 39
| null |
45
| 34
|
e5400cc71bfa087164153d468979c5a3abc24841
| 1,187
|
game
|
Apache License 2.0
|
broadcast/samples/system/app/src/main/java/com/ansorod/systembroadcasts/receiver/LocaleChangeReceiver.kt
|
ansorod
| 379,045,809
| false
| null |
package com.ansorod.systembroadcasts.receiver
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
class LocaleChangeReceiver: BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
intent?.let { receivedIntent ->
Log.i("jamal", "onReceive: ACTION -> ${receivedIntent.action}")
printExtras(receivedIntent.extras)
}
}
private fun printExtras(bundleExtras: Bundle?) {
if(bundleExtras == null) {
Log.i("jamal", "Bundle is empty")
return
}
val keySet = bundleExtras.keySet()
for(key in keySet) {
Log.i("jamal", "KEY: $key - VALUE: ${bundleExtras[key]}")
}
}
}
| 0
|
Kotlin
|
0
| 0
|
7a02eadf933d52a521a2dd41fce5606ac8937fff
| 819
|
android_adv_school
|
Apache License 2.0
|
app/src/main/java/it/fscarponi/opensea/MainActivity.kt
|
fscarponi
| 499,792,882
| false
| null |
package it.fscarponi.opensea
import android.content.Context
import android.net.Uri
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.*
import androidx.compose.ui.platform.LocalContext
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import it.fscarponi.opensea.di.DIModules
import it.fscarponi.opensea.ui.theme.OpenSeaTheme
import org.kodein.di.DI
import org.kodein.di.DIAware
import org.kodein.di.compose.rememberInstance
import org.kodein.di.compose.withDI
import org.kodein.di.instance
import ovh.plrapps.mapcompose.core.TileStreamProvider
import ovh.plrapps.mapcompose.ui.MapUI
import java.io.InputStream
class MainActivity : ComponentActivity(), DIAware {
override val di: DI = DI.lazy {
import(DIModules.viewModels)
}
private val viewModel: OpenSeaMapViewModel by instance()
private val repo: OpenSeaRepository by instance()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val navController = rememberNavController()
OpenSeaTheme {
// A surface container using the "background" color from the theme
NavHost(navController = navController, startDestination = "HOME") {
composable("HOME") {
OpenSeaMap(viewModel = viewModel, navController = navController, repo)
}
composable("USER") { }
composable("mapDownload") { withDI(di = di) { MapDownloader(navController) } }
}
}
}
}
}
class OpenSeaTileStreamProvider(private val context: Context, private val mapUri: Uri, private val repo: OpenSeaRepository) : TileStreamProvider {
override suspend fun getTileStream(row: Int, col: Int, zoomLvl: Int): InputStream? {
return repo.getTileStream(row, col, zoomLvl)
}
}
@Composable
fun OpenSeaMap(viewModel: OpenSeaMapViewModel = OpenSeaMapViewModel(), navController: NavHostController, repository: OpenSeaRepository) {
if (viewModel.mapUri != null) {
viewModel.setTileStreamProvider(
OpenSeaTileStreamProvider(LocalContext.current, viewModel.mapUri!!, repository)
)
MapUI(state = viewModel.state)
} else {
Column() {
Text("no map found")
Button(onClick = { navController.navigate("mapDownload") }) {
Text("Download MAP")
}
}
}
}
@Composable
fun MapDownloader(navController: NavHostController) {
val openSeaMapViewModel: OpenSeaMapViewModel by rememberInstance()
var uri by remember {
mutableStateOf<Uri?>(null)
}
val chooser = rememberLauncherForActivityResult(
contract =
ActivityResultContracts.GetContent()
) {
openSeaMapViewModel.mapUri = it
uri = it
}
Column {
Text("Map download not yet implemented, load map from devices")
TextButton(onClick = {
chooser.launch("*/*")
}) {
Text("CHOOSE")
}
if (uri != null) {
Text(uri.toString())
TextButton(onClick = {
println(openSeaMapViewModel.mapUri)
navController.navigate("HOME")
}) {
Text("BACK TO MAP")
}
}
}
}
| 0
|
Kotlin
|
0
| 1
|
33b4e19c7a5d8a38d5ae0e5d4aae5f500c117a55
| 3,879
|
OpenSea
|
MIT License
|
game/plugins/src/main/kotlin/gg/rsmod/plugins/content/areas/spawns/spawns_15251.plugin.kts
|
2011Scape
| 578,880,245
| false
|
{"Kotlin": 8904349, "Dockerfile": 1354}
|
package gg.rsmod.plugins.content.areas.spawns
spawn_npc(
npc = Npcs.ALBINO_BAT,
x = 3796,
z = 9463,
height = 0,
walkRadius = 5,
direction = Direction.NORTH,
static = false,
) // Albino bat
spawn_npc(
npc = Npcs.ALBINO_BAT,
x = 3802,
z = 9448,
height = 0,
walkRadius = 5,
direction = Direction.NORTH,
static = false,
) // Albino bat
spawn_npc(
npc = Npcs.ALBINO_BAT,
x = 3789,
z = 9441,
height = 0,
walkRadius = 5,
direction = Direction.NORTH,
static = false,
) // Albino bat
spawn_npc(
npc = Npcs.ALBINO_BAT,
x = 3815,
z = 9465,
height = 0,
walkRadius = 5,
direction = Direction.NORTH,
static = false,
) // Albino bat
spawn_npc(
npc = Npcs.ALBINO_BAT,
x = 3812,
z = 9429,
height = 0,
walkRadius = 5,
direction = Direction.NORTH,
static = false,
) // Albino bat
spawn_npc(
npc = Npcs.ALBINO_BAT,
x = 3823,
z = 9452,
height = 0,
walkRadius = 5,
direction = Direction.NORTH,
static = false,
) // Albino bat
spawn_npc(
npc = Npcs.ALBINO_BAT,
x = 3833,
z = 9424,
height = 0,
walkRadius = 5,
direction = Direction.NORTH,
static = false,
) // Albino bat
spawn_npc(
npc = Npcs.ALBINO_BAT,
x = 3820,
z = 9418,
height = 0,
walkRadius = 5,
direction = Direction.NORTH,
static = false,
) // Albino bat
spawn_npc(
npc = Npcs.ALBINO_BAT,
x = 3830,
z = 9460,
height = 0,
walkRadius = 5,
direction = Direction.NORTH,
static = false,
) // Albino bat
spawn_npc(
npc = Npcs.ALBINO_BAT,
x = 3804,
z = 9421,
height = 0,
walkRadius = 5,
direction = Direction.NORTH,
static = false,
) // Albino bat
spawn_npc(
npc = Npcs.ALBINO_BAT,
x = 3784,
z = 9418,
height = 0,
walkRadius = 5,
direction = Direction.NORTH,
static = false,
) // Albino bat
spawn_npc(
npc = Npcs.ALBINO_BAT,
x = 3779,
z = 9433,
height = 0,
walkRadius = 5,
direction = Direction.NORTH,
static = false,
) // Albino bat
spawn_npc(
npc = Npcs.CAVE_HORROR_4354,
x = 3777,
z = 9460,
height = 0,
walkRadius = 5,
direction = Direction.NORTH,
static = false,
) // Cave horror
spawn_npc(
npc = Npcs.CAVE_HORROR_4354,
x = 3790,
z = 9446,
height = 0,
walkRadius = 5,
direction = Direction.NORTH,
static = false,
) // Cave horror
spawn_npc(
npc = Npcs.CAVE_HORROR_4354,
x = 3796,
z = 9435,
height = 0,
walkRadius = 5,
direction = Direction.NORTH,
static = false,
) // Cave horror
spawn_npc(
npc = Npcs.CAVE_HORROR_4354,
x = 3809,
z = 9449,
height = 0,
walkRadius = 5,
direction = Direction.NORTH,
static = false,
) // Cave horror
spawn_npc(
npc = Npcs.CAVE_HORROR_4354,
x = 3813,
z = 9449,
height = 0,
walkRadius = 5,
direction = Direction.NORTH,
static = false,
) // Cave horror
spawn_npc(
npc = Npcs.CAVE_HORROR_4354,
x = 3812,
z = 9426,
height = 0,
walkRadius = 5,
direction = Direction.NORTH,
static = false,
) // Cave horror
spawn_npc(
npc = Npcs.CAVE_HORROR_4355,
x = 3794,
z = 9439,
height = 0,
walkRadius = 5,
direction = Direction.NORTH,
static = false,
) // Cave horror
spawn_npc(
npc = Npcs.CAVE_HORROR_4355,
x = 3835,
z = 9427,
height = 0,
walkRadius = 5,
direction = Direction.NORTH,
static = false,
) // Cave horror
spawn_npc(
npc = Npcs.CAVE_HORROR_4356,
x = 3785,
z = 9465,
height = 0,
walkRadius = 5,
direction = Direction.NORTH,
static = false,
) // Cave horror
spawn_npc(
npc = Npcs.CAVE_HORROR_4356,
x = 3797,
z = 9450,
height = 0,
walkRadius = 5,
direction = Direction.NORTH,
static = false,
) // Cave horror
spawn_npc(
npc = Npcs.CAVE_HORROR_4356,
x = 3804,
z = 9442,
height = 0,
walkRadius = 5,
direction = Direction.NORTH,
static = false,
) // Cave horror
spawn_npc(
npc = Npcs.CAVE_HORROR_4356,
x = 3779,
z = 9439,
height = 0,
walkRadius = 5,
direction = Direction.NORTH,
static = false,
) // Cave horror
spawn_npc(
npc = Npcs.CAVE_HORROR_4356,
x = 3834,
z = 9418,
height = 0,
walkRadius = 5,
direction = Direction.NORTH,
static = false,
) // Cave horror
spawn_npc(
npc = Npcs.CAVE_HORROR_4356,
x = 3804,
z = 9423,
height = 0,
walkRadius = 5,
direction = Direction.NORTH,
static = false,
) // Cave horror
spawn_npc(
npc = Npcs.CAVE_HORROR_4356,
x = 3794,
z = 9422,
height = 0,
walkRadius = 5,
direction = Direction.NORTH,
static = false,
) // Cave horror
spawn_npc(
npc = Npcs.CAVE_HORROR_4356,
x = 3794,
z = 9413,
height = 0,
walkRadius = 5,
direction = Direction.NORTH,
static = false,
) // Cave horror
spawn_npc(
npc = Npcs.CAVE_HORROR_4357,
x = 3792,
z = 9420,
height = 0,
walkRadius = 5,
direction = Direction.NORTH,
static = false,
) // Cave horror
| 39
|
Kotlin
|
143
| 34
|
e5400cc71bfa087164153d468979c5a3abc24841
| 5,125
|
game
|
Apache License 2.0
|
spring-boot/API cliente e cadastro/src/main/kotlin/sptech/projetojpa1/dominio/Pergunta.kt
|
kronos-agendamento
| 758,290,087
| false
|
{"Kotlin": 39215, "HTML": 38487, "CSS": 23175, "JavaScript": 5155}
|
package sptech.projetojpa1.dominio
import jakarta.persistence.Entity
import jakarta.persistence.GeneratedValue
import jakarta.persistence.GenerationType
import jakarta.persistence.Id
import jakarta.persistence.ManyToOne
import org.hibernate.annotations.JdbcTypeCode
import org.hibernate.type.SqlTypes
@Entity
class Pergunta (
@field:Id @field:GeneratedValue(strategy = GenerationType.IDENTITY)
var codigoPergunta: Int,
var tipo:String,
var nome:String,
@field:ManyToOne
val resposta:Resposta
) {
}
| 0
|
Kotlin
|
0
| 2
|
6ec5df80b3c05b4ea2d0436551da6f00cfaf9f44
| 523
|
projeto-teste
|
MIT License
|
threejs_kt/src/main/kotlin/three/CubicBezierCurve3.module_three.kt
|
liorgonnen
| 278,797,136
| false
| null |
@file:JsQualifier("THREE")
@file:Suppress("ABSTRACT_MEMBER_NOT_IMPLEMENTED", "VAR_TYPE_MISMATCH_ON_OVERRIDE", "INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS", "EXTERNAL_DELEGATION", "PackageDirectoryMismatch")
package three.js
import kotlin.js.*
import kotlin.js.Json
import org.khronos.webgl.*
import org.w3c.dom.*
import org.w3c.dom.events.*
import org.w3c.dom.parsing.*
import org.w3c.dom.svg.*
import org.w3c.dom.url.*
import org.w3c.fetch.*
import org.w3c.files.*
import org.w3c.notifications.*
import org.w3c.performance.*
import org.w3c.workers.*
import org.w3c.xhr.*
open external class CubicBezierCurve3(v0: Vector3, v1: Vector3, v2: Vector3, v3: Vector3) : Curve<Vector3> {
open var v0: Vector3
open var v1: Vector3
open var v2: Vector3
open var v3: Vector3
}
| 0
|
Kotlin
|
2
| 4
|
6455743160f672803e94c4b9211d38588025746d
| 855
|
pacman3d
|
MIT License
|
src/main/java/org/ethtrader/ticker/Entry.kt
|
jaycarey
| 69,341,866
| false
| null |
package org.ethtrader.ticker
import java.io.File
import java.net.CookieHandler
import java.net.CookieManager
import java.net.URL
import java.util.concurrent.TimeUnit
fun main(args: Array<String>) {
try {
CookieHandler.setDefault(CookieManager(null, java.net.CookiePolicy.ACCEPT_ALL));
fun getResourceUrl(path: String): URL = URL(args[5] + path)
val outputDir = File("output")
outputDir.mkdirs()
while (true) {
try {
val config = TickerEthConfig(::getResourceUrl)
val reader = DataReader(config.providers)
val tickerFactory = TickerFactory(outputDir, ::getResourceUrl)
val client = OAuthClient(config.reddit.apiUrl, AuthInfo(args[1], args[2], args[3], args[4]))
val reddit = Reddit(client, args[0])
val test = args.contains("--test")
val data = reader.read(config.dataPoints)
config.tickers.entries.forEach {
try {
val (name, tickerConfig) = it
val ticker = tickerFactory.produceTicker(name, data, tickerConfig)
if (!test) reddit.uploadImage(name, ticker)
} catch (e: Exception) {
println("ERROR: " + e.message)
e.printStackTrace()
}
}
try {
val oldCss = reddit.getStylesheet()
File(outputDir, "old.css").writeTextAndLog(oldCss, "Wrote old css to %s")
val newCss = tickerFactory.getAndResetCss(oldCss)
File(outputDir, "new.css").writeTextAndLog(newCss, "Wrote new css to %s")
if (!test) reddit.uploadStylesheet(newCss)
} catch (e: Throwable) {
println("Error trying to update tickers")
e.printStackTrace()
}
println("Waiting ${config.reddit.frequencySeconds} seconds.")
Thread.sleep(TimeUnit.SECONDS.toMillis(config.reddit.frequencySeconds))
if (test) break;
} catch (e: Throwable) {
System.err.println("Unexpected error while running ticker." + e)
}
}
} catch (e: Throwable) {
System.err.println("Usage: <<subreddit>> <<username>> <<password>> <<clientId>> <<secret>> <<resourceUrl>>")
System.err.println("clientId and secret can be administered here: https://www.reddit.com/prefs/apps/")
System.err.println("resourceUrl points to the configuration/resources to build the ticker.")
System.err.println("\n Error: ${e.message}")
e.printStackTrace()
}
}
fun File.writeTextAndLog(text: String, message: String) {
writeText(text)
println(message.format(absolutePath))
}
| 0
|
Kotlin
|
3
| 3
|
6a4883fa9eed62af2eaa481069406ad52d1f6ad7
| 2,895
|
ethtrader-ticker
|
Apache License 2.0
|
app/src/main/kotlin/me/sweetll/tucao/business/drrr/DrrrDetailActivity.kt
|
rain2372
| 163,959,729
| true
|
{"Kotlin": 555375, "Java": 227611, "Makefile": 3381}
|
package me.sweetll.tucao.business.drrr
import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.databinding.DataBindingUtil
import android.net.Uri
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.widget.FrameLayout
import com.github.piasy.biv.BigImageViewer
import com.github.piasy.biv.indicator.progresspie.ProgressPieIndicator
import com.github.piasy.biv.loader.glide.GlideImageLoader
import com.github.piasy.biv.view.BigImageView
import me.sweetll.tucao.AppApplication
import me.sweetll.tucao.Const
import me.sweetll.tucao.R
import me.sweetll.tucao.base.BaseActivity
import me.sweetll.tucao.business.drrr.adapter.ReplyAdapter
import me.sweetll.tucao.business.drrr.model.MultipleItem
import me.sweetll.tucao.business.drrr.model.Post
import me.sweetll.tucao.business.drrr.viewmodel.DrrrDetailViewModel
import me.sweetll.tucao.databinding.ActivityDrrrDetailBinding
class DrrrDetailActivity : BaseActivity() {
lateinit var binding: ActivityDrrrDetailBinding
lateinit var viewModel: DrrrDetailViewModel
override fun getStatusBar() = binding.statusBar
override fun getToolbar() = binding.toolbar
lateinit var post: Post
lateinit var adapter: ReplyAdapter
var thumb: String = ""
var source: String = ""
private fun bigImageViewerDialog(): Dialog {
val view = LayoutInflater.from(this).inflate(R.layout.dialog_big_image_viewer, null)
val bigImageView = view.findViewById<BigImageView>(R.id.bigImage)
bigImageView.setProgressIndicator(ProgressPieIndicator())
val dialog = Dialog(this, android.R.style.Theme_Black_NoTitleBar_Fullscreen)
dialog.setCancelable(true)
dialog.setContentView(view, FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT))
dialog.setOnShowListener {
bigImageView.showImage(Uri.parse(thumb), Uri.parse(source))
}
return dialog
}
companion object {
const val REQUEST_NEW_REPLY = 1
private const val ARG_POST = "post"
fun intentTo(context: Context, post: Post) {
val intent = Intent(context, DrrrDetailActivity::class.java)
intent.putExtra(ARG_POST, post)
context.startActivity(intent)
}
}
override fun initView(savedInstanceState: Bundle?) {
initBigImageViewer()
post = intent.getParcelableExtra(ARG_POST)
binding = DataBindingUtil.setContentView(this, R.layout.activity_drrr_detail)
viewModel = DrrrDetailViewModel(this)
binding.viewModel = viewModel
binding.swipeRefresh.setColorSchemeResources(R.color.colorPrimary)
binding.swipeRefresh.setOnRefreshListener {
viewModel.loadData()
}
setupRecycler()
}
private fun initBigImageViewer() {
BigImageViewer.initialize(GlideImageLoader.with(AppApplication.get()))
}
private fun setupRecycler() {
val data = mutableListOf(MultipleItem(post))
data.add(MultipleItem(post.replyNum))
adapter = ReplyAdapter(this, data)
adapter.setOnLoadMoreListener({
viewModel.loadMoreData()
}, binding.replyRecycler)
adapter.setEnableLoadMore(false)
binding.replyRecycler.adapter = adapter
binding.replyRecycler.layoutManager = LinearLayoutManager(this)
}
fun setRefreshing(refreshing: Boolean) {
binding.swipeRefresh.isRefreshing = refreshing
}
fun loadData(data: MutableList<MultipleItem>, total: Int) {
adapter.data.subList(2, adapter.data.size).clear()
adapter.data[1].replyNum(total)
adapter.data.addAll(data)
adapter.notifyDataSetChanged()
if (data.size < viewModel.size) {
adapter.setEnableLoadMore(false)
} else {
adapter.setEnableLoadMore(true)
}
}
fun loadMoreData(data: MutableList<MultipleItem>?, total: Int, flag: Int) {
when (flag) {
Const.LOAD_MORE_COMPLETE -> {
adapter.data[1].replyNum(total)
adapter.notifyItemChanged(1)
adapter.addData(data!!)
adapter.loadMoreComplete()
}
Const.LOAD_MORE_END -> {
adapter.data[1].replyNum(total)
adapter.notifyItemChanged(1)
adapter.addData(data!!)
adapter.loadMoreEnd()
}
Const.LOAD_MORE_FAIL -> {
adapter.loadMoreFail()
}
}
}
fun showSourceImage(thumb: String, source: String) {
this.thumb = thumb
this.source = source
bigImageViewerDialog().show()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_NEW_REPLY && resultCode == Activity.RESULT_OK) {
viewModel.loadData()
} else {
super.onActivityResult(requestCode, resultCode, data)
}
}
override fun initToolbar() {
super.initToolbar()
supportActionBar?.let {
it.title = "查看回复"
it.setDisplayHomeAsUpEnabled(true)
}
}
}
| 1
|
Kotlin
|
1
| 1
|
af67233c8b8e7fb418d0c0135dce58e3ba79f66b
| 5,338
|
Tucao
|
MIT License
|
libraries/stdlib/jvm/compileOnly/ConcurrentModificationException.kt
|
JetBrains
| 3,432,266
| false
|
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
|
/*
* Copyright 2010-2024 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package java.util
public open class ConcurrentModificationException : RuntimeException {
public constructor()
public constructor(message: String?)
public constructor(message: String?, cause: Throwable?)
public constructor(cause: Throwable?)
}
| 181
|
Kotlin
|
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 469
|
kotlin
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.