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
app/src/main/java/cn/neday/sheep/viewmodel/MainViewModel.kt
gitter-badger
203,146,869
false
{"Gradle": 7, "Markdown": 6, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "YAML": 2, "Proguard": 1, "INI": 1, "Kotlin": 79, "XML": 65, "Java": 7}
package cn.neday.sheep.viewmodel /** * IndexViewModel * * @author nEdAy */ class MainViewModel : BaseViewModel() { var mLastActiveFragmentTag: String? = null }
1
null
1
1
9c8ddc824a6a7eb079d41707c98ec5252d22230d
169
Sheep
MIT License
plugins/evaluation-plugin/core/src/com/intellij/cce/metric/LatencyMetrics.kt
JetBrains
2,489,216
false
null
package com.intellij.cce.metric import com.intellij.cce.core.Lookup import com.intellij.cce.core.Session import com.intellij.cce.metric.util.Sample abstract class LatencyMetric(override val name: String) : Metric { private val sample = Sample() override val value: Double get() = compute(sample) override fun evaluate(sessions: List<Session>, comparator: SuggestionsComparator): Double { val fileSample = Sample() sessions.stream() .flatMap { session -> session.lookups.stream() } .filter(::shouldInclude) .forEach { this.sample.add(it.latency.toDouble()) fileSample.add(it.latency.toDouble()) } return compute(fileSample) } abstract fun compute(sample: Sample): Double open fun shouldInclude(lookup: Lookup) = true } class MaxLatencyMetric : LatencyMetric(NAME) { override val valueType = MetricValueType.INT override fun compute(sample: Sample): Double = sample.max() companion object { const val NAME = "Max Latency" } } class TotalLatencyMetric : LatencyMetric(NAME) { override val valueType = MetricValueType.DOUBLE override val showByDefault = false override fun compute(sample: Sample): Double = sample.sum() companion object { const val NAME = "Total Latency" } } class MeanLatencyMetric(private val filterZeroes: Boolean = false) : LatencyMetric(NAME) { override val valueType = MetricValueType.DOUBLE override fun compute(sample: Sample): Double = sample.mean() override fun shouldInclude(lookup: Lookup) = if (filterZeroes) lookup.latency > 0 else true companion object { const val NAME = "Mean Latency" } }
214
null
4829
15,129
5578c1c17d75ca03071cc95049ce260b3a43d50d
1,642
intellij-community
Apache License 2.0
app/src/main/java/com/enigma/nearby/data/remote/retrofit/RequestInterceptor.kt
Doodg
217,362,673
false
null
package com.enigma.nearby.data.remote.retrofit import okhttp3.Interceptor import okhttp3.Response private const val CLIENT_ID = "client_id" private const val CLIENT_ID_VALUE = "E0AVU3HPLONXPYCDA24O4ED2RJFY3U1E1GO1UC1QOZMOOMCP" private const val CLIENT_SECRET = "client_secret" private const val CLIENT_SECRET_TOKEN = "<KEY>" private const val V_VERSION = "v" private const val V_VERSION_VALUE = "20180323" private const val ITEM_LIMIT = "limit" private const val ITEM_PER_PAGE_LIMIT = "20" class RequestInterceptor : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { var request = chain.request() val url = request.url.newBuilder() .addQueryParameter( CLIENT_ID, CLIENT_ID_VALUE ) .addQueryParameter( CLIENT_SECRET, CLIENT_SECRET_TOKEN ) .addQueryParameter( V_VERSION, V_VERSION_VALUE ) .addQueryParameter( ITEM_LIMIT, ITEM_PER_PAGE_LIMIT ) .build() request = request.newBuilder().url(url).build() return chain.proceed(request) } }
0
Kotlin
0
0
e9053be681f9aaa366b7f74a87bae4e4c8054154
1,239
NearBy
Apache License 2.0
grpc-order-management-service/src/main/kotlin/com/ribbontek/ordermanagement/mapping/ProductMapping.kt
ribbontek
834,289,255
false
{"Kotlin": 424897, "Shell": 26370, "HTML": 1565, "Dockerfile": 557, "PLpgSQL": 398}
package com.ribbontek.ordermanagement.mapping import com.ribbontek.grpccourse.Product import com.ribbontek.grpccourse.product import com.ribbontek.ordermanagement.repository.product.ProductEntity fun ProductEntity.toProduct(): Product { val source = this return product { this.requestId = source.requestId.toString() source.discount?.code?.let { this.discountCode = it } this.categoryCode = source.category.code!! this.title = source.title this.description = source.description this.quantity = source.quantity this.price = source.price.toFloat() source.sku?.let { this.sku = it } } }
0
Kotlin
0
0
8116d11ba6f180493d88a2d132b1be79be3db1b4
662
grpc-course
MIT License
app/src/main/java/github/leavesczy/track/click/view/UncheckViewOnClick.kt
leavesCZY
672,474,352
false
{"Kotlin": 68337}
package github.leavesczy.track.click.view /** * @Author: leavesCZY * @Github: https://github.com/leavesCZY * @Desc: */ @Target(AnnotationTarget.FUNCTION) @Retention(AnnotationRetention.RUNTIME) annotation class UncheckViewOnClick
0
Kotlin
2
68
34cbe8905b0b7bf2aa3149ee3b2f837b57c68379
234
Track
Apache License 2.0
app/src/main/kotlin/com/droibit/quickly/data/repository/source/AppInfoDataSourceImpl.kt
droibit
72,275,775
false
null
package com.droibit.quickly.data.repository.source import android.content.pm.ApplicationInfo.FLAG_SYSTEM import android.content.pm.PackageInfo import android.content.pm.PackageManager import com.droibit.quickly.data.repository.appinfo.AppInfo import rx.Observable import rx.Single import rx.lang.kotlin.singleOf class AppInfoDataSourceImpl(private val pm: PackageManager) : AppInfoDataSource { override fun getAll(): Observable<AppInfo> { return Observable.from(pm.getInstalledPackages(0)) .map { it.toAppInfo() } } override fun get(packageName: String): Single<AppInfo> { return singleOf(pm.getPackageInfo(packageName, 0)) .map { it.toAppInfo() } } private fun PackageInfo.toAppInfo(): AppInfo { return AppInfo( packageName = packageName, name = "${applicationInfo.loadLabel(pm)}", versionCode = versionCode, versionName = versionName ?: "(NULL)", icon = applicationInfo.icon, preInstalled = (applicationInfo.flags and FLAG_SYSTEM) == 1, lastUpdateTime = lastUpdateTime ) } }
0
Kotlin
1
0
46e739b2bf48bdcc302bd042941ac337b7232a3f
1,181
quickly
Apache License 2.0
modules/json-test/src/test/kotlin/com/oxviewer/core/json/JsonTest.kt
0xViewer
127,707,384
false
null
/* * Copyright 2018 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.oxviewer.core.json import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFails expect fun newJsonFactory(): JsonFactory class JsonTest { private val factory = newJsonFactory() @Test fun testParseJsonObject() { val json = factory.parseJson("{\n" + " \"array\": [\n" + " 1,\n" + " 2,\n" + " 3\n" + " ],\n" + " \"boolean\": true,\n" + " \"null\": null,\n" + " \"number\": 123,\n" + " \"object\": {\n" + " \"a\": \"b\",\n" + " \"c\": \"d\",\n" + " \"e\": \"f\"\n" + " },\n" + " \"string\": \"Hello World\"\n" + "}") assertEquals(true, json is JsonObject) val jo = json as JsonObject val ja = jo.getJsonArray("array") assertEquals(3, ja.size()) assertEquals(1, ja.getInt(0)) assertEquals(2, ja.getInt(1)) assertEquals(3, ja.getInt(2)) assertEquals(true, jo.getBoolean("boolean")) assertFails { jo.getBoolean("null") } assertFails { jo.getInt("null") } assertFails { jo.getFloat("null") } assertFails { jo.getString("null") } assertFails { jo.getJsonObject("null") } assertFails { jo.getJsonArray("null") } assertEquals(123, jo.getInt("number")) val jo2 = jo.getJsonObject("object") assertEquals("b", jo2.getString("a")) assertEquals("d", jo2.getString("c")) assertEquals("f", jo2.getString("e")) assertEquals("Hello World", jo.getString("string")) } @Test fun testParseJsonArray() { val json = factory.parseJson("[1, \"2\"]") assertEquals(true, json is JsonArray) val ja = json as JsonArray assertEquals(2, ja.size()) assertEquals(1, ja.getInt(0)) assertEquals("2", ja.getString(1)) } @Test fun testParseError() { assertFails { factory.parseJson("123") } assertFails { factory.parseJson("123.43") } assertFails { factory.parseJson("\"nihao\"") } assertFails { factory.parseJson("false") } assertFails { factory.parseJson("null") } } private fun <T> testJsonObjectPut( getter: JsonObject.(String) -> T, setter: JsonObject.(String, T) -> JsonObject, value1: T, value2: T ) { val jo = factory.newJsonObject() assertFails { jo.getter("name") } jo.setter("name", value1).setter("name", value2) assertEquals(value2, jo.getter("name")) } @Test fun testJsonObjectPutBoolean() = testJsonObjectPut(JsonObject::getBoolean, JsonObject::put, false, true) @Test fun testJsonObjectPutInt() = testJsonObjectPut(JsonObject::getInt, JsonObject::put, 12, 21) @Test fun testJsonObjectPutFloat() = testJsonObjectPut(JsonObject::getFloat, JsonObject::put, 12.0f, 21.0f) @Test fun testJsonObjectPutString() = testJsonObjectPut(JsonObject::getString, JsonObject::put, "12", "21") @Test fun testJsonObjectPutObject() { val jo = factory.newJsonObject() assertFails { jo.getJsonObject("name") } jo.put("name", factory.newJsonObject().put("name", "value")) val jo2 = jo.getJsonObject("name") assertEquals("value", jo2.getString("name")) } @Test fun testJsonObjectPutArray() { val jo = factory.newJsonObject() assertFails { jo.getJsonArray("name") } jo.put("name", factory.newJsonArray().add("value")) val ja2 = jo.getJsonArray("name") assertEquals(1, ja2.size()) assertEquals("value", ja2.getString(0)) } @Test fun testJsonObjectMixPut() { val jo = factory.newJsonObject() assertFails { jo.getBoolean("boolean") } assertFails { jo.getInt("boolean") } jo.put("boolean", false) assertEquals(false, jo.getBoolean("boolean")) assertFails { jo.getInt("boolean") } jo.put("boolean", 100) assertFails { jo.getBoolean("boolean") } assertEquals(100, jo.getInt("boolean")) } private fun newTestJsonObject(): JsonObject = factory.newJsonObject().apply { put("boolean", false) put("int", 100) put("float", 34.32f) put("string", "nihao") put("object", factory.newJsonObject().put("name", "value")) put("array", factory.newJsonArray().add("value")) } private fun assertTestJsonObject(jo: JsonObject) { assertEquals(false, jo.getBoolean("boolean")) assertEquals(100, jo.getInt("int")) assertEquals(34.32f, jo.getFloat("float")) assertEquals("nihao", jo.getString("string")) val jo2 = jo.getJsonObject("object") assertEquals("value", jo2.getString("name")) val ja2 = jo.getJsonArray("array") assertEquals("value", ja2.getString(0)) } @Test fun testJsonObjectAddGet() = assertTestJsonObject(newTestJsonObject()) @Test fun testJsonObjectToString() = assertTestJsonObject(factory.parseJson(newTestJsonObject().toString()) as JsonObject) private fun newTestJsonArray(): JsonArray = factory.newJsonArray().apply { add(false) add(100) add(34.32f) add("string") add(factory.newJsonObject().put("name", "value")) add(factory.newJsonArray().add("value")) } private fun assertTestJsonArray(ja: JsonArray) { assertEquals(6, ja.size()) assertEquals(false, ja.getBoolean(0)) assertEquals(100, ja.getInt(1)) assertEquals(34.32f, ja.getFloat(2)) assertEquals("string", ja.getString(3)) val jo2 = ja.getJsonObject(4) assertEquals("value", jo2.getString("name")) val ja2 = ja.getJsonArray(5) assertEquals("value", ja2.getString(0)) } @Test fun testJsonArrayAddGet() = assertTestJsonArray(newTestJsonArray()) @Test fun testJsonArrayToString() = assertTestJsonArray(factory.parseJson(newTestJsonArray().toString()) as JsonArray) }
0
Kotlin
0
1
af449253143eb8594a5aeabe7396d4fc980fb9c4
6,233
0xviewer-core
Apache License 2.0
app/src/main/java/com/stocksexchange/android/api/model/OrderParameters.kt
libertaria-project
183,030,087
true
{"Kotlin": 2210140}
package com.stocksexchange.android.api.model import android.os.Parcelable import com.stocksexchange.android.model.OrderModes import com.stocksexchange.android.model.SortTypes import kotlinx.android.parcel.Parcelize /** * Parameters storing order related data. */ @Parcelize data class OrderParameters( val marketName: String, val searchQuery: String, val mode: OrderModes, val type: OrderTypes, val status: OrderStatuses, val tradeType: OrderTradeTypes, val ownerType: OrderOwnerTypes, val sortType: SortTypes, val count: Int ) : Parcelable { companion object { const val DEFAULT_MARKET_NAME = "ALL" const val DEFAULT_ORDERS_COUNT = 50 /** * Retrieves parameters for loading active orders. * * @return The parameters for loading active orders */ fun getActiveOrdersParameters(): OrderParameters { return getDefaultParameters().copy( marketName = OrderParameters.DEFAULT_MARKET_NAME, type = OrderTypes.ACTIVE, status = OrderStatuses.PENDING, mode = OrderModes.STANDARD ) } /** * Retrieves parameters for loading completed orders. * * @return The parameters for loading completed orders */ fun getCompletedOrdersParameters(): OrderParameters { return getDefaultParameters().copy( marketName = OrderParameters.DEFAULT_MARKET_NAME, type = OrderTypes.COMPLETED, status = OrderStatuses.FINISHED, mode = OrderModes.STANDARD ) } /** * Retrieves parameters for loading cancelled orders. * * @return The parameters for loading cancelled orders */ fun getCancelledOrdersParameters(): OrderParameters { return getDefaultParameters().copy( marketName = OrderParameters.DEFAULT_MARKET_NAME, type = OrderTypes.CANCELLED, status = OrderStatuses.CANCELLED, mode = OrderModes.STANDARD ) } /** * Retrieves parameters for loading search orders. * * @param type The type of orders to search * * @return The parameters for loading search orders */ fun getSearchOrdersParameters(type: OrderTypes): OrderParameters { return getDefaultParameters().copy( marketName = OrderParameters.DEFAULT_MARKET_NAME, type = type, status = OrderStatuses.INVALID, mode = OrderModes.SEARCH ) } /** * Retrieves a default set of parameters. * * @return The default order parameters */ fun getDefaultParameters(): OrderParameters { return OrderParameters( marketName = DEFAULT_MARKET_NAME, searchQuery = "", mode = OrderModes.STANDARD, type = OrderTypes.ACTIVE, status = OrderStatuses.INVALID, tradeType = OrderTradeTypes.ALL, ownerType = OrderOwnerTypes.OWN, sortType = SortTypes.DESC, count = DEFAULT_ORDERS_COUNT ) } } /** * A field that returns lowercase version of the search query. */ val lowercasedSearchQuery: String get() = searchQuery.toLowerCase() }
0
Kotlin
0
0
35a7f9a61f52f68ab3267da24da3c1d77d84e9c3
3,563
Android-app
MIT License
TestApiKotlin/app/src/main/java/com/example/testapikotlin/PinPlace.kt
Quinet-Maxence
372,178,534
false
null
package com.example.testapikotlin import android.annotation.SuppressLint import android.content.Context import android.graphics.Bitmap import android.graphics.Canvas import android.os.Parcel import android.os.Parcelable import android.view.LayoutInflater import android.view.View import android.widget.FrameLayout import com.alkurop.streetviewmarker.Place import com.google.android.gms.maps.model.LatLng data class PinPlace( val pinId: String?, val pinLocation: LatLng?, val title: String?, val description: String? = null) : Place, Parcelable { override fun getId(): String = pinId.toString() override fun getLocation(): LatLng = pinLocation!! override fun getMarkerPath(): String? = null override fun getDrawableRes(): Int = 0 @SuppressLint("SetTextI18n") override fun getBitmap(context: Context, distanceMeters: Int): Bitmap? { val li = LayoutInflater.from(context) val view = FrameLayout(context) val childView = li.inflate(R.layout.view_street_marker, view, true) // childView.textView.text = title // childView.distanceTv.text = "${distanceMeters}m" //Provide it with a layout params. It should necessarily be wrapping the //content as we not really going to have a parent for it. view.layoutParams = FrameLayout.LayoutParams( FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT ) //Pre-measure the childView so that height and width don't remain null. view.measure( View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED) ) //Assign a size and position to the childView and all of its descendants view.layout(0, 0, view.measuredWidth, view.measuredHeight) //Create the bitmap val bitmap = Bitmap.createBitmap( view.measuredWidth, view.measuredHeight, Bitmap.Config.ARGB_8888 ) //Create a canvas with the specified bitmap to draw into val c = Canvas(bitmap) //Render this childView (and all of its children) to the given Canvas view.draw(c) return bitmap } companion object { @JvmField val CREATOR: Parcelable.Creator<PinPlace> = object : Parcelable.Creator<PinPlace> { override fun createFromParcel(source: Parcel): PinPlace = PinPlace(source) override fun newArray(size: Int): Array<PinPlace?> = arrayOfNulls(size) } } constructor(source: Parcel) : this( source.readString(), source.readParcelable<LatLng>(LatLng::class.java.classLoader), source.readString(), source.readString() ) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeString(pinId) dest.writeParcelable(pinLocation, 0) dest.writeString(title) dest.writeString(description) } }
0
Kotlin
0
0
34fc4b86b39e560e4361383fc9c985add0fbe14a
3,066
InteraEsch
The Unlicense
src/test/kotlin/ktgen/ExampleKeyboard.kt
BarbieCue
621,481,927
false
null
package org.example import kotlinx.serialization.serializer import nl.adaptivity.xmlutil.core.XmlVersion import nl.adaptivity.xmlutil.serialization.XML internal fun exampleKeyboardEnglishUSA(): KeyboardLayout? = try { val xml = XML { xmlVersion = XmlVersion.XML10 } val serializer = serializer<KeyboardLayout>() xml.decodeFromString(serializer, ktouchKeyboardLayoutEnglishUSA) } catch (e: Exception) { System.err.println("Error on parsing example keyboard ${e.message}") throw e } internal val ktouchKeyboardLayoutEnglishUSA = """ <?xml version="1.0"?> <keyboardLayout> <id>{6a1fed47-1713-437c-931e-2ebc3ba1f366}</id> <title>English (USA)</title> <name>us</name> <width>1430</width> <height>480</height> <keys> <key top="200" left="180" width="80" height="80" fingerIndex="0"> <char modifier="right_shift" position="topLeft">A</char> <char position="hidden">a</char> </key> <key top="200" left="280" width="80" height="80" fingerIndex="1"> <char modifier="right_shift" position="topLeft">S</char> <char position="hidden">s</char> </key> <key top="200" left="380" width="80" height="80" fingerIndex="2"> <char modifier="right_shift" position="topLeft">D</char> <char position="hidden">d</char> </key> <key top="200" left="480" width="80" height="80" hasHapticMarker="true" fingerIndex="3"> <char modifier="right_shift" position="topLeft">F</char> <char position="hidden">f</char> </key> <key top="200" left="780" width="80" height="80" hasHapticMarker="true" fingerIndex="4"> <char modifier="left_shift" position="topLeft">J</char> <char position="hidden">j</char> </key> <key top="200" left="880" width="80" height="80" fingerIndex="5"> <char modifier="left_shift" position="topLeft">K</char> <char position="hidden">k</char> </key> <key top="200" left="980" width="80" height="80" fingerIndex="6"> <char modifier="left_shift" position="topLeft">L</char> <char position="hidden">l</char> </key> <key top="200" left="1080" width="80" height="80" fingerIndex="7"> <char modifier="left_shift" position="topLeft">:</char> <char position="bottomLeft">;</char> </key> <key top="0" left="0" width="80" height="80" fingerIndex="0"> <char modifier="right_shift" position="topLeft">~</char> <char position="bottomLeft">`</char> </key> <key top="0" left="100" width="80" height="80" fingerIndex="0"> <char modifier="right_shift" position="topLeft">!</char> <char position="bottomLeft">1</char> </key> <key top="0" left="200" width="80" height="80" fingerIndex="1"> <char modifier="right_shift" position="topLeft">@</char> <char position="bottomLeft">2</char> </key> <key top="0" left="300" width="80" height="80" fingerIndex="2"> <char modifier="right_shift" position="topLeft">#</char> <char position="bottomLeft">3</char> </key> <key top="0" left="400" width="80" height="80" fingerIndex="3"> <char modifier="right_shift" position="topLeft">${'$'}</char> <char position="bottomLeft">4</char> </key> <key top="0" left="500" width="80" height="80" fingerIndex="3"> <char modifier="right_shift" position="topLeft">%</char> <char position="bottomLeft">5</char> </key> <key top="0" left="600" width="80" height="80" fingerIndex="4"> <char modifier="left_shift" position="topLeft">^</char> <char position="bottomLeft">6</char> </key> <key top="0" left="700" width="80" height="80" fingerIndex="4"> <char modifier="left_shift" position="topLeft">&amp;</char> <char position="bottomLeft">7</char> </key> <key top="0" left="800" width="80" height="80" fingerIndex="5"> <char modifier="left_shift" position="topLeft">*</char> <char position="bottomLeft">8</char> </key> <key top="0" left="900" width="80" height="80" fingerIndex="6"> <char modifier="left_shift" position="topLeft">(</char> <char position="bottomLeft">9</char> </key> <key top="0" left="1000" width="80" height="80" fingerIndex="7"> <char modifier="left_shift" position="topLeft">)</char> <char position="bottomLeft">0</char> </key> <key top="0" left="1100" width="80" height="80" fingerIndex="7"> <char modifier="left_shift" position="topLeft">_</char> <char position="bottomLeft">-</char> </key> <key top="0" left="1200" width="80" height="80" fingerIndex="7"> <char modifier="left_shift" position="topLeft">+</char> <char position="bottomLeft">=</char> </key> <key top="100" left="150" width="80" height="80" fingerIndex="0"> <char modifier="right_shift" position="topLeft">Q</char> <char position="hidden">q</char> </key> <key top="100" left="250" width="80" height="80" fingerIndex="1"> <char modifier="right_shift" position="topLeft">W</char> <char position="hidden">w</char> </key> <key top="100" left="350" width="80" height="80" fingerIndex="2"> <char modifier="right_shift" position="topLeft">E</char> <char position="hidden">e</char> </key> <key top="100" left="450" width="80" height="80" fingerIndex="3"> <char modifier="right_shift" position="topLeft">R</char> <char position="hidden">r</char> </key> <key top="100" left="550" width="80" height="80" fingerIndex="3"> <char modifier="right_shift" position="topLeft">T</char> <char position="hidden">t</char> </key> <key top="300" left="230" width="80" height="80" fingerIndex="0"> <char modifier="right_shift" position="topLeft">Z</char> <char position="hidden">z</char> </key> <key top="100" left="750" width="80" height="80" fingerIndex="4"> <char modifier="left_shift" position="topLeft">U</char> <char position="hidden">u</char> </key> <key top="100" left="850" width="80" height="80" fingerIndex="5"> <char modifier="left_shift" position="topLeft">I</char> <char position="hidden">i</char> </key> <key top="100" left="950" width="80" height="80" fingerIndex="6"> <char modifier="left_shift" position="topLeft">O</char> <char position="hidden">o</char> </key> <key top="100" left="1050" width="80" height="80" fingerIndex="7"> <char modifier="left_shift" position="topLeft">P</char> <char position="hidden">p</char> </key> <key top="100" left="1150" width="80" height="80" fingerIndex="7"> <char modifier="left_shift" position="topLeft">{</char> <char position="bottomLeft">[</char> </key> <key top="100" left="1250" width="80" height="80" fingerIndex="7"> <char modifier="left_shift" position="topLeft">}</char> <char position="bottomLeft">]</char> </key> <key top="200" left="580" width="80" height="80" fingerIndex="3"> <char modifier="right_shift" position="topLeft">G</char> <char position="hidden">g</char> </key> <key top="200" left="680" width="80" height="80" fingerIndex="4"> <char modifier="left_shift" position="topLeft">H</char> <char position="hidden">h</char> </key> <key top="200" left="1180" width="80" height="80" fingerIndex="7"> <char modifier="left_shift" position="topLeft">"</char> <char position="bottomLeft">'</char> </key> <key top="100" left="1350" width="80" height="80" fingerIndex="7"> <char modifier="left_shift" position="topLeft">|</char> <char position="bottomLeft">\</char> </key> <key top="100" left="650" width="80" height="80" fingerIndex="4"> <char modifier="left_shift" position="topLeft">Y</char> <char position="hidden">y</char> </key> <key top="300" left="330" width="80" height="80" fingerIndex="1"> <char modifier="right_shift" position="topLeft">X</char> <char position="hidden">x</char> </key> <key top="300" left="430" width="80" height="80" fingerIndex="2"> <char modifier="right_shift" position="topLeft">C</char> <char position="hidden">c</char> </key> <key top="300" left="530" width="80" height="80" fingerIndex="3"> <char modifier="right_shift" position="topLeft">V</char> <char position="hidden">v</char> </key> <key top="300" left="630" width="80" height="80" fingerIndex="3"> <char modifier="right_shift" position="topLeft">B</char> <char position="hidden">b</char> </key> <key top="300" left="730" width="80" height="80" fingerIndex="4"> <char modifier="left_shift" position="topLeft">N</char> <char position="hidden">n</char> </key> <key top="300" left="830" width="80" height="80" fingerIndex="4"> <char modifier="left_shift" position="topLeft">M</char> <char position="hidden">m</char> </key> <key top="300" left="930" width="80" height="80" fingerIndex="5"> <char modifier="left_shift" position="topLeft">&lt;</char> <char position="bottomLeft">,</char> </key> <key top="300" left="1030" width="80" height="80" fingerIndex="6"> <char modifier="left_shift" position="topLeft">></char> <char position="bottomLeft">.</char> </key> <key top="300" left="1130" width="80" height="80" fingerIndex="7"> <char modifier="left_shift" position="topLeft">?</char> <char position="bottomLeft">/</char> </key> <specialKey top="100" left="0" width="130" height="80" type="tab"/> <specialKey top="200" left="1280" width="150" height="80" type="return"/> <specialKey top="300" left="1230" width="200" height="80" modifierId="right_shift" type="shift"/> <specialKey top="400" left="1150" width="130" height="80" label="Alt" type="other"/> <specialKey top="400" left="1300" width="130" height="80" label="Ctrl" type="other"/> <specialKey top="400" left="150" width="130" height="80" label="Alt" type="other"/> <specialKey top="400" left="0" width="130" height="80" label="Ctrl" type="other"/> <specialKey top="400" left="300" width="830" height="80" type="space"/> <specialKey top="300" left="0" width="210" height="80" modifierId="left_shift" type="shift"/> <specialKey top="200" left="0" width="160" height="80" type="capslock"/> <specialKey top="0" left="1300" width="130" height="80" type="backspace"/> </keys> </keyboardLayout> """.trimIndent()
1
null
0
2
3d046f526f65fcb2660e6d830792c1a20ba1c54d
12,455
ktgen
MIT License
infra/src/fanpoll/infra/notification/channel/sms/senders/TwilioSMSSender.kt
csieflyman
359,559,498
false
{"Kotlin": 785294, "JavaScript": 17435, "HTML": 6167, "PLpgSQL": 5563, "Dockerfile": 126}
/* * Copyright (c) 2023. fanpoll All rights reserved. */ package fanpoll.infra.notification.channel.sms.senders import com.twilio.Twilio import com.twilio.exception.ApiException import com.twilio.rest.api.v2010.account.Message import com.twilio.type.PhoneNumber import fanpoll.infra.base.json.kotlinx.json import fanpoll.infra.logging.writers.LogWriter import fanpoll.infra.notification.NotificationLogConfig import fanpoll.infra.notification.channel.NotificationChannelSender import fanpoll.infra.notification.channel.sms.SMSContent import fanpoll.infra.notification.logging.NotificationMessageLog import fanpoll.infra.notification.message.NotificationMessage import io.github.oshai.kotlinlogging.KotlinLogging import java.time.Duration import java.time.Instant data class TwilioSMSConfig( val accountSid: String, val authToken: String, val fromPhoneNumber: String ) class TwilioSMSSender( private val config: TwilioSMSConfig, private val loggingConfig: NotificationLogConfig, private val logWriter: LogWriter ) : NotificationChannelSender { private val logger = KotlinLogging.logger {} private val senderName = "TwilioSMSSender" override val maxReceiversPerRequest: Int = 1 init { Twilio.init(config.accountSid, config.authToken) } override suspend fun send(message: NotificationMessage) { message.receivers.map { message.copy(receivers = listOf(it)) }.forEach { sendSingle(it) } } private suspend fun sendSingle(message: NotificationMessage) { val log = message.toNotificationMessageLog() val to = message.receivers[0] val body = (message.content as SMSContent).body try { log.sendAt = Instant.now() val twilioMessage = Message.creator( PhoneNumber(to), PhoneNumber(config.fromPhoneNumber), body ) val response = twilioMessage.create() log.rspAt = Instant.now() log.duration = Duration.between(log.sendAt, log.rspAt) log.rspMsg = response.sid log.rspBody = response.body if (response.errorCode != null) { log.success = false log.rspCode = response.errorCode?.toString() log.errorMsg = response.errorMessage } else { log.success = true log.rspCode = response.status.name } if (loggingConfig.logSuccessReqBody) log.content = body if (!log.success || loggingConfig.logSuccess) { writeLog(log) } logger.debug { "[$senderName] sendSMS: ${json.encodeToJsonElement(NotificationMessageLog.serializer(), log)}" } } catch (ex: ApiException) { log.rspAt = Instant.now() log.duration = Duration.between(log.sendAt, log.rspAt) log.success = false log.rspCode = "statusCode = {${ex.statusCode}, errorCode = ${ex.code}" log.rspBody = ex.moreInfo log.errorMsg = "[$senderName] sendSMS error: ${ex.message}" logger.error(ex) { "${log.errorMsg} => ${json.encodeToJsonElement(NotificationMessageLog.serializer(), log)}" } writeLog(log) } } private suspend fun writeLog(notificationMessageLog: NotificationMessageLog) { if (loggingConfig.enabled) logWriter.write(notificationMessageLog) } override fun shutdown() { logger.info { "shutdown $senderName..." } Twilio.destroy() logger.info { "shutdown $senderName completed" } } }
1
Kotlin
9
74
1a7d54115dbc42c6a02230f527d9ad56862b4a0b
3,647
multi-projects-architecture-with-Ktor
MIT License
src/main/kotlin/com/ecwid/apiclient/v3/dto/customer/result/CustomerCreateResult.kt
Alexeyyy
288,178,467
true
{"Kotlin": 428980}
package com.ecwid.apiclient.v3.dto.customer.result data class CustomerCreateResult( var id: Int = 0 )
0
Kotlin
0
0
c52ef344a82d1884a633354b4e6b97984e3147ba
105
ecwid-java-api-client
Apache License 2.0
app/src/main/java/com/tinashe/hymnal/ui/collections/add/NewCollectionFragment.kt
vantykyb
278,181,327
true
{"Kotlin": 164832, "Shell": 242}
package com.tinashe.hymnal.ui.collections.add import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.tinashe.hymnal.R import com.tinashe.hymnal.data.model.TitleBody import com.tinashe.hymnal.databinding.FragmentNewCollectionBinding class NewCollectionFragment : Fragment() { private var binding: FragmentNewCollectionBinding? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return FragmentNewCollectionBinding.inflate(inflater, container, false).also { binding = it }.root } fun getTitleBody(): TitleBody? { val title = binding?.edtTitle?.text?.toString() val description = binding?.edtDescription?.text?.toString() return if (title.isNullOrEmpty()) { binding?.tilTitle?.error = getString(R.string.error_required) null } else { TitleBody(title, description) } } }
0
null
0
0
c67778d8f99dca9bbbb86af2c0d8c542ecc4b5f5
1,105
cis-android
Apache License 2.0
app/src/main/java/com/elhady/movies/ui/video/VideoViewModel.kt
islamelhady
301,591,032
false
{"Kotlin": 284088}
package com.elhady.movies.ui.video import androidx.lifecycle.ViewModel import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject @HiltViewModel class VideoViewModel @Inject constructor(): ViewModel() { // TODO: Implement the ViewModel }
1
Kotlin
0
0
6ea9c5203f82fc57e279b426560f397987aab6d2
262
movie-night-v2
Apache License 2.0
compiler/fir/tree/src/org/jetbrains/kotlin/fir/expressions/impl/FirThrowExpressionImpl.kt
damenez
176,209,431
true
{"Markdown": 56, "Gradle": 497, "Gradle Kotlin DSL": 215, "Java Properties": 12, "Shell": 11, "Ignore List": 10, "Batchfile": 9, "Git Attributes": 1, "Protocol Buffer": 12, "Java": 5238, "Kotlin": 43905, "Proguard": 7, "XML": 1594, "Text": 9172, "JavaScript": 239, "JAR Manifest": 2, "Roff": 209, "Roff Manpage": 34, "INI": 95, "AsciiDoc": 1, "SVG": 30, "HTML": 462, "Groovy": 31, "JSON": 17, "JFlex": 3, "Maven POM": 94, "CSS": 1, "Ant Build System": 50, "C": 1, "ANTLR": 1, "Scala": 1}
/* * Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.fir.expressions.impl import com.intellij.psi.PsiElement import org.jetbrains.kotlin.fir.FirAbstractElement import org.jetbrains.kotlin.fir.FirElement import org.jetbrains.kotlin.fir.FirSession import org.jetbrains.kotlin.fir.expressions.FirExpression import org.jetbrains.kotlin.fir.expressions.FirThrowExpression import org.jetbrains.kotlin.fir.transformSingle import org.jetbrains.kotlin.fir.visitors.FirTransformer class FirThrowExpressionImpl( session: FirSession, psi: PsiElement?, override var exception: FirExpression ) : FirAbstractExpression(session, psi), FirThrowExpression { override fun <D> transformChildren(transformer: FirTransformer<D>, data: D): FirElement { exception = exception.transformSingle(transformer, data) return super<FirAbstractExpression>.transformChildren(transformer, data) } }
0
Kotlin
0
2
9a2178d96bd736c67ba914b0f595e42d1bba374d
1,041
kotlin
Apache License 2.0
src/boj_9063/Kotlin.kt
devetude
70,114,524
false
{"Java": 563470, "Kotlin": 19807}
package boj_9063 import java.util.StringTokenizer import kotlin.math.abs fun main() { var minX = Int.MAX_VALUE var maxX = Int.MIN_VALUE var minY = Int.MAX_VALUE var maxY = Int.MIN_VALUE repeat(readln().toInt()) { val st = StringTokenizer(readln()) val x = st.nextToken().toInt() val y = st.nextToken().toInt() minX = minX.coerceAtMost(x) maxX = maxX.coerceAtLeast(x) minY = minY.coerceAtMost(y) maxY = maxY.coerceAtLeast(y) } val dX = abs(n = maxX - minX) val dY = abs(n = maxY - minY) println(dX * dY) }
0
Java
7
20
4b933ac8fc71ee0d1c90414767044645a6226918
602
BOJ-PSJ
Apache License 2.0
app/src/androidTest/java/pl/droidsonroids/clicktest/clicktest/EspressoTest.kt
DroidsOnRoids
106,624,679
false
null
package pl.droidsonroids.clicktest.clicktest import android.support.test.espresso.Espresso.onView import android.support.test.espresso.action.ViewActions.click import android.support.test.espresso.assertion.ViewAssertions.matches import android.support.test.espresso.matcher.ViewMatchers.isClickable import android.support.test.espresso.matcher.ViewMatchers.withContentDescription import android.support.test.rule.ActivityTestRule import android.support.test.runner.AndroidJUnit4 import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class EspressoTest { @get:Rule public val rule = ActivityTestRule<MainActivity>(MainActivity::class.java, true, true) @Test fun shouldNotPerformClick() { onView(withContentDescription("test")).perform(click()).check(matches(isClickable())) } }
0
Kotlin
0
0
60d870f1e5a3c945e64e366c4a68f65510a7da98
862
android-click-test
MIT License
src/main/kotlin/info/benjaminhill/bot/ev3/BoundedMotor.kt
salamanders
209,807,576
false
null
package info.benjaminhill.sketchy.brickpi import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.cancellable import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flow import java.util.* import kotlin.time.ExperimentalTime class BoundedMotor(port: Port) : TachoMotor(port) { private lateinit var tachoBounds: ClosedRange<Int> @ExperimentalCoroutinesApi @ExperimentalTime suspend fun calibrate() { println("Motor $port set LOWER bounds: (d=decrease, q=quit, i=increase):") clicks().collect { when (it) { 'd' -> rotate(-0.25) 'i' -> rotate(0.25) } } val tachoMin = updates().first().position println("Motor $port set UPPER bounds: (d=decrease, q=quit, i=increase):") clicks().collect { when (it) { 'd' -> rotate(-0.25) 'i' -> rotate(0.25) } } val tachoMax = updates().first().position tachoBounds = tachoMin..tachoMax } } fun clicks(quitChar: Char = 'q'): Flow<Char> = flow { Scanner(System.`in`).use { input -> do { val ch = input.next().single() emit(ch) } while (ch != quitChar) } }.cancellable()
1
Kotlin
0
1
308913d916d72844fe8306418234433f8650ec67
1,332
talkinghead
MIT License
app/src/main/kotlin/net/primal/android/networking/primal/upload/api/UploadApi.kt
PrimalHQ
639,579,258
false
{"Kotlin": 2739955}
package net.primal.android.networking.primal.upload.api import net.primal.android.nostr.model.NostrEvent interface UploadApi { suspend fun uploadChunk(chunkEvent: NostrEvent) suspend fun completeUpload(completeEvent: NostrEvent): String suspend fun cancelUpload(cancelEvent: NostrEvent) }
79
Kotlin
15
124
e95bbd03e3e6d57e5710449a9f968f42778fa1cd
306
primal-android-app
MIT License
androidApp/src/main/java/dev/johnoreilly/starwars/androidApp/components/StarWarsBottomNavigation.kt
manuelduarte077
490,356,804
false
null
package dev.johnoreilly.starwars.androidApp.components import androidx.compose.material.BottomNavigation import androidx.compose.material.BottomNavigationItem import androidx.compose.material.Icon import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.navigation.NavHostController import androidx.navigation.compose.currentBackStackEntryAsState import com.google.accompanist.insets.navigationBarsPadding import dev.johnoreilly.starwars.androidApp.navigation.bottomNavigationItems @Composable fun StarWarsBottomNavigation(navController: NavHostController) { BottomNavigation(modifier = Modifier.navigationBarsPadding()) { val navBackStackEntry by navController.currentBackStackEntryAsState() val currentRoute = navBackStackEntry?.destination?.route bottomNavigationItems.forEach { item -> BottomNavigationItem( icon = { Icon( painterResource(item.icon), contentDescription = item.iconContentDescription ) }, selected = currentRoute == item.route, onClick = { navController.navigate(item.route) { popUpTo(navController.graph.id) launchSingleTop = true } } ) // end BottomNavigationItem } } }
0
Kotlin
0
0
b8c5920d3adace9bf4a80f6be88cb0e35da4bc30
1,541
StarWarsKMM
Apache License 2.0
app/src/main/java/com/nielaclag/openweather/data/model/room/supportmodel/CoordinatePersistence.kt
knightniel
878,358,271
false
{"Kotlin": 421417}
package com.nielaclag.openweather.data.model.room.supportmodel import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** * Created by Niel on 10/21/2024. */ @JsonClass(generateAdapter = true) data class CoordinatePersistence( @Json(name = "latitude") val latitude: Double, @Json(name = "longitude") val longitude: Double )
0
Kotlin
0
0
9dea4075f20a42b97e58e77d273e2ff8191700fd
355
OpenWeather
MIT License
cinescout/screenplay/data/remote/trakt/src/commonMain/kotlin/screenplay/data/remote/trakt/model/TraktTvShowMetadata.kt
fardavide
280,630,732
false
null
package screenplay.data.remote.trakt.model import cinescout.screenplay.domain.model.id.ScreenplayIds import cinescout.screenplay.domain.model.id.TvShowIds import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable typealias TraktTvShowsMetadataResponse = List<TraktTvShowMetadataBody> @Serializable @SerialName(TraktContentType.TvShow) data class TraktTvShowMetadataBody( @SerialName(TraktContent.Ids) val ids: TraktTvShowIds ) : TraktScreenplayMetadataBody { override fun ids(): ScreenplayIds = TvShowIds( trakt = ids.trakt, tmdb = ids.tmdb ) } /** * Same as [TraktTvShowMetadataBody] but with optional fields. */ @Serializable data class OptTraktTvShowMetadataBody( @SerialName(TraktContent.Ids) val ids: OptTraktTvShowIds )
14
Kotlin
2
6
f04a22b832397f22065a85af038dd15d90225cde
799
CineScout
Apache License 2.0
sykepenger-model/src/test/kotlin/no/nav/helse/sykdomstidslinje/SykdomshistorikkTest.kt
navikt
193,907,367
false
null
package no.nav.helse.sykdomstidslinje import no.nav.helse.hendelser.til import no.nav.helse.inspectors.inspektør import no.nav.helse.testhelpers.S import no.nav.helse.testhelpers.TestHendelse import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test internal class SykdomshistorikkTest { private lateinit var historikk: Sykdomshistorikk @BeforeEach fun setup() { historikk = Sykdomshistorikk() } @Test fun `fjerner hel periode`() { val tidslinje = 10.S historikk.håndter(TestHendelse(tidslinje)) historikk.fjernDager(tidslinje.periode()!!) assertEquals(2, historikk.inspektør.elementer()) assertFalse(historikk.inspektør.tidslinje(0).iterator().hasNext()) assertTrue(historikk.inspektør.tidslinje(1).iterator().hasNext()) } @Test fun `fjerner del av periode`() { val tidslinje = 10.S historikk.håndter(TestHendelse(tidslinje)) historikk.fjernDager(tidslinje.førsteDag() til tidslinje.sisteDag().minusDays(1)) assertEquals(2, historikk.inspektør.elementer()) assertEquals(1, historikk.inspektør.tidslinje(0).count()) } @Test fun `tømmer historikk`() { historikk.håndter(TestHendelse(1.S)) historikk.tøm() assertEquals(2, historikk.inspektør.elementer()) } @Test fun `tømmer ikke tom historikk`() { historikk.tøm() assertEquals(0, historikk.inspektør.elementer()) } @Test fun `tømmer ikke historikk når den er tom`() { val tidslinje = 10.S historikk.håndter(TestHendelse(tidslinje)) historikk.fjernDager(tidslinje.periode()!!) historikk.tøm() assertEquals(2, historikk.inspektør.elementer()) assertFalse(historikk.inspektør.tidslinje(0).iterator().hasNext()) assertTrue(historikk.inspektør.tidslinje(1).iterator().hasNext()) } }
0
Kotlin
2
4
a3ba622f138449986fc9fd44e467104a61b95577
1,961
helse-spleis
MIT License
clients/pay/src/main/kotlin/top/bettercode/summer/tools/pay/weixin/entity/JsapiWCPayRequest.kt
top-bettercode
387,652,015
false
{"Kotlin": 2939064, "Java": 24119, "JavaScript": 22541, "CSS": 22336, "HTML": 15833}
package top.bettercode.summer.tools.pay.weixin.entity import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonIgnore import com.fasterxml.jackson.annotation.JsonProperty import top.bettercode.summer.tools.lang.util.RandomUtil /** * @author <NAME> */ data class JsapiWCPayRequest @JvmOverloads constructor( /** * 公众号id;必填;appId为当前服务商号绑定的appid;示例:wx8888888888888888 */ @field:JsonProperty("appId") var appId: String, /** * 订单详情扩展字符串;必填;统一下单接口返回的prepay_id参数值,提交格式如:prepay_id=***;示例:prepay_id=123456789 */ @field:JsonProperty("package") var `package`: String, /** * 签名;必填;签名,详见签名生成算法;示例:C380BEC2BFD727A4B6845133519F3AD6 */ @field:JsonProperty("paySign") var paySign: String? = null, /** * 时间戳;必填;当前的时间,其他详见时间戳规则;示例:1414561699 */ @field:JsonProperty("timeStamp") var timeStamp: String = (System.currentTimeMillis() / 1000).toString(), /** * 随机字符串;必填;随机字符串,不长于32位。推荐随机数生成算法;示例:5K8264ILTKCH16CQ2502SI8ZNMTM67VS */ @field:JsonProperty("nonceStr") var nonceStr: String = RandomUtil.nextString2(32), /** * 签名方式;必填;签名类型,默认为MD5,支持HMAC-SHA256和MD5。注意此处需与统一下单的签名类型一致;示例:MD5 */ @field:JsonProperty("signType") var signType: String = "MD5", /** * 其他 */ @get:JsonAnyGetter @field:JsonAnySetter var other: MutableMap<String, Any?> = mutableMapOf() ) { @JsonIgnore fun put(key: String, value: Any?) { other[key] = value } @JsonIgnore fun get(key: String): Any? { return other[key] } }
0
Kotlin
0
1
d07ed7250e6dcdbcce51f27f5f22602e9c222b3c
1,812
summer
Apache License 2.0
shared/src/commonMain/kotlin/DI.kt
sciack
679,501,002
false
{"Kotlin": 165543, "Swift": 592, "Shell": 228}
import news.newsModule import org.kodein.di.DI import org.kodein.di.factory fun di() = DI { import(newsModule) } inline fun <reified A : Any, reified T : Any> DI.instanceWithArgs(arg: A): T { val factory by factory<A, T>() return factory.invoke(arg) }
8
Kotlin
0
0
24d1d71356140710ab63fb3f96819543c8ff09ce
266
news_kmp
Apache License 2.0
sample/src/main/java/com/xingray/sample/page/main/MainContract.kt
XingRay
196,392,587
false
null
package com.xingray.sample.page.main import com.xingray.mvp.MvpPresenter import com.xingray.mvp.MvpView /** * xxx * * @author : leixing * @version : 1.0.0 * mail : <EMAIL> * @date : 2019/7/10 20:00 */ interface MainContract { interface View : MvpView<Presenter> { fun showLoading() fun dismissLoading() fun showTestList(tests: List<Test>) } interface Presenter : MvpPresenter<View> { fun loadData() } }
0
Kotlin
1
1
f0c87739ef929c824eea6188fa373b56532cd6a6
465
MVP
Apache License 2.0
app/src/main/java/com/yougame/takayamaaren/yougame/ui/good/GameView.kt
428talent
167,779,777
false
{"Gradle": 5, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Markdown": 1, "Java": 3, "Proguard": 1, "XML": 144, "Kotlin": 120}
package com.yougame.takayamaaren.yougame.ui.good import com.yougame.takayamaaren.yougame.sdk.model.response.Game import com.yougame.takayamaaren.yougame.sdk.model.response.Good import com.yougame.takayamaaren.yougame.ui.base.View import com.yougame.takayamaaren.yougame.ui.good.components.comment.CommentItem import com.yougame.takayamaaren.yougame.ui.good.components.good.GoodItem interface GameView : View { fun onGameLoad(game: Game) fun onGameCoverLoad(url: String) fun onGoodsLoad(good: List<GoodItem>) fun onCommentLoad(comment: List<CommentItem>) fun onAddCartComplete(goodIds: List<Int>) fun setCommentSummary(summaryText: String, averageRatingText: String) }
0
Kotlin
0
0
7220b15262652bd59f8c8b035c88bdb02f78f6e6
693
YouGame-Android
MIT License
build-event-collectorator/src/main/kotlin/org/gradle/buildeng/analysis/consumer/BuildConsumer.kt
gradle
164,492,972
false
null
package org.gradle.buildeng.analysis.consumer import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.ObjectMapper import com.google.cloud.storage.BlobId import com.google.cloud.storage.BlobInfo import com.google.cloud.storage.Storage import com.google.cloud.storage.StorageOptions import io.netty.buffer.ByteBuf import io.netty.buffer.ByteBufHolder import io.netty.buffer.Unpooled import io.netty.handler.codec.base64.Base64 import io.netty.handler.codec.http.HttpResponseStatus import io.netty.util.CharsetUtil import io.reactivex.netty.channel.ContentSource import io.reactivex.netty.protocol.http.client.HttpClient import io.reactivex.netty.protocol.http.client.HttpClientResponse import io.reactivex.netty.protocol.http.sse.ServerSentEvent import org.gradle.buildeng.analysis.common.ServerConnectionInfo import rx.Observable import rx.exceptions.Exceptions import java.io.ByteArrayOutputStream import java.io.IOException import java.time.Instant import java.time.ZoneOffset import java.time.format.DateTimeFormatter import java.util.concurrent.atomic.AtomicReference class BuildConsumer(private val geServer: ServerConnectionInfo) { private val httpClient = HttpClient.newClient(geServer.socketAddress).unsafeSecure() private val objectMapper = ObjectMapper() private val eventTypes = setOf( "BuildStarted", "MvnBuildStarted", "BuildFinished", "MvnBuildFinished", "MvnExecutionStarted", "MvnExecutionFinished", "MvnProjectStarted", "MvnProjectFinished", "LoadBuildStarted", "LoadBuildFinished", "MvnSettingsStarted", "MvnSettingsFinished", "ProjectEvaluationStarted", "ProjectEvaluationFinished", "MvnToolchainsStarted", "MvnToolchainsFinished", "PluginApplicationStarted", "MvnPluginApplication", "BuildRequestedTasks", "MvnBuildRequestedGoals", "BuildModes", "DaemonState", "JvmArgs", // Gradle-only "Hardware", "MvnHardware", "Os", "MvnOs", "Jvm", "MvnJvm", "ProjectStructure", "MvnProjectStructure", "BasicMemoryStats", "MvnBasicMemoryStats", "Locality", "MvnLocality", "Encoding", "MvnEncoding", "ScopeIds", "MvnScopeIds", "FileRefRoots", "MvnFileRefRoots", "TaskStarted", "TaskFinished", "MvnGoalExecutionStarted", "MvnGoalExecutionFinished", "BuildCacheRemoteLoadStarted", "BuildCacheRemoteStoreStarted", "BuildCacheRemoteStoreFinished", "BuildCachePackStarted", "BuildCachePackFinished", "BuildCacheUnpackStarted", "BuildCacheUnpackFinished", "BuildCacheRemoteLoadFinished", "MvnBuildCacheRemoteLoadStarted", "MvnBuildCacheRemoteStoreStarted", "MvnBuildCacheRemoteStoreFinished", "MvnBuildCachePackStarted", "MvnBuildCachePackFinished", "MvnBuildCacheUnpackStarted", "MvnBuildCacheUnpackFinished", "MvnBuildCacheRemoteLoadFinished", "TestStarted", "TestFinished", // Tests Gradle-only for now "BuildAgent", "MvnBuildAgent", "ExceptionData", "MvnExceptionData", "UserTag", "MvnUserTag", "UserLink", "MvnUserLink", "UserNamedValue", "MvnUserNamedValue", "Repository", "ConfigurationResolutionData", "NetworkDownloadActivityStarted", "NetworkDownloadActivityFinished" // Network/repo Gradle-only ) // "OutputLogEvent", "OutputStyledTextEvent" private val storage: Storage = StorageOptions.getDefaultInstance().service private val daySlashyFormat: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd") fun consume(startEpoch: Long, gcsBucketName: String) { buildStream(startEpoch) .doOnSubscribe { println("Streaming builds from [${geServer.socketAddress.hostName}] to gs://$gcsBucketName/") } .map { serverSentEvent -> parse(serverSentEvent) } .map { json -> Pair(json["buildId"].asText(), json["timestamp"].asLong()) } .flatMap({ (buildId, timestamp) -> buildEventStream(buildId) .doOnSubscribe { println("Streaming events for build $buildId at $timestamp") } .toList() .map { serverSentEvents -> try { val localDate = Instant.ofEpochMilli(timestamp).atZone(ZoneOffset.UTC).toLocalDate() val blobKey = "${localDate.format(daySlashyFormat)}/$buildId-json.txt" val blobInfo = BlobInfo .newBuilder(BlobId.of(gcsBucketName, blobKey)) .setContentType("text/plain") .build() storage.create(blobInfo, byteBufsToJoinedArray(serverSentEvents)) println("[${System.currentTimeMillis()}] $blobKey written") } finally { serverSentEvents.forEach { assert(it.release()) } } } }, 20) .toBlocking() .subscribe() } fun byteBufsToJoinedArray(input: List<ByteBufHolder>): ByteArray { val outputStream: ByteArrayOutputStream = ByteArrayOutputStream() val newlineBytes = "\n".toByteArray() input.forEach { serverSentEvent -> val event = serverSentEvent.content() if (event.hasArray()) { outputStream.write(event.array()) } else { val bytes = ByteArray(event.readableBytes()) event.readBytes(bytes) outputStream.write(bytes) } outputStream.write(newlineBytes) } return outputStream.toByteArray() } fun parse(serverSentEvent: ServerSentEvent): JsonNode { try { return objectMapper.readTree(serverSentEvent.contentAsString()) } catch (e: IOException) { throw Exceptions.propagate(e) } finally { val deallocated = serverSentEvent.release() assert(deallocated) } } private fun buildStream(fromTimestamp: Long): Observable<ServerSentEvent> { return resume("/build-export/v1/builds/since/$fromTimestamp") } private fun buildEventStream(buildId: String): Observable<ServerSentEvent> { return resume("/build-export/v1/build/$buildId/events?eventTypes=${eventTypes.joinToString(",")}", null) } private fun resume(url: String, lastEventId: String? = null): Observable<ServerSentEvent> { val eventId = AtomicReference<String>() val authByteBuf = Unpooled.copiedBuffer("${geServer.username}:${geServer.password}".toCharArray(), CharsetUtil.UTF_8) val authValue = "Basic " + Base64.encode(authByteBuf).toString(CharsetUtil.UTF_8) var request = httpClient .createGet(url) .addHeader("Authorization", authValue) .addHeader("Accept", "text/event-stream") if (lastEventId != null) { request = request.addHeader("Last-Event-ID", lastEventId) } return request .flatMap { response -> getContentAsSse(response) } .doOnNext { serverSentEvent: ServerSentEvent -> eventId.set(serverSentEvent.eventIdAsString) } .onErrorResumeNext { println("Error: ${it.message} — ${it.cause}") if (eventId.get() != null) { println("Error streaming ${eventId.get()} from $url: ${it.message}, resuming from " + eventId.get() + "...") resume(url, eventId.get()) } else { println("Error streaming $url: ${it.message}, resuming from null...") resume(url, null) } } } private fun getContentAsSse(response: HttpClientResponse<ByteBuf>): ContentSource<ServerSentEvent> { if (response.status != HttpResponseStatus.OK) { return ContentSource(IllegalArgumentException("HTTP Status: ${response.status}")) } return response.contentAsServerSentEvents } }
1
Kotlin
4
9
ad0d42ab18e7bfaf7605e79349490b188ef42a82
8,264
build-analysis-demo
MIT License
src/main/kotlin/us/venky/mn/repositories/LocationRepository.kt
ramana-git
512,732,391
false
null
package us.venky.mn.repositories import io.micronaut.data.annotation.Repository import io.micronaut.data.repository.CrudRepository import us.venky.mn.entities.Location import java.util.UUID @Repository interface LocationRepository : CrudRepository<Location,UUID>{ //Custom methods - Auto implemented fun findOne(id:UUID): Location fun list():List<Location> }
0
Kotlin
0
0
8f0f79341932c753b67acb7edaeeb3d768184bbd
372
micronaut-library
MIT License
expresspay-sdk/src/main/java/com/expresspay/sdk/views/expresscardpay/ExpressCardDetailsActivity.kt
ExpresspaySa
589,460,465
false
{"Kotlin": 442513, "Java": 48886}
package com.expresspay.sdk.views.expresscardpay import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.commitNow import com.expresspay.sdk.databinding.ActivityExpressCardPayBinding import com.expresspay.sdk.model.request.card.ExpresspayCard class ExpressCardDetailsActivity : AppCompatActivity() { private lateinit var binding: ActivityExpressCardPayBinding companion object{ var amount:String = "" var currency:String = "" var onSubmitCardDetails:((ExpresspayCard) -> Unit)? = null } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityExpressCardPayBinding.inflate( layoutInflater) setContentView(binding.root) loadFragment() } override fun onResume() { super.onResume() ExpressCardPay.shared()?._onPresent?.let { it(this) } } private fun loadFragment(){ val fragment = ExpressCardDetailFragment( onSubmit = onSubmitCardDetails, amount = amount, currency = currency ) supportFragmentManager .beginTransaction() .add(binding.container.id, fragment, fragment.javaClass.name) .commit() } }
0
Kotlin
1
0
b9884f65a65d46d78695b9761afafe5ee9120e92
1,312
expresspay-android-sdk-code
MIT License
app/src/main/java/ru/z13/catapi/app/shedulers/SchedulersFacade.kt
Z-13
276,085,095
false
null
package ru.z13.catapi.app.shedulers import io.reactivex.Scheduler import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import javax.inject.Inject import javax.inject.Singleton /** * @author <NAME> (z-13.github.io) */ @Singleton class SchedulersFacade @Inject constructor() { fun io() : Scheduler { return Schedulers.io() } fun computation() : Scheduler { return Schedulers.computation() } fun ui() : Scheduler { return AndroidSchedulers.mainThread() } }
0
Kotlin
0
0
9131573bc85cc6bd1f246edae6eea31e7a955faf
554
catapi
Apache License 2.0
api/src/test/kotlin/edu/wgu/osmt/api/model/ApiCollectionTest.kt
wgu-opensource
371,168,832
false
{"TypeScript": 870780, "Kotlin": 663910, "HTML": 153260, "JavaScript": 87226, "Shell": 42875, "HCL": 13700, "SCSS": 9144, "Java": 8284, "Smarty": 5908, "Dockerfile": 477}
package edu.wgu.osmt.api.model import edu.wgu.osmt.mockdata.MockData import org.assertj.core.api.Assertions import org.junit.jupiter.api.BeforeAll import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance @TestInstance(TestInstance.Lifecycle.PER_CLASS) internal class ApiCollectionTest { private lateinit var mockData : MockData @BeforeAll fun setup() { mockData = MockData() } @Test fun testApiCollection() { // Arrange val col = mockData.getCollection(1) // Act val api = col?.let { ApiCollection(it, ArrayList(), mockData.appConfig) } // Assert Assertions.assertThat(col?.creationDate).isEqualTo(api?.creationDate?.toLocalDateTime()) Assertions.assertThat(col?.updateDate).isEqualTo(api?.updateDate?.toLocalDateTime()) Assertions.assertThat(col?.uuid).isEqualTo(api?.uuid) Assertions.assertThat(col?.name).isEqualTo(api?.name) Assertions.assertThat(col?.author?.value).isEqualTo(api?.author) Assertions.assertThat(col?.archiveDate).isEqualTo(api?.archiveDate?.toLocalDateTime()) Assertions.assertThat(col?.publishDate).isEqualTo(api?.publishDate?.toLocalDateTime()) } }
59
TypeScript
9
38
c0453c9f678615a8da004b7cd4010c79585a028c
1,229
osmt
Apache License 2.0
api/src/test/kotlin/edu/wgu/osmt/api/model/ApiCollectionTest.kt
wgu-opensource
371,168,832
false
{"TypeScript": 870780, "Kotlin": 663910, "HTML": 153260, "JavaScript": 87226, "Shell": 42875, "HCL": 13700, "SCSS": 9144, "Java": 8284, "Smarty": 5908, "Dockerfile": 477}
package edu.wgu.osmt.api.model import edu.wgu.osmt.mockdata.MockData import org.assertj.core.api.Assertions import org.junit.jupiter.api.BeforeAll import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance @TestInstance(TestInstance.Lifecycle.PER_CLASS) internal class ApiCollectionTest { private lateinit var mockData : MockData @BeforeAll fun setup() { mockData = MockData() } @Test fun testApiCollection() { // Arrange val col = mockData.getCollection(1) // Act val api = col?.let { ApiCollection(it, ArrayList(), mockData.appConfig) } // Assert Assertions.assertThat(col?.creationDate).isEqualTo(api?.creationDate?.toLocalDateTime()) Assertions.assertThat(col?.updateDate).isEqualTo(api?.updateDate?.toLocalDateTime()) Assertions.assertThat(col?.uuid).isEqualTo(api?.uuid) Assertions.assertThat(col?.name).isEqualTo(api?.name) Assertions.assertThat(col?.author?.value).isEqualTo(api?.author) Assertions.assertThat(col?.archiveDate).isEqualTo(api?.archiveDate?.toLocalDateTime()) Assertions.assertThat(col?.publishDate).isEqualTo(api?.publishDate?.toLocalDateTime()) } }
59
TypeScript
9
38
c0453c9f678615a8da004b7cd4010c79585a028c
1,229
osmt
Apache License 2.0
core/domain/src/main/java/com/timurkhabibulin/domain/me/FavoritesUseCase.kt
Timur-Khabibulin
659,241,111
false
{"Kotlin": 223902}
package com.timurkhabibulin.domain.me import androidx.paging.Pager import androidx.paging.PagingConfig import androidx.paging.PagingData import com.timurkhabibulin.domain.entities.Photo import com.timurkhabibulin.domain.photos.PhotosRepository import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.withContext import javax.inject.Inject class FavoritesUseCase @Inject constructor( private val favoritesRepository: FavoritesRepository, private val photosRepository: PhotosRepository, private val dispatcher: CoroutineDispatcher ) { fun getFavoritesPhotos(): Flow<PagingData<Photo>> { return Pager( config = PagingConfig(enablePlaceholders = false, pageSize = FavoritesPagingSource.PAGE_SIZE), pagingSourceFactory = { FavoritesPagingSource(favoritesRepository, photosRepository, dispatcher) } ).flow.flowOn(dispatcher) } suspend fun isFavorite(id: String): Boolean = withContext(dispatcher) { favoritesRepository.isFavorite(id) } suspend fun addToFavorite(id: String) = withContext(dispatcher) { favoritesRepository.addToFavorite(id) } suspend fun removeFromFavorite(id: String) = withContext(dispatcher) { favoritesRepository.removeFromFavorite(id) } }
0
Kotlin
1
13
d4bebce237761c6d846c86e3c7e928a8db319e1b
1,384
Mysplash
MIT License
app/src/main/java/com/hgroup/roomnote/repository/NoteRepository.kt
hasangurbuzz
354,874,257
false
null
package com.hgroup.roomnote.repository import com.hgroup.roomnote.database.NoteDao import com.hgroup.roomnote.model.Note class NoteRepository(private val noteDao: NoteDao) { val readAllNotes = noteDao.getAllNotes() suspend fun addNote(note: Note) { noteDao.addNote(note) } suspend fun updateNote(note: Note) { noteDao.updateNote(note) } suspend fun deleteNote(note: Note) { noteDao.deleteNote(note) } suspend fun deleteAllNotes() { noteDao.deleteAllNotes() } }
0
Kotlin
0
0
9c3c9b277f2e65eb96204513bd885f79cc8ffa71
535
RoomNoteApp
MIT License
vector/src/main/java/im/vector/app/core/settings/connectionmethods/onion/TorEventBroadcaster.kt
FaradayApp
732,727,396
false
{"Kotlin": 15866016, "Java": 250183, "Shell": 102807, "HTML": 28529, "Python": 25379, "FreeMarker": 7662, "JavaScript": 7070, "Ruby": 3420, "Gherkin": 58}
/* * Copyright (c) 2023 New Vector Ltd * * 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 im.vector.app.core.settings.connectionmethods.onion import io.matthewnelson.topl_service_base.TorPortInfo import io.matthewnelson.topl_service_base.TorServiceEventBroadcaster import org.matrix.android.sdk.api.settings.LightweightSettingsStorage import timber.log.Timber import javax.inject.Inject /** * Listener class to Tor Broadcast Events. */ class TorEventBroadcaster @Inject constructor( private val torService: TorService, private val torEventListener: TorEventListener, private val lightweightSettingsStorage: LightweightSettingsStorage ) : TorServiceEventBroadcaster() { /** * Receives current information concerning ports through which onion connection is supposed to be established. */ override fun broadcastPortInformation(torPortInfo: TorPortInfo) { Timber.d("PortInfo: socksPort" + torPortInfo.socksPort + " httpPort" + torPortInfo.httpPort) if (torPortInfo.httpPort != null) { val port = Integer.valueOf(torPortInfo.httpPort!!.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[1]) torService.isProxyRunning = true torService.proxyPort = port lightweightSettingsStorage.setProxyPort(port) Timber.i("torServiceEventBroadcasterListener $port") torEventListener.onConnectionEstablished() } else { torService.isProxyRunning = false torEventListener.onConnectionFailed() } } override fun broadcastBandwidth(bytesRead: String, bytesWritten: String) { Timber.v("bandwidth: $bytesRead, $bytesWritten") } override fun broadcastDebug(msg: String) { Timber.d("debug: $msg") } override fun broadcastException(msg: String?, e: Exception) { Timber.e("exception: " + msg + ", " + e.message) torEventListener.onConnectionFailed() } override fun broadcastLogMessage(logMessage: String?) { Timber.d(logMessage.orEmpty()) } override fun broadcastNotice(msg: String) { Timber.v(msg) if (msg.startsWith("NOTICE|BaseEventListener|Bootstrapped")) { msg.substringAfterLast('|').substringBeforeLast("%") val logMessage = msg.substringAfterLast('|').substringBeforeLast("%") torEventListener.onTorLogEvent("Tor: $logMessage%") } } override fun broadcastTorState(state: String, networkState: String) { Timber.d("$state, $networkState") torEventListener.onTorLogEvent("$state, $networkState") } }
0
Kotlin
2
0
c30564a1a90a8906bb29cc67592d76c082289dca
3,161
Faraday-android
Apache License 2.0
app/src/main/java/com/vladislav/posts/testapplication/presentation/ui/postdetails/PostDetails.kt
binkos
393,090,587
false
null
package com.vladislav.posts.testapplication.presentation.ui.postdetails import androidx.compose.foundation.Image import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.CircularProgressIndicator import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import coil.ImageLoader import coil.compose.ImagePainter import coil.compose.rememberImagePainter import coil.request.CachePolicy import coil.transform.CircleCropTransformation import com.google.accompanist.swiperefresh.SwipeRefresh import com.google.accompanist.swiperefresh.rememberSwipeRefreshState import com.vladislav.posts.testapplication.R import com.vladislav.posts.testapplication.domain.model.PostDetails @Composable fun PostDetails(viewModel: PostDetailsViewModel) { val postDetailsState = viewModel.postDetailsStateFlow.collectAsState() val isRefreshState = viewModel.isLoadingState.collectAsState() SwipeRefresh( state = rememberSwipeRefreshState(isRefreshState.value), onRefresh = { viewModel.refreshPostDetails() } ) { SuccessState(postDetailsState.value) } } @Composable fun SuccessState(postDetails: PostDetails) { if (postDetails.userName == "" && postDetails.url == "") return val painter = rememberImagePainter( data = postDetails.url, builder = { crossfade(true) transformations(CircleCropTransformation()) }, imageLoader = ImageLoader .Builder(LocalContext.current) .networkCachePolicy(CachePolicy.ENABLED) .error(R.drawable.ic_error) .build() ) if (painter.state is ImagePainter.State.Loading) { Box(Modifier.padding(start = 22.dp, top = 20.dp)) { CircularProgressIndicator() } } Column( Modifier .fillMaxSize() .padding(16.dp) .verticalScroll(rememberScrollState()) ) { Row { Image( painter = painter, modifier = Modifier.size(64.dp), contentDescription = null ) Text( text = postDetails.userName, modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp) ) } Text( text = postDetails.title, modifier = Modifier.padding(top = 8.dp), fontFamily = FontFamily.SansSerif, fontSize = 18.sp, fontWeight = FontWeight.Medium ) Text( text = postDetails.body, fontStyle = FontStyle.Italic, modifier = Modifier.padding(top = 8.dp), fontFamily = FontFamily.SansSerif, fontSize = 14.sp ) } }
0
Kotlin
0
0
b58ed33f6a60d672cb79f798df7be2fd22e38d7e
3,210
Simple_posts_app
Apache License 2.0
app/src/main/java/com/example/enderecos_room_database/domain/model/Address.kt
Pedroid1
631,916,486
false
null
package com.example.enderecos_room_database.domain.model import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "address") data class Address( @PrimaryKey(autoGenerate = true) val uid: Int?, val client: String, val street: String, val number: String, val district: String, val complement: String, val contact: String ) : java.io.Serializable
0
Kotlin
0
0
4652c02d924e99df397b2edbd00760f185b1b55c
396
endere-os-room-database
Apache License 2.0
src/main/kotlin/no/nav/syfo/dialogmelding/status/domain/DialogmeldingStatus.kt
navikt
378,118,189
false
{"Kotlin": 660898, "Dockerfile": 226}
package no.nav.syfo.dialogmelding.status.domain import no.nav.syfo.dialogmelding.apprec.domain.Apprec import no.nav.syfo.dialogmelding.apprec.domain.ApprecStatus import no.nav.syfo.dialogmelding.bestilling.domain.DialogmeldingToBehandlerBestilling import no.nav.syfo.dialogmelding.status.database.PDialogmeldingStatus import no.nav.syfo.dialogmelding.status.kafka.KafkaDialogmeldingStatusDTO import no.nav.syfo.util.nowUTC import java.time.OffsetDateTime import java.util.* enum class DialogmeldingStatusType { BESTILT, SENDT, OK, AVVIST } data class DialogmeldingStatus private constructor( val uuid: UUID, val bestilling: DialogmeldingToBehandlerBestilling, val status: DialogmeldingStatusType, val tekst: String? = null, val createdAt: OffsetDateTime, val publishedAt: OffsetDateTime? = null, ) { companion object { fun bestilt(bestilling: DialogmeldingToBehandlerBestilling): DialogmeldingStatus = create( status = DialogmeldingStatusType.BESTILT, bestilling = bestilling, ) fun sendt(bestilling: DialogmeldingToBehandlerBestilling): DialogmeldingStatus = create( status = DialogmeldingStatusType.SENDT, bestilling = bestilling, ) fun fromApprec(apprec: Apprec): DialogmeldingStatus { return when (apprec.statusKode) { ApprecStatus.OK -> create( bestilling = apprec.bestilling, status = DialogmeldingStatusType.OK, ) ApprecStatus.AVVIST -> create( bestilling = apprec.bestilling, status = DialogmeldingStatusType.AVVIST, tekst = apprec.feilTekst, ) } } fun fromPDialogmeldingStatus( pDialogmeldingStatus: PDialogmeldingStatus, bestilling: DialogmeldingToBehandlerBestilling, ): DialogmeldingStatus = DialogmeldingStatus( uuid = pDialogmeldingStatus.uuid, status = DialogmeldingStatusType.valueOf(pDialogmeldingStatus.status), tekst = pDialogmeldingStatus.tekst, createdAt = pDialogmeldingStatus.createdAt, publishedAt = pDialogmeldingStatus.publishedAt, bestilling = bestilling, ) private fun create( status: DialogmeldingStatusType, bestilling: DialogmeldingToBehandlerBestilling, tekst: String? = null, ) = DialogmeldingStatus( uuid = UUID.randomUUID(), bestilling = bestilling, status = status, tekst = tekst, createdAt = nowUTC(), ) } } fun DialogmeldingStatus.toKafkaDialogmeldingStatusDTO(): KafkaDialogmeldingStatusDTO = KafkaDialogmeldingStatusDTO( uuid = this.uuid.toString(), createdAt = this.createdAt, status = this.status.name, tekst = this.tekst, bestillingUuid = this.bestilling.uuid.toString(), )
2
Kotlin
1
0
847e3b34d73b0a0caf3791f685aaf7c51ba4ffa4
3,006
isdialogmelding
MIT License
year2022/test/cz/veleto/aoc/year2022/Day01Test.kt
haluzpav
573,073,312
false
{"Kotlin": 164348}
package cz.veleto.aoc.year2022 import cz.veleto.aoc.core.AocDay import kotlin.test.Test import kotlin.test.assertEquals class Day01Test { private val task = Day01(AocDay.Config("Day01_test")) @Test fun testPart1() { assertEquals("24000", task.part1()) } @Test fun testPart2() { assertEquals("45000", task.part2()) } }
0
Kotlin
0
1
32003edb726f7736f881edc263a85a404be6a5f0
366
advent-of-pavel
Apache License 2.0
src/main/kotlin/no/nav/familie/ef/sak/iverksett/oppgaveterminbarn/TerminbarnTilUtplukkForOppgave.kt
navikt
206,805,010
false
null
package no.nav.familie.ef.sak.iverksett.oppgaveterminbarn import java.time.LocalDate import java.util.UUID data class TerminbarnTilUtplukkForOppgave( val behandlingId: UUID, val fagsakId: UUID, val eksternFagsakId: Long, val termindatoBarn: LocalDate )
8
Kotlin
2
0
826996ddfeb9a0ec01a8b3525cb5841bd41bd7dd
271
familie-ef-sak
MIT License
app/src/main/java/com/irancell/nwg/ios/data/remote/response/Site.kt
afshin1394
755,443,887
false
{"Kotlin": 803604}
package com.irancell.nwg.ios.data.remote.response import android.os.Parcelable import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName import com.irancell.nwg.ios.data.local.DatabaseSite import com.irancell.nwg.ios.data.model.SiteDomain import com.irancell.nwg.ios.data.remote.response.SiteResponse import kotlinx.parcelize.Parcelize @Parcelize data class Site( @SerializedName("site_name") @Expose val site_name: String, @SerializedName("technologies") @Expose val technologies: String, @SerializedName("region") @Expose val region_name: String, @SerializedName("province") @Expose val province: String, @SerializedName("vendor") @Expose val vendor: String, @SerializedName("contractor") @Expose val contractor: String, @SerializedName("site_type") @Expose val site_type: String, @SerializedName("tower_height") @Expose val tower_height: Double, @SerializedName("site_installation_type") @Expose val site_installation_type: String, @SerializedName("site_status") @Expose val site_status: String, @SerializedName("audit_status") @Expose val audit_status: Int, @SerializedName("audit_priority") @Expose val audit_priority: Int, @SerializedName("projectId") @Expose val projectId: Int, @SerializedName("latitude") @Expose val latitude: Double, @SerializedName("longitude") @Expose val longitude: Double, @SerializedName("audit_id") @Expose val audit_id : Int ): Parcelable fun List<Site>.asDatabaseModel(projectId: Int): List<DatabaseSite> { return map { DatabaseSite( site_name = it.site_name, technologies = it.technologies, region_name = it.region_name, province = it.province, vendor = it.vendor, contractor = it.contractor, site_type = it.site_type, tower_height = it.tower_height.toString(), site_installation_type = it.site_installation_type, site_status = it.site_status, audit_status = it.audit_status, audit_priority = it.audit_priority, projectId = projectId, latitude = it.latitude.toString(), longitude = it.longitude.toString(), audit_id = it.audit_id ) } }
0
Kotlin
0
0
23a544780da643c4fa190bbe48d3bd9aa5673d88
2,423
Audit
MIT License
src/main/kotlin/me/exerro/dataflow/nodes/transformers/UdpUnpack.kt
exerro
575,968,163
false
{"Kotlin": 55236}
package me.exerro.dataflow.nodes.transformers import kotlinx.coroutines.CoroutineScope import me.exerro.dataflow.MetadataKey import me.exerro.dataflow.Node import java.net.DatagramPacket /** TODO */ class UdpUnpack: Node() { /** TODO */ val packets = inputStream<DatagramPacket>() /** TODO */ val data = outputStream<ByteArray>() //////////////////////////////////////////////////////////////////////////// override val inputs = listOf(packets) override val outputs = listOf(data) context(CoroutineScope) override suspend fun start() { while (true) { val packet = packets.pull() val result = ByteArray(packet.length) packet.data.copyInto(result, 0, 0, result.size) data.push(result) } } //////////////////////////////////////////////////////////////////////////// init { setMetadata(MetadataKey.Label, "UdpUnpack") } }
0
Kotlin
0
0
59e925ac4e09890cd16460a44059997522d58149
951
data-flow-thing
MIT License
shared/src/commonMain/kotlin/App.kt
tmromao
676,528,481
false
null
import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue @Composable fun App() { MaterialTheme { Text("Hello ${getPlatformName()}") } } expect fun getPlatformName(): String
0
Kotlin
0
0
0f85230c3431f4b7a8c2524e59c13a48ffc376d1
451
MySubscriptionV4
Apache License 2.0
shared/src/commonMain/kotlin/App.kt
tmromao
676,528,481
false
null
import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue @Composable fun App() { MaterialTheme { Text("Hello ${getPlatformName()}") } } expect fun getPlatformName(): String
0
Kotlin
0
0
0f85230c3431f4b7a8c2524e59c13a48ffc376d1
451
MySubscriptionV4
Apache License 2.0
app/src/main/java/dev/apes/pawmance/utils/TextChangeListener.kt
forceporquillo
424,718,550
false
null
package dev.apes.pawmance.utils import android.text.Editable import android.text.TextWatcher abstract class TextChangeListener : TextWatcher { override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {} override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) { onTextChanged(charSequence) } override fun afterTextChanged(editable: Editable) {} abstract fun onTextChanged(charSequence: CharSequence?) }
0
Kotlin
0
1
5a8dd89637968a1cd56ede5ea073fb61feb38637
471
pawmance-android
Apache License 2.0
ktmidi-ci/src/commonMain/kotlin/dev/atsushieno/ktmidi/ci/MidiCIDevice.kt
atsushieno
340,913,447
false
{"Kotlin": 744891, "Swift": 600, "Shell": 319, "HTML": 308}
package dev.atsushieno.ktmidi.ci import dev.atsushieno.ktmidi.ci.Message.Companion.muidString import dev.atsushieno.ktmidi.ci.profilecommonrules.CommonRulesProfileService import dev.atsushieno.ktmidi.ci.propertycommonrules.PropertyCommonHeaderKeys import kotlinx.datetime.Clock enum class ConnectionChange { Added, Removed } /** * Represents A MIDI-CI Device entity, or a Function Block[*1]. * * [*1] M2-101-UM_v1_2: MIDI-CI specification section 3.1 states: * "Each Function Block that supports MIDI-CI shall have a different MUID and act as a unique MIDI-CI Device" * */ class MidiCIDevice(val muid: Int, val config: MidiCIDeviceConfiguration, private val sendCIOutput: (group: Byte, data: List<Byte>) -> Unit, private val sendMidiMessageReport: (protocol: MidiMessageReportProtocol, data: List<Byte>) -> Unit ) { val initiator by lazy { MidiCIInitiator(this, config.initiator, sendCIOutput) } val responder by lazy { MidiCIResponder(this, config.responder, sendCIOutput, sendMidiMessageReport) } val device: MidiCIDeviceInfo get() = config.device class Events { val unknownMessageReceived = mutableListOf<(data: List<Byte>) -> Unit>() val discoveryReceived = mutableListOf<(msg: Message.DiscoveryInquiry) -> Unit>() val discoveryReplyReceived = mutableListOf<(Message.DiscoveryReply) -> Unit>() val endpointInquiryReceived = mutableListOf<(msg: Message.EndpointInquiry) -> Unit>() val endpointReplyReceived = mutableListOf<(Message.EndpointReply) -> Unit>() val invalidateMUIDReceived = mutableListOf<(Message.InvalidateMUID) -> Unit>() val profileInquiryReceived = mutableListOf<(msg: Message.ProfileInquiry) -> Unit>() val profileInquiryReplyReceived = mutableListOf<(Message.ProfileReply) -> Unit>() val setProfileOnReceived = mutableListOf<(profile: Message.SetProfileOn) -> Unit>() val setProfileOffReceived = mutableListOf<(profile: Message.SetProfileOff) -> Unit>() val profileAddedReceived = mutableListOf<(Message.ProfileAdded) -> Unit>() val profileRemovedReceived = mutableListOf<(Message.ProfileRemoved) -> Unit>() val profileEnabledReceived = mutableListOf<(Message.ProfileEnabled) -> Unit>() val profileDisabledReceived = mutableListOf<(Message.ProfileDisabled) -> Unit>() val profileDetailsInquiryReceived = mutableListOf<(Message.ProfileDetailsInquiry) -> Unit>() val profileDetailsReplyReceived = mutableListOf<(Message.ProfileDetailsReply) -> Unit>() val profileSpecificDataReceived = mutableListOf<(Message.ProfileSpecificData) -> Unit>() val propertyCapabilityInquiryReceived = mutableListOf<(Message.PropertyGetCapabilities) -> Unit>() val propertyCapabilityReplyReceived = mutableListOf<(Message.PropertyGetCapabilitiesReply) -> Unit>() val getPropertyDataReceived = mutableListOf<(msg: Message.GetPropertyData) -> Unit>() val getPropertyDataReplyReceived = mutableListOf<(msg: Message.GetPropertyDataReply) -> Unit>() val setPropertyDataReceived = mutableListOf<(msg: Message.SetPropertyData) -> Unit>() val setPropertyDataReplyReceived = mutableListOf<(msg: Message.SetPropertyDataReply) -> Unit>() val subscribePropertyReplyReceived = mutableListOf<(msg: Message.SubscribePropertyReply) -> Unit>() val subscribePropertyReceived = mutableListOf<(msg: Message.SubscribeProperty) -> Unit>() val propertyNotifyReceived = mutableListOf<(msg: Message.PropertyNotify) -> Unit>() val processInquiryReceived = mutableListOf<(msg: Message.ProcessInquiry) -> Unit>() val processInquiryReplyReceived = mutableListOf<(msg: Message.ProcessInquiryReply) -> Unit>() val midiMessageReportReceived = mutableListOf<(msg: Message.MidiMessageReportInquiry) -> Unit>() val midiMessageReportReplyReceived = mutableListOf<(msg: Message.MidiMessageReportReply) -> Unit>() val endOfMidiMessageReportReceived = mutableListOf<(msg: Message.MidiMessageReportNotifyEnd) -> Unit>() } val events = Events() val logger = Logger() val connections = mutableMapOf<Int, MidiCIInitiator.ClientConnection>() val connectionsChanged = mutableListOf<(change: ConnectionChange, connection: MidiCIInitiator.ClientConnection) -> Unit>() var profileService: MidiCIProfileService = CommonRulesProfileService() val localProfiles = ObservableProfileList(config.localProfiles) // Request sender fun sendDiscovery(group: Byte, ciCategorySupported: Byte = MidiCISupportedCategories.THREE_P) = sendDiscovery(Message.DiscoveryInquiry( Message.Common(muid, MidiCIConstants.BROADCAST_MUID_32, MidiCIConstants.ADDRESS_FUNCTION_BLOCK, group), DeviceDetails( device.manufacturerId, device.familyId, device.modelId, device.versionId ), ciCategorySupported, config.receivableMaxSysExSize, config.outputPathId)) fun sendDiscovery(msg: Message.DiscoveryInquiry) { logger.logMessage(msg, MessageDirection.Out) val buf = MutableList<Byte>(config.receivableMaxSysExSize) { 0 } sendCIOutput(msg.group, CIFactory.midiCIDiscovery( buf, MidiCIConstants.CI_VERSION_AND_FORMAT, msg.sourceMUID, msg.device.manufacturer, msg.device.family, msg.device.modelNumber, msg.device.softwareRevisionLevel, msg.ciCategorySupported, msg.receivableMaxSysExSize, msg.outputPathId )) } fun sendNakForUnknownCIMessage(group: Byte, data: List<Byte>) { val source = data[1] val originalSubId = data[3] val sourceMUID = CIRetrieval.midiCIGetSourceMUID(data) val destinationMUID = CIRetrieval.midiCIGetDestinationMUID(data) val nak = MidiCIAckNakData(source, sourceMUID, destinationMUID, originalSubId, CINakStatus.MessageNotSupported, 0, listOf(), listOf()) val dst = MutableList<Byte>(config.receivableMaxSysExSize) { 0 } sendCIOutput(group, CIFactory.midiCIAckNak(dst, true, nak)) } fun sendNakForUnknownMUID(common: Message.Common, originalSubId2: Byte) { sendNakForError(common, originalSubId2, CINakStatus.Nak, 0, message = "CI Device is not connected. (MUID: ${common.destinationMUID.muidString})") } fun sendNakForError(common: Message.Common, originalSubId2: Byte, statusCode: Byte, statusData: Byte, details: List<Byte> = List(5) {0}, message: String) { sendNakForError(Message.Nak(common, originalSubId2, statusCode, statusData, details, MidiCIConverter.encodeStringToASCII(message).toASCIIByteArray().toList())) } fun sendNakForError(msg: Message.Nak) { logger.logMessage(msg, MessageDirection.Out) val buf = MutableList<Byte>(config.receivableMaxSysExSize) { 0 } sendCIOutput(msg.group, CIFactory.midiCIAckNak(buf, true, msg.address, MidiCIConstants.CI_VERSION_AND_FORMAT, msg.sourceMUID, msg.destinationMUID, msg.originalSubId, msg.statusCode, msg.statusData, msg.details, msg.message)) } fun invalidateMUID(address: Byte, group: Byte, targetMUID: Int, message: String) { logger.logError(message) val msg = Message.InvalidateMUID(Message.Common(muid, targetMUID, address, group), targetMUID) invalidateMUID(msg) } fun invalidateMUID(msg: Message.InvalidateMUID) { logger.logMessage(msg, MessageDirection.Out) val buf = MutableList<Byte>(config.receivableMaxSysExSize) { 0 } sendCIOutput(msg.group, CIFactory.midiCIDiscoveryInvalidateMuid(buf, MidiCIConstants.CI_VERSION_AND_FORMAT, msg.sourceMUID, msg.targetMUID)) } // Input handlers var processUnknownCIMessage: (group: Byte, data: List<Byte>) -> Unit = { group, data -> logger.nak(data, MessageDirection.In) events.unknownMessageReceived.forEach { it(data) } sendNakForUnknownCIMessage(group, data) } fun defaultProcessInvalidateMUID(msg: Message.InvalidateMUID) { val conn = connections[msg.targetMUID] if (conn != null) { connections.remove(msg.targetMUID) connectionsChanged.forEach { it(ConnectionChange.Removed, conn) } } } var processInvalidateMUID: (msg: Message.InvalidateMUID) -> Unit = { msg -> logger.logMessage(msg, MessageDirection.In) events.invalidateMUIDReceived.forEach { it(msg) } defaultProcessInvalidateMUID(msg) } // to Discovery (responder) val sendDiscoveryReply: (msg: Message.DiscoveryReply) -> Unit = { msg -> logger.logMessage(msg, MessageDirection.Out) val dst = MutableList<Byte>(config.receivableMaxSysExSize) { 0 } sendCIOutput(msg.group, CIFactory.midiCIDiscoveryReply( dst, MidiCIConstants.CI_VERSION_AND_FORMAT, msg.sourceMUID, msg.destinationMUID, msg.device.manufacturer, msg.device.family, msg.device.modelNumber, msg.device.softwareRevisionLevel, config.capabilityInquirySupported, config.receivableMaxSysExSize, msg.outputPathId, msg.functionBlock ) ) } val getDiscoveryReplyForInquiry: (request: Message.DiscoveryInquiry) -> Message.DiscoveryReply = { request -> val deviceDetails = DeviceDetails(device.manufacturerId, device.familyId, device.modelId, device.versionId) Message.DiscoveryReply(Message.Common(muid, request.sourceMUID, request.address, request.group), deviceDetails, config.capabilityInquirySupported, config.receivableMaxSysExSize, request.outputPathId, config.functionBlock) } var processDiscovery: (msg: Message.DiscoveryInquiry) -> Unit = { msg -> logger.logMessage(msg, MessageDirection.In) events.discoveryReceived.forEach { it(msg) } val reply = getDiscoveryReplyForInquiry(msg) sendDiscoveryReply(reply) } val sendEndpointReply: (msg: Message.EndpointReply) -> Unit = { msg -> logger.logMessage(msg, MessageDirection.Out) val dst = MutableList<Byte>(config.receivableMaxSysExSize) { 0 } sendCIOutput(msg.group, CIFactory.midiCIEndpointMessageReply( dst, MidiCIConstants.CI_VERSION_AND_FORMAT, msg.sourceMUID, msg.destinationMUID, msg.status, msg.data) ) } val getEndpointReplyForInquiry: (msg: Message.EndpointInquiry) -> Message.EndpointReply = { msg -> val prodId = config.productInstanceId if (prodId.length > 16 || prodId.any { it.code < 0x20 || it.code > 0x7E }) throw IllegalStateException("productInstanceId shall not be any longer than 16 bytes in size and must be all in ASCII code between 32 and 126") Message.EndpointReply(Message.Common(muid, msg.sourceMUID, msg.address, msg.group), msg.status, if (msg.status == MidiCIConstants.ENDPOINT_STATUS_PRODUCT_INSTANCE_ID && prodId.isNotBlank()) prodId.toASCIIByteArray().toList() else listOf() ) } var processEndpointMessage: (msg: Message.EndpointInquiry) -> Unit = { msg -> logger.logMessage(msg, MessageDirection.In) events.endpointInquiryReceived.forEach { it(msg) } val reply = getEndpointReplyForInquiry(msg) sendEndpointReply(reply) } // to Reply to Discovery (initiator) val handleNewEndpoint = { msg: Message.DiscoveryReply -> // If successfully discovered, continue to endpoint inquiry val connection = MidiCIInitiator.ClientConnection(initiator, msg.sourceMUID, msg.device) val existing = connections[msg.sourceMUID] if (existing != null) { connections.remove(msg.sourceMUID) connectionsChanged.forEach { it(ConnectionChange.Removed, existing) } } connections[msg.sourceMUID]= connection connectionsChanged.forEach { it(ConnectionChange.Added, connection) } if (config.autoSendEndpointInquiry) initiator.sendEndpointMessage(msg.group, msg.sourceMUID, MidiCIConstants.ENDPOINT_STATUS_PRODUCT_INSTANCE_ID) if (config.autoSendProfileInquiry && (msg.ciCategorySupported.toInt() and MidiCISupportedCategories.PROFILE_CONFIGURATION.toInt()) != 0) initiator.requestProfiles(msg.group, MidiCIConstants.ADDRESS_FUNCTION_BLOCK, msg.sourceMUID) if (config.autoSendPropertyExchangeCapabilitiesInquiry && (msg.ciCategorySupported.toInt() and MidiCISupportedCategories.PROPERTY_EXCHANGE.toInt()) != 0) initiator.requestPropertyExchangeCapabilities(msg.group, MidiCIConstants.ADDRESS_FUNCTION_BLOCK, msg.sourceMUID, config.maxSimultaneousPropertyRequests) } var processDiscoveryReply: (msg: Message.DiscoveryReply) -> Unit = { msg -> logger.logMessage(msg, MessageDirection.In) events.discoveryReplyReceived.forEach { it(msg) } handleNewEndpoint(msg) } var onAck: (sourceMUID: Int, destinationMUID: Int, originalTransactionSubId: Byte, nakStatusCode: Byte, nakStatusData: Byte, nakDetailsForEachSubIdClassification: List<Byte>, messageLength: UShort, messageText: List<Byte>) -> Unit = { _,_,_,_,_,_,_,_ -> } var onNak: (sourceMUID: Int, destinationMUID: Int, originalTransactionSubId: Byte, nakStatusCode: Byte, nakStatusData: Byte, nakDetailsForEachSubIdClassification: List<Byte>, messageLength: UShort, messageText: List<Byte>) -> Unit = { _,_,_,_,_,_,_,_ -> } private fun defaultProcessAckNak(isNak: Boolean, sourceMUID: Int, destinationMUID: Int, originalTransactionSubId: Byte, statusCode: Byte, statusData: Byte, detailsForEachSubIdClassification: List<Byte>, messageLength: UShort, messageText: List<Byte>) { if (isNak) onNak(sourceMUID, destinationMUID, originalTransactionSubId, statusCode, statusData, detailsForEachSubIdClassification, messageLength, messageText) else onAck(sourceMUID, destinationMUID, originalTransactionSubId, statusCode, statusData, detailsForEachSubIdClassification, messageLength, messageText) } private val defaultProcessAck = { sourceMUID: Int, destinationMUID: Int, originalTransactionSubId: Byte, statusCode: Byte, statusData: Byte, detailsForEachSubIdClassification: List<Byte>, messageLength: UShort, messageText: List<Byte> -> defaultProcessAckNak(false, sourceMUID, destinationMUID, originalTransactionSubId, statusCode, statusData, detailsForEachSubIdClassification, messageLength, messageText) } var processAck = defaultProcessAck private val defaultProcessNak = { sourceMUID: Int, destinationMUID: Int, originalTransactionSubId: Byte, statusCode: Byte, statusData: Byte, detailsForEachSubIdClassification: List<Byte>, messageLength: UShort, messageText: List<Byte> -> defaultProcessAckNak(true, sourceMUID, destinationMUID, originalTransactionSubId, statusCode, statusData, detailsForEachSubIdClassification, messageLength, messageText) } var processNak = defaultProcessNak val defaultProcessEndpointReply = { msg: Message.EndpointReply -> val conn = connections[msg.sourceMUID] if (conn != null) { if (msg.status == MidiCIConstants.ENDPOINT_STATUS_PRODUCT_INSTANCE_ID) { val s = msg.data.toByteArray().decodeToString() if (s.all { it.code in 32..126 } && s.length <= 16) conn.productInstanceId = s else invalidateMUID(msg.address, msg.group, msg.sourceMUID, "Invalid product instance ID") } } } var processEndpointReply: (msg: Message.EndpointReply) -> Unit = { msg -> logger.logMessage(msg, MessageDirection.In) events.endpointReplyReceived.forEach { it(msg) } defaultProcessEndpointReply(msg) } // Local Profile Configuration val sendProfileReply: (msg: Message.ProfileReply) -> Unit = { msg -> logger.logMessage(msg, MessageDirection.Out) val dst = MutableList<Byte>(config.receivableMaxSysExSize) { 0 } sendCIOutput(msg.group, CIFactory.midiCIProfileInquiryReply(dst, msg.address, msg.sourceMUID, msg.destinationMUID, msg.enabledProfiles, msg.disabledProfiles) ) } private fun getAllAddresses(address: Byte) = sequence { if (address == MidiCIConstants.ADDRESS_FUNCTION_BLOCK) yieldAll(localProfiles.profiles.map { it.address }.distinct().sorted()) else yield(address) } val getProfileRepliesForInquiry: (msg: Message.ProfileInquiry) -> Sequence<Message.ProfileReply> = { msg -> sequence { getAllAddresses(msg.address).forEach { address -> yield(Message.ProfileReply(Message.Common(muid, msg.sourceMUID, address, msg.group), localProfiles.getMatchingProfiles(address, true), localProfiles.getMatchingProfiles(address, false))) } } } var processProfileInquiry: (msg: Message.ProfileInquiry) -> Unit = { msg -> logger.logMessage(msg, MessageDirection.In) events.profileInquiryReceived.forEach { it(msg) } getProfileRepliesForInquiry(msg).forEach { reply -> sendProfileReply(reply) } } var onProfileSet = mutableListOf<(profile: MidiCIProfile) -> Unit>() private val defaultProcessSetProfile = { group: Byte, address: Byte, initiatorMUID: Int, destinationMUID: Int, profile: MidiCIProfileId, numChannelsRequested: Short, enabled: Boolean -> val newEntry = MidiCIProfile(profile, group, address, enabled, numChannelsRequested) val existing = localProfiles.profiles.firstOrNull { it.profile == profile } if (existing != null) localProfiles.remove(existing) localProfiles.add(newEntry) onProfileSet.forEach { it(newEntry) } enabled } private fun sendSetProfileReport(group: Byte, address: Byte, profile: MidiCIProfileId, enabled: Boolean) { val dst = MutableList<Byte>(config.receivableMaxSysExSize) { 0 } sendCIOutput(group, CIFactory.midiCIProfileReport(dst, address, enabled, muid, profile)) } fun sendProfileAddedReport(group: Byte, profile: MidiCIProfile) { val dst = MutableList<Byte>(config.receivableMaxSysExSize) { 0 } sendCIOutput(group, CIFactory.midiCIProfileAddedRemoved(dst, profile.address, false, muid, profile.profile)) } fun sendProfileRemovedReport(group: Byte, profile: MidiCIProfile) { val dst = MutableList<Byte>(config.receivableMaxSysExSize) { 0 } sendCIOutput(group, CIFactory.midiCIProfileAddedRemoved(dst, profile.address, true, muid, profile.profile)) } fun defaultProcessSetProfileOn(msg: Message.SetProfileOn) { // send Profile Enabled Report only when it is actually enabled if (defaultProcessSetProfile(msg.group, msg.address, msg.sourceMUID, msg.destinationMUID, msg.profile, msg.numChannelsRequested, true)) sendSetProfileReport(msg.group, msg.address, msg.profile, true) } fun defaultProcessSetProfileOff(msg: Message.SetProfileOff) { // send Profile Disabled Report only when it is actually disabled if (!defaultProcessSetProfile(msg.group, msg.address, msg.sourceMUID, msg.destinationMUID, msg.profile, 0, false)) sendSetProfileReport(msg.group, msg.address, msg.profile, false) } var processSetProfileOn = { msg: Message.SetProfileOn -> logger.logMessage(msg, MessageDirection.In) events.setProfileOnReceived.forEach { it(msg) } defaultProcessSetProfileOn(msg) } var processSetProfileOff = { msg: Message.SetProfileOff -> logger.logMessage(msg, MessageDirection.In) events.setProfileOffReceived.forEach { it(msg) } defaultProcessSetProfileOff(msg) } fun sendProfileDetailsReply(msg: Message.ProfileDetailsReply) { val dst = MutableList<Byte>(config.receivableMaxSysExSize) { 0 } sendCIOutput(msg.group, CIFactory.midiCIProfileDetailsReply(dst, msg.address, msg.sourceMUID, msg.destinationMUID, msg.profile, msg.target, msg.data)) } private fun getProfileDetailsReplyForInquiry(msg: Message.ProfileDetailsInquiry, data: List<Byte>) = Message.ProfileDetailsReply(Message.Common(muid, msg.sourceMUID, msg.address, msg.group), msg.profile, msg.target, data) fun defaultProcessProfileDetailsInquiry(msg: Message.ProfileDetailsInquiry) { val data = profileService.getProfileDetails(msg.profile, msg.target) if (data != null) sendProfileDetailsReply(getProfileDetailsReplyForInquiry(msg, data)) else sendNakForError(Message.Common(muid, msg.sourceMUID, msg.address, msg.group), CISubId2.PROFILE_DETAILS_INQUIRY, 0, 0, message = "Profile Details Inquiry against unknown target (profile=${msg.profile}, target=${msg.target})") } var processProfileDetailsInquiry: (msg: Message.ProfileDetailsInquiry) -> Unit = { msg -> logger.logMessage(msg, MessageDirection.In) events.profileDetailsInquiryReceived.forEach { it(msg) } defaultProcessProfileDetailsInquiry(msg) } var processProfileSpecificData: (msg: Message.ProfileSpecificData) -> Unit = { msg -> logger.logMessage(msg, MessageDirection.In) events.profileSpecificDataReceived.forEach { it(msg) } } // Property Exchange var processSubscribeProperty: (msg: Message.SubscribeProperty) -> Unit = { msg -> // It may be either a new subscription, a property update notification, or end of subscription from either side val command = responder.propertyService.getHeaderFieldString(msg.header, PropertyCommonHeaderKeys.COMMAND) when (command) { MidiCISubscriptionCommand.START -> initiator.processSubscribeProperty(msg) MidiCISubscriptionCommand.FULL, MidiCISubscriptionCommand.PARTIAL, MidiCISubscriptionCommand.NOTIFY -> responder.processSubscribeProperty(msg) MidiCISubscriptionCommand.END -> { // We need to identify whether it is sent by the notifier or one of the subscribers // FIXME: select either of the targets initiator.processSubscribeProperty(msg) // for a subscriber responder.processSubscribeProperty(msg) // for the notifier } } } var processSubscribePropertyReply: (msg: Message.SubscribePropertyReply) -> Unit = { msg -> // It may be a reply to // - new subscription (contains new subscribeId) to initiator, // - value update (status) to responder // - end subscription from either side. We identify by subscriptionId // (whether it is in our listening subscriptions xor it is request to unsubscribe from client) // We need to identify whether it is sent by the notifier or one of the subscribers // FIXME: select either of the targets initiator.processSubscribePropertyReply(msg) // for a subscriber responder.processSubscribePropertyReply(msg) // for the notifier } var processPropertyNotify: (propertyNotify: Message.PropertyNotify) -> Unit = { msg -> logger.logMessage(msg, MessageDirection.In) events.propertyNotifyReceived.forEach { it(msg) } // no particular things to do. Event handlers should be used if any. } fun processInput(group: Byte, data: List<Byte>) { if (data[0] != MidiCIConstants.UNIVERSAL_SYSEX || data[2] != MidiCIConstants.SYSEX_SUB_ID_MIDI_CI) return // not MIDI-CI sysex if (data.size < Message.COMMON_HEADER_SIZE) return // insufficient buffer size in any case val common = Message.Common( CIRetrieval.midiCIGetSourceMUID(data), CIRetrieval.midiCIGetDestinationMUID(data), CIRetrieval.midiCIGetAddressing(data), group ) if (data.size < (Message.messageSizes[data[3]] ?: Int.MAX_VALUE)) { logger.logError("Insufficient message size for ${data[3]}: ${data.size}") return // insufficient buffer size for the message } if (common.destinationMUID != muid && common.destinationMUID != MidiCIConstants.BROADCAST_MUID_32) return // we are not the target // catch errors for (potentially) insufficient buffer sizes try { processInputUnchecked(common, data) } catch(ex: IndexOutOfBoundsException) { val address = CIRetrieval.midiCIGetAddressing(data) val sourceMUID = CIRetrieval.midiCIGetSourceMUID(data) sendNakForError(Message.Common(muid, sourceMUID, address, group), data[3], CINakStatus.MalformedMessage, 0, List(5) { 0 }, ex.message ?: ex.toString()) } } val localPendingChunkManager = PropertyChunkManager() private fun handleChunk(common: Message.Common, requestId: Byte, chunkIndex: Short, numChunks: Short, header: List<Byte>, body: List<Byte>, onComplete: (header: List<Byte>, body: List<Byte>) -> Unit) { val pendingChunkManager = connections[common.sourceMUID]?.pendingChunkManager ?: localPendingChunkManager if (chunkIndex < numChunks) { pendingChunkManager.addPendingChunk(Clock.System.now().epochSeconds, common.sourceMUID, requestId, header, body) } else { val existing = if (chunkIndex > 1) pendingChunkManager.finishPendingChunk(common.sourceMUID, requestId, body) else null val msgHeader = existing?.first ?: header val msgBody = existing?.second ?: body onComplete(msgHeader, msgBody) } } private fun processInputUnchecked(common: Message.Common, data: List<Byte>) { when (data[3]) { // Protocol Negotiation - we ignore them. Falls back to NAK // Discovery CISubId2.DISCOVERY_REPLY -> { val ciSupported = data[24] val device = CIRetrieval.midiCIGetDeviceDetails(data) val max = CIRetrieval.midiCIMaxSysExSize(data) // only available in MIDI-CI 1.2 or later. val initiatorOutputPath = if (data.size > 29) data[29] else 0 val functionBlock = if (data.size > 30) data[30] else 0 // Reply to Discovery processDiscoveryReply(Message.DiscoveryReply( common, device, ciSupported, max, initiatorOutputPath, functionBlock)) } CISubId2.ENDPOINT_MESSAGE_REPLY -> { val sourceMUID = CIRetrieval.midiCIGetSourceMUID(data) val status = data[13] val dataLength = data[14] + (data[15].toInt() shl 7) val dataValue = data.drop(16).take(dataLength) processEndpointReply(Message.EndpointReply(common, status, dataValue)) } CISubId2.INVALIDATE_MUID -> { val targetMUID = CIRetrieval.midiCIGetMUIDToInvalidate(data) processInvalidateMUID(Message.InvalidateMUID(common, targetMUID)) } CISubId2.ACK -> { // ACK MIDI-CI processAck( CIRetrieval.midiCIGetSourceMUID(data), CIRetrieval.midiCIGetDestinationMUID(data), data[13], data[14], data[15], data.drop(16).take(5), (data[21] + (data[22].toInt() shl 7)).toUShort(), data.drop(23) ) } CISubId2.NAK -> { // NAK MIDI-CI processNak( CIRetrieval.midiCIGetSourceMUID(data), CIRetrieval.midiCIGetDestinationMUID(data), data[13], data[14], data[15], data.drop(16).take(5), (data[21] + (data[22].toInt() shl 7)).toUShort(), data.drop(23) ) } // Profile Configuration CISubId2.PROFILE_INQUIRY_REPLY -> { val profiles = CIRetrieval.midiCIGetProfileSet(data) initiator.processProfileReply(Message.ProfileReply( common, profiles.filter { it.second }.map { it.first }, profiles.filter { !it.second }.map { it.first }) ) } CISubId2.PROFILE_ADDED_REPORT -> { val profile = CIRetrieval.midiCIGetProfileId(data) initiator.processProfileAddedReport(Message.ProfileAdded(common, profile)) } CISubId2.PROFILE_REMOVED_REPORT -> { val profile = CIRetrieval.midiCIGetProfileId(data) initiator.processProfileRemovedReport(Message.ProfileRemoved(common, profile)) } CISubId2.PROFILE_DETAILS_REPLY -> { val profile = CIRetrieval.midiCIGetProfileId(data) val target = data[18] val dataSize = data[19] + (data[20] shl 7) val details = data.drop(21).take(dataSize) initiator.processProfileDetailsReply(Message.ProfileDetailsReply(common, profile, target, details)) } CISubId2.PROFILE_ENABLED_REPORT -> { val profile = CIRetrieval.midiCIGetProfileId(data) val channels = (data[18] + (data[19] shl 7)).toShort() initiator.processProfileEnabledReport(Message.ProfileEnabled(common, profile, channels)) } CISubId2.PROFILE_DISABLED_REPORT -> { val profile = CIRetrieval.midiCIGetProfileId(data) val channels = (data[18] + (data[19] shl 7)).toShort() initiator.processProfileDisabledReport(Message.ProfileDisabled(common, profile, channels)) } // Property Exchange CISubId2.PROPERTY_CAPABILITIES_REPLY -> { initiator.processPropertyCapabilitiesReply(Message.PropertyGetCapabilitiesReply( common, CIRetrieval.midiCIGetMaxPropertyRequests(data)) ) } CISubId2.PROPERTY_GET_DATA_REPLY -> { val header = CIRetrieval.midiCIGetPropertyHeader(data) val requestId = data[13] val numChunks = CIRetrieval.midiCIGetPropertyTotalChunks(data) val chunkIndex = CIRetrieval.midiCIGetPropertyChunkIndex(data) val body = CIRetrieval.midiCIGetPropertyBodyInThisChunk(data) handleChunk(common, requestId, chunkIndex, numChunks, header, body) { wholeHeader, wholeBody -> initiator.processGetDataReply(Message.GetPropertyDataReply(common, requestId, wholeHeader, wholeBody)) } } CISubId2.PROPERTY_SET_DATA_REPLY -> { val header = CIRetrieval.midiCIGetPropertyHeader(data) val requestId = data[13] initiator.processSetDataReply(Message.SetPropertyDataReply( common, requestId, header)) } CISubId2.PROPERTY_SUBSCRIBE -> { val requestId = data[13] val headerSize = data[14] + (data[15].toInt() shl 7) val header = data.drop(16).take(headerSize) val numChunks = CIRetrieval.midiCIGetPropertyTotalChunks(data) val chunkIndex = CIRetrieval.midiCIGetPropertyChunkIndex(data) val body = CIRetrieval.midiCIGetPropertyBodyInThisChunk(data) handleChunk(common, requestId, chunkIndex, numChunks, header, body) { wholeHeader, wholeBody -> processSubscribeProperty(Message.SubscribeProperty(common, requestId, wholeHeader, wholeBody)) } } CISubId2.PROPERTY_SUBSCRIBE_REPLY -> { val requestId = data[13] val headerSize = data[14] + (data[15].toInt() shl 7) val header = data.drop(16).take(headerSize) processSubscribePropertyReply(Message.SubscribePropertyReply(common, requestId, header, listOf())) } CISubId2.PROPERTY_NOTIFY -> { val requestId = data[13] val headerSize = data[14] + (data[15].toInt() shl 7) val header = data.drop(16).take(headerSize) val numChunks = CIRetrieval.midiCIGetPropertyTotalChunks(data) val chunkIndex = CIRetrieval.midiCIGetPropertyChunkIndex(data) val body = CIRetrieval.midiCIGetPropertyBodyInThisChunk(data) handleChunk(common, requestId, chunkIndex, numChunks, header, body) { wholeHeader, wholeBody -> processPropertyNotify(Message.PropertyNotify(common, requestId, wholeHeader, wholeBody)) } } // Process Inquiry CISubId2.PROCESS_INQUIRY_CAPABILITIES_REPLY -> { val supportedFeatures = data[13] initiator.processProcessInquiryReply(Message.ProcessInquiryReply(common, supportedFeatures)) } CISubId2.PROCESS_INQUIRY_MIDI_MESSAGE_REPORT_REPLY -> { val systemMessages = data[13] // data[14] is reserved val channelControllerMessages = data[15] val noteDataMessages = data[16] initiator.processMidiMessageReportReply(Message.MidiMessageReportReply( common, systemMessages, channelControllerMessages, noteDataMessages)) } CISubId2.PROCESS_INQUIRY_END_OF_MIDI_MESSAGE -> { initiator.processEndOfMidiMessageReport(Message.MidiMessageReportNotifyEnd(common)) } // Responder inputs // Discovery CISubId2.DISCOVERY_INQUIRY -> { val device = CIRetrieval.midiCIGetDeviceDetails(data) val ciSupported = data[24] val max = CIRetrieval.midiCIMaxSysExSize(data) // only available in MIDI-CI 1.2 or later. val initiatorOutputPath = if (data.size > 29) data[29] else 0 processDiscovery(Message.DiscoveryInquiry(common, device, ciSupported, max, initiatorOutputPath)) } CISubId2.ENDPOINT_MESSAGE_INQUIRY -> { // only available in MIDI-CI 1.2 or later. val status = data[13] processEndpointMessage(Message.EndpointInquiry(common, status)) } // Profile Configuration CISubId2.PROFILE_INQUIRY -> { processProfileInquiry(Message.ProfileInquiry(common)) } CISubId2.SET_PROFILE_ON, CISubId2.SET_PROFILE_OFF -> { val enabled = data[3] == CISubId2.SET_PROFILE_ON val profileId = CIRetrieval.midiCIGetProfileId(data) val channels = (data[18] + (data[19] shl 7)).toShort() if (enabled) processSetProfileOn(Message.SetProfileOn(common, profileId, channels)) else processSetProfileOff(Message.SetProfileOff(common, profileId)) } CISubId2.PROFILE_DETAILS_INQUIRY -> { val profileId = CIRetrieval.midiCIGetProfileId(data) val target = data[13] processProfileDetailsInquiry(Message.ProfileDetailsInquiry(common, profileId, target)) } CISubId2.PROFILE_SPECIFIC_DATA -> { val profileId = CIRetrieval.midiCIGetProfileId(data) val dataLength = CIRetrieval.midiCIGetProfileSpecificDataSize(data) processProfileSpecificData(Message.ProfileSpecificData(common, profileId, data.drop(21).take(dataLength))) } // Property Exchange CISubId2.PROPERTY_CAPABILITIES_INQUIRY -> { val max = CIRetrieval.midiCIGetMaxPropertyRequests(data) responder.processPropertyCapabilitiesInquiry( Message.PropertyGetCapabilities(common, max)) } CISubId2.PROPERTY_GET_DATA_INQUIRY -> { val requestId = data[13] val header = CIRetrieval.midiCIGetPropertyHeader(data) responder.processGetPropertyData(Message.GetPropertyData(common, requestId, header)) } CISubId2.PROPERTY_SET_DATA_INQUIRY -> { val requestId = data[13] val header = CIRetrieval.midiCIGetPropertyHeader(data) val numChunks = CIRetrieval.midiCIGetPropertyTotalChunks(data) val chunkIndex = CIRetrieval.midiCIGetPropertyChunkIndex(data) val body = CIRetrieval.midiCIGetPropertyBodyInThisChunk(data) handleChunk(common, requestId, chunkIndex, numChunks, header, body) { wholeHeader, wholeBody -> responder.processSetPropertyData(Message.SetPropertyData(common, requestId, wholeHeader, wholeBody)) } } // CISubId2.PROPERTY_SUBSCRIBE -> implemented earlier // CISubId2.PROPERTY_SUBSCRIBE_REPLY -> implemented earlier // CISubId2.PROPERTY_NOTIFY -> implemented earlier CISubId2.PROCESS_INQUIRY_CAPABILITIES -> { responder.processProcessInquiry(Message.ProcessInquiry(common)) } CISubId2.PROCESS_INQUIRY_MIDI_MESSAGE_REPORT -> { val messageDataControl = data[13] val systemMessages = data[14] // data[15] is reserved val channelControllerMessages = data[16] val noteDataMessages = data[17] responder.processMidiMessageReport(Message.MidiMessageReportInquiry( common, messageDataControl, systemMessages, channelControllerMessages, noteDataMessages)) } else -> { processUnknownCIMessage(common.group, data) } } } }
5
Kotlin
5
53
4f65a0a7749e24facdc29e89a5ea140b32f2a86d
38,382
ktmidi
MIT License
kdb/src/commonMain/kotlin/tk/mallumo/kdb/logger.kt
mallumoSK
310,360,057
false
null
package tk.mallumo.kdb internal expect fun log(data: String, offset: Int = 12) internal inline fun tryPrint(function: () -> Unit) { try { function.invoke() } catch (e: Throwable) { e.printStackTrace() } } internal inline fun tryIgnore(function: () -> Unit) { try { function.invoke() } catch (e: Throwable) { } }
0
Kotlin
0
0
5573ea6ffac276c3de83fac1b038de347eef0e0f
362
kdb
Apache License 2.0
ui/src/main/java/ru/tinkoff/acquiring/sdk/redesign/mainform/MainFormLauncher.kt
itlogic
293,802,517
true
{"Gradle": 12, "Markdown": 4, "INI": 5, "Text": 1, "Shell": 1, "Ignore List": 8, "Batchfile": 1, "Proguard": 3, "XML": 266, "Kotlin": 383, "Java": 1, "JSON": 2, "Java Properties": 1, "YAML": 4}
package ru.tinkoff.acquiring.sdk.redesign.mainform import android.content.Context import android.content.Intent import android.os.Parcelable import androidx.activity.result.contract.ActivityResultContract import androidx.appcompat.app.AppCompatActivity.RESULT_OK import kotlinx.android.parcel.Parcelize import ru.tinkoff.acquiring.sdk.exceptions.AcquiringApiException import ru.tinkoff.acquiring.sdk.models.options.screen.PaymentOptions import ru.tinkoff.acquiring.sdk.redesign.common.LauncherConstants.EXTRA_CARD_ID import ru.tinkoff.acquiring.sdk.redesign.common.LauncherConstants.EXTRA_ERROR import ru.tinkoff.acquiring.sdk.redesign.common.LauncherConstants.EXTRA_PAYMENT_ID import ru.tinkoff.acquiring.sdk.redesign.common.LauncherConstants.EXTRA_REBILL_ID import ru.tinkoff.acquiring.sdk.redesign.common.LauncherConstants.RESULT_ERROR import ru.tinkoff.acquiring.sdk.redesign.common.result.AcqPaymentResult import ru.tinkoff.acquiring.sdk.redesign.mainform.ui.MainPaymentFormActivity import ru.tinkoff.acquiring.sdk.utils.getError object MainFormLauncher { sealed class Result class Success( override val paymentId: Long? = null, override val cardId: String? = null, override val rebillId: String? = null ) : Result(), AcqPaymentResult.Success object Canceled : Result(), AcqPaymentResult.Canceled class Error( override val error: Throwable, override val errorCode: Int? ) : Result(), AcqPaymentResult.Error { constructor(error: AcquiringApiException) : this(error, error.response?.errorCode?.toInt()) } @Parcelize class StartData( val paymentOptions: PaymentOptions, val paymentId: Int? = null ) : Parcelable object Contract : ActivityResultContract<StartData, Result>() { override fun createIntent(context: Context, input: StartData) = MainPaymentFormActivity.intent(input.paymentOptions, context) override fun parseResult(resultCode: Int, intent: Intent?): Result = when (resultCode) { RESULT_OK -> { checkNotNull(intent) Success( intent.getLongExtra(EXTRA_PAYMENT_ID, -1), intent.getStringExtra(EXTRA_CARD_ID), intent.getStringExtra(EXTRA_REBILL_ID), ) } RESULT_ERROR -> { val th = intent.getError() Error(th, (th as? AcquiringApiException)?.response?.errorCode?.toInt()) } else -> Canceled } internal fun createSuccessIntent( paymentId: Long? = null, cardId: String? = null, rebillId: String? = null ): Intent { val intent = Intent() intent.putExtra(EXTRA_PAYMENT_ID, paymentId) intent.putExtra(EXTRA_CARD_ID, cardId) intent.putExtra(EXTRA_REBILL_ID, rebillId) return intent } internal fun createSuccessIntent( success: AcqPaymentResult.Success ) = createSuccessIntent(success.paymentId, success.cardId, success.cardId) internal fun createFailedIntent(throwable: Throwable): Intent { return Intent().putExtra(EXTRA_ERROR, throwable) } internal fun createFailedIntent(error: AcqPaymentResult.Error) = createFailedIntent(error.error) } }
0
Kotlin
0
0
8de009c2ae6ca40843c74799429346fcfa74820c
3,400
AcquiringSdkAndroid
Apache License 2.0
agp-7.1.0-alpha01/tools/base/build-system/gradle-core/src/main/java/com/android/build/api/component/analytics/AnalyticsEnabledApplicationVariantBuilder.kt
jomof
502,039,754
false
{"Java": 35519326, "Kotlin": 22849138, "C++": 2171001, "HTML": 1377915, "Starlark": 915536, "C": 141955, "Shell": 110207, "RenderScript": 58853, "Python": 25635, "CMake": 18109, "Batchfile": 12180, "Perl": 9310, "Dockerfile": 5690, "Makefile": 4535, "CSS": 4148, "JavaScript": 3488, "PureBasic": 2359, "GLSL": 1628, "AIDL": 1117, "Prolog": 277}
/* * Copyright (C) 2020 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.build.api.component.analytics import com.android.build.api.variant.ApplicationVariantBuilder import com.android.build.api.variant.DependenciesInfoBuilder import com.android.tools.build.gradle.internal.profile.VariantMethodType import com.google.wireless.android.sdk.stats.GradleBuildVariant import javax.inject.Inject /** * Shim object for [ApplicationVariantBuilder] that records all mutating accesses to the analytics. */ open class AnalyticsEnabledApplicationVariantBuilder @Inject constructor( override val delegate: ApplicationVariantBuilder, stats: GradleBuildVariant.Builder ) : AnalyticsEnabledVariantBuilder(delegate, stats), ApplicationVariantBuilder { override val debuggable: Boolean get() = delegate.debuggable override val dependenciesInfo: DependenciesInfoBuilder get() { stats.variantApiAccessBuilder.addVariantAccessBuilder().type = VariantMethodType.VARIANT_BUILDER_DEPENDENCIES_INFO_VALUE return delegate.dependenciesInfo } override var androidTestEnabled: Boolean get() = delegate.enableAndroidTest set(value) { stats.variantApiAccessBuilder.addVariantAccessBuilder().type = VariantMethodType.ANDROID_TEST_ENABLED_VALUE delegate.enableAndroidTest = value } override var enableAndroidTest: Boolean get() = delegate.enableAndroidTest set(value) { stats.variantApiAccessBuilder.addVariantAccessBuilder().type = VariantMethodType.ANDROID_TEST_ENABLED_VALUE delegate.enableAndroidTest = value } override var enableTestFixtures: Boolean get() = delegate.enableTestFixtures set(value) { stats.variantApiAccessBuilder.addVariantAccessBuilder().type = VariantMethodType.TEST_FIXTURES_ENABLED_VALUE delegate.enableTestFixtures = value } }
1
Java
1
0
9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51
2,546
CppBuildCacheWorkInProgress
Apache License 2.0
src/main/kotlin/com/immanuelqrw/core/api/FullyUniqueControllable.kt
immanuelqrw
161,011,686
false
null
package com.immanuelqrw.core.api import com.immanuelqrw.core.entity.UniqueEntityable /** * Interface which supports all CRUD actions for unique id entities */ interface FullyUniqueControllable<T : UniqueEntityable> : Postable<T>, UniqueGetable<T>, UniquePutable<T>, UniquePatchable<T>, UniqueDeletable<T>, Countable
0
Kotlin
0
0
08dc61e1503694bd620b8583e60068c020fdf44c
320
Nucleus-API
MIT License
mediator/src/main/kotlin/no/nav/dagpenger/mottak/behov/eksterne/SøknadFaktaQuizLøser.kt
navikt
351,793,236
false
null
package no.nav.dagpenger.mottak.behov.eksterne import com.fasterxml.jackson.databind.JsonNode import de.slub.urn.URN import mu.KotlinLogging import no.nav.dagpenger.mottak.AvsluttetArbeidsforhold import no.nav.dagpenger.mottak.SøknadFakta import no.nav.dagpenger.mottak.avsluttetArbeidsforhold import no.nav.helse.rapids_rivers.JsonMessage import no.nav.helse.rapids_rivers.MessageContext import no.nav.helse.rapids_rivers.RapidsConnection import no.nav.helse.rapids_rivers.River import no.nav.helse.rapids_rivers.asLocalDate import no.nav.helse.rapids_rivers.asLocalDateTime import no.nav.helse.rapids_rivers.withMDC import java.time.LocalDate import java.time.format.DateTimeParseException internal class SøknadFaktaQuizLøser( private val søknadQuizOppslag: SøknadQuizOppslag, rapidsConnection: RapidsConnection ) : River.PacketListener { private companion object { val logger = KotlinLogging.logger { } val sikkerlogg = KotlinLogging.logger("tjenestekall") } private val løserBehov = listOf( "ØnskerDagpengerFraDato", "Søknadstidspunkt", "Verneplikt", "FangstOgFiske", "SisteDagMedArbeidsplikt", "SisteDagMedLønn", "Lærling", "EØSArbeid", "Rettighetstype", "KanJobbeDeltid", "KanJobbeHvorSomHelst", "HelseTilAlleTyperJobb", "VilligTilÅBytteYrke", "FortsattRettKorona", "JobbetUtenforNorge" ) init { River(rapidsConnection).apply { validate { it.demandValue("@event_name", "faktum_svar") } validate { it.demandAllOrAny("@behov", løserBehov) } validate { it.rejectKey("@løsning") } validate { it.requireKey("InnsendtSøknadsId") } validate { it.interestedIn("søknad_uuid", "@id") } }.register(this) } override fun onPacket(packet: JsonMessage, context: MessageContext) { withMDC( mapOf( "søknad_uuid" to packet["søknad_uuid"].asText(), "behovId" to packet["@id"].asText() ) ) { try { val innsendtSøknadsId = packet.getInnsendtSøknadsId() val søknad = søknadQuizOppslag.hentSøknad(innsendtSøknadsId) packet["@løsning"] = packet["@behov"].map { it.asText() }.filter { it in løserBehov }.map { behov -> behov to when (behov) { "ØnskerDagpengerFraDato" -> søknad.ønskerDagpengerFraDato() "Søknadstidspunkt" -> søknad.søknadstidspunkt() "Verneplikt" -> søknad.verneplikt() "FangstOgFiske" -> søknad.fangstOgFisk() "EØSArbeid" -> søknad.harJobbetIeøsOmråde() "SisteDagMedArbeidsplikt" -> søknad.sisteDagMedLønnEllerArbeidsplikt() "SisteDagMedLønn" -> søknad.sisteDagMedLønnEllerArbeidsplikt() "Lærling" -> søknad.lærling() "Rettighetstype" -> søknad.rettighetstypeUtregning() "KanJobbeDeltid" -> søknad.kanJobbeDeltid() "KanJobbeHvorSomHelst" -> søknad.kanJobbeHvorSomHelst() "HelseTilAlleTyperJobb" -> søknad.helseTilAlleTyperJobb() "VilligTilÅBytteYrke" -> søknad.villigTilÅBytteYrke() "FortsattRettKorona" -> søknad.fortsattRettKorona() "JobbetUtenforNorge" -> søknad.jobbetUtenforNorge() else -> throw IllegalArgumentException("Ukjent behov $behov") } }.toMap() context.publish(packet.toJson()) logger.info("løste søknadfakta-behov for innsendt søknad med id $innsendtSøknadsId") } catch (e: Exception) { // midlertig til vi klarer å nøste opp i det som faktisk får dette til å kræsje logger.error(e) { "feil ved søknadfakta-behov" } sikkerlogg.error(e) { "feil ved søknadfakta-behov. \n packet: ${packet.toJson()}" } } } } } private fun JsonMessage.getInnsendtSøknadsId(): String { return this["InnsendtSøknadsId"]["urn"] .asText() .let { URN.rfc8141().parse(it) } .namespaceSpecificString() .toString() } private fun SøknadFakta.sisteDagMedLønnEllerArbeidsplikt(): LocalDate { if (getFakta("arbeidsforhold").isEmpty()) return getFakta("arbeidsforhold.datodagpenger").first()["value"].asLocalDate() return when (avsluttetArbeidsforhold().first().sluttårsak) { AvsluttetArbeidsforhold.Sluttårsak.ARBEIDSGIVER_KONKURS -> sisteDagMedLønnKonkurs() else -> sisteDagMedLønnEllerArbeidspliktResten() } } private fun SøknadFakta.sisteDagMedLønnKonkurs(): LocalDate { return getFakta("arbeidsforhold").first().let { localDateEllerNull(it["properties"]["lonnkonkursmaaned_dato"]) ?: it["properties"]["konkursdato"].asLocalDate() } } // Varighet på arbeidsforholdet (til dato) ?: Lønnspliktperiode for arbeidsgiver (til dato) ?: Arbeidstid redusert fra ?: Permitteringsperiode (fra dato) private fun SøknadFakta.sisteDagMedLønnEllerArbeidspliktResten(): LocalDate { return getFakta("arbeidsforhold").first().let { localDateEllerNull(it["properties"]["datotil"]) ?: localDateEllerNull(it["properties"]["lonnspliktigperiodedatotil"]) ?: localDateEllerNull(it["properties"]["redusertfra"]) ?: getFakta("arbeidsforhold.permitteringsperiode") .first()["properties"]["permiteringsperiodedatofra"].asLocalDate() } } private fun localDateEllerNull(jsonNode: JsonNode?): LocalDate? = jsonNode?.let { try { LocalDate.parse(jsonNode.asText()) } catch (e: DateTimeParseException) { // Optional datoer får noen ganger verdi “NaN-aN-aN” null } } private fun SøknadFakta.lærling() = getFakta("arbeidsforhold").any { it["properties"]?.get("laerling")?.asBoolean() ?: false } private fun SøknadFakta.søknadstidspunkt() = getFakta("innsendtDato").first()["value"].asLocalDateTime().toLocalDate() private fun SøknadFakta.ønskerDagpengerFraDato() = getFakta("arbeidsforhold.datodagpenger").first()["value"].asLocalDate() private fun SøknadFakta.verneplikt() = getBooleanFaktum("ikkeavtjentverneplikt", true).not() // omvendt logikk i søknad; verdi == true --> søker har ikke inntekt fra fangst og fisk private fun SøknadFakta.fangstOgFisk() = getBooleanFaktum("egennaering.fangstogfiske").not() // omvendt logikk i søknad; verdi == true --> søker har ikke jobbet i EØS området private fun SøknadFakta.harJobbetIeøsOmråde() = getBooleanFaktum("eosarbeidsforhold.jobbetieos", true).not() private fun SøknadFakta.jobbetUtenforNorge() = this.avsluttetArbeidsforhold().any { it.land != "NOR" } private fun SøknadFakta.fortsattRettKorona() = getBooleanFaktum("fornyetrett.bruktopp").not() private fun SøknadFakta.rettighetstypeUtregning(): List<Map<String, Boolean>> = rettighetstypeUtregning(this.avsluttetArbeidsforhold()) private fun SøknadFakta.kanJobbeDeltid() = getBooleanFaktum("reellarbeidssoker.villigdeltid") private fun SøknadFakta.kanJobbeHvorSomHelst() = getBooleanFaktum("reellarbeidssoker.villigpendle") private fun SøknadFakta.helseTilAlleTyperJobb() = getBooleanFaktum("reellarbeidssoker.villighelse") private fun SøknadFakta.villigTilÅBytteYrke() = getBooleanFaktum("reellarbeidssoker.villigjobb") internal fun rettighetstypeUtregning(avsluttedeArbeidsforhold: List<AvsluttetArbeidsforhold>) = avsluttedeArbeidsforhold.map { mapOf( "Lønnsgaranti" to (it.sluttårsak == AvsluttetArbeidsforhold.Sluttårsak.ARBEIDSGIVER_KONKURS), "PermittertFiskeforedling" to (it.fiskeforedling), "Permittert" to (it.sluttårsak == AvsluttetArbeidsforhold.Sluttårsak.PERMITTERT && !it.fiskeforedling), "Ordinær" to ( it.sluttårsak != AvsluttetArbeidsforhold.Sluttårsak.PERMITTERT && it.sluttårsak != AvsluttetArbeidsforhold.Sluttårsak.ARBEIDSGIVER_KONKURS && !it.fiskeforedling ) ) }
0
Kotlin
0
0
8418dbb025414654794336dac377fb89df378f3a
8,287
dp-mottak
MIT License
src/commonMain/kotlin/com.github.florent37/log/Logger.kt
florent37
156,610,018
false
null
package com.sto.kn.lib expect class PlatformLogger() { var enabled: Boolean fun logDebug(tag: String, message: String) fun logError(tag: String, message: String) fun logError(tag: String, message: String, exception: Throwable) } object Logger { private val platformLogger = PlatformLogger() var enabled get() = platformLogger.enabled set(value) { platformLogger.enabled = value } fun d(tag: String, message: String){ platformLogger.logDebug(tag, message) } fun e(tag: String, message: String, exception: Throwable? = null){ exception?.let { platformLogger.logError(tag, message, exception) } ?: run { platformLogger.logError(tag, message) } } }
3
Kotlin
6
49
6edbaae29521da74578141628ef67763aee77633
784
Multiplatform-Log
Apache License 2.0
app/src/main/java/dev/jatzuk/snowwallpaper/ui/imagepicker/viewpager/pagetransformers/ZoomOutPageTransformer.kt
jatzuk
226,588,177
false
null
package dev.jatzuk.snowwallpaper.ui.imagepicker.viewpager.pagetransformers import android.view.View import androidx.viewpager2.widget.ViewPager2 import kotlin.math.abs import kotlin.math.max private const val MIN_SCALE = 0.85f private const val MIN_ALPHA = 0.5f class ZoomOutPageTransformer : ViewPager2.PageTransformer { override fun transformPage(view: View, position: Float) { view.apply { val pageWidth = width val pageHeight = height when { position < -1 -> alpha = 0f position <= 1 -> { val scaleFactor = max(MIN_SCALE, 1 - abs(position)) val verticalMargin = pageHeight * (1 - scaleFactor) / 2 val horizontalMargin = pageWidth * (1 - scaleFactor) / 2 translationX = if (position < 0) horizontalMargin - verticalMargin / 2 else horizontalMargin + verticalMargin / 2 scaleX = scaleFactor scaleY = scaleFactor alpha = (MIN_ALPHA + (((scaleFactor - MIN_SCALE) / (1 - MIN_SCALE)) * (1 - MIN_ALPHA))) } else -> alpha = 0f } } } }
0
Kotlin
2
0
d44778249bd7a6a12931331aadbd08b6806d4397
1,289
SnowWallpaper
Apache License 2.0
packages/android/app/src/main/java/bible/instant/ui/main/VerseResultAdapter.kt
knpwrs
209,888,824
false
null
package bible.instant.ui.main import android.content.Context import android.content.Intent import android.os.Build import android.text.Spannable import android.text.SpannableStringBuilder import android.text.Spanned import android.text.style.ImageSpan import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.LinearLayout import android.widget.TextView import androidx.core.content.ContextCompat import androidx.core.text.HtmlCompat import androidx.recyclerview.widget.RecyclerView import bible.instant.R import bible.instant.getBookName import bible.instant.getTranslationLabel import instantbible.data.Data import instantbible.service.Service class VerseResultViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val verseRoot: LinearLayout = itemView.findViewById(R.id.verse_root) val verseTitle: TextView = itemView.findViewById(R.id.verse_title) val verseText: TextView = itemView.findViewById(R.id.verse_text) val translationsHolder: LinearLayout = itemView.findViewById(R.id.translations) var copyText = "" } class CopyrightViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) class VerseResultAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() { companion object { const val VERSE_VIEW: Int = 1 const val COPYRIGHT_VIEW: Int = 2 } var data = listOf<Service.Response.VerseResult>() set(value) { field = value notifyDataSetChanged() } override fun getItemCount(): Int { return if (data.isNotEmpty()) { data.size + 1 // Add one for copyrights view } else { 0 } } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { if (position <= data.lastIndex) { bindVerseViewHolder(position, holder as VerseResultViewHolder) } } private fun bindVerseViewHolder( position: Int, holder: VerseResultViewHolder ) { val item = data[position] holder.verseTitle.text = getTitle(item) holder.verseText.text = getHighlightedText(holder.verseText.context, item) holder.copyText = getCopyText(item) for (t in 0 until holder.translationsHolder.childCount) { val btn = holder.translationsHolder.getChildAt(t) as Button setButtonStyle( btn, if (t == item.topTranslationValue) { R.style.ibButtonBold } else { R.style.ibButton } ) } for (t in 0 until holder.translationsHolder.childCount) { val btn = holder.translationsHolder.getChildAt(t) as Button btn.setOnClickListener { holder.verseText.text = getHighlightedText(holder.verseText.context, item, t) holder.copyText = getCopyText(item, t) for (t in 0 until holder.translationsHolder.childCount) { setButtonStyle( holder.translationsHolder.getChildAt(t) as Button, R.style.ibButton ); } setButtonStyle(btn, R.style.ibButtonBold) } } holder.verseRoot.setOnLongClickListener { val sendIntent: Intent = Intent().apply { action = Intent.ACTION_SEND putExtra(Intent.EXTRA_TEXT, holder.copyText) type = "text/plain" } val shareIntent = Intent.createChooser(sendIntent, null) holder.verseRoot.context.startActivity(shareIntent) true } } private fun getTitle(item: Service.Response.VerseResult) = "${getBookName(item.key.book)} ${item.key.chapter}:${item.key.verse}" private fun getText(item: Service.Response.VerseResult, idx: Int = item.topTranslationValue) = item.getText(idx) private fun getCopyText( item: Service.Response.VerseResult, translationId: Int = item.topTranslationValue ) = "${getTitle(item)} ${getTranslationLabel(translationId)}\n${getText(item, translationId)}" private fun getHighlightedText( context: Context, item: Service.Response.VerseResult, idx: Int = item.topTranslationValue ): Spanned { val text = item.getText(idx) if (text.isEmpty()) { return getMissingText(context, getTranslationLabel(idx)) } return HtmlCompat.fromHtml( item.highlightsList.fold( item.getText(idx), { text, word -> word.toRegex(RegexOption.IGNORE_CASE).replace(text) { "<b><font color='${ContextCompat.getColor( context, R.color.ibTextHighlight )}' >${it.value}</font></b>" } }), HtmlCompat.FROM_HTML_MODE_LEGACY ) } private fun getMissingText( context: Context, translation: String ): Spanned { val ssb = SpannableStringBuilder(" This verse is not available in the $translation translation") ssb.setSpan( ImageSpan(context, R.drawable.ic_fa_dove_solid), 0, 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE ) return ssb } override fun getItemViewType(position: Int): Int { return if (position > 0 && position > data.lastIndex) { COPYRIGHT_VIEW } else { VERSE_VIEW } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { return if (viewType == VERSE_VIEW) { createVerseResultViewHolder(parent) } else { createCopyrightViewHolder(parent) } } private fun createVerseResultViewHolder(parent: ViewGroup): VerseResultViewHolder { val layoutInflater = LayoutInflater.from(parent.context) val view = layoutInflater.inflate(R.layout.verse_result_view, parent, false) val translationsHolder: LinearLayout = view.findViewById(R.id.translations) for (t in 0 until Data.Translation.TOTAL_VALUE) { val btn = Button(view.context) btn.text = getTranslationLabel(t) setButtonStyle(btn, R.style.ibButton) btn.background = null btn.minWidth = 0 btn.minimumWidth = 0 btn.minHeight = 0 btn.minimumHeight = 0 btn.setPadding(0, 0, 0, 0) val marginParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT ); marginParams.setMargins(0, 0, 10, 0); btn.layoutParams = marginParams; btn.setTag(R.string.translation_tag, t) translationsHolder.addView(btn) } return VerseResultViewHolder(view) } private fun createCopyrightViewHolder(parent: ViewGroup): CopyrightViewHolder { val layoutInflater = LayoutInflater.from(parent.context) val view = layoutInflater.inflate(R.layout.copyright_view, parent, false) return CopyrightViewHolder(view) } private fun setButtonStyle(btn: Button, style: Int) { if (Build.VERSION.SDK_INT < 23) { btn.setTextAppearance(btn.context, style) } else { btn.setTextAppearance(style) } } }
27
TypeScript
1
12
1fbad67792f448a7f87dcd3cfa6f3fa65526be08
7,664
instant.bible
MIT License
app/src/main/java/xyz/codegeek/outbreakvisualizer/Di/apiModule.kt
rock16
253,742,097
false
null
package xyz.codegeek.outbreakvisualizer.Di import okhttp3.OkHttpClient import org.koin.dsl.module import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import xyz.codegeek.outbreakvisualizer.api.Cov19Service val apiModule = module (override = true) { single { provideOkhttpClient() } single { provideRetrofit(get()) } single { provideService(get()) } } fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit { return Retrofit.Builder().baseUrl(Cov19Service.ENDPOINT).client(okHttpClient) .addConverterFactory(GsonConverterFactory.create()).build() } fun provideOkhttpClient(): OkHttpClient { return OkHttpClient().newBuilder().build() } fun provideService(retrofit: Retrofit): Cov19Service = retrofit.create(Cov19Service::class.java)
0
Kotlin
0
0
f6956a75225592a35d57fe2d518305cf0d3f61fb
794
Covid-19-Tracker
Apache License 2.0
app/src/main/java/com/wechantloup/side/dagger/components/ApplicationComponent.kt
Pilou44
187,889,252
false
null
package com.wechantloup.side.dagger.components import android.app.Application import com.wechantloup.side.dagger.modules.ActivityBuilder import com.wechantloup.side.dagger.modules.ApplicationModule import com.wechantloup.side.dagger.modules.InternetModule import com.wechantloup.side.modules.MyApplication import dagger.BindsInstance import dagger.Component import dagger.android.AndroidInjector import dagger.android.support.AndroidSupportInjectionModule import dagger.android.support.DaggerApplication import javax.inject.Singleton @Singleton @Component(modules = [AndroidSupportInjectionModule::class, ApplicationModule::class, InternetModule::class, ActivityBuilder::class]) interface ApplicationComponent : AndroidInjector<DaggerApplication> { @Component.Builder interface Builder { @BindsInstance fun application(application: Application): Builder fun applicationModule(applicationModule: ApplicationModule): Builder fun build(): ApplicationComponent } fun inject(target: MyApplication) class Initializer private constructor() { companion object { fun init(application: Application): ApplicationComponent { return DaggerApplicationComponent.builder() .application(application) .applicationModule(ApplicationModule(application)) .build() } } } }
0
Kotlin
0
0
0bae574d1c95ec8c0e72435a0d74d07e011203b7
1,431
side
Apache License 2.0
app/src/main/java/com/battagliandrea/covid19/ui/dailycases/DailyCasesAdapter.kt
battagliandrea
259,086,086
false
null
package com.battagliandrea.covid19.ui.dailycases import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.battagliandrea.covid19.R import com.battagliandrea.covid19.ui.items.base.ListItem import com.battagliandrea.covid19.ui.items.caseitem.CaseItem import com.battagliandrea.covid19.ui.items.lodingitem.LoadingItem import com.battagliandrea.covid19.ui.items.caseitem.CaseItemVH import com.battagliandrea.covid19.ui.items.lodingitem.LoadingItemVH import javax.inject.Inject class DailyCasesAdapter @Inject constructor() : RecyclerView.Adapter<RecyclerView.ViewHolder>() { companion object{ const val TYPE_LOADING = 0 const val TYPE_DEFAULT = 1 } // var onItemClickListener: OnItemClickListener? = null private var data: MutableList<ListItem> = mutableListOf() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { return when(viewType){ TYPE_DEFAULT -> { val view = LayoutInflater.from(parent.context).inflate(R.layout.view_case_horizontal_item, parent, false) CaseItemVH(view) } TYPE_LOADING -> { val view = LayoutInflater.from(parent.context).inflate(R.layout.view_loading_item, parent, false) LoadingItemVH( view ) } else -> { throw RuntimeException("No supported viewType") } } } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { when(getItemViewType(position)){ TYPE_DEFAULT -> (holder as CaseItemVH).render(data[position] as CaseItem) TYPE_LOADING -> (holder as LoadingItemVH).render(data[position] as LoadingItem) else -> { throw RuntimeException("No supported viewType") } } } override fun getItemCount(): Int { return data.size } override fun getItemId(position: Int): Long { return data[position].id.hashCode().toLong() } override fun getItemViewType(position: Int): Int { return when(data[position]){ is LoadingItem -> TYPE_LOADING is CaseItem -> TYPE_DEFAULT else -> -1 } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // UTILS //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// fun updateList(data: List<ListItem>){ if(this.data != data){ // val diffCallback = BeersDiffUtils(this.data, data) // val diffResult = DiffUtil.calculateDiff(diffCallback) this.data.clear() this.data.addAll(data) // diffResult.dispatchUpdatesTo(this) notifyDataSetChanged() } } }
0
Kotlin
0
1
145434b1ac9ab02164402ca9705250020c4b8276
2,991
Covid-19
Apache License 2.0
AndroidContactExample/app/src/main/java/com/waynestalk/contactexample/contact/ContactEmail.kt
xhhuango
262,588,464
false
{"Jupyter Notebook": 49573021, "Kotlin": 265587, "Swift": 163046, "TypeScript": 14366, "Go": 8073, "Shell": 4571, "JavaScript": 3704, "HTML": 3547, "Ruby": 1806, "Objective-C": 908, "SCSS": 80, "CSS": 25}
package com.waynestalk.contactexample.contact data class ContactEmail( val id: Long, val email: String, val type: Int, )
0
Jupyter Notebook
19
24
c2702503ff55f221a58d6b384d87d8d12cb0be12
134
waynestalk
MIT License
src/main/kotlin/com/github/thibseisel/diff/myers/PathNode.kt
thibseisel
329,431,410
false
null
package com.github.thibseisel.diff.myers internal class PathNode( /** * Position in the original sequence. */ val i: Int, /** * Position in the revised sequence. */ val j: Int, val snake: Boolean, /** * Whether this is a bootstrap node. * Bootstrap nodes have one of their two coordinates less than zero. */ val bootstrap: Boolean, /** * The previous node in the path. */ val prev: PathNode? ) { /** * Skips sequences of [PathNode]s until a snake or bootstrap node is found, or the end of the path is reached. * @return The next first [PathNode] or bootstrap node in the path, or `null` if none found. */ fun previousSnake(): PathNode? = when { bootstrap -> null !snake && prev != null -> prev.previousSnake() else -> this } override fun toString(): String = buildString { append('[') var node: PathNode? = this@PathNode while (node != null) { append('(') append(node.i) append(',') append(node.j) append(')') node = node.prev } append(']') } }
0
Kotlin
0
0
aae1e13aac0c19b86855c4ba7eaa238f9681b867
1,203
kotlin-diff
Apache License 2.0
app/src/main/java/com/github/corentinc/notificoin/MainApplication.kt
corentin-c
235,539,306
false
null
package com.github.corentinc.notificoin import android.app.Application import com.github.corentinc.logger.NotifiCoinLogger import com.github.corentinc.notificoin.injection.* import org.koin.android.ext.koin.androidContext import org.koin.android.ext.koin.androidLogger import org.koin.androidx.fragment.koin.fragmentFactory import org.koin.core.context.startKoin class MainApplication : Application() { override fun onCreate() { super.onCreate() try { startKoin { androidLogger() fragmentFactory() androidContext(this@MainApplication) modules( listOf( fragmentModule, homeModule, databaseModule, adModule, searchModule, webPageModule, notificationModule, alarmManagerModule, searchAdsPositionModule, detectNewAdsModule, sharedPreferencesModule, adListModule, editSearchModule, searchesRecyclerViewModule, searchPositionModule, settingsModule, batteryWarningModule ) ) } } catch (exception: IllegalStateException) { NotifiCoinLogger.i(this.applicationContext.resources.getString(R.string.koinAlreadyStarted)) } } }
0
Kotlin
0
1
47ec5cbe754c9cae371546e08d74b43b20644cb0
1,620
notificoin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaximumSubsequenceScore.kt
ashtanko
203,993,092
false
null
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.PriorityQueue import kotlin.math.max /** * 2542. Maximum Subsequence Score * @see <a href="https://leetcode.com/problems/maximum-subsequence-score/">leetcode page</a> */ fun interface MaximumSubsequenceScore { fun maxScore(nums1: IntArray, nums2: IntArray, k: Int): Long } /** * Approach: Priority Queue */ class MaximumSubsequenceScorePQ : MaximumSubsequenceScore { override fun maxScore(nums1: IntArray, nums2: IntArray, k: Int): Long { // Sort pair (nums1[i], nums2[i]) by nums2[i] in decreasing order. val n: Int = nums1.size val pairs = Array(n) { IntArray(2) } for (i in 0 until n) { pairs[i] = intArrayOf(nums1[i], nums2[i]) } pairs.sortWith { a: IntArray, b: IntArray -> b[1] - a[1] } // Use a min-heap to maintain the top k elements. val topKHeap: PriorityQueue<Int> = PriorityQueue(k) { a, b -> a - b } var topKSum: Long = 0 for (i in 0 until k) { topKSum += pairs[i][0].toLong() topKHeap.add(pairs[i][0]) } // The score of the first k pairs. var answer = topKSum * pairs[k - 1][1] // Iterate over every nums2[i] as minimum from nums2. for (i in k until n) { // Remove the smallest integer from the previous top k elements // then ddd nums1[i] to the top k elements. topKSum += pairs[i][0] - topKHeap.poll() topKHeap.add(pairs[i][0]) // Update answer as the maximum score. answer = max(answer, topKSum * pairs[i][1]) } return answer } }
6
null
0
19
c6e2befdce892e9f2caf1d98f54dc1dd9b2c89ba
2,264
kotlab
Apache License 2.0
executor/invoker/src/commonMain/kotlin/io/github/charlietap/chasm/executor/invoker/instruction/memory/load/LoadSizedUnsignedNumberValueExecutorImpl.kt
CharlieTap
743,980,037
false
{"Kotlin": 898736, "WebAssembly": 7119}
@file:Suppress("NOTHING_TO_INLINE") package io.github.charlietap.chasm.executor.invoker.instruction.memory.load import com.github.michaelbull.result.Result import com.github.michaelbull.result.binding import io.github.charlietap.chasm.ast.instruction.MemArg import io.github.charlietap.chasm.executor.invoker.ext.peekFrameOrError import io.github.charlietap.chasm.executor.invoker.ext.popI32 import io.github.charlietap.chasm.executor.runtime.Stack import io.github.charlietap.chasm.executor.runtime.error.InvocationError import io.github.charlietap.chasm.executor.runtime.store.Store import io.github.charlietap.chasm.executor.runtime.value.NumberValue internal inline fun <S, U> LoadSizedUnsignedNumberValueExecutorImpl( store: Store, stack: Stack, memArg: MemArg, sizeInBytes: Int, crossinline reader: SizedNumberValueReader<U>, crossinline transformer: (U) -> S, crossinline constructor: (S) -> NumberValue<S>, ): Result<Unit, InvocationError> = binding { val frame = stack.peekFrameOrError().bind() val memoryAddress = frame.state.module.memoryAddress(0).bind() val memory = store.memory(memoryAddress).bind() val baseAddress = stack.popI32().bind() val effectiveAddress = baseAddress + memArg.offset.toInt() val result = reader(memory.data, effectiveAddress, sizeInBytes).bind() val value = constructor(transformer(result)) stack.push(Stack.Entry.Value(value)) }
2
Kotlin
1
16
1566c1b504b4e0a31ae5008f5ada463c47de71c5
1,436
chasm
Apache License 2.0
app/src/main/java/com/arcadone/pokestorie/composables/LoadingContent.kt
ArcaDone
804,002,329
false
{"Kotlin": 88338}
package com.arcadone.pokestorie.composables import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import com.arcadone.pokestorie.ui.theme.PokeStorieAppTheme @Composable fun LoadingContent() { Box( modifier = Modifier .fillMaxSize(), contentAlignment = Alignment.Center ) { ImageGIF() } } @Preview @Composable private fun Preview() { PokeStorieAppTheme { LoadingContent() } }
0
Kotlin
0
0
b5cdf21b656222931531755081f9a5a68ea7ceb1
654
pokeStorie
MIT License
kotlin-remix-run-router/src/jsMain/generated/remix/run/router/LazyRouteFunction.kt
JetBrains
93,250,841
false
{"Kotlin": 11411371, "JavaScript": 154302}
package remix.run.router import js.promise.Promise /** * lazy() function to load a route definition, which can add non-matching * related properties to a route */ typealias LazyRouteFunction<R /* : AgnosticRouteObject */> = () -> Promise<R>
28
Kotlin
173
1,250
9e9dda28cf74f68b42a712c27f2e97d63af17628
246
kotlin-wrappers
Apache License 2.0
app/src/main/java/br/edu/puccampinas/pi3/PerfilActivity.kt
Jean2505
619,002,734
false
null
package br.edu.puccampinas.pi3 import android.content.Intent import android.content.res.ColorStateList import android.graphics.BitmapFactory import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.MotionEvent import android.widget.Button import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts import androidx.core.content.ContextCompat import androidx.core.net.toUri import br.edu.puccampinas.pi3.databinding.ActivityPerfilBinding import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.ktx.auth import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.ktx.Firebase import com.google.firebase.storage.ktx.storage import com.squareup.picasso.Picasso import de.hdodenhof.circleimageview.CircleImageView import java.io.File class PerfilActivity : AppCompatActivity() { private var db = FirebaseFirestore.getInstance() private lateinit var email: String private lateinit var binding: ActivityPerfilBinding private val user = Firebase.auth.currentUser private lateinit var imgDentista: CircleImageView private lateinit var auth: FirebaseAuth private lateinit var btnFoto: Button private val cameraProviderResult = registerForActivityResult(ActivityResultContracts.RequestPermission()){ if(it){ abrirTelaDePreview() }else{ Toast.makeText(this, "Você precisa permitir o uso da câmera!", Toast.LENGTH_SHORT).show() } } private val storageresult = registerForActivityResult(ActivityResultContracts.RequestPermission()){ if(it){ Toast.makeText(this, "vou chorar", Toast.LENGTH_LONG).show() }else{ Toast.makeText(this, "Você precisa permitir o uso da câmera!", Toast.LENGTH_SHORT).show() } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_perfil) binding = ActivityPerfilBinding.inflate(layoutInflater) setContentView(binding.root) binding.btnFoto.setOnClickListener { println("AAAAAAAAAAAAAAAAAA") storageresult.launch(android.Manifest.permission.READ_EXTERNAL_STORAGE) cameraProviderResult.launch(android.Manifest.permission.CAMERA) } btnFoto = findViewById(R.id.btnFoto) auth = Firebase.auth binding.btnDeslogar.setOnClickListener { Firebase.auth.signOut() val iLogin = Intent(this, LoginActivity::class.java) startActivity(iLogin) } binding.scSwitch.setOnCheckedChangeListener{ buttonView, isChecked -> attStatus(isChecked) if(isChecked) { binding.tvStatus.text = "Disponível" }else{ binding.tvStatus.text = "Ocupado" } } binding.btnVoltar.setOnClickListener{ if(intent.getStringExtra("foto") == "sim"){ val iVolta = Intent(this, EmergenciasActivity::class.java) startActivity(iVolta) } else { this.finish() } //val intent = Intent(this, EmergenciasActivity::class.java) //this.startActivity(intent) } binding.btnEdit.setOnClickListener{ val newbackground = R.drawable.boxedit val corIcone = ContextCompat.getColor(this, R.color.azulescuro) binding.etCv.setBackgroundResource(newbackground) binding.etNome.setBackgroundResource(newbackground) binding.etEmail.setBackgroundResource(newbackground) binding.etTelef.setBackgroundResource(newbackground) binding.etSenha.setBackgroundResource(newbackground) binding.etEnd1.setBackgroundResource(newbackground) binding.etEnd2.setBackgroundResource(newbackground) binding.etEnd3.setBackgroundResource(newbackground) binding.etCv.compoundDrawableTintList = ColorStateList.valueOf(corIcone) binding.etNome.compoundDrawableTintList = ColorStateList.valueOf(corIcone) binding.etTelef.compoundDrawableTintList = ColorStateList.valueOf(corIcone) binding.etEmail.compoundDrawableTintList = ColorStateList.valueOf(corIcone) binding.etSenha.compoundDrawableTintList = ColorStateList.valueOf(corIcone) binding.etEnd1.compoundDrawableTintList = ColorStateList.valueOf(corIcone) binding.etEnd2.compoundDrawableTintList = ColorStateList.valueOf(corIcone) binding.etEnd3.compoundDrawableTintList = ColorStateList.valueOf(corIcone) binding.etEmail.isEnabled = true binding.btnConcEmail.isEnabled = true binding.etSenha.text = null binding.etSenha.isEnabled = true binding.btnConcSenha.isEnabled = true binding.etNome.isEnabled = true binding.btnConcNome.isEnabled = true binding.etTelef.isEnabled = true binding.btnConcTelef.isEnabled = true binding.etEnd1.isEnabled = true binding.btnConcEnd1.isEnabled = true binding.etEnd2.isEnabled = true binding.btnConcEnd2.isEnabled = true binding.etEnd3.isEnabled = true binding.btnConcEnd3.isEnabled = true binding.etCv.isEnabled = true binding.btnConcCv.isEnabled = true } binding.btnConcEmail.setOnClickListener{ val newbackground = R.drawable.textbox val corIcone = ContextCompat.getColor(this, R.color.azulclaro) binding.etEmail.setBackgroundResource(newbackground) binding.etEmail.compoundDrawableTintList = ColorStateList.valueOf(corIcone) if(intent.getStringExtra("email") != null){ //email = intent.getStringExtra("email")!! email = user!!.email.toString() Toast.makeText(this, email, Toast.LENGTH_SHORT).show() } db.collection("dentistas").whereEqualTo("email", email) .get() .addOnSuccessListener { documents -> for(document in documents) { db.collection("dentistas").document(document.id) .update("email", binding.etEmail.text.toString()) } } user!!.updateEmail(binding.etEmail.text.toString()) .addOnCompleteListener { task -> if (task.isSuccessful) { Toast.makeText(this, "Email Atualizado", Toast.LENGTH_SHORT).show() } else{ Toast.makeText(this, "Para alterar seu email, faça o login novamente!", Toast.LENGTH_LONG).show() Firebase.auth.signOut() val iRelog = Intent(this, LoginActivity::class.java) this.startActivity(iRelog) } } } binding.btnConcSenha.setOnClickListener{ val newbackground = R.drawable.textbox val corIcone = ContextCompat.getColor(this, R.color.azulclaro) binding.etSenha.setBackgroundResource(newbackground) binding.etSenha.compoundDrawableTintList = ColorStateList.valueOf(corIcone) user!!.updatePassword(binding.etSenha.text.toString()) .addOnCompleteListener { task -> if (task.isSuccessful) { Toast.makeText(this, "Senha Atualizada", Toast.LENGTH_SHORT).show() } else{ Toast.makeText(this, "Para alterar sua senha, faça o login novamente!", Toast.LENGTH_LONG).show() Firebase.auth.signOut() val iRelog = Intent(this, LoginActivity::class.java) this.startActivity(iRelog) } } } binding.btnConcNome.setOnClickListener{ val newbackground = R.drawable.textbox val corIcone = ContextCompat.getColor(this, R.color.azulclaro) binding.etNome.setBackgroundResource(newbackground) binding.etNome.compoundDrawableTintList = ColorStateList.valueOf(corIcone) db.collection("dentistas").whereEqualTo("email", user!!.email) .get() .addOnSuccessListener { documents -> for(document in documents) { db.collection("dentistas").document(document.id) .update("name", binding.etNome.text.toString()) } } } binding.btnConcTelef.setOnClickListener{ val newbackground = R.drawable.textbox val corIcone = ContextCompat.getColor(this, R.color.azulclaro) binding.etTelef.setBackgroundResource(newbackground) binding.etTelef.compoundDrawableTintList = ColorStateList.valueOf(corIcone) db.collection("dentistas").whereEqualTo("email", user!!.email) .get() .addOnSuccessListener { documents -> for(document in documents) { db.collection("dentistas").document(document.id) .update("telefone", binding.etTelef.text.toString()) } } } binding.btnConcEnd1.setOnClickListener{ val newbackground = R.drawable.textbox val corIcone = ContextCompat.getColor(this, R.color.azulclaro) binding.etEnd1.setBackgroundResource(newbackground) binding.etEnd1.compoundDrawableTintList = ColorStateList.valueOf(corIcone) db.collection("dentistas").whereEqualTo("email", user!!.email) .get() .addOnSuccessListener { documents -> for(document in documents) { db.collection("dentistas").document(document.id) .update("end1", binding.etEnd1.text.toString()) } } } binding.btnConcEnd2.setOnClickListener{ val newbackground = R.drawable.textbox val corIcone = ContextCompat.getColor(this, R.color.azulclaro) binding.etEnd2.setBackgroundResource(newbackground) binding.etEnd2.compoundDrawableTintList = ColorStateList.valueOf(corIcone) db.collection("dentistas").whereEqualTo("email", user!!.email) .get() .addOnSuccessListener { documents -> for(document in documents) { db.collection("dentistas").document(document.id) .update("end2", binding.etEnd2.text.toString()) } } } binding.btnConcEnd3.setOnClickListener{ val newbackground = R.drawable.textbox val corIcone = ContextCompat.getColor(this, R.color.azulclaro) binding.etEnd3.setBackgroundResource(newbackground) binding.etEnd3.compoundDrawableTintList = ColorStateList.valueOf(corIcone) db.collection("dentistas").whereEqualTo("email", user!!.email) .get() .addOnSuccessListener { documents -> for(document in documents) { db.collection("dentistas").document(document.id) .update("end3", binding.etEnd3.text.toString()) } } } binding.btnConcCv.setOnClickListener{ val newbackground = R.drawable.textbox val corIcone = ContextCompat.getColor(this, R.color.azulclaro) binding.etCv.setBackgroundResource(newbackground) binding.etCv.compoundDrawableTintList = ColorStateList.valueOf(corIcone) db.collection("dentistas").whereEqualTo("email", user!!.email) .get() .addOnSuccessListener { documents -> for(document in documents) { db.collection("dentistas").document(document.id) .update("cv", binding.etCv.text.toString()) } } } binding.etCv.setOnClickListener{ binding.etCv.hint = null } } private fun attStatus(status: Boolean) { db.collection("dentistas").whereEqualTo("email", user!!.email) .get() .addOnSuccessListener { documents -> for(document in documents) { db.collection("dentistas").document(document.id) .update("status", status) } } } public override fun onStart() { super.onStart() binding.etEmail.hint = user!!.email if(intent.getStringExtra("fotoPerfil") != null){ val img = intent.getStringExtra("fotoPerfil")?.let { File(it) } Picasso.with(this).load("file:" + img!!.absolutePath).fit().centerInside().into(binding.imgDentista); enviarFoto() } else{ db.collection("dentistas").whereEqualTo("email",user!!.email).get() .addOnSuccessListener { documents -> for(document in documents){ val foto = document["foto"] val storage = Firebase.storage val storageRef1 = storage.getReferenceFromUrl(foto.toString()) val localFile1 = File.createTempFile("images","jpg") storageRef1.getFile(localFile1).addOnSuccessListener { // Local temp file has been created val bitmap = BitmapFactory.decodeFile(localFile1.absolutePath) Picasso.with(this).load("file:" + localFile1.absolutePath).fit().centerInside().into(binding.imgDentista) //Picasso.with(this).load("file:" + localFile1.absolutePath).into(binding.ivFoto1) //binding.ivFoto1.setImageBitmap(bitmap) }.addOnFailureListener { // Handle any errors Toast.makeText(this, "deu errado irmão", Toast.LENGTH_SHORT).show() } } } } db.collection("dentistas").whereEqualTo("email", user.email) .get() .addOnSuccessListener { documents -> for(document in documents) { db.collection("dentistas").document(document.id) .addSnapshotListener{documento, error -> if(documento != null){ binding.etNome.hint = documento.getString("name") binding.etTelef.hint = documento.getString("telefone") binding.etEnd1.hint = documento.getString("end1") binding.etEnd2.hint = documento.getString("end2") binding.etEnd3.hint = documento.getString("end3") binding.etCv.hint = documento.getString("cv") //Toast.makeText(this, documento.getString("status"), Toast.LENGTH_SHORT).show() if(documento.getBoolean("status") == true) { binding.scSwitch.isChecked = true binding.tvStatus.text = "Disponível" } else if (documento.getBoolean("status") == false) { binding.scSwitch.isChecked = false binding.tvStatus.text = "Ocupado" } } } } } } private fun abrirTelaDePreview(){ val intentCameraPreview = Intent(this, CameraPreviewActivity::class.java) intentCameraPreview.putExtra("perfil", "sim") startActivity(intentCameraPreview) } private fun enviarFoto(){ val milis = System.currentTimeMillis() val foto = "gs://prijinttres.appspot.com/perfis/img-${milis}.jpeg" Firebase.storage.getReference().child("perfis/img-${milis}.jpeg") .putFile(File(intent.getStringExtra("fotoPerfil")).toUri()) db.collection("dentistas").whereEqualTo("email",user!!.email).get() .addOnSuccessListener { documents -> for(document in documents){ db.collection("dentistas").document(document.id) .update("foto", foto) } } } }
0
Kotlin
0
0
1302c6f0b19e3f3d40807301050b197e4455998d
17,125
Projeto-Integrador-3
MIT License
features/players/presentation/src/main/java/com/themanol/reactbasket/players/presentation/viewmodel/PlayersViewModel.kt
themanol
212,338,612
false
null
package com.themanol.reactbasket.players.presentation.viewmodel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.themanol.reactbasket.domain.Player import com.themanol.reactbasket.domain.ResultState import com.themanol.reactbasket.players.domain.repository.PlayersRepository import com.themanol.reactbasket.viewmodels.BaseViewModel import io.reactivex.rxkotlin.addTo import io.reactivex.schedulers.Schedulers class PlayersViewModel(val repo: PlayersRepository) : BaseViewModel() { private val _playersListLiveData = MutableLiveData<List<Player>>() val playersListLiveData: LiveData<List<Player>> = _playersListLiveData private val _progressLiveData = MutableLiveData<Boolean>() val progressLiveData: LiveData<Boolean> = _progressLiveData private val _onScrollEndLiveData = MutableLiveData<(String) -> Unit>() val onScrollEndLiveData: LiveData<(String) -> Unit> = _onScrollEndLiveData private val _loadingLiveData = MutableLiveData<Boolean>() val loadingMoreLiveData: LiveData<Boolean> = _loadingLiveData private val _onQueryChangeLiveData = MutableLiveData<(String) -> Unit>() val onQueryChangeLiveData: LiveData<(String) -> Unit> = _onQueryChangeLiveData private val _onCloseSearchLiveData = MutableLiveData<() -> Unit>() val onCloseSearchLiveData: LiveData<() -> Unit> = _onCloseSearchLiveData var lastSearch: String = "" init { val playersObservable = repo.playersObservable .subscribeOn(Schedulers.io()) .share() playersObservable.subscribe { result -> when (result.status) { ResultState.SUCCESS -> _playersListLiveData.postValue(result.data) ResultState.ERROR -> mErrorLiveData.postValue(result.error) else -> { //Do Nothing } } _progressLiveData.postValue(result.status == ResultState.IN_PROGRESS) } .addTo(disposables) playersObservable.subscribe { res -> _onScrollEndLiveData.postValue { query -> if (res.status != ResultState.IN_PROGRESS) { if (query.isEmpty()) { repo.fetchMorePlayers() } else { repo.searchPlayersNext(query) } } } }.addTo(disposables) playersObservable.subscribe { _onQueryChangeLiveData.postValue { query -> if (it.status != ResultState.IN_PROGRESS && query.isNotEmpty()) { repo.searchPlayers(query) lastSearch = query } } }.addTo(disposables) playersObservable.subscribe { _onCloseSearchLiveData.postValue { if (it.status != ResultState.IN_PROGRESS) { repo.fetchPlayers() lastSearch = "" } } }.addTo(disposables) val morePlayersObservable = repo.morePlayersObservable .subscribeOn(Schedulers.io()) .share() morePlayersObservable.subscribe { result -> when (result.status) { ResultState.SUCCESS -> result.data?.let { newList -> _playersListLiveData.value?.let { _playersListLiveData.postValue(it.plus(newList)) } } ResultState.ERROR -> mErrorLiveData.postValue(result.error) else -> { //Do Nothing } } _loadingLiveData.postValue(result.status == ResultState.IN_PROGRESS) }.addTo(disposables) } }
0
Kotlin
0
4
d74c24f8b022dec35327743987eace70a8b02f86
3,788
basket-react-architecture
Apache License 2.0
src/main/kotlin/com/surrealdev/gretio/mpp/net/spojo/passThru/PtReadMsgsResponse.kt
SurrealDevelopment
378,748,964
false
null
package com.surrealdev.gretio.mpp.net.spojo.passThru import com.surrealdev.gretio.mpp.net.spojo.MESSAGE_ID_PT_READ_MSGS import kotlinx.serialization.Required import kotlinx.serialization.Serializable @Serializable class PtReadMsgsResponse( override val passThruResult: Int, val msgs: List<PtMessage>, override val cseq: Int? = null ) : PtResponse() { @Required override val id: Int = MESSAGE_ID_PT_READ_MSGS }
0
Kotlin
0
0
2438012c05a9f9897c934abe439977fc06dafc85
431
GretioApiSpec
Apache License 2.0
src/main/kotlin/com/surrealdev/gretio/mpp/net/spojo/passThru/PtReadMsgsResponse.kt
SurrealDevelopment
378,748,964
false
null
package com.surrealdev.gretio.mpp.net.spojo.passThru import com.surrealdev.gretio.mpp.net.spojo.MESSAGE_ID_PT_READ_MSGS import kotlinx.serialization.Required import kotlinx.serialization.Serializable @Serializable class PtReadMsgsResponse( override val passThruResult: Int, val msgs: List<PtMessage>, override val cseq: Int? = null ) : PtResponse() { @Required override val id: Int = MESSAGE_ID_PT_READ_MSGS }
0
Kotlin
0
0
2438012c05a9f9897c934abe439977fc06dafc85
431
GretioApiSpec
Apache License 2.0
shared/src/commonMain/kotlin/cat/alexgluque/paraulogicsolver/data/words/O.kt
alexluque
451,162,453
false
null
package cat.alexgluque.paraulogicsolver.data.words val wordsO = listOf( "o2", "o3", "oasi", "ob-", "obac -aga", "obaga", "obagor", "obagós -osa", "obcecació", "obcecadament", "obcecar", "obduració", "obediència", "obediencial", "obedient", "obedientment", "obeïdor -a", "obeir", "obelisc", "obenc", "obencadura", "obenquell", "obert -a", "oberta", "obertura", "oberturisme", "oberturista", "obès -esa", "obesitat", "obi", "obituari -ària", "objecció", "objectabilitat", "objectable", "objectar", "objecte", "objectiu -iva", "objectivació", "objectivament", "objectivar", "objectivisme", "objectivista", "objectivitat", "objector objectora", "objurgació", "objurgar", "oblació", "oblada1", "oblada2", "oblat oblata", "oblata", "oblatiu -iva", "oblia", "oblic -iqua", "oblidable", "oblidadís -issa", "oblidador -a", "oblidament", "oblidança", "oblidar", "oblidós -osa", "obligació", "obligacionista", "obligadament", "obligador -a", "obligança", "obligant", "obligar", "obligat -ada", "obligatori -òria", "obligatòriament", "obligatorietat", "obliquament", "obliquangle", "obliquar", "obliqüitat", "oblit", "obliteració", "obliterador -a", "obliterar", "oblivió", "oblong -a", "obnoxi -òxia", "obnubilació", "obnubilar", "oboè", "oboista", "obovat -ada", "obra", "obrador", "obradura", "obrall", "obrar", "obratge", "obreampolles", "obrecartes", "obrellaunes", "obrepció", "obreptici -ícia", "obreptíciament", "obrer obrera", "obreria", "obrerisme", "obrerista", "obridor1 -a", "obridor2 -a", "obriment", "obrir", "obriüllar", "obriülls", "obscè -ena", "obscenament", "obscenitat", "obscur -a", "obscurament", "obscurantisme", "obscurantista", "obscuriment", "obscurir", "obscuritat", "obsecració", "obsedir", "obseqüent", "obsequi", "obsequiador -a", "obsequiar", "obsequiós -osa", "obsequiosament", "obsequiositat", "observable", "observació", "observacional", "observador -a", "observança", "observant", "observar", "observatori", "obsés -essa", "obsessió", "obsessionar", "obsessiu -iva", "obsidiana", "obsidional", "obsolescència", "obsolet -a", "obstacle", "obstaculitzar", "obstar", "obstetre obstetra", "obstètric -a", "obstetrícia", "obstinació", "obstinadament", "obstinar-se", "obstinat -ada", "obstrucció", "obstruccionisme", "obstruccionista", "obstructiu -iva", "obstruir", "obtemperar", "obtenció", "obtenidor -a", "obteniment", "obtenir", "obtentor", "obtestació", "obtundent", "obturació", "obturador -a", "obturar", "obtús -usa", "obtusament", "obtusangle", "obús", "obvenció", "obvenir", "obventici -ícia", "obvers", "obvi òbvia", "obviar", "obvietat", "oc", "oca", "ocapi", "ocarina", "ocàs", "ocasió", "ocasionador -a", "ocasional", "ocasionalisme", "ocasionalista", "ocasionalment", "ocasionar", "ocater ocatera", "occamisme", "occident", "occidental", "occidentalització", "occidentalitzar", "occidor -a", "occidu -ídua", "occípit", "occipital", "occipito-", "occir", "occisió", "occità -ana", "occitànic -a", "occitanisme", "occitanista", "occitanitzar", "oceà -ana", "oceànic -a", "oceano-", "oceanògraf oceanògrafa", "oceanografia", "oceanogràfic -a", "oceanòleg oceanòloga", "oceanologia", "ocel", "ocell", "ocella", "ocellada", "ocellaire", "ocellam", "ocel·lar", "ocel·lat -ada", "ocelleria", "ocellets", "ocelot", "oci", "ociós -osa", "ociosament", "ociositat", "oclocràcia", "oclocràtic -a", "oclusió", "oclusiu -iva", "ocnàcies", "ocórrer", "ocraci -àcia", "ocre", "ocro-", "ocromonadals", "ocrós -osa", "oct-", "octa", "octà", "octa- [o octo-, o oct-]", "octaedre [o octàedre]", "octaèdric -a", "octaedrita", "octaetèride", "octàgon", "octagonal", "octàmer -a", "octanol", "octant", "octau -ava", "octavari", "octaví", "octavià -ana", "octet", "octo-", "octodòntids", "octogenari -ària", "octogèsim -a", "octogesimal", "octògon", "octogonal", "octosíl·lab -a", "octosil·làbic -a", "octubrada", "octubrar-se", "octubre", "octubrer -a", "octuplicar", "ocular", "ocularment", "oculista", "oculomotor -a", "oculomotriu", "ocult -a", "ocultable", "ocultació", "ocultador -a", "ocultament", "ocultar", "ocultisme", "ocultista", "ocumé", "ocupa", "ocupable", "ocupació", "ocupacional", "ocupador -a", "ocupant", "ocupar", "ocurrència", "ocurrent", "oda", "odalisca", "odèon", "odi", "odiar", "odiós -osa", "odiosament", "odiositat", "odissea", "odobènids", "odonats", "odont-", "odonto- [o odont-]", "odontoblast", "odontocets", "odontòcit", "odontoide", "odontòleg odontòloga", "odontologia", "odontològic -a", "odontoma", "odorant", "odorar", "odorífer -a", "odorós -osa", "odre", "odrer odrera", "odrina", "oersted", "oest", "ofec", "ofegabous", "ofegador -a", "ofegament", "ofegar", "ofegat -ada", "ofegor", "ofegós -osa", "ofelimitat", "ofendre", "ofenedor -a", "ofenós -osa", "ofensa", "ofensiu -iva", "ofensivament", "ofensor -a", "oferent", "oferidor -a", "oferiment", "oferina", "oferir", "oferta", "oferter", "ofertor ofertora", "ofertori", "office", "ofici", "oficial1", "oficial2 oficiala", "oficialista", "oficialitat", "oficialitzar", "oficialment", "oficiant", "oficiar", "oficina", "oficinal", "oficinesc -a", "oficinista", "oficiós -osa", "oficiosament", "oficiositat", "oficleide", "ofíctids", "ofídic -a", "ofídids", "ofidis", "ofimàtica", "ofio-", "ofioglossals", "ofioglossòpsids", "ofioide", "ofiolita", "ofita", "ofític -a", "ofiuroïdeus", "ofrena", "ofrenar", "oftalm-", "oftàlmia", "oftàlmic -a", "oftalmo- [o oftalm-]", "oftalmòleg oftalmòloga", "oftalmologia", "oftalmològic -a", "oftalmoplegia", "oftalmoscopi", "oftalmoscòpia", "ofuscació", "ofuscament", "ofuscar", "ogiva", "ogival", "ogre ogressa", "oh", "ohm", "ohmímetre", "oi1", "oi2", "oiar", "oiat -ada", "oïble", "oidà", "oïda", "oïdi", "oídium", "oïdor1 -a", "oïdor2 -a", "oient", "oïment", "oimés", "oint", "oioi", "oiós -osa", "oiosament", "oir", "oixque", "okapi", "oldre", "oleàcies", "oleaginós -osa", "oleandre", "oleandrina", "oleasa", "oleat", "olècran", "olècranon", "olefina", "olefínic -a", "olei-", "oleic -a", "oleícola", "oleïcultor oleïcultora", "oleïcultura", "oleífer -a", "oleïna", "oleo- [o olei-]", "oleodinàmic -a", "oleoducte", "oleografia", "oleogràfic -a", "oleohidràulica", "oleomargarina", "oleòmetre", "oleoresina", "olesà -ana", "olfacció", "olfacte", "olfactiu -iva", "olfactori -òria", "oli", "oliada", "oliaire", "oliana", "olianes", "oliar", "oliasses", "olíban", "olier -a", "oliera", "olifant", "olig-", "oligarca", "oligarquia", "oligàrquic -a", "oligàrquicament", "oligist", "oligo- [o olig-]", "oligocè -ena", "oligocènic -a", "oligòclasi", "oligoelement", "oligofrènia", "oligofrènic -a", "oligohalí -ina", "oligolecític -a", "oligòmer", "oligopoli", "oligopolístic -a", "oligopsoni", "oligoquets", "oligosacàrid", "oligosaprobi -òbia", "oligòtrof -a", "oligotròfia", "oligotròfic -a", "olimpíada", "olímpic -a", "olímpicament", "olimpisme", "oliós -osa", "olistòlit", "olistostroma", "oliu1", "oliu2", "oliva", "olivaci -àcia", "olivada", "olivaire", "olivar", "olivarda", "olivardó", "olivarer -a", "olivari -ària", "olivar-se", "olivater olivatera", "oliveda", "olivella", "oliver1", "oliver2 -a", "olivera", "oliverar", "olivereda", "oliverer -a", "olivereta", "olivet", "olivicultura", "olivila", "olivines", "olivínic -a", "olivó", "olla", "ollada", "ollaire", "ollal", "ollam", "ollaó", "oller1", "oller2 ollera", "olleria", "olm", "olor", "olorar", "olorós -osa", "olorosament", "olotí -ina", "om", "oma", "omar", "ombra", "ombrada", "ombradís -issa", "ombradiu", "ombrall", "ombrar", "ombratge", "ombreig", "ombrejar", "ombrel·la", "ombrer -a", "ombria", "ombriu -iva", "ombrívol -a", "ombro-", "ombrós -osa", "ombú", "omeda", "omega", "omeia", "oment", "omental", "ometre", "omfacita", "omfal-", "omfalo- [o omfal-]", "omfalocele", "ominós -osa", "ominosament", "omís -isa", "omissible", "omissió", "omni-", "omnidireccional", "omnímodament", "omnímode -a", "omnipotència", "omnipotent", "omnipotentment", "omnipresència", "omnipresent", "omnisciència", "omniscient", "omnívor -a", "omo-", "omòfag -a", "omofàgia", "omòplat", "omplir", "on", "ona", "onada", "onagràcies", "onagre", "onanisme", "onanista", "onatge", "onc-", "onclastre", "oncle", "onco- [o onc-]", "oncogen -ògena", "oncogèn", "oncogènesi", "oncogènia", "oncogènic -a", "oncòleg oncòloga", "oncologia", "oncològic -a", "oncosi", "oncòtic -a", "onda", "ondàmetre", "ondar", "ondat -ada", "ondejar", "ondejat -ada", "ondina", "ondòmetre", "ondós -osa", "ondulació", "ondulador -a", "ondulant", "ondular", "ondulat -ada", "ondulatori -òria", "ondulós -osa", "oneig", "onejant", "onejar", "onerari -ària", "onerós -osa", "onerosament", "onic-", "onico- [o onic-]", "onicofàgia", "onicòfors", "onicoptosi", "oníquia", "oníric -a", "oniro-", "oniromància", "onocròtal", "onomància", "onomasiologia", "onomasiològic -a", "onomàstic -a", "onomàsticon", "onomatopeia", "onomatopeic -a", "onosma", "onsa", "onsevol", "onsevulga", "onsevulla", "onso", "ontinyentí -ina", "onto-", "ontogènia", "ontòleg ontòloga", "ontologia", "ontològic -a", "ontologisme", "onze", "onzè -ena", "oo-", "oocist", "oòcit", "oogàmia", "oogènesi", "oogoni", "oogònia", "ooide", "oòlit", "oolita", "oolític -a", "oomicets", "oomicots", "oosfera", "oòspora", "opac -a", "opacament", "opacitat", "opalescència", "opalescent", "opalí -ina", "opció", "opcional", "operable", "operació", "operacional", "operador -a", "operand", "operar", "operari operària", "operatiu -iva", "operativitat", "operatori -òria", "opercle", "opercular", "operculat -ada", "operculiforme", "operculina", "opereta", "operista", "operístic -a", "operó", "operós -osa", "operosament", "opi", "opiaci -àcia", "opianina", "opiat -ada", "opiata", "opilació", "opilar", "opilatiu -iva", "opilions", "opim -a", "opimament", "opinable", "opinant", "opinar", "opínic", "opinió", "opiniós -osa", "opiòman -a", "opiomania", "opípar -a", "opíparament", "opisòmetre", "opisto-", "opistobranquis", "opistògnat -a", "opistògraf", "opistòton", "opo-", "opobàlsam", "oponent", "opopònac", "oportú -una", "oportunament", "oportunisme", "oportunista", "oportunitat", "oposable", "oposadament", "oposant", "oposar", "oposat -ada", "oposició", "oposicionista", "opositar", "opositi-", "opositor opositora", "opòssum", "opoteràpia", "opoteràpic -a", "opressió", "opressiu -iva", "opressivament", "opressor -a", "oprimir", "oprobi", "oprobiós -osa", "oprobiosament", "opsiòmetre", "opsomania", "opsonina", "opsonització", "opsonitzar", "optable", "optació", "optar", "optatiu -iva", "opticoelasticitat", "optimació", "optimar", "optimisme", "optimista", "optimització", "optimitzar", "opto-", "optoacoblador", "optoelectrònic -a", "optòmetre", "optometria", "optomètric -a", "optrònica", "opugnable", "opugnació", "opugnador -a", "opugnar", "opulència", "opulent -a", "opulentament", "opus", "opuscle", "oquer oquera", "or", "ora", "oració", "oracional", "oracioner -a", "oracle", "oracular", "orada", "orador oradora", "oradura", "oral", "oralment", "orangutan", "orant", "orar", "orat -ada", "oratge", "oratgell", "oratjol", "oratjós -osa", "oratori1", "oratori2 -òria", "oratòriament", "orb -a", "orbament", "orbar", "orbe", "orbetat", "orbicular", "orbicularment", "orbital", "orbitar", "orbitari -ària", "orbitolina", "orc1", "orc2 -a", "orca", "orcaneta", "orceïna", "orcina", "orcinol", "ordalia", "orde", "ordenable", "ordenació", "ordenada", "ordenadament", "ordenador -a", "ordenament", "ordenança", "ordenancista", "ordenand", "ordenant", "ordenar", "ordèol", "ordi", "ordiar1", "ordiar2", "ordiat", "ordidor -a", "ordidura", "ordier -a", "ordinació", "ordinador", "ordinal", "ordinari -ària", "ordinàriament", "ordinatiu -iva", "ordinograma", "ordiós -osa", "ordir", "ordissatge", "ordit", "ordovicià -ana", "ordovícic -a", "ordre", "orèada", "oreig", "orejada", "orejar", "orella", "orellada", "orellal", "orellana", "orellar", "orellat -ada", "orellera", "orelleta", "orelló", "orellut -uda", "oremus", "oreneta", "orenga", "orenol", "orenola", "orenyola", "oreopitec", "orèxia", "orfandat", "orfe òrfena", "orfebre", "orfebreria", "orfenat", "orfenesa", "orfeó", "orfeònic -a", "orfeonista", "orfisme", "organdí", "organdisatge", "orgànic -a", "orgànicament", "organicisme", "organicista", "organigrama", "organisme", "organista", "organístic -a", "organitzabilitat", "organitzable", "organització", "organitzador -a", "organitzar", "organitzat -ada", "organitzatiu -iva", "organo-", "organoborà", "organoclorat -ada", "organofosforat -ada", "organogen -ògena", "organogènesi", "organogènia", "organografia", "organogràfic -a", "organolèptic -a", "organologia", "organològic -a", "organometall", "organometàl·lic -a", "organoplàstic -a", "orgànul", "organzí", "orgasme", "orgàstic -a", "orgia", "orgíac -a", "orgiàstic -a", "orgue", "orguener orguenera", "orgueneria", "orguenet", "orgull", "orgullar", "orgullós -osa", "orgullosament", "oricalc", "oricto-", "orictognòsia", "orictografia", "orient", "orientació", "orientador -a", "oriental", "orientalisme", "orientalista", "orientalística", "orientalitzar", "orientar", "orientatiu -iva", "orífex", "orifici", "oriflama", "origen", "original", "originalitat", "originalment", "originar", "originari -ària", "originàriament", "orina", "orinada", "orinador", "orinaire", "orinal", "orinar", "orinc", "orincar", "orinera", "orins", "oriol", "oriola", "oriolà -ana", "oriòlids", "oripell", "oripellar", "oripeller oripellera", "oriünd -a", "orla", "orlador orladora", "orlar", "orleanisme", "orló", "ormeig", "ormejar", "ormí", "ornadament", "ornament", "ornamentació", "ornamental", "ornamentar", "ornamentista", "ornar", "orni", "ornit-", "ornitina", "ornitisquis", "ornito- [o ornit-]", "ornitodelfs", "ornitòfil -a", "ornitofília", "ornitògal", "ornitòleg ornitòloga", "ornitologia", "ornitològic -a", "ornitomància", "ornitòpodes", "ornitorrinc", "ornitorrínquids", "oró", "oro-", "orobancàcies", "orobanque", "oròfit", "orogen", "orogènesi", "orogènia", "orogènic -a", "orografia", "orogràfic -a", "orohidrografia", "oromo", "oronejar", "oronell1", "oronell2", "oronella", "oroneta", "orònim", "oronímic -a", "oros", "oroval", "orpesa", "orpiment", "orquejar", "orqueria", "orquestra", "orquestració", "orquestral", "orquestrar", "orquestrina", "orqui-", "orquidàcies", "orquídia", "orquido-", "orquio- [o orqui-, o orquido-]", "orquiocele", "orquitis", "orri", "orriaire", "orsa", "orsada", "orsai", "orsapop", "orsar", "orsejar", "orticó", "ortiga", "ortigada", "ortigall", "ortigar1", "ortigar2", "ortigosa", "ortiu -iva", "orto", "orto-", "ortoàcid", "ortoamfíbols", "ortobòric", "ortocentre", "ortoceràtids", "ortòclasi", "ortocromàtic -a", "ortodòncia", "ortodox -a", "ortodoxament", "ortodòxia", "ortodromia", "ortodròmic -a", "ortoedre [o ortòedre]", "ortoèpia", "ortoèpic -a", "ortoepista", "ortoèster", "ortofonia", "ortoform", "ortofosfat", "ortofosfòric", "ortofotogrametria", "ortofotomapa", "ortògnat -a", "ortognatisme", "ortogonal", "ortogonalitat", "ortogonalment", "ortografia", "ortografiar", "ortogràfic -a", "ortogràficament", "ortoheli", "ortohidrogen", "ortologia", "ortològic -a", "ortomòrfic -a", "ortonormal", "ortopèdia", "ortopèdic -a", "ortopedista", "ortoperiòdic", "ortopiroxens", "ortoplàsia", "ortopnea", "ortòpters", "ortoròmbic -a", "ortosa", "ortoscòpia", "ortoscòpic -a", "ortosilicat", "ortosilícic", "ortostàtic -a", "ortotipografia", "ortòton -a", "ortotònic -a", "ortotricals", "ortòtrop -a", "ortotropisme", "orval", "orxata", "orxater orxatera", "orxateria", "orxegada", "orxegar", "orxella", "orxeller orxellera", "os1", "os2", "osa", "osc osca", "osca", "oscadís -issa", "oscar", "oscil·lació", "oscil·lador -a", "oscil·lant", "oscil·lar", "oscil·latori -òria", "oscil·latorials", "oscil·lo-", "oscil·lògraf", "oscil·lograma", "oscil·lòmetre", "oscil·lometria", "oscil·loscopi", "oscitació", "oscitant", "oscoumbre -a", "oscoúmbric -a", "osculació", "osculador -a", "osculatriu", "osfi-", "osfio- [o osfi-]", "osmanlí", "osmazom", "osmi", "osmo-", "osmologia", "osmòmetre", "osmometria", "osmomètric -a", "osmoreceptor -a", "osmoregulació", "osmosi", "osmòtic -a", "osmunda", "osmundals", "osonenc -a", "ossa1", "ossa2", "ossada", "ossam", "ossamenta", "ossaments", "ossari", "ossat -ada", "osseïna", "ossera", "osset", "osseta", "ossi òssia", "ossi-", "ossicle", "ossífic -a", "ossificable", "ossificació", "ossificar", "ossívor -a", "ossó", "ossós -osa", "ossut -uda", "osta", "ostaga", "ostàlgia", "ostatge", "osteàlgia", "osteïctis", "osteïna", "osteïtis", "ostensibilitat", "ostensible", "ostensiblement", "ostensió", "ostensiu -iva", "ostensori", "ostentació", "ostentador -a", "ostentar", "ostentós -osa", "ostentosament", "osteo-", "osteoartropatia", "osteoblast", "osteocele", "osteòcit", "osteoclast", "osteocol·la", "osteòcop", "osteogen -ògena", "osteogènesi", "osteogènia", "osteogènic -a", "osteografia", "osteologia", "osteològic -a", "osteoma", "osteomalàcia", "osteomielitis", "osteòpata", "osteopatia", "osteoplàstia", "osteoporosi", "osteòtom", "osteotomia", "osteotòmic -a", "ostiari", "ostiariat", "ostíol", "ostra", "ostraci -àcia", "ostracisme", "ostracoderms", "ostracodes", "ostraire", "ostreï-", "ostreïcultor ostreïcultora", "ostreïcultura", "ostreïforme", "ostrer -a", "ostrera", "ostreria", "ostri-", "ostrícola", "ostrífer -a", "ostrogot ostrogoda", "ot-", "otàlgia", "otàrids", "otiatria", "otídids", "otitis", "oto- [o ot-]", "otoció", "otòfon", "otòleg otòloga", "otòlit", "otologia", "otomà otomana", "otomana", "otorrinolaringòleg otorrinolaringòloga", "otorrinolaringologia", "otoscopi", "otoscòpia", "ou", "ouaire", "ouat -ada", "ouataire", "ouater ouatera", "ouateria", "ouera", "ovació", "ovacionar", "oval", "ovalar", "ovalat -ada", "ovari", "ovari-", "ovàric -a", "ovario- [o ovari-]", "ovariotomia", "ovaritis", "ovat -ada", "ovella", "ovellenc -a", "oveller ovellera", "oví -ina", "ovi-", "ovicultura", "oviducte", "ovífer -a", "oviforme", "ovíger -a", "ovípar -a", "oviparisme", "oviscapte", "ovívor -a", "ovni", "ovo- [o ovi-]", "ovoalbúmina", "ovocèl·lula", "ovoidal", "ovoide", "ovovitel·lina", "ovovivípar -a", "ovoviviparisme", "ovulació", "ovular1", "ovular2", "ovuli-", "ovulífer -a", "ovulíger -a", "ox-", "oxalat", "oxàlic", "oxalidàcies", "oxalúria", "oxazina", "oxazole", "oxazolina", "oxazolona", "oxhídric -a", "oxi-", "oxiacetilènic -a", "oxiàcid", "oxidabilitat", "oxidable", "oxidació", "oxidant", "oxidar", "oxidasa", "oxidatiu -iva", "oxidoreducció", "oxidoreductasa", "oxídul", "oxigen", "oxigenació", "oxigenador", "oxigenar", "oxihemoglobina", "oxima", "oximel", "oxímoron", "oxina", "oxirrinc -a", "oxisal", "oxitall", "oxitocina", "oxíton -a", "oxo- [o ox-]", "oxoàcid", "oxoni", "ozalid", "ozena", "ozó", "ozocerita", "ozònid", "ozonització", "ozonitzador -a", "ozonitzar", "ozono-", "ozonòlisi", "ozonòmetre", "ozonometria", "ozonomètric -a", "ozonosfera", "ozonosonda" )
0
Kotlin
0
0
4d1d0b78d4c5d8b9a9d7c20a75e1fc857e9b1ccf
24,448
ParaulogicSolver
Apache License 2.0
intellij-plugin/educational-core/src/com/jetbrains/edu/learning/actions/ToggleRestServicesAction.kt
JetBrains
43,696,115
false
null
package com.jetbrains.edu.learning.actions import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAwareToggleAction import com.jetbrains.edu.learning.authUtils.OAuthRestService import com.jetbrains.edu.learning.messages.EduCoreBundle class ToggleRestServicesAction : DumbAwareToggleAction(EduCoreBundle.lazyMessage("action.toggle.rest.services.title")) { override fun isSelected(e: AnActionEvent): Boolean = OAuthRestService.isRestServicesEnabled override fun setSelected(e: AnActionEvent, state: Boolean) { OAuthRestService.isRestServicesEnabled = state } override fun getActionUpdateThread() = ActionUpdateThread.BGT }
7
null
49
150
9cec6c97d896f4485e76cf9a2a95f8a8dd21c982
738
educational-plugin
Apache License 2.0
app/src/main/java/com/sys1yagi/mastodon/android/ui/navigation/home/toot/TootRouter.kt
sys1yagi
88,218,508
false
null
package com.sys1yagi.mastodon.android.ui.navigation.home.toot import android.app.Activity import android.content.Intent import javax.inject.Inject class TootRouter @Inject constructor() : TootContract.Router { override fun chooseAttachment(activity: Activity) { val intent = Intent(Intent.ACTION_OPEN_DOCUMENT) intent.addCategory(Intent.CATEGORY_OPENABLE) intent.type = "image/*" activity.startActivityForResult(intent, TootContract.REQUEST_ID_CHOOSE_ATTACHMENT) } }
13
HTML
1
30
52f97dc70109e72b1d60bbc5011ad1ffda8ca3c0
514
DroiDon
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsintegrationapi/models/adjudications/AdjudicationsPunishmentSchedule.kt
ministryofjustice
572,524,532
false
{"Kotlin": 921384, "Python": 32511, "Shell": 16913, "Dockerfile": 1120, "Makefile": 888}
package uk.gov.justice.digital.hmpps.hmppsintegrationapi.models.adjudications class AdjudicationsPunishmentSchedule( val days: Number? = null, val startDate: String? = null, val endDate: String? = null, val suspendedUntil: String? = null, )
2
Kotlin
1
2
10a77e18de365f7ac4d2d1f675853f37e0f65ac5
250
hmpps-integration-api
MIT License
lightsaber/processor/src/test/java/com/joom/lightsaber/processor/validation/SanityCheckerTest.kt
joomcode
170,310,869
false
null
/* * Copyright 2022 SIA Joom * * 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.joom.lightsaber.processor.validation import com.joom.lightsaber.processor.integration.IntegrationTestRule import org.junit.Rule import org.junit.Test class SanityCheckerTest { @get:Rule val integrationTestRule = IntegrationTestRule("test_case_projects/sanity") @Test fun test_check_failed_when_provide_as_argument_has_wrong_type() { integrationTestRule.assertInvalidProject( sourceCodeDir = "invalid_provided_as", message = "@ProvidedAs binding's argument java.lang.String isn't a super type of" + " the host class test_case_projects.sanity.invalid_provided_as.Dependency" ) } @Test fun test_check_failed_when_dependency_is_an_abstract() { integrationTestRule.assertInvalidProject( sourceCodeDir = "invalid_access_level", message = "Providable class cannot be abstract: Ltest_case_projects/sanity/invalid_access_level/AbstractClassDependency;" ) } @Test fun test_check_failed_when_dependency_injected_in_static_field() { integrationTestRule.assertInvalidProject( sourceCodeDir = "static_field_injection", message = "Static field injection is not supported yet: FieldMirror{name = dependency, " + "type = Ltest_case_projects/sanity/static_field_injection/Dependency;}" ) } @Test fun test_check_failed_when_dependency_injected_in_static_method() { integrationTestRule.assertInvalidProject( sourceCodeDir = "static_method_injection", message = "Static method injection is not supported yet: MethodMirror{name = staticMethodWithInjection, " + "type = (Ltest_case_projects/sanity/static_method_injection/Dependency;)V}" ) } @Test fun test_check_failed_when_module_inherits_types_that_not_allowed() { integrationTestRule.assertInvalidProject( sourceCodeDir = "module_with_invalid_parent", message = "test_case_projects.sanity.module_with_invalid_parent.AppModule has a super type of test_case_projects.sanity.module_with_invalid_parent.AppModule " + "instead of java.lang.Object or com.joom.lightsaber.ContractConfiguration" ) } @Test fun test_check_successful_when_module_inherits_contract_configuration() { integrationTestRule.assertValidProject("module_inherits_contract_configuration_class") } @Test fun test_check_failed_when_module_with_imported_by_does_not_have_default_constructor() { integrationTestRule.assertInvalidProject( sourceCodeDir = "non_constructable_module_with_imported_by", message = "Module test_case_projects.sanity.non_constructable_module_with_imported_by.AppModule with @ImportedBy annotation must have a default constructor" ) } @Test fun test_check_fails_when_contract_configuration_is_an_abstract() { integrationTestRule.assertInvalidProject( sourceCodeDir = "abstract_contract_configuration", message = "Contract configuration test_case_projects.sanity.abstract_contract_configuration.AppContractConfiguration should be a concrete class" ) } @Test fun test_check_failed_when_provided_as_has_generic_class_argument() { integrationTestRule.assertInvalidProject( sourceCodeDir = "provide_as_with_generic_argument_class", message = "@ProvidedAs bindings cannot have a generic type java.util.List as an argument" ) } @Test fun test_check_failed_when_provided_as_has_generic_class_host() { integrationTestRule.assertInvalidProject( sourceCodeDir = "provide_as_with_generic_host_class", message = "@ProvidedAs bindings aren't supported for a generic type test_case_projects.sanity.provide_as_with_generic_host_class.Dependency" ) } @Test fun test_check_failed_when_provide_as_has_non_inherited_argument() { integrationTestRule.assertInvalidProject( sourceCodeDir = "provide_as_with_not_inherited_argument", message = "@ProvidedAs binding's argument test_case_projects.sanity.provide_as_with_not_inherited_argument.InterfaceThatHostClassDoesNotInherit" + " isn't a super type of the host class test_case_projects.sanity.provide_as_with_not_inherited_argument.Dependency" ) } @Test fun test_check_failed_when_provide_as_containing_argument_class_with_injectable_constructor() { integrationTestRule.assertInvalidProject( sourceCodeDir = "provide_as_with_argument_class_containing_injectable_constructor", message = "@ProvidedAs binding's argument test_case_projects.sanity.provide_as_with_argument_class_containing_injectable_constructor.ClassWithInjectableConstructor cannot have an @Inject constructor" ) } @Test fun test_check_failed_when_provide_as_containing_host_class_as_argument() { integrationTestRule.assertInvalidProject( sourceCodeDir = "provide_as_with_host_class_as_argument", message = "@ProvidedAs bindings cannot have a host class test_case_projects.sanity.provide_as_with_host_class_as_argument.Dependency as an argument" ) } @Test fun test_check_failed_when_factory_host_is_not_an_interface() { integrationTestRule.assertInvalidProject( sourceCodeDir = "factory_is_not_an_interface", message = "Factory test_case_projects.sanity.factory_is_not_an_interface.FactoryClass must be an interface" ) } @Test fun test_check_failed_when_factory_contains_generic_parameters() { integrationTestRule.assertInvalidProject( sourceCodeDir = "factory_contains_generic_parameters", message = "Factory test_case_projects.sanity.factory_contains_generic_parameters.FactoryInterface mustn't contain generic parameters" ) } @Test fun test_check_fails_when_factory_does_not_have_any_methods() { integrationTestRule.assertInvalidProject( sourceCodeDir = "factory_without_methods", message = "Factory test_case_projects.sanity.factory_without_methods.FactoryInterface must contain at least one method" ) } @Test fun test_check_fails_when_factory_does_not_have_any_methods2() { integrationTestRule.assertInvalidProject( sourceCodeDir = "factory_creating_instance_type_differ_from_return_annotation", message = "Method test_case_projects.sanity.factory_creating_instance_type_differ_from_return_annotation.FactoryInterface.buildInstance returns " + "test_case_projects.sanity.factory_creating_instance_type_differ_from_return_annotation.Instance which isn't an ancestor of " + "test_case_projects.sanity.factory_creating_instance_type_differ_from_return_annotation.ActualInstance from the @Factory.Return annotation" ) } }
2
Kotlin
0
14
3fd794c40eff21e24747bc590e4361f3e4bfa228
7,155
lightsaber
Apache License 2.0
subprojects/protocol/src/main/kotlin/com/handtruth/mc/mcsman/protocol/HandshakePaket.kt
handtruth
417,843,728
false
null
package com.handtruth.mc.mcsman.protocol import com.handtruth.mc.paket.Paket import com.handtruth.mc.paket.PaketCreator import com.handtruth.mc.paket.fields.string import com.handtruth.mc.paket.fields.uint16 import com.handtruth.mc.paket.fields.varInt class HandshakePaket(address: String = "localhost", port: UShort = 1337u) : Paket() { override val id = PaketID.Handshake val version by varInt(3) var address by string(address) var port by uint16(port) companion object : PaketCreator<HandshakePaket> { override fun produce() = HandshakePaket() } }
0
Kotlin
0
0
58b2d4bd0413522dbf1cbabc1c8bab78e1b1edfe
587
mcsman
Apache License 2.0
domain/src/main/kotlin/team/applemango/runnerbe/domain/runningitem/usecase/RunningItemFinishUseCase.kt
ricky-buzzni
485,390,072
false
{"Kotlin": 615137}
/* * RunnerBe © 2022 Team AppleMango. all rights reserved. * RunnerBe license is under the MIT. * * [RunningItemFinishUseCase.kt] created by Ji Sungbin on 22. 2. 28. 오후 9:36 * * Please see: https://github.com/applemango-runnerbe/RunnerBe-Android/blob/main/LICENSE. */ package team.applemango.runnerbe.domain.runningitem.usecase import team.applemango.runnerbe.domain.runningitem.repository.RunningItemRepository class RunningItemFinishUseCase(private val repo: RunningItemRepository) { suspend operator fun invoke( jwt: String, postId: Int, ) = runCatching { repo.finish( jwt = jwt, postId = postId ) } }
0
null
0
0
f48fb298c07732a9c32afcff0bddb16f9fe2e37a
683
RunnerBe-Android
MIT License
src/me/anno/ui/editor/components/ComponentUI.kt
AntonioNoack
266,471,164
false
null
package me.anno.remsstudio.ui import me.anno.animation.Type import me.anno.gpu.blending.BlendMode import me.anno.gpu.blending.BlendMode.Companion.blendModes import me.anno.io.files.FileReference import me.anno.remsstudio.RemsStudio import me.anno.remsstudio.animation.AnimatedProperty import me.anno.remsstudio.objects.Transform import me.anno.remsstudio.ui.input.ColorInputV2 import me.anno.remsstudio.ui.input.FloatInputV2 import me.anno.remsstudio.ui.input.FloatVectorInputV2 import me.anno.remsstudio.ui.input.IntInputV2 import me.anno.studio.Inspectable import me.anno.ui.Panel import me.anno.ui.input.* import me.anno.ui.Style import me.anno.utils.Color.toHexColor import me.anno.utils.Color.toVecRGBA import me.anno.utils.structures.ValueWithDefault import me.anno.utils.structures.ValueWithDefaultFunc import org.joml.Quaternionf import org.joml.Vector2f import org.joml.Vector3f import org.joml.Vector4f object ComponentUIV2 { /** * creates a panel with the correct input for the type, and sets the default values: * title, tool tip text, type, start value * callback is used to adjust the value * */ @Suppress("unchecked_cast") // all casts are checked in all known use-cases ;) fun <V> vi( inspected: List<Inspectable>, self: Transform, title: String, ttt: String, type: Type?, value: V, style: Style, setValue: (V) -> Unit ): Panel { val t = inspected.filterIsInstance<Transform>() return when (value) { is Boolean -> BooleanInput(title, value, type?.defaultValue as? Boolean ?: false, style) .setChangeListener { RemsStudio.largeChange("Set $title to $it") { setValue(it as V) } } .setIsSelectedListener { self.show(t, null) } .setTooltip(ttt) is Int -> IntInput(title, title, value, type ?: Type.INT, style) .setChangeListener { RemsStudio.incrementalChange("Set $title to $it", title) { setValue(it.toInt() as V) } } .setIsSelectedListener { self.show(t, null) } .setTooltip(ttt) is Long -> IntInput(title, title, value, type ?: Type.LONG, style) .setChangeListener { RemsStudio.incrementalChange("Set $title to $it", title) { setValue(it as V) } } .setIsSelectedListener { self.show(t, null) } .setTooltip(ttt) is Float -> FloatInput(title, title, value, type ?: Type.FLOAT, style) .setChangeListener { RemsStudio.incrementalChange("Set $title to $it", title) { setValue(it.toFloat() as V) } } .setIsSelectedListener { self.show(t, null) } .setTooltip(ttt) is Double -> FloatInput(title, title, value, type ?: Type.DOUBLE, style) .setChangeListener { RemsStudio.incrementalChange("Set $title to $it", title) { setValue(it as V) } } .setIsSelectedListener { self.show(t, null) } .setTooltip(ttt) is Vector2f -> FloatVectorInput(title, title, value, type ?: Type.VEC2, style) .addChangeListener { x, y, _, _, _ -> RemsStudio.incrementalChange("Set $title to ($x,$y)", title) { setValue(Vector2f(x.toFloat(), y.toFloat()) as V) } } .setIsSelectedListener { self.show(t, null) } .setTooltip(ttt) is Vector3f -> if (type == Type.COLOR3) { ColorInput(style, title, title, Vector4f(value, 1f), false) .setChangeListener { r, g, b, _, _ -> RemsStudio.incrementalChange("Set $title to ${Vector3f(r, g, b).toHexColor()}", title) { setValue(Vector3f(r, g, b) as V) } } .setIsSelectedListener { self.show(t, null) } .setTooltip(ttt) } else { FloatVectorInput(title, title, value, type ?: Type.VEC3, style) .addChangeListener { x, y, z, _, _ -> RemsStudio.incrementalChange("Set $title to ($x,$y,$z)", title) { setValue(Vector3f(x.toFloat(), y.toFloat(), z.toFloat()) as V) } } .setIsSelectedListener { self.show(t, null) } .setTooltip(ttt) } is Vector4f -> { if (type == null || type == Type.COLOR) { ColorInput(style, title, title, value, true) .setChangeListener { r, g, b, a, _ -> RemsStudio.incrementalChange("Set $title to ${Vector4f(r, g, b, a).toHexColor()}", title) { setValue(Vector4f(r, g, b, a) as V) } } .setIsSelectedListener { self.show(t, null) } .setTooltip(ttt) } else { FloatVectorInput(title, title, value, type, style) .addChangeListener { x, y, z, w, _ -> RemsStudio.incrementalChange("Set $title to ($x,$y,$z,$w)", title) { setValue(Vector4f(x.toFloat(), y.toFloat(), z.toFloat(), w.toFloat()) as V) } } .setIsSelectedListener { self.show(t, null) } .setTooltip(ttt) } } is Quaternionf -> FloatVectorInput(title, title, value, type ?: Type.QUATERNION, style) .addChangeListener { x, y, z, w, _ -> RemsStudio.incrementalChange(title) { setValue(Quaternionf(x, y, z, w) as V) } } .setIsSelectedListener { self.show(t, null) } .setTooltip(ttt) is String -> TextInputML(title, value, style) .addChangeListener { RemsStudio.incrementalChange("Set $title to \"$it\"", title) { setValue(it as V) } } .setIsSelectedListener { self.show(t, null) } .setTooltip(ttt) is FileReference -> FileInput(title, style, value, emptyList()) .setChangeListener { RemsStudio.incrementalChange("Set $title to \"$it\"", title) { setValue(it as V) } } .setIsSelectedListener { self.show(t, null) } .setTooltip(ttt) is BlendMode -> { val values = blendModes.values val valueNames = values.map { it to it.naming } EnumInput( title, true, valueNames.first { it.first == value }.second.name, valueNames.map { it.second }, style ) .setChangeListener { name, index, _ -> RemsStudio.incrementalChange("Set $title to $name", title) { setValue(valueNames[index].first as V) } } .setIsSelectedListener { self.show(t, null) } .setTooltip(ttt) } is Enum<*> -> { val values = EnumInput.getEnumConstants(value.javaClass) EnumInput.createInput(title, value, style) .setChangeListener { name, index, _ -> RemsStudio.incrementalChange("Set $title to $name") { setValue(values[index] as V) } } .setIsSelectedListener { self.show(t, null) } .setTooltip(ttt) } is ValueWithDefaultFunc<*>, is ValueWithDefault<*> -> throw IllegalArgumentException("Must pass value, not ValueWithDefault(Func)!") else -> throw RuntimeException("Type $value not yet implemented!") } } private fun toColor(v: Any?): Vector4f { return when (v) { is Vector4f -> v is Vector3f -> Vector4f(v, 1f) is Int -> v.toVecRGBA() is Long -> v.toInt().toVecRGBA() else -> Vector4f(0f, 0f, 0f, 1f) } } /** * creates a panel with the correct input for the type, and sets the default values: * title, tool tip text, type, start value * modifies the AnimatedProperty-Object, so no callback is needed * */ fun vi( self: Transform, title: String, ttt: String, values: AnimatedProperty<*>, style: Style ): Panel { val time = self.lastLocalTime val sl = { self.show(listOf(self), listOf(values)) } return when (val value = values[time]) { is Int -> IntInputV2(title, title, values, time, style) .setChangeListener { RemsStudio.incrementalChange("Set $title to $it", title) { self.putValue(values, it.toInt(), false) } } .setIsSelectedListener(sl) .setTooltip(ttt) is Long -> IntInputV2(title, title, values, time, style) .setChangeListener { RemsStudio.incrementalChange("Set $title to $it", title) { self.putValue(values, it, false) } } .setIsSelectedListener(sl) .setTooltip(ttt) is Float -> FloatInputV2(title, title, values, time, style) .setChangeListener { RemsStudio.incrementalChange("Set $title to $it", title) { self.putValue(values, it.toFloat(), false) } } .setIsSelectedListener(sl) .setTooltip(ttt) is Double -> FloatInputV2(title, title, values, time, style) .setChangeListener { RemsStudio.incrementalChange("Set $title to $it", title) { self.putValue(values, it, false) } } .setIsSelectedListener(sl) .setTooltip(ttt) is Vector2f -> FloatVectorInputV2(title, values, time, style) .addChangeListener { x, y, _, _, _ -> RemsStudio.incrementalChange("Set $title to ($x,$y)", title) { self.putValue(values, Vector2f(x.toFloat(), y.toFloat()), false) } } .setIsSelectedListener(sl) .setTooltip(ttt) is Vector3f -> if (values.type == Type.COLOR3) { ColorInputV2(style, title, title, Vector4f(value, 1f), false, values) .setChangeListener { r, g, b, _, _ -> RemsStudio.incrementalChange("Set $title to ${Vector3f(r, g, b).toHexColor()}", title) { self.putValue(values, Vector3f(r, g, b), false) } } .setResetListener { toColor(values.defaultValue) } .setIsSelectedListener(sl) .setTooltip(ttt) } else { FloatVectorInputV2(title, values, time, style) .addChangeListener { x, y, z, _, _ -> RemsStudio.incrementalChange("Set $title to ($x,$y,$z)", title) { self.putValue(values, Vector3f(x.toFloat(), y.toFloat(), z.toFloat()), false) } } .setIsSelectedListener(sl) .setTooltip(ttt) } is Vector4f -> { if (values.type == Type.COLOR) { ColorInputV2(style, title, title, value, true, values) .setChangeListener { r, g, b, a, _ -> RemsStudio.incrementalChange("Set $title to ${Vector4f(r, g, b, a).toHexColor()}", title) { self.putValue(values, Vector4f(r, g, b, a), false) } } .setResetListener { toColor(values.defaultValue) } .setIsSelectedListener(sl) .setTooltip(ttt) } else { FloatVectorInputV2(title, values, time, style) .addChangeListener { x, y, z, w, _ -> RemsStudio.incrementalChange("Set $title to ($x,$y,$z,$w)", title) { self.putValue( values, Vector4f(x.toFloat(), y.toFloat(), z.toFloat(), w.toFloat()), false ) } } .setIsSelectedListener(sl) .setTooltip(ttt) } } is String -> TextInputML(title, value, style) .addChangeListener { RemsStudio.incrementalChange("Set $title to $it") { self.putValue(values, it, false) } } .setIsSelectedListener(sl) .setTooltip(ttt) is Quaternionf -> FloatVectorInputV2(title, values, time, style) .addChangeListener { x, y, z, w, _ -> RemsStudio.incrementalChange("Set $title to ($x,$y,$z,$w)", title) { self.putValue(values, Quaternionf(x, y, z, w), false) } } .setIsSelectedListener(sl) .setTooltip(ttt) else -> throw RuntimeException("Type $value not yet implemented!") } } /** * creates a panel with the correct input for the type, and sets the default values: * title, tool tip text, type, start value * modifies the AnimatedProperty-Object, so no callback is needed * */ fun vis( transforms: List<Transform>, title: String, ttt: String, allValues: List<AnimatedProperty<*>?>, style: Style ): Panel { val values = allValues[0]!! val self = transforms[0] val time = self.lastLocalTime val sl = { self.show(transforms, allValues) } return when (val value = values[time]) { is Int -> IntInputV2(title, title, values, time, style) .setChangeListener { RemsStudio.incrementalChange("Set $title to $it", title) { val ii = it.toInt() for (i in allValues.indices) { transforms[i].putValue(allValues[i], ii, false) } } } .setIsSelectedListener(sl) .setTooltip(ttt) is Long -> IntInputV2(title, title, values, time, style) .setChangeListener { RemsStudio.incrementalChange("Set $title to $it", title) { for (i in allValues.indices) { transforms[i].putValue(allValues[i], it, false) } } } .setIsSelectedListener(sl) .setTooltip(ttt) is Float -> FloatInputV2(title, title, values, time, style) .setChangeListener { RemsStudio.incrementalChange("Set $title to $it", title) { val ii = it.toFloat() for (i in allValues.indices) { transforms[i].putValue(allValues[i], ii, false) } } } .setIsSelectedListener(sl) .setTooltip(ttt) is Double -> FloatInputV2(title, title, values, time, style) .setChangeListener { RemsStudio.incrementalChange("Set $title to $it", title) { for (i in allValues.indices) { transforms[i].putValue(allValues[i], it, false) } } } .setIsSelectedListener(sl) .setTooltip(ttt) is Vector2f -> FloatVectorInputV2(title, values, time, style) .addChangeListener { x, y, _, _, _ -> RemsStudio.incrementalChange("Set $title to ($x,$y)", title) { // multiple instances? for (i in allValues.indices) { transforms[i].putValue(allValues[i], Vector2f(x.toFloat(), y.toFloat()), false) } } } .setIsSelectedListener(sl) .setTooltip(ttt) is Vector3f -> if (values.type == Type.COLOR3) { ColorInputV2(style, title, title, Vector4f(value, 1f), false, values) .setChangeListener { r, g, b, _, _ -> RemsStudio.incrementalChange("Set $title to ${Vector3f(r, g, b).toHexColor()}", title) { // multiple instances? for (i in allValues.indices) { transforms[i].putValue(allValues[i], Vector3f(r, g, b), false) } } } .setResetListener { toColor(values.defaultValue) } .setIsSelectedListener(sl) .setTooltip(ttt) } else { FloatVectorInputV2(title, values, time, style) .addChangeListener { x, y, z, _, _ -> RemsStudio.incrementalChange("Set $title to ($x,$y,$z)", title) { // multiple instances? for (i in allValues.indices) { transforms[i].putValue( allValues[i], Vector3f(x.toFloat(), y.toFloat(), z.toFloat()), false ) } } } .setIsSelectedListener(sl) .setTooltip(ttt) } is Vector4f -> { if (values.type == Type.COLOR) { ColorInputV2(style, title, title, value, true, values) .setChangeListener { r, g, b, a, _ -> RemsStudio.incrementalChange("Set $title to ${Vector4f(r, g, b, a).toHexColor()}", title) { // multiple instances? for (i in allValues.indices) { transforms[i].putValue(allValues[i], Vector4f(r, g, b, a), false) } } } .setResetListener { toColor(values.defaultValue) } .setIsSelectedListener(sl) .setTooltip(ttt) } else { FloatVectorInputV2(title, values, time, style) .addChangeListener { x, y, z, w, _ -> RemsStudio.incrementalChange("Set $title to ($x,$y,$z,$w)", title) { // multiple instances? for (i in allValues.indices) { transforms[i].putValue( allValues[i], Vector4f(x.toFloat(), y.toFloat(), z.toFloat(), w.toFloat()), false ) } } } .setIsSelectedListener(sl) .setTooltip(ttt) } } is String -> TextInputML(title, value, style) .addChangeListener { RemsStudio.incrementalChange("Set $title to $it") { for (i in allValues.indices) { transforms[i].putValue(allValues[i], it, false) } } } .setIsSelectedListener(sl) .setTooltip(ttt) is Quaternionf -> FloatVectorInputV2(title, values, time, style) .addChangeListener { x, y, z, w, _ -> RemsStudio.incrementalChange("Set $title to ($x,$y,$z,$w)", title) { for (i in allValues.indices) { transforms[i].putValue(allValues[i], Quaternionf(x, y, z, w), false) } } } .setIsSelectedListener(sl) .setTooltip(ttt) else -> throw RuntimeException("Type $value not yet implemented!") } } }
0
null
3
8
e5f0bb17202552fa26c87c230e31fa44cd3dd5c6
22,215
RemsStudio
Apache License 2.0
app/src/main/java/com/sitamadex11/CovidHelp/fragments/WestBengalFragment.kt
theDIRone
362,289,927
false
{"Kotlin": 248218}
package com.sitamadex11.CovidHelp.fragments import android.content.Context import android.content.Intent import android.net.ConnectivityManager import android.net.NetworkInfo import android.net.Uri import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.fragment.app.Fragment import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.material.button.MaterialButton import com.google.android.material.card.MaterialCardView import com.sitamadex11.CovidHelp.R import com.sitamadex11.CovidHelp.adapter.SomeannoyingDialogAdapter import com.sitamadex11.CovidHelp.model.SomeannoynigDialogItems import com.sitamadex11.CovidHelp.util.Constants import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.jsoup.Jsoup class WestBengalFragment : Fragment(), View.OnClickListener { lateinit var btnEService: MaterialButton lateinit var cvBed: MaterialCardView lateinit var cvSafeHome: MaterialCardView lateinit var cvHelpDesk: MaterialCardView lateinit var cvCenter: MaterialCardView lateinit var cvAmbulance: MaterialCardView lateinit var cvHearse: MaterialCardView lateinit var cvNodal: MaterialCardView lateinit var cvBurial: MaterialCardView lateinit var rvSomeannoying: RecyclerView lateinit var btnResources: MaterialButton lateinit var btnGetCylinder: MaterialButton lateinit var btnChatBot: MaterialButton lateinit var txtAvailBed: TextView lateinit var txtAvailCylinder: TextView lateinit var txtAskHelp: TextView lateinit var url: String lateinit var intent: Intent lateinit var btnRetry: MaterialButton lateinit var btnExit: MaterialButton private val itemList = ArrayList<SomeannoynigDialogItems>() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment val view = inflater.inflate(R.layout.fragment_west_bengal, container, false) val isConnected = checkConnectivity(requireContext()) if (!isConnected) { val customLayout = layoutInflater .inflate( R.layout.network_check_dialog, null ) msgInit(customLayout) val builder = AlertDialog.Builder(requireContext()) builder.setView(customLayout) builder.setCancelable(false) val dialog = builder.create() btnExit.setOnClickListener { requireActivity().finish() } btnRetry.setOnClickListener { if (checkConnectivity(requireContext())) { //Do some thing dialog.hide() itemListAdder( R.drawable.oxygen_tank, "Oxygen", "https://covid.someannoying.com/oxy.php" ) itemListAdder( R.drawable.ambulance, "Ambulance", "https://covid.someannoying.com/amb.php" ) itemListAdder( R.drawable.app_logo, "Test Resources", "https://covid.someannoying.com/tests.php" ) itemListAdder( R.drawable.app_logo, "Medicines", "https://covid.someannoying.com/med.php" ) itemListAdder( R.drawable.help_desk, "Helpdesk", "https://covid.someannoying.com/help.php" ) itemListAdder( R.drawable.app_logo, "Plasma/Blood", "https://covid.someannoying.com/plasma.php" ) itemListAdder( R.drawable.app_logo, "Doctor", "https://covid.someannoying.com/doc.php" ) itemListAdder( R.drawable.home, "Home Services", "https://covid.someannoying.com/homes.php" ) itemListAdder( R.drawable.app_logo, "Meal Services", "https://covid.someannoying.com/food/" ) itemListAdder( R.drawable.app_logo, "Others", "https://covid.someannoying.com/others.php" ) btnEService = view!!.findViewById(R.id.btnEServce) btnResources = view!!.findViewById(R.id.btnResources) btnGetCylinder = view!!.findViewById(R.id.btnGetCylinder) btnChatBot = view!!.findViewById(R.id.btnChatBot) txtAvailBed = view.findViewById(R.id.txtAvailBed) txtAvailCylinder = view.findViewById(R.id.txtAvailCylinder) txtAskHelp = view.findViewById(R.id.txtAskHelp) fetchBedCylinderCount() btnEService.setOnClickListener(this) btnResources.setOnClickListener(this) btnGetCylinder.setOnClickListener(this) btnChatBot.setOnClickListener(this) txtAskHelp.setOnClickListener(this) } else { Toast.makeText( requireContext(), "Sorry!! No Internet connection found", Toast.LENGTH_SHORT ).show() } } dialog.show() } else { //Do some thing itemListAdder( R.drawable.oxygen_tank, "Oxygen", "https://covid.someannoying.com/oxy.php" ) itemListAdder( R.drawable.ambulance, "Ambulance", "https://covid.someannoying.com/amb.php" ) itemListAdder( R.drawable.app_logo, "Test Resources", "https://covid.someannoying.com/tests.php" ) itemListAdder( R.drawable.app_logo, "Medicines", "https://covid.someannoying.com/med.php" ) itemListAdder( R.drawable.help_desk, "Helpdesk", "https://covid.someannoying.com/help.php" ) itemListAdder( R.drawable.app_logo, "Plasma/Blood", "https://covid.someannoying.com/plasma.php" ) itemListAdder(R.drawable.app_logo, "Doctor", "https://covid.someannoying.com/doc.php") itemListAdder( R.drawable.home, "Home Services", "https://covid.someannoying.com/homes.php" ) itemListAdder( R.drawable.app_logo, "Meal Services", "https://covid.someannoying.com/food/" ) itemListAdder( R.drawable.app_logo, "Others", "https://covid.someannoying.com/others.php" ) btnEService = view!!.findViewById(R.id.btnEServce) btnResources = view!!.findViewById(R.id.btnResources) btnGetCylinder = view!!.findViewById(R.id.btnGetCylinder) btnChatBot = view!!.findViewById(R.id.btnChatBot) txtAvailBed = view.findViewById(R.id.txtAvailBed) txtAvailCylinder = view.findViewById(R.id.txtAvailCylinder) txtAskHelp = view.findViewById(R.id.txtAskHelp) fetchBedCylinderCount() btnEService.setOnClickListener(this) btnResources.setOnClickListener(this) btnGetCylinder.setOnClickListener(this) btnChatBot.setOnClickListener(this) txtAskHelp.setOnClickListener(this) } return view } private fun fetchBedCylinderCount() { val someUrl = Constants.someUrl val wbUrl = Constants.wbUrl CoroutineScope(Dispatchers.IO).launch { val docSome = Jsoup.connect(someUrl).get() val docWb = Jsoup.connect(wbUrl).get() val cylinderCnt = docSome.select("#content [class='badge badge-pill badge-success']") val bedCnt = docWb.select("#counter2") withContext(Dispatchers.Main) { txtAvailBed.text = bedCnt.text() txtAvailCylinder.text = cylinderCnt.text() .substring(cylinderCnt.text().length - 2, cylinderCnt.text().length) } } } private fun init(customLayout: View) { cvBed = customLayout.findViewById(R.id.cvBed) cvSafeHome = customLayout.findViewById(R.id.cvHome) cvHelpDesk = customLayout.findViewById(R.id.cvHelpDesk) cvCenter = customLayout.findViewById(R.id.cvCenter) cvAmbulance = customLayout.findViewById(R.id.cvAmbulance) cvHearse = customLayout.findViewById(R.id.cvHearse) cvNodal = customLayout.findViewById(R.id.cvNodal) cvBurial = customLayout.findViewById(R.id.cvBurial) } override fun onClick(v: View?) { when (v!!.id) { R.id.btnEServce -> { val customLayout = layoutInflater .inflate( R.layout.custom_dialog_layout_wb, null ) init(customLayout) clickHandle() val builder = AlertDialog.Builder(requireContext()) builder.setView(customLayout) val dialog = builder.create() dialog.show() } R.id.cvBed -> { url = "https://excise.wb.gov.in/CHMS/Public/Page/CHMS_Public_Hospital_Bed_Availability.aspx" intentBrowse() } R.id.cvHome -> { url = "https://excise.wb.gov.in/CHMS/Public/Page/CHMS_Public_Safe_Home_Bed_Availability.aspx" intentBrowse() } R.id.cvHelpDesk -> { url = "https://excise.wb.gov.in/CHMS/Public/Page/CHMS_Public_District_Contact_Details.aspx?Telephone_Number_Flag=A" intentBrowse() } R.id.cvCenter -> { url = "https://excise.wb.gov.in/CHMS/Public/Page/CHMS_Public_District_Contact_Details.aspx?Telephone_Number_Flag=C" intentBrowse() } R.id.cvAmbulance -> { url = "https://excise.wb.gov.in/CHMS/Public/Page/CHMS_Public_MIS_Ambulance.aspx" intentBrowse() } R.id.cvHearse -> { url = "https://excise.wb.gov.in/CHMS/Public/Page/CHMS_Public_MIS_Hearse_Van.aspx" intentBrowse() } R.id.cvNodal -> { url = "https://excise.wb.gov.in/CHMS/Public/Page/CHMS_Public_Cremation_Nodal_Officer.aspx" intentBrowse() } R.id.cvBurial -> { url = "https://excise.wb.gov.in/CHMS/Public/Page/CHMS_Public_Burial_Cremation_Information.aspx" intentBrowse() } R.id.btnResources -> { val customLayout = layoutInflater .inflate( R.layout.custom_dialog_layout_someannoying, null ) val someannoyingDialogAdapter = SomeannoyingDialogAdapter(requireContext()) rvSomeannoying = customLayout.findViewById(R.id.rvSomeannoying) rvSomeannoying.layoutManager = GridLayoutManager(requireContext(), 2) rvSomeannoying.adapter = someannoyingDialogAdapter someannoyingDialogAdapter.updateList(itemList) val builder = AlertDialog.Builder(requireContext()) builder.setView(customLayout) val dialog = builder.create() dialog.show() } R.id.btnGetCylinder -> { url = "https://covid.someannoying.com/project_oxygen/" intentBrowse() } R.id.btnChatBot -> { openWhatsapp("+917596056446") } R.id.txtAskHelp -> { url = "https://covid.someannoying.com/ask.html" intentBrowse() } } } private fun intentBrowse() { intent = Intent() intent.action = Intent.ACTION_VIEW intent.data = Uri.parse(url) requireContext().startActivity(intent) } private fun clickHandle() { cvBed.setOnClickListener(this) cvSafeHome.setOnClickListener(this) cvHelpDesk.setOnClickListener(this) cvCenter.setOnClickListener(this) cvAmbulance.setOnClickListener(this) cvHearse.setOnClickListener(this) cvNodal.setOnClickListener(this) cvBurial.setOnClickListener(this) } private fun itemListAdder(img: Int, name: String, url: String) { itemList.add(SomeannoynigDialogItems(img, name, url)) } private fun openWhatsapp(num: String) { val intent = Intent(Intent.ACTION_VIEW) intent.`package` = "com.whatsapp" intent.data = Uri.parse("https://api.whatsapp.com/send?phone=$num&text=Help Me") if (requireActivity().packageManager.resolveActivity(intent, 0) != null) { startActivity(intent) } else { Toast.makeText(requireContext(), "Please install whatsapp", Toast.LENGTH_SHORT).show() } } private fun msgInit(v: View?) { btnExit = v!!.findViewById(R.id.btnExit) btnRetry = v.findViewById(R.id.btnRetry) } fun checkConnectivity(context: Context): Boolean { val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val activeNetwork: NetworkInfo? = connectivityManager.activeNetworkInfo if (activeNetwork?.isConnected != null) { return activeNetwork.isConnected } else { return false } } }
9
Kotlin
26
17
f7070477b5a6d0051f1e1f41fe5c856480e21edf
14,965
CovidHelp
MIT License
library/src/main/java/app/juky/squircleview/data/SquircleStyle.kt
CodeHunterDev
467,601,524
true
{"Kotlin": 46757}
package app.juky.squircleview.data import android.content.Context import android.graphics.Bitmap import android.graphics.drawable.Drawable import android.graphics.drawable.GradientDrawable import android.os.Build import android.view.View import androidx.annotation.ColorInt import androidx.annotation.ColorRes import androidx.annotation.DrawableRes import androidx.annotation.IntRange import androidx.core.content.ContextCompat import androidx.core.graphics.drawable.toBitmap import app.juky.squircleview.utils.SquircleGradient import app.juky.squircleview.utils.SquircleShadowProvider.getShadowProvider import app.juky.squircleview.utils.getDefaultRippleDrawable import app.juky.squircleview.utils.getTransparentRippleDrawable /** * Because there are multiple Squircle components (Button, ImageView, ConstraintLayout) there is no possibility * to have 1 super class which will implement all variables. In order to support programmatically changing the * attributes, this style class has been created which will directly communicate with the View and the Core to * update the styles where necessary. */ class SquircleStyle(val context: Context, val view: View, internal val core: SquircleCore) { /** * Set the background image */ var backgroundImage: Bitmap? get() = core.backgroundImage set(value) { core.backgroundImage = value view.invalidate() } /** * Set the background color by color int */ var backgroundColor: Int get() = core.backgroundColor set(@ColorInt color) { core.backgroundColor = color core.shapePaint.color = core.backgroundColor view.invalidate() } /** * Set the background color by resource id */ var backgroundColorRes: Int get() = core.backgroundColor set(@ColorRes resId) { backgroundColor = ContextCompat.getColor(view.context, resId) } /** * Set the elevation of the shadow */ var shadowElevation: Float get() = core.shadowElevation set(value) { core.shadowElevation = value view.elevation = shadowElevation view.invalidate() } /** * Set the shadow color of the elevation by color int */ var shadowElevationColor: Int get() = core.shadowElevationColor set(@ColorInt color) { core.shadowElevationColor = color if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { view.outlineAmbientShadowColor = core.shadowElevationColor view.outlineSpotShadowColor = core.shadowElevationColor view.outlineProvider = getShadowProvider() } view.invalidate() } /** * Set the shadow color of the elevation by resource id */ var shadowElevationColorRes: Int get() = core.shadowElevationColor set(@ColorRes resId) { shadowElevationColor = ContextCompat.getColor(view.context, resId) } /** * Set a drawable gradient as background. Note: Currently, only Gradient Drawables which have * a shape around it are supported, though you could just use a shape without specifying anything. * * ``` * <?xml version="1.0" encoding="utf-8"?> * <shape xmlns:android="http://schemas.android.com/apk/res/android"> * <gradient * android:endColor="#EC5396" * android:startColor="#FFCB71" * android:type="linear" /> * </shape> * ``` */ var gradientDrawable: GradientDrawable? get() = core.gradientDrawable set(drawable) { core.gradientDrawable = drawable view.invalidate() } /** * Set the gradient start color by color int */ var gradientStartColor: Int get() = core.gradientStartColor set(@ColorInt color) { core.gradientStartColor = color view.invalidate() } /** * Set the gradient start color by resource ID. Note: this CANNOT be an android.R.color.* value, because * it won't work with a LinearGradient. */ var gradientStartColorRes: Int get() = core.gradientStartColor set(@ColorRes resId) { gradientStartColor = ContextCompat.getColor(view.context, resId) } /** * Set the gradient end color by color int */ var gradientEndColor: Int get() = core.gradientEndColor set(@ColorInt color) { core.gradientEndColor = color view.invalidate() } /** * Set the gradient end color by resource ID. Note: this CANNOT be an android.R.color.* value, because * it won't work with a LinearGradient. */ var gradientEndColorRes: Int get() = core.gradientEndColor set(@ColorRes resId) { gradientEndColor = ContextCompat.getColor(view.context, resId) } /** * Set the gradient direction using a GradientDirection */ var gradientDirection: GradientDirection get() = core.gradientDirection set(direction) { core.gradientDirection = direction SquircleGradient.onViewSizeChanged(view.width, view.height, view, core) } /** * Set the border color by color int */ var borderColor: Int get() = core.borderColor set(@ColorInt color) { core.borderColor = color core.borderPaint.apply { this.color = core.borderColor } view.invalidate() } /** * Set the border color by resource ID */ var borderColorRes: Int get() = core.borderColor set(@ColorRes resId) { borderColor = ContextCompat.getColor(view.context, resId) } /** * Set the width of the border */ var borderWidth: Float get() = core.borderWidth set(width) { core.borderWidth = width core.borderPaint.apply { this.strokeWidth = core.borderWidth } view.invalidate() } /** * Enable or disable the ripple effect */ var rippleEnabled: Boolean get() = core.rippleEnabled set(enabled) { core.rippleEnabled = enabled if (rippleEnabled && view.hasOnClickListeners()) { view.foreground = rippleDrawable ?: context.getDefaultRippleDrawable() } else { view.foreground = context.getTransparentRippleDrawable() } view.invalidate() } /** * Set a drawable as ripple foreground * * ``` * <ripple xmlns:android="http://schemas.android.com/apk/res/android" * android:color="#2C1D1F"> * <item android:id="@android:id/mask"> * <shape android:shape="rectangle"> * <solid android:color="#2C1D1F" /> * </shape> * </item> * </ripple> * ``` */ var rippleDrawable: Drawable? get() = core.rippleDrawable set(drawable) { core.rippleDrawable = drawable if (view.hasOnClickListeners()) view.foreground = core.rippleDrawable view.invalidate() } /** * Retrieve the configured corner smoothing percentage */ fun getCornerSmoothing() = core.cornerSmoothing /** * Change the default corner smoothing if you want to deflect from the original Squircle. Default Squircle value is 67% */ fun setCornerSmoothing(@IntRange(from = 0, to = Constants.DEFAULT_CORNER_SMOOTHING) cornerSmoothing: Int) { core.cornerSmoothing = cornerSmoothing view.invalidate() } /** * Set the background image using a drawable * * @param drawable Drawable? Background image drawable */ fun setBackgroundImage(drawable: Drawable?) { core.backgroundImage = drawable?.toBitmap() view.invalidate() } /** * Set background image with a drawable resource id * * @param resId Int Drawable resource ID */ fun setBackgroundImage(@DrawableRes resId: Int) { setBackgroundImage(ContextCompat.getDrawable(context, resId)) } /** * Set the gradient as background using a gradient resource id. Note: Currently, only Gradient Drawables which have * a shape around it are supported, though you could just use a shape without specifying anything. * * ``` * <?xml version="1.0" encoding="utf-8"?> * <shape xmlns:android="http://schemas.android.com/apk/res/android"> * <gradient * android:endColor="#EC5396" * android:startColor="#FFCB71" * android:type="linear" /> * </shape> * ``` * @param resId Int Resource id of gradient */ fun setGradientDrawable(@DrawableRes resId: Int) { core.gradientDrawable = ContextCompat.getDrawable(context, resId) as? GradientDrawable view.invalidate() } /** * Set the gradient direction using an angle from 0 to 360 * * @param angle Int Angle from 0 to 360 degrees */ fun setGradientDirection(angle: Int) { core.gradientDirection = GradientDirection.getByAngle(angle) SquircleGradient.onViewSizeChanged(view.width, view.height, view, core) } /** * Setup a ripple, which will usually happen after a click listener has been set afterwards */ internal fun setupRipple() { // Trigger setter which will invalidate the view rippleEnabled = core.rippleEnabled } }
0
null
0
0
7d91bb922fdbe6d64d68a2db16172b0b83bea2fe
9,716
SquircleView
MIT License
core/compiler.common.jvm/src/org/jetbrains/kotlin/load/java/JavaNullabilityAnnotationsStatus.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.load.java data class JavaNullabilityAnnotationsStatus( val reportLevelBefore: ReportLevel, val sinceVersion: KotlinVersion? = KotlinVersion(1, 0), val reportLevelAfter: ReportLevel = reportLevelBefore, ) { companion object { val DEFAULT = JavaNullabilityAnnotationsStatus(ReportLevel.STRICT) } }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
564
kotlin
Apache License 2.0
app/src/main/java/com/dee/popularmovies/data/network/local/DataStoreHelper.kt
DeeAndroid
611,321,790
false
null
package com.dee.popularmovies.data.network.local import android.content.Context import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.preferencesDataStore import androidx.lifecycle.LiveData import androidx.lifecycle.asLiveData import com.dee.popularmovies.data.network.local.Constants.MVE_PREF_NAME import kotlinx.coroutines.flow.map //Instance of DataStore val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = MVE_PREF_NAME) /** * Add Boolean to the data store */ suspend fun Context.writeBool(key: String, value: Boolean) { dataStore.edit { pref -> pref[booleanPreferencesKey(key)] = value } } /** * Reading the Boolean from the data store */ fun Context.readBool(key: String): LiveData<Boolean?> { return dataStore.data.map { pref -> pref[booleanPreferencesKey(key)] }.asLiveData() }
0
Kotlin
0
0
bcbaf3d0318821e2a26b03358d70c9e0aee542a3
1,035
TmdbMovies
MIT License
BACK_UP/9-RxJava/AndroidArchitectureStudy/app/src/main/java/com/mtjin/androidarchitecturestudy/data/search/source/local/MovieLocalDataSource.kt
mtjin
255,555,417
false
null
package com.mtjin.androidarchitecturestudy.data.search.source.local import com.mtjin.androidarchitecturestudy.data.search.Movie import io.reactivex.Completable import io.reactivex.Single interface MovieLocalDataSource { fun insertMovies(movies: List<Movie>): Completable fun getAllMovies(): Single<List<Movie>> fun getSearchMovies(title: String): Single<List<Movie>> fun deleteAllMovies(): Completable }
1
Kotlin
1
17
affc89caa7d0daa93b474a47826ee34401af986e
421
android-architecture-study-movieapp
MIT License
app/src/main/java/ga/justdevelops/temonitorv2/ui/main/MainFragment.kt
Alex-mur
238,934,871
false
null
package ga.justdevelops.temonitorv2.ui.main import android.animation.Animator import android.animation.AnimatorInflater import android.app.AlertDialog import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.EditText import android.widget.FrameLayout import android.widget.TextView import androidx.fragment.app.DialogFragment import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import ga.justdevelops.temonitorv2.R import kotlinx.android.synthetic.main.main_fragment.* import kotlinx.coroutines.* class MainFragment : Fragment(), EditAddressDialogFragment.EditAddressListener { companion object { fun newInstance() = MainFragment() } private lateinit var viewModel: MainViewModel private val sensorsViewList = ArrayList<FrameLayout>() private val animations = ArrayList<Animator>() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val view = inflater.inflate(R.layout.main_fragment, container, false) findAllViews(view) return view } private fun findAllViews(view: View) { sensorsViewList.add(view.findViewById(R.id.sensor_0)) sensorsViewList.add(view.findViewById(R.id.sensor_1)) sensorsViewList.add(view.findViewById(R.id.sensor_2)) sensorsViewList.add(view.findViewById(R.id.sensor_3)) sensorsViewList.add(view.findViewById(R.id.sensor_4)) sensorsViewList.add(view.findViewById(R.id.sensor_5)) sensorsViewList.add(view.findViewById(R.id.sensor_6)) sensorsViewList.add(view.findViewById(R.id.sensor_7)) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) initViewModel() subscribeLiveData() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initListeners() } private fun initViewModel() { viewModel = ViewModelProvider(this).get(MainViewModel::class.java) } override fun onResume() { super.onResume() viewModel.startSensorsDataUpdating() } override fun onPause() { super.onPause() viewModel.stopSensorsUpdating() } private fun subscribeLiveData() { viewModel.getSensorsList().observe(this, Observer { list -> CoroutineScope(Dispatchers.Main).launch { list.forEach { if (it.value.isNotEmpty()) { withContext(Dispatchers.IO) {Thread.sleep(300)} startSwingAnimation(it.id) setSensorName(it.id, it.name) setSensorValue(it.id, it.value) setSensorDate(it.id, it.date) enableSensor(it.id) } else { disableSensor(it.id) } } } }) viewModel.getIsShowEditAddressDialog().observe(this, Observer { if (it) showChangeAddressDialog() }) viewModel.getIsShowConnectionAlert().observe(this, Observer { if (it) showConnectionAlert() else hideConnectionAlert() }) } private fun startSwingAnimation(id: Int) { context?.let { val animation = AnimatorInflater.loadAnimator(it, R.animator.flipper) animations.add(animation) sensorsViewList[id] .let { sensorLayout -> animation.setTarget(sensorLayout) animation.start() } } } private fun hideConnectionAlert() { tv_connection_alert.visibility = View.GONE } private fun showConnectionAlert() { tv_connection_alert.visibility = View.VISIBLE } private fun enableSensor(id: Int) { sensorsViewList[id].visibility = View.VISIBLE } private fun disableSensor(id: Int) { sensorsViewList[id].visibility = View.GONE } private fun setSensorName(id: Int, name: String) { sensorsViewList[id].findViewById<TextView>(R.id.tv_sensor_name).text = name } private fun setSensorValue(id: Int, value: String) { sensorsViewList[id].findViewById<TextView>(R.id.tv_sensor_value).text = value } private fun setSensorDate(id: Int, date: String) { sensorsViewList[id].findViewById<TextView>(R.id.tv_sensor_date_value).text = date } override fun onDestroyView() { animations.forEach { it.cancel() it.end() } animations.clear() super.onDestroyView() } private fun showRenameSensorDialog(id: Int) { val input = EditText(context) AlertDialog.Builder(context) .setTitle(getString(R.string.rename_sensor)) .setView(input) .setPositiveButton(getString(R.string.btn_save)) { dialog, _ -> viewModel.renameSensor(id, input.text.toString()) dialog.dismiss() } .setNeutralButton(getString(R.string.btn_cancel)) { dialog, _ -> dialog.dismiss() } .show() } private fun initListeners() { for (i in 0..7) { sensorsViewList[i].findViewById<TextView>(R.id.tv_sensor_name).setOnLongClickListener { showRenameSensorDialog(i) true } } iv_settings.setOnClickListener { viewModel.onSettingsBtnPressed() } } private fun showChangeAddressDialog() { EditAddressDialogFragment.getInstance(viewModel.getCurrentDeviceAddress()).let { it.setStyle(DialogFragment.STYLE_NORMAL, 0) it.show(childFragmentManager, "") } } override fun onAddressEdited(address: String) { viewModel.setDeviceAddress(address) } }
0
Kotlin
0
0
a4e71af619e721ae9f69119ba3eff0c9297880a2
6,124
temonitor
Apache License 2.0
test-utils/src/main/kotlin/com/google/devtools/ksp/processor/JavaToKotlinMapProcessor.kt
google
297,744,725
false
{"Kotlin": 2173589, "Shell": 5321, "Java": 3893}
/* * Copyright 2020 Google LLC * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.devtools.ksp.processor import com.google.devtools.ksp.KspExperimental import com.google.devtools.ksp.getJavaClassByName import com.google.devtools.ksp.getKotlinClassByName import com.google.devtools.ksp.processing.Resolver import com.google.devtools.ksp.symbol.* import com.google.devtools.ksp.getClassDeclarationByName @KspExperimental open class JavaToKotlinMapProcessor : AbstractTestProcessor() { val results = mutableListOf<String>() val typeCollector = TypeCollectorNoAccessor() val types = mutableSetOf<KSType>() val javaClasses = listOf( "java.lang.String", "java.lang.Integer", "java.util.List", "java.util.Map.Entry", "java.lang.Void", ) val kotlinClasses = listOf( "kotlin.Throwable", "kotlin.Int", "kotlin.Nothing", "kotlin.IntArray", ) override fun process(resolver: Resolver): List<KSAnnotated> { javaClasses.forEach { val k = resolver.mapJavaNameToKotlin( resolver.getKSNameFromString(it) )?.asString() results.add("$it -> $k") } kotlinClasses.forEach { val j = resolver.mapKotlinNameToJava( resolver.getKSNameFromString(it) )?.asString() results.add("$it -> $j") } if (resolver.getClassDeclarationByName("java.lang.String") != resolver.getJavaClassByName("kotlin.String")) results.add("Error: getJavaClassByName") if (resolver.getClassDeclarationByName("kotlin.String") != resolver.getKotlinClassByName("java.lang.String")) results.add("Error: getKotlinClassByName") return emptyList() } override fun toResult(): List<String> { return results } }
370
Kotlin
268
2,854
a977fb96b05ec9c3e15b5a0cf32e8e7ea73ab3b3
2,479
ksp
Apache License 2.0
shared/presentation/src/androidMain/kotlin/com/moonlightbutterfly/rigplay/gamelist/view/GameListViewImpl.kt
Dragoonov
653,808,838
false
null
package com.moonlightbutterfly.rigplay.gamelist.view import com.arkivanov.mvikotlin.core.utils.diff import com.arkivanov.mvikotlin.core.view.BaseMviView import com.arkivanov.mvikotlin.core.view.ViewRenderer import com.moonlightbutterfly.rigplay.gamelist.stateholder.GameListStateHolder import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch class GameListViewImpl( private val stateHolder: GameListStateHolder, coroutineScope: CoroutineScope ) : BaseMviView<GameListView.Model, GameListView.Event>(), GameListView { override val renderer: ViewRenderer<GameListView.Model> = diff { diff(GameListView.Model::games) { coroutineScope.launch { stateHolder.games.emit(it) } } diff(get = GameListView.Model::isLoading, set = { coroutineScope.launch { stateHolder.isLoading.value = it } }) } init { coroutineScope.launch { stateHolder.refreshListener.collect { dispatch(GameListView.Event.RefreshTriggered) } } } }
0
Kotlin
0
0
c8a45a5db1fbe73f1801b67dbdd0b70a1757b380
1,173
RigPlay
Apache License 2.0
src/main/kotlin/no/nav/syfo/client/saf/SafJournalpostClient.kt
navikt
121,716,621
false
{"Kotlin": 371293, "Dockerfile": 440}
package no.nav.syfo.client.saf import io.ktor.client.HttpClient import io.ktor.client.request.header import io.ktor.client.request.post import io.ktor.http.ContentType import io.ktor.http.contentType import kotlinx.coroutines.runBlocking import no.nav.helsearbeidsgiver.utils.log.logger import no.nav.syfo.client.saf.model.GetJournalpostRequest import no.nav.syfo.client.saf.model.JournalResponse import no.nav.syfo.client.saf.model.Journalpost class SafJournalpostClient( private val httpClient: HttpClient, private val basePath: String, private val getAccessToken: () -> String ) { private val logger = this.logger() fun getJournalpostMetadata(journalpostId: String): Journalpost? { val accessToken = getAccessToken() logger.info("Henter journalpostmetadata for $journalpostId with token size " + accessToken.length) val response = runBlocking { httpClient.post<JournalResponse>(basePath) { contentType(ContentType.Application.Json) header("Authorization", "Bearer $accessToken") header("X-Correlation-ID", journalpostId) body = GetJournalpostRequest(query = lagQuery(journalpostId)) } } if (response.status == 401) { throw NotAuthorizedException(journalpostId) } if (response.errors != null && response.errors.isNotEmpty()) { throw ErrorException(journalpostId, response.errors.toString()) } return response.data!!.journalpost } } open class SafJournalpostException(journalpostId: String) : Exception(journalpostId) open class NotAuthorizedException(journalpostId: String) : SafJournalpostException("SAF ga ikke tilgang til å lese ut journalpost '$journalpostId'") open class ErrorException(journalpostId: String, errors: String) : SafJournalpostException("SAF returnerte feil journalpost '$journalpostId': $errors") open class EmptyException(journalpostId: String) : SafJournalpostException("SAF returnerte tom journalpost '$journalpostId'")
10
Kotlin
3
4
ee6a2a64ac24730782e8078f3d75e14a79fdebe3
2,059
syfoinntektsmelding
MIT License
packages/react-native-gradle-plugin/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/internal/BuildCodegenCLITaskTest.kt
react-native-tvos
177,633,560
false
{"C++": 4171493, "Java": 2894629, "JavaScript": 2550826, "Objective-C++": 1744757, "Objective-C": 1406737, "Kotlin": 1267557, "Ruby": 439793, "CMake": 94624, "TypeScript": 85912, "Shell": 59007, "C": 53931, "Assembly": 14920, "HTML": 1473, "Swift": 739}
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.react.tasks.internal import com.facebook.react.tests.createTestTask import org.junit.Assert.assertEquals import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder class BuildCodegenCLITaskTest { @get:Rule val tempFolder = TemporaryFolder() @Test fun buildCodegenCli_bashWindowsHome_isSetCorrectly() { val bashPath = tempFolder.newFile("bash").absolutePath val task = createTestTask<BuildCodegenCLITask> { it.bashWindowsHome.set(bashPath) } assertEquals(bashPath, task.bashWindowsHome.get()) } }
10
C++
144
928
46d7dc3cedec1cb71538c13df1eeb53b40865f7f
757
react-native-tvos
MIT License
src/main/kotlin/com/sakurawald/silicon/action/abstracts/LoginAction.kt
K85
390,397,490
false
null
@file:Suppress("unused") package com.sakurawald.silicon.action.abstracts import com.sakurawald.silicon.data.beans.request.LoginRequest import com.sakurawald.silicon.data.beans.response.LoginResponse import com.sakurawald.silicon.debug.LoggerManager import com.sakurawald.silicon.debug.LoggerManager.logDebug import okhttp3.Response abstract class LoginAction : Action<LoginRequest, LoginResponse>() { abstract override fun execute(requestBean: LoginRequest): LoginResponse companion object { @JvmStatic fun getLoginMessage(response: Response): String { return response.code.toString() + " " + response.message } /** * 根据HTTP请求中Headers中的set-cookie参数获取cookie. */ @JvmStatic fun getLoginToken(response: Response, cookie_name: String): String? { /** Analyse Cookies. */ val setCookie = response.headers("set-cookie").toString() logDebug("Login Action: set-cookie = $setCookie") val offset = cookie_name.length + 1 var token: String? = null try { token = setCookie.substring(setCookie.indexOf("$cookie_name=") + offset, setCookie.indexOf(";")) } catch (e: StringIndexOutOfBoundsException) { LoggerManager.reportException(e) } return token } } }
0
Kotlin
0
0
aa5fc191833bac53eed2e87464605e9f10d7f5fb
1,384
Silicon
The Unlicense
TUIKit/TUICallKit/tuicallkit-kt/src/main/java/com/tencent/qcloud/tuikit/tuicallkit/view/common/RoundShadowLayout.kt
TencentCloud
572,969,313
false
{"Text": 1, "Ignore List": 4, "Markdown": 22, "Gradle": 20, "XML": 1030, "Java": 1084, "Proguard": 1, "JSON": 4, "Kotlin": 85, "INI": 1, "Shell": 1, "Batchfile": 1, "Java Properties": 1}
package com.tencent.qcloud.tuikit.tuicallkit.view.common import android.content.Context import android.graphics.* import android.graphics.drawable.BitmapDrawable import android.util.AttributeSet import android.widget.FrameLayout import com.tencent.qcloud.tuikit.tuicallkit.R class RoundShadowLayout(context: Context, attrs: AttributeSet?) : FrameLayout(context, attrs) { private val radiusArray = FloatArray(8) private var shadowPaint: Paint private var shadowRect: RectF private var shadowPath: Path private var shadowRadius = 15f private var shadowColor = 0 private var shadowX = 0f private var shadowY = 0f private var roundRadius = 32f private var roundPaint: Paint private var roundRect: RectF private var roundPath: Path constructor(context: Context) : this(context, null) {} init { shadowColor = context.resources.getColor(R.color.tuicallkit_color_bg_float_view) for (i in radiusArray.indices) { radiusArray[i] = roundRadius } roundPaint = Paint() roundPath = Path() roundRect = RectF() shadowRect = RectF() shadowPath = Path() shadowPaint = Paint() } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { var width = 0 var height = 0 for (i in 0 until childCount) { val child = getChildAt(i) val lp = child.layoutParams val childWidthSpec = getChildMeasureSpec(widthMeasureSpec - shadowRadius.toInt() * 2, 0, lp.width) val childHeightSpec = getChildMeasureSpec(heightMeasureSpec - shadowRadius.toInt() * 2, 0, lp.height) measureChild(child, childWidthSpec, childHeightSpec) val mlp = child.layoutParams as MarginLayoutParams val childWidth = child.measuredWidth + mlp.leftMargin + mlp.rightMargin val childHeight = child.measuredHeight + mlp.topMargin + mlp.bottomMargin width = width.coerceAtLeast(childWidth) height = height.coerceAtLeast(childHeight) } setMeasuredDimension( width + paddingLeft + paddingRight + shadowRadius.toInt() * 2, height + paddingTop + paddingBottom + shadowRadius.toInt() * 2 ) } override fun onSizeChanged(width: Int, height: Int, oldw: Int, oldh: Int) { super.onSizeChanged(width, height, oldw, oldh) if (width > 0 && height > 0 && shadowRadius > 0) { setBackgroundCompat(width, height) } } override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { for (i in 0 until childCount) { val child = getChildAt(i) val lp = child.layoutParams as MarginLayoutParams val lc = shadowRadius.toInt() + lp.leftMargin + paddingLeft val tc = shadowRadius.toInt() + lp.topMargin + paddingTop val rc = lc + child.measuredWidth val bc = tc + child.measuredHeight child.layout(lc, tc, rc, bc) } } override fun dispatchDraw(canvas: Canvas) { roundRect[shadowRadius, shadowRadius, width - shadowRadius] = height - shadowRadius canvas!!.saveLayer(roundRect, null, Canvas.ALL_SAVE_FLAG) super.dispatchDraw(canvas) roundPath.reset() roundPath.addRoundRect(roundRect, radiusArray, Path.Direction.CW) clipRound(canvas) canvas.restore() } private fun clipRound(canvas: Canvas) { roundPaint.color = Color.WHITE roundPaint.isAntiAlias = true roundPaint.style = Paint.Style.FILL roundPaint.xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_OUT) val path = Path() path.addRect(0f, 0f, width.toFloat(), height.toFloat(), Path.Direction.CW) path.op(roundPath, Path.Op.DIFFERENCE) canvas.drawPath(path, roundPaint) } private fun setBackgroundCompat(width: Int, height: Int) { val bitmap: Bitmap = createShadowBitmap(width, height, shadowRadius, shadowX, shadowY, shadowColor) val drawable = BitmapDrawable(resources, bitmap) background = drawable } private fun createShadowBitmap( shadowWidth: Int, shadowHeight: Int, shadowRadius: Float, dx: Float, dy: Float, shadowColor: Int ): Bitmap { val output: Bitmap = Bitmap.createBitmap(shadowWidth, shadowHeight, Bitmap.Config.ARGB_8888) val canvas = Canvas(output) shadowRect[shadowRadius, shadowRadius, shadowWidth - shadowRadius] = shadowHeight - shadowRadius shadowRect.top += dy shadowRect.bottom -= dy shadowRect.left += dx shadowRect.right -= dx shadowPaint.isAntiAlias = true shadowPaint.style = Paint.Style.FILL shadowPaint.color = shadowColor if (!isInEditMode) { shadowPaint.setShadowLayer(shadowRadius, dx, dy, shadowColor) } shadowPath.reset() shadowPath.addRoundRect(shadowRect, radiusArray, Path.Direction.CW) canvas.drawPath(shadowPath, shadowPaint) return output } }
1
Java
9
29
f13719f2d8a7fce2ff4683a3ac70dd91a1be2245
5,121
chat-uikit-android
Apache License 2.0
src/main/kotlin/minek/kotlin/everywhere/server/ContainerServer.kt
kotlin-everywhere
92,652,503
false
{"Kotlin": 20093}
package minek.kotlin.everywhere.server import org.eclipse.jetty.server.Server import org.eclipse.jetty.servlet.ServletHandler import org.eclipse.jetty.servlet.ServletHolder fun <T : Container> T.runServer(port: Int): T { val server = Server(port) val handler = ServletHandler() server.handler = handler handler.addServletWithMapping(ServletHolder(ContainerServlet(this)), "/*") server.start() server.join() return this }
0
Kotlin
0
0
2239c8a90738f56fe5881891f92b09401484f6e9
452
_kotlin-everywhere-server
MIT License
app/src/main/java/com/yoyiyi/soleil/module/app/BrowerActivity.kt
yoyiyi
97,073,764
false
null
package com.yoyiyi.soleil.module.app import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.text.TextUtils import android.view.KeyEvent import android.view.Menu import android.view.MenuItem import android.view.View import android.webkit.WebChromeClient import android.webkit.WebSettings import android.webkit.WebView import android.webkit.WebViewClient import cn.sharesdk.onekeyshare.OnekeyShare import com.yoyiyi.soleil.R import com.yoyiyi.soleil.constant.Constants import com.yoyiyi.soleil.utils.AppUtils import com.yoyiyi.soleil.utils.ClipboardUtils import com.yoyiyi.soleil.utils.ToastUtils import com.yoyiyi.soleil.widget.statusbar.StatusBarUtil import kotlinx.android.synthetic.main.activity_brower.* import kotlinx.android.synthetic.main.common_toolbar.* import kotlinx.android.synthetic.main.layout_loading.* /** * @author zzq 作者 E-mail: [email protected] * * * @date 创建时间:2017/6/9 21:56 * * 描述:浏览器界面 */ class BrowerActivity : AppCompatActivity() { private var mTitle: String? = null private var mUrl: String? = null private var mImg: String? = null companion object { fun startActivity(context: Context, url: String, title: String, img: String) { val intent = Intent(context, BrowerActivity::class.java) intent.putExtra(Constants.EXTRA_TITLE, title) intent.putExtra(Constants.EXTRA_URL, url) intent.putExtra(Constants.EXTRA_IMAGE, img) context.startActivity(intent) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_brower) initVariables() initWedgit() } private fun initToolar() { toolbar?.let { it.setNavigationIcon(R.drawable.ic_clip_back_white) it.title = if (TextUtils.isEmpty(mTitle)) "详情" else mTitle setSupportActionBar(it) it.setNavigationOnClickListener { finish() } } } private fun initWedgit() { initToolar() initWebView() StatusBarUtil.setColorNoTranslucent(this, AppUtils.getColor(R.color.colorPrimary)) //强制隐藏加载框 // AppUtils.runOnUIDelayed(() -> mPwLoading.setVisibility(View.GONE), 650); } private fun initVariables() { intent?.let { mTitle = intent.getStringExtra(Constants.EXTRA_TITLE) mUrl = intent.getStringExtra(Constants.EXTRA_URL) mImg = intent.getStringExtra(Constants.EXTRA_IMAGE) } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_brower, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId when (id) { R.id.menu_open -> { val intent = Intent(Intent.ACTION_VIEW) intent.data = Uri.parse(mUrl) startActivity(intent) } R.id.menu_share -> showShare() R.id.menu_copy -> { ClipboardUtils.copyText(mUrl) ToastUtils.showSingleLongToast("复制成功") } } return super.onOptionsItemSelected(item) } internal inner class WebClientBase : WebViewClient() { override fun onPageFinished(webView: WebView, s: String) { super.onPageFinished(webView, s) pw_loading?.visibility = View.GONE web_view?.settings?.blockNetworkImage = false val h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED) val w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED) web_view?.measure(w, h) } override fun onReceivedError(webView: WebView, i: Int, s: String, s1: String) { super.onReceivedError(webView, i, s, s1) pw_loading?.visibility = View.GONE val errorHtml = "<html><body><h2>找不到网页</h2></body></html>" web_view?.loadDataWithBaseURL(null, errorHtml, "text/html", "UTF-8", null) } } @SuppressLint("SetJavaScriptEnabled") internal fun initWebView() { val webChromeClient = WebClient() val webViewClient = WebClientBase() val webSettings = web_view.settings //设置js支持 webSettings.javaScriptEnabled = true // 设置支持javascript脚本 webSettings.javaScriptCanOpenWindowsAutomatically = false //设置缓存 webSettings.cacheMode = WebSettings.LOAD_NO_CACHE webSettings.domStorageEnabled = true webSettings.setGeolocationEnabled(true) webSettings.useWideViewPort = true//关键点 webSettings.loadWithOverviewMode = true//全屏 webSettings.builtInZoomControls = true// 设置显示缩放按钮 webSettings.setSupportZoom(true)//支持缩放 webSettings.displayZoomControls = false webSettings.setAppCacheEnabled(true) webSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN web_view.isDrawingCacheEnabled = true web_view.settings.blockNetworkImage = true web_view.setWebViewClient(webViewClient) web_view.requestFocus(View.FOCUS_DOWN) web_view.settings.defaultTextEncodingName = "UTF-8" web_view.setWebChromeClient(webChromeClient) web_view.loadUrl(mUrl) } override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean { if (keyCode == KeyEvent.KEYCODE_BACK && web_view!!.canGoBack()) { web_view.goBack()// 返回前一个页面 return true } return super.onKeyDown(keyCode, event) } internal inner class WebClient : WebChromeClient() { override fun onProgressChanged(webView: WebView, i: Int) { if (i >= 40) { pw_loading.visibility = View.GONE } else { pw_loading.visibility = View.VISIBLE } web_view?.settings?.blockNetworkImage = false super.onProgressChanged(webView, i) } } override fun onDestroy() { web_view?.destroy() super.onDestroy() } private fun showShare() { // ShareSDK.initSDK(this); val oks = OnekeyShare() //关闭sso授权 oks.disableSSOWhenAuthorize() // title标题,印象笔记、邮箱、信息、微信、人人网和QQ空间等使用 oks.setTitle("来自" + getString(R.string.app_name) + "的分享") // titleUrl是标题的网络链接,QQ和QQ空间等使用 oks.setTitleUrl(mUrl) // text是分享文本,所有平台都需要这个字段 oks.text = mTitle + "" + mUrl oks.setImageUrl(mImg) // imagePath是图片的本地路径,Linked-In以外的平台都支持此参数 //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片 // url仅在微信(包括好友和朋友圈)中使用 oks.setUrl(mUrl) // comment是我对这条分享的评论,仅在人人网和QQ空间使用 oks.setComment("文本") // site是分享此内容的网站名称,仅在QQ空间使用 oks.setSite(getString(R.string.app_name)) // siteUrl是分享此内容的网站地址,仅在QQ空间使用 oks.setSiteUrl(mUrl) // 启动分享GUI oks.show(this) } }
2
null
25
141
044f76fd499bb49b0fe94d9c83c9bb1db283b8ea
7,164
bilisoleil-kotlin
Apache License 2.0
app/src/main/java/com/videoengager/demoapp/PushNotificationsReceiverService.kt
VideoEngager
367,585,600
false
{"Kotlin": 77119}
package com.videoengager.demoapp import android.Manifest import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Build import android.util.Log import androidx.core.app.ActivityCompat import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import com.google.firebase.messaging.FirebaseMessagingService import com.google.firebase.messaging.RemoteMessage import java.util.Random import java.util.UUID class PushNotificationsReceiverService : FirebaseMessagingService() { val CHANNEL_ID = "14bafbfc-22f8-11ee-be56-0242ac120002" override fun onMessageReceived(message: RemoteMessage) { Log.d("PushNotifications", message.data.toString()) if(message.notification!=null && message.data.isNotEmpty() && message.data.containsKey("veurl")) { //send custom notification when App is on foreground val pendingIntent: PendingIntent = PendingIntent.getActivity(this, 0, Intent(this, VEActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK action = Intent.ACTION_VIEW data = Uri.parse(message.data.get("veurl")) }, PendingIntent.FLAG_IMMUTABLE ) val builder = NotificationCompat.Builder(applicationContext, CHANNEL_ID) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle(message.notification?.title) .setContentText(message.notification?.body) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setContentIntent(pendingIntent) .setAutoCancel(true) createNotificationChannel(CHANNEL_ID) with(NotificationManagerCompat.from(this)) { if (ActivityCompat.checkSelfPermission(applicationContext, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED){ notify(Random().nextInt(), builder.build()) } } } } private fun createNotificationChannel(channelID : String) { // Create the NotificationChannel, but only on API 26+ because // the NotificationChannel class is new and not in the support library if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val importance = NotificationManager.IMPORTANCE_DEFAULT val channel = NotificationChannel(channelID, "VideoCall channel", importance).apply { description = "" } // Register the channel with the system val notificationManager: NotificationManager = applicationContext.getSystemService( Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(channel) } } }
0
Kotlin
0
1
fd4121325d798f8d329ce5babe77094b6a77bd14
3,033
SmartVideo-Android-SDK-Demo-App
MIT License
app/src/main/java/com/bimalghara/mp3downloader/presentation/home/HomeFragment.kt
bimalgharagithubprofile
656,034,656
false
null
package com.bimalghara.mp3downloader.presentation.home import android.app.Activity import android.content.Intent import android.os.Build import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.activity.result.contract.ActivityResultContracts import androidx.documentfile.provider.DocumentFile import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import com.bimalghara.mp3downloader.R import com.bimalghara.mp3downloader.data.error.* import com.bimalghara.mp3downloader.databinding.FragmentHomeBinding import com.bimalghara.mp3downloader.presentation.base.BaseFragment import com.bimalghara.mp3downloader.utils.* import com.bimalghara.mp3downloader.utils.FileUtil.protectedDirectories import com.bimalghara.mp3downloader.utils.permissions.PermissionManager import com.bimalghara.mp3downloader.utils.permissions.Permissions import com.google.android.material.progressindicator.CircularProgressIndicator.INDICATOR_DIRECTION_COUNTERCLOCKWISE import com.google.android.material.progressindicator.CircularProgressIndicatorSpec import com.google.android.material.progressindicator.IndeterminateDrawable import dagger.hilt.android.AndroidEntryPoint /** * Created by BimalGhara */ @AndroidEntryPoint class HomeFragment : BaseFragment<FragmentHomeBinding>() { private val logTag = javaClass.simpleName private val homeViewModel: HomeViewModel by viewModels() private val permissionManager = PermissionManager.from(this) private var progressIndicatorDrawable: IndeterminateDrawable<CircularProgressIndicatorSpec>? = null private val startActivityForDirectoryPickUp = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> if (result.resultCode == Activity.RESULT_OK) { val treeUri = result.data?.data Log.e(logTag, "selected treeUri: ${treeUri.toString()}") if (treeUri != null && context != null) { val treeDocument:DocumentFile? = DocumentFile.fromTreeUri(context!!, treeUri) Log.e(logTag, "selected treeDocument: ${treeDocument?.uri?.path}") if(treeDocument != null){ Log.e(logTag, "selected treeDocument canWrite: ${treeDocument.canWrite()}") if(treeDocument.canWrite()){ homeViewModel.setSelectedPath(treeDocument) } else homeViewModel.showError(CustomException(cause = ERROR_WRITE_PERMISSION)) } else homeViewModel.showError(CustomException(cause = ERROR_SELECT_DIRECTORY_FAILED)) } else homeViewModel.showError(CustomException(cause = ERROR_SELECT_DIRECTORY_FAILED)) } } override fun getFragmentBinding( inflater: LayoutInflater, container: ViewGroup? ) = FragmentHomeBinding.inflate(inflater, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.etDestinationFolder.setOnClickListener { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) { permissionManager .request(Permissions.Storage) .rationale("We need all Permissions to save file") .checkPermission { granted -> if (granted) { Log.e(logTag, "runtime permissions allowed") startActivityDirectoryPickUp() } else { Log.e(logTag, "runtime permissions denied") homeViewModel.showError(CustomException(cause = ERROR_NO_PERMISSION)) } } } else startActivityDirectoryPickUp() } binding.btnClearLink.setOnClickListener { binding.etLink.setText("") } context?.let { context -> val spec = CircularProgressIndicatorSpec( context, null, 0, com.google.android.material.R.style.Widget_Material3_CircularProgressIndicator_ExtraSmall ).apply { indicatorColors = intArrayOf(context.getColorFromAttr(com.google.android.material.R.attr.colorOnPrimary)) trackThickness = context.resources.getDimension(R.dimen.track_thickness).toInt() indicatorDirection = INDICATOR_DIRECTION_COUNTERCLOCKWISE } progressIndicatorDrawable = IndeterminateDrawable.createCircularDrawable(context, spec) } binding.btnDownload.setOnClickListener { binding.root.hideKeyboard() context?.let { context -> homeViewModel.grabVideoInfo(context, binding.etLink.text) } } } override fun observeViewModel() { observeError(homeViewModel.errorSingleEvent) observe(homeViewModel.selectedPathLiveData) { Log.d(logTag, "observe selectedPathLiveData | $it") if(it?.uri?.path != null) { val folder = it.uri.path!!.split("/").last() if (protectedDirectories.contains(folder)) { homeViewModel.setSelectedPath(null) homeViewModel.showError(CustomException(cause = ERROR_PROTECTED_DIRECTORY)) } else { binding.etDestinationFolder.text = folder } } } observe(homeViewModel.videoDetailsLiveData) { Log.d(logTag, "observe usersLiveData | $it") when (it) { is ResourceWrapper.Loading -> { disableInputs() } is ResourceWrapper.Success -> { it.data!!.also { vd -> vd.selectedUri = homeViewModel.selectedPathLiveData.value?.uri } findNavController().navigate( HomeFragmentDirections.actionUsersFragmentToProcessFileFragment(it.data) ) } else -> { enableInputs() } } } } private fun startActivityDirectoryPickUp() { val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE) startActivityForDirectoryPickUp.launch(intent) } private fun enableInputs() { binding.btnDownload.icon = null context?.let { binding.btnDownload.text = it.getStringFromResource(R.string.download) } binding.etLink.isEnabled = true binding.etLink.alpha = 1F binding.etDestinationFolder.isEnabled = true binding.etDestinationFolder.alpha = 1F binding.btnDownload.isEnabled = true binding.btnDownload.isClickable = true } private fun disableInputs() { progressIndicatorDrawable?.let{ binding.btnDownload.icon = progressIndicatorDrawable } context?.let { binding.btnDownload.text = it.getStringFromResource(R.string.grabbing) } binding.etLink.isEnabled = false binding.etLink.alpha = 0.5F binding.etDestinationFolder.isEnabled = false binding.etDestinationFolder.alpha = 0.5F binding.btnDownload.isEnabled = false binding.btnDownload.isClickable = false } }
0
Kotlin
0
0
e1e9308e28938e6fb4b0f1f6327538cff3776dbf
7,434
Android-YouTube-Video-Downloader-Convert-mp3-using-ytdlp-FFmpeg
Apache License 2.0
cmp-common/src/commonMain/kotlin/ru/beryukhov/coffeegram/PagesContent.kt
phansier
274,754,270
false
null
@file:OptIn(ExperimentalResourceApi::class) package ru.beryukhov.coffeegram import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Create import androidx.compose.material.icons.filled.Settings import androidx.compose.material3.Icon import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import coffeegram.cmp_common.generated.resources.Res import coffeegram.cmp_common.generated.resources.calendar import coffeegram.cmp_common.generated.resources.settings import io.github.alexzhirkevich.cupertino.adaptive.AdaptiveNavigationBar import io.github.alexzhirkevich.cupertino.adaptive.AdaptiveNavigationBarItem import io.github.alexzhirkevich.cupertino.adaptive.AdaptiveScaffold import org.jetbrains.compose.resources.ExperimentalResourceApi import org.jetbrains.compose.resources.stringResource import ru.beryukhov.coffeegram.app_ui.CoffeegramTheme import ru.beryukhov.coffeegram.model.DaysCoffeesStore import ru.beryukhov.coffeegram.model.NavigationIntent import ru.beryukhov.coffeegram.model.NavigationState import ru.beryukhov.coffeegram.model.NavigationStore import ru.beryukhov.coffeegram.model.ThemeState import ru.beryukhov.coffeegram.model.ThemeStore import ru.beryukhov.coffeegram.pages.CoffeeListAppBar import ru.beryukhov.coffeegram.pages.CoffeeListPage import ru.beryukhov.coffeegram.pages.SettingsAppBar import ru.beryukhov.coffeegram.pages.SettingsPage import ru.beryukhov.coffeegram.pages.TableAppBar import ru.beryukhov.coffeegram.pages.TablePage @Composable fun PagesContent( navigationStore: NavigationStore, daysCoffeesStore: DaysCoffeesStore, themeStore: ThemeStore, modifier: Modifier = Modifier, topPadding: Dp = 0.dp, ) { val navigationState: NavigationState by navigationStore.state.collectAsState() val currentNavigationState = navigationState val snackbarHostState = remember { SnackbarHostState() } CoffeegramTheme( themeState = themeState(themeStore) ) { AdaptiveScaffold( modifier = modifier, topBar = { when (currentNavigationState) { is NavigationState.TablePage -> TableAppBar( yearMonth = currentNavigationState.yearMonth, navigationStore ) is NavigationState.CoffeeListPage -> CoffeeListAppBar( navigationStore ) is NavigationState.SettingsPage -> SettingsAppBar() } } ) { Column(modifier = Modifier.padding(it)) { Spacer(Modifier.padding(top = topPadding).align(Alignment.CenterHorizontally)) when (currentNavigationState) { is NavigationState.TablePage -> TablePage( yearMonth = currentNavigationState.yearMonth, daysCoffeesStore = daysCoffeesStore, navigationStore = navigationStore ) is NavigationState.CoffeeListPage -> CoffeeListPage( daysCoffeesStore = daysCoffeesStore, navigationState = currentNavigationState ) is NavigationState.SettingsPage -> SettingsPage( themeStore = themeStore, snackbarHostState = snackbarHostState, ) } AdaptiveNavigationBar { AdaptiveNavigationBarItem( selected = currentNavigationState is NavigationState.TablePage, onClick = { navigationStore.newIntent( NavigationIntent.ReturnToTablePage ) }, label = { Text(stringResource(Res.string.calendar)) }, icon = { Icon( imageVector = Icons.Default.Create, contentDescription = "", ) }) AdaptiveNavigationBarItem( selected = currentNavigationState is NavigationState.SettingsPage, onClick = { navigationStore.newIntent( NavigationIntent.ToSettingsPage ) }, label = { Text(stringResource(Res.string.settings)) }, icon = { Icon( imageVector = Icons.Default.Settings, contentDescription = "", ) }) } } } } } data class Dependencies( val navigationStore: NavigationStore, val daysCoffeesStore: DaysCoffeesStore, val themeStore: ThemeStore, ) @Composable fun DefaultPreview(dependencies: Dependencies) { PagesContent( navigationStore = dependencies.navigationStore, daysCoffeesStore = dependencies.daysCoffeesStore, themeStore = dependencies.themeStore ) } @Composable private fun themeState(themeStore: ThemeStore): ThemeState { val themeState: ThemeState by themeStore.state.collectAsState() return themeState }
3
null
33
440
cc0bad34d13051d0972141e0048c3ff611bf6a5e
5,969
Coffeegram
Apache License 2.0
clients/amt_enhetsregister/src/main/kotlin/no/nav/amt/tiltak/clients/amt_enhetsregister/AmtEnhetsregisterClient.kt
navikt
393,356,849
false
null
package no.nav.amt.tiltak.clients.amt_enhetsregister import no.nav.amt.tiltak.common.json.JsonUtils.fromJson import no.nav.common.rest.client.RestClient.baseClient import okhttp3.OkHttpClient import okhttp3.Request import java.util.function.Supplier class AmtEnhetsregisterClient( private val url: String, private val tokenProvider: Supplier<String>, private val httpClient: OkHttpClient = baseClient(), ) : EnhetsregisterClient { override fun hentVirksomhet(organisasjonsnummer: String): Virksomhet { val request = Request.Builder() .url("$url/api/enhet/$organisasjonsnummer") .addHeader("Authorization", "Bearer ${tokenProvider.get()}") .get() .build() httpClient.newCall(request).execute().use { response -> if (response.code == 404) { return Virksomhet( navn = "Ukjent virksomhet", organisasjonsnummer = organisasjonsnummer, overordnetEnhetOrganisasjonsnummer = "999999999", overordnetEnhetNavn = "Ukjent virksomhet", ) } if (!response.isSuccessful) { throw RuntimeException("Klarte ikke å hente enhet fra amt-enhetsregister. organisasjonsnummer=${organisasjonsnummer} status=${response.code}") } val body = response.body?.string() ?: throw RuntimeException("Body is missing") val enhetDto = fromJson(body, EnhetDto::class.java) return Virksomhet( navn = enhetDto.navn, organisasjonsnummer = enhetDto.organisasjonsnummer, overordnetEnhetOrganisasjonsnummer = enhetDto.overordnetEnhetOrganisasjonsnummer, overordnetEnhetNavn = enhetDto.overordnetEnhetNavn, ) } } }
3
Kotlin
1
2
90b2da08f224d9b05496cecc36434d95762e4cd5
1,572
amt-tiltak
MIT License
injective-core/src/jvmMain/kotlin/injective/permissions/v1beta1/params.converter.kt
jdekim43
759,720,689
false
{"Kotlin": 8940168, "Java": 3242559}
// Transform from injective/permissions/v1beta1/params.proto @file:GeneratorVersion(version = "0.3.1") package injective.permissions.v1beta1 import kr.jadekim.protobuf.`annotation`.GeneratorVersion import kr.jadekim.protobuf.converter.ProtobufConverter public actual object ParamsConverter : ProtobufConverter<Params> by ParamsJvmConverter
0
Kotlin
0
0
eb9b3ba5ad6b798db1d8da208b5435fc5c1f6cdc
343
chameleon.proto
Apache License 2.0
WanAndroid/app/src/main/java/com/lifeidroid/wanandroid/viewmodel/QuestionViewModel.kt
lifeidroid
558,747,549
false
{"Kotlin": 288735}
package com.lifeidroid.wanandroid.viewmodel import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.viewModelScope import com.lifeidroid.wanandroid.base.BaseViewModel import com.lifeidroid.wanandroid.http.RequestStatus import com.lifeidroid.wanandroid.model.entity.ArticleModel import com.lifeidroid.wanandroid.model.entity.QuestionModel import com.lifeidroid.wanandroid.model.entity.net.QuestionEntity import com.lifeidroid.wanandroid.utils.ResultDataUtils import com.lifeidroid.wanandroid.utils.T import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import javax.inject.Inject /** * <pre> * author : lifei * e-mail : <EMAIL> * time : 2022/10/18 * desc : * version: 1.0 * </pre> */ @HiltViewModel class QuestionViewModel @Inject constructor(savedStateHandle: SavedStateHandle) : BaseViewModel( savedStateHandle ) { @Inject lateinit var questionModel: QuestionModel @Inject lateinit var articleModel: ArticleModel var questionDataSource = mutableStateListOf<QuestionEntity.Data>() private set /** * 更新文章列表收藏状态 * @param index Int */ fun updateQuestionDataSourceCollect(index: Int) { var collect = !questionDataSource[index].collect!! doCollect(questionDataSource[index].id!!,collect) questionDataSource[index] = questionDataSource[index].copy( collect = collect ) } fun doCollect(id:Int,collect:Boolean){ if (collect) {//收藏 viewModelScope.launch { articleModel.collectArticle(id).observeForever { when (it.requestStatus) { RequestStatus.ERROR -> { T.showToast(it.error!!.message!!) } } } } } else {//取消收藏 viewModelScope.launch { articleModel.unCollectArticle(id).observeForever { when (it.requestStatus) { RequestStatus.ERROR -> { T.showToast(it.error!!.message!!) } } } } } } /** * 加载文章列表 * @param isRefresh Boolean */ fun loadQuestion(isRefresh: Boolean) { if (isRefresh) { swipeLazyColumState.startRefresh() } viewModelScope.launch { questionModel.getWenDa(isRefresh).observeForever() { ResultDataUtils.dellRefreshAndLoadMoreCustom( it, questionDataSource, { articleEntity -> articleEntity.datas }, this@QuestionViewModel, questionModel ) } } } }
0
Kotlin
0
2
d4c473db5b5e2a93098b2b11a56773d8d27494e0
3,066
WanAndroid
Apache License 2.0
src/core/src/main/kotlin/com/gabrielbmoro/moviedb/core/ui/widgets/MovieImage.kt
gabrielbmoro
574,746,759
false
{"Kotlin": 162208}
package com.gabrielbmoro.moviedb.ui.common.widgets import androidx.compose.foundation.Image import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import coil.compose.AsyncImage import coil.request.ImageRequest import com.gabrielbmoro.moviedb.R @Composable fun MovieImage( imageUrl: String?, contentDescription: String, contentScale: ContentScale, modifier: Modifier = Modifier, ) { if (imageUrl != null) { val context = LocalContext.current val imageRequest = ImageRequest.Builder(context) .placeholder(R.drawable.ic_movie) .data(imageUrl) .build() AsyncImage( model = imageRequest, contentScale = contentScale, alignment = Alignment.TopCenter, contentDescription = contentDescription, modifier = modifier ) } else { Image( painter = painterResource(id = R.drawable.ic_movie), contentScale = contentScale, alignment = Alignment.TopCenter, contentDescription = contentDescription, modifier = modifier ) } }
4
Kotlin
2
39
acb9a76f49a07e08eddf6a1c5daae103e5a0642c
1,346
MovieDB-Android
MIT License
shared/src/commonMain/kotlin/com/bumble/puzzyx/composable/EntryCard.kt
mike-n-jordan
704,665,102
false
{"Kotlin": 110536, "Python": 1808}
package com.bumble.puzzyx.composable import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.bumble.puzzyx.imageloader.ResourceImage import com.bumble.puzzyx.model.Entry import com.bumble.puzzyx.ui.colors @Composable fun EntryCard( entry: Entry, modifier: Modifier = Modifier, ) { Box( modifier = modifier.clip(RoundedCornerShape(16.dp)) ) { when (entry) { is Entry.Text -> TextEntry(entry) is Entry.Image -> ResourceImage( path = "participant/${entry.path}", contentDescription = entry.contentDescription, contentScale = entry.contentScale, modifier = Modifier.fillMaxSize().align(Alignment.Center) ) is Entry.ComposableContent -> entry.content() } GitHubHeader( entry = entry, modifier = Modifier.padding(8.dp) ) } } @Composable fun GitHubHeader( entry: Entry, modifier: Modifier = Modifier ) { Row( verticalAlignment = Alignment.CenterVertically, modifier = modifier ) { ResourceImage( path = "github.png", contentScale = ContentScale.Inside, modifier = Modifier .size(32.dp) .padding(2.dp) ) Spacer( modifier = Modifier.size(4.dp) ) Text( text = entry.githubUserName, fontSize = 18.sp, fontWeight = FontWeight.Bold ) } } @Composable fun TextEntry( entry: Entry.Text, modifier: Modifier = Modifier ) { val colorIdx = remember { colors.indices.random() } Text( text = entry.message, fontSize = 16.sp, modifier = modifier .fillMaxSize() .background(colors[colorIdx]) .padding(12.dp) .padding(top = 36.dp), ) } @Composable fun EntryCardSmall( entry: Entry.Text, modifier: Modifier = Modifier, ) { OptimisingLayout( modifier = modifier, optimalWidth = 150.dp, ) { Column( modifier = Modifier .fillMaxSize() ) { Text(entry.githubUserName) Text(entry.message) } } }
0
Kotlin
0
0
1796d1b0b6274ab24f9ecec8d1a76c9b32bffddd
3,070
live-mosaic
Apache License 2.0
features/manage-accounts/src/test/java/teamcityapp/features/manage_accounts/viewmodel/ManageAccountsViewModelTest.kt
vase4kin
68,111,887
false
{"Gradle": 29, "JSON": 2, "Java Properties": 2, "Markdown": 6, "Shell": 1, "Ignore List": 26, "Batchfile": 1, "Text": 1, "YAML": 5, "INI": 24, "Proguard": 25, "XML": 228, "Java": 33, "Kotlin": 580, "HTML": 1, "Gradle Kotlin DSL": 1}
/* * Copyright 2020 Andrey Tolpeev * * 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 teamcityapp.features.manage_accounts.viewmodel import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.doAnswer import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.times import com.nhaarman.mockitokotlin2.verify import com.nhaarman.mockitokotlin2.verifyNoMoreInteractions import com.nhaarman.mockitokotlin2.whenever import com.xwray.groupie.GroupAdapter import com.xwray.groupie.GroupieViewHolder import org.junit.After import org.junit.Before import org.junit.Test import teamcityapp.features.manage_accounts.router.ManageAccountsRouter import teamcityapp.features.manage_accounts.tracker.ManageAccountsTracker import teamcityapp.features.manage_accounts.view.AccountItemFactory import teamcityapp.libraries.cache_manager.CacheManager import teamcityapp.libraries.storage.Storage import teamcityapp.libraries.storage.models.UserAccount class ManageAccountsViewModelTest { private val storage: Storage = mock() private val router: ManageAccountsRouter = mock() private val tracker: ManageAccountsTracker = mock() private val showSslDisabledInfoDialog: () -> Unit = mock() private val showRemoveAccountDialog: (onAccountRemove: () -> Unit) -> Unit = mock() private val cacheManager: CacheManager = mock() private val itemFactory: AccountItemFactory = mock() private val adapter: GroupAdapter<GroupieViewHolder> = mock() private val userAccount: UserAccount = mock() private lateinit var viewModel: ManageAccountsViewModel @Before fun setUp() { viewModel = ManageAccountsViewModel( storage, router, tracker, cacheManager, itemFactory, adapter ) } @After fun tearDown() { verifyNoMoreInteractions( storage, router, tracker, showSslDisabledInfoDialog, showRemoveAccountDialog, cacheManager, adapter ) } @Test fun testOnAccountRemove_OnlyOneAccount() { doAnswer { listOf(userAccount) }.whenever(storage).userAccounts viewModel.onAccountRemove(userAccount).invoke() verify(storage).userAccounts verify(tracker).trackAccountRemove() verify(storage).removeUserAccount(userAccount) verify(cacheManager).evictAllCache() verify(router).openLogin() } @Test fun testOnAccountRemove_AccountIsActive() { whenever(userAccount.isActive).thenReturn(true) doAnswer { listOf(userAccount, mock()) }.whenever(storage).userAccounts viewModel.onAccountRemove(userAccount).invoke() verify(storage).userAccounts verify(tracker).trackAccountRemove() verify(storage).removeUserAccount(userAccount) verify(storage).setOtherUserActive() verify(router).openHome() } @Test fun testOnAccountRemove_AccountIsNotActive() { whenever(userAccount.isActive).thenReturn(false) doAnswer { listOf(userAccount, mock(), mock()) }.whenever(storage).userAccounts viewModel.onAccountRemove(userAccount).invoke() verify(storage, times(2)).userAccounts verify(tracker).trackAccountRemove() verify(storage).removeUserAccount(userAccount) verify(adapter).updateAsync(any()) } }
0
Kotlin
11
52
9abb1ed56c127d64679124c38d30b0014ec024de
3,947
TeamCityApp
Apache License 2.0