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
material-prefs-colorpicker/src/main/java/com/imangazaliev/materialprefs/views/ColorCircleView.kt
ImangazalievM
293,368,380
false
{"Kotlin": 67071}
package com.imangazalievm.materialprefs.views import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.drawable.Drawable import android.util.AttributeSet import android.view.View import androidx.annotation.ColorInt import androidx.core.content.ContextCompat import com.imangazalievm.materialprefs.color.R import com.imangazalievm.materialprefs.util.dpToPx internal class ColorCircleView( context: Context, attrs: AttributeSet? = null ) : View(context, attrs) { private val strokePaint = Paint() private val fillPaint = Paint() private val borderWidth = 1.dpToPx(context) private var transparentGrid: Drawable? = null init { setWillNotDraw(false) strokePaint.style = Paint.Style.STROKE strokePaint.isAntiAlias = true strokePaint.color = Color.BLACK strokePaint.strokeWidth = borderWidth.toFloat() fillPaint.style = Paint.Style.FILL fillPaint.isAntiAlias = true fillPaint.color = Color.DKGRAY } @ColorInt var color: Int = Color.BLACK set(value) { field = value fillPaint.color = value invalidate() } @ColorInt var border: Int = Color.DKGRAY set(value) { field = value strokePaint.color = value invalidate() } override fun onMeasure( widthMeasureSpec: Int, heightMeasureSpec: Int ) = super.onMeasure(widthMeasureSpec, widthMeasureSpec) override fun onDraw(canvas: Canvas) { super.onDraw(canvas) if (color == Color.TRANSPARENT) { if (transparentGrid == null) { transparentGrid = ContextCompat.getDrawable( context, R.drawable.transparentgrid ) } transparentGrid?.setBounds(0, 0, measuredWidth, measuredHeight) transparentGrid?.draw(canvas) } else { canvas.drawCircle( measuredWidth / 2f, measuredHeight / 2f, (measuredWidth / 2f) - borderWidth, fillPaint ) } canvas.drawCircle( measuredWidth / 2f, measuredHeight / 2f, (measuredWidth / 2f) - borderWidth, strokePaint ) } override fun onDetachedFromWindow() { super.onDetachedFromWindow() transparentGrid = null } }
2
Kotlin
6
59
2ee8cc8e22b03da157e99b406457628efa4ba79e
2,536
material-prefs
Apache License 2.0
app/src/main/java/com/vodolazskiy/forecastapplication/core/di/modules/ServiceModule.kt
Denis10
180,340,842
false
null
package com.vodolazskiy.forecastapplication.core.di.modules import com.vodolazskiy.forecastapplication.domain.CurrentLocationService import com.vodolazskiy.forecastapplication.domain.ForecastService import com.vodolazskiy.forecastapplication.service.CurrentLocationServiceImpl import com.vodolazskiy.forecastapplication.service.ForecastServiceImpl import dagger.Binds import dagger.Module import javax.inject.Singleton @Module(includes = [ NetworkModule::class ]) interface ServiceModule { @Singleton @Binds fun provideLocationService(service: CurrentLocationServiceImpl): CurrentLocationService @Singleton @Binds fun provideForecastService(service: ForecastServiceImpl): ForecastService }
0
Kotlin
0
0
e6e157d013259a8431b345c0c28d54cf9ecc1659
722
Forecast
Apache License 2.0
mobile/src/androidTest/java/com/ashomok/lullabies/ui/main_activity/media_browser/MediaBrowserFragmentFavouritesTest.kt
ashomokdev
179,253,799
true
{"Gradle": 3, "Java Properties": 3, "Markdown": 2, "Shell": 2, "Text": 2, "Ignore List": 1, "Batchfile": 2, "Proguard": 1, "Java": 95, "XML": 92, "JSON": 6, "Kotlin": 20}
package com.ashomok.lullabies.ui.main_activity.media_browser import android.content.Context import androidx.appcompat.widget.AppCompatImageButton import androidx.lifecycle.Lifecycle import androidx.test.core.app.launchActivity import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.action.ViewActions.swipeLeft import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.* import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry.getInstrumentation import com.ashomok.lullabies.R import com.ashomok.lullabies.ui.main_activity.MusicPlayerActivity import com.ashomok.lullabies.utils.dao.FavouriteMusicDAO import org.hamcrest.Matchers.allOf import org.hamcrest.Matchers.instanceOf import org.junit.After import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class MediaBrowserFragmentFavouritesTest { @Before fun emptyFavouritesListBefore() { val targetContext = getInstrumentation().targetContext FavouriteMusicDAO.getInstance( targetContext.getSharedPreferences( targetContext.getString(R.string.preferences), Context.MODE_PRIVATE ) ).cleanFavouriteMusicList() } @After fun emptyFavouritesListAfter() { val targetContext = getInstrumentation().targetContext FavouriteMusicDAO.getInstance( targetContext.getSharedPreferences( targetContext.getString(R.string.preferences), Context.MODE_PRIVATE ) ).cleanFavouriteMusicList() } @Test //https://github.com/ashomokdev/lullabies-v3/issues/91 fun testEvent91_NoEmptyViewWhenExpected() { //GIVEN val scenario = launchActivity<MusicPlayerActivity>() scenario.moveToState(Lifecycle.State.RESUMED) Thread.sleep(200) //WHEN //set 1st music as favourite onView(allOf(isDisplayed(), withId(R.id.tap_me_img))).perform(click()) Thread.sleep(200) scenario.onActivity { activity -> Assert.assertTrue(activity.mediaBrowser.isConnected) Assert.assertTrue( activity.mediaController.playbackState?.state == 3 || activity.mediaController.playbackState?.state == 6 ) } onView(withId(R.id.fragment_playback_controls)).perform(click()) onView(withId(R.id.favourite_icon)).perform(click()) onView( allOf( instanceOf(AppCompatImageButton::class.java), withParent(withId(R.id.toolbar)) ) ).perform(click()) onView(withId(R.id.pager)).perform(swipeLeft()) //set 2nd music as favourite Thread.sleep(300) onView(allOf(isDisplayed(), withId(R.id.tap_me_img))).perform(click()) scenario.onActivity { activity -> Assert.assertTrue( activity.mediaController.playbackState?.state == 3 || activity.mediaController.playbackState?.state == 6 ) } onView(withId(R.id.fragment_playback_controls)).perform(click()) onView(withId(R.id.favourite_icon)).perform(click()) onView( allOf( instanceOf(AppCompatImageButton::class.java), withParent(withId(R.id.toolbar)) ) ).perform(click()) //open my favourites onView( allOf( instanceOf(AppCompatImageButton::class.java), withParent(withId(R.id.toolbar)) ) ).perform(click()) onView(withId(R.id.navigation_my_favorites)).perform(click()) //switch to 1st music onView(allOf(isDisplayed(), withId(R.id.tap_me_img))).perform(click()) scenario.onActivity { activity -> Assert.assertTrue( activity.mediaController.playbackState?.state == 3 || activity.mediaController.playbackState?.state == 6 ) } //uncheck favourite for 1st music onView(withId(R.id.fragment_playback_controls)).perform(click()) onView(withId(R.id.favourite_icon)).perform(click()) onView( allOf( instanceOf(AppCompatImageButton::class.java), withParent(withId(R.id.toolbar)) ) ).perform(click()) Thread.sleep(300) //play music onView(allOf(isDisplayed(), withId(R.id.tap_me_img))).perform(click()) //THEN KOALA scenario.onActivity { activity -> Assert.assertTrue(activity.mediaController.metadata?.description?.title.toString() == "Коала") } //CLEAN UP (uncheck all favourites) onView(withId(R.id.fragment_playback_controls)).perform(click()) onView(withId(R.id.favourite_icon)).perform(click()) onView( allOf( instanceOf(AppCompatImageButton::class.java), withParent(withId(R.id.toolbar)) ) ).perform(click()) onView(allOf(isDisplayed(), withId(R.id.empty_result_layout))).check(matches(isDisplayed())) onView(withId(R.id.play_pause)).perform(click()) onView(allOf(isDisplayed(), withId(R.id.empty_result_layout))).check(matches(isDisplayed())) } }
19
Java
1
1
8f6811e9566376fb66f45afcc1d6c7bc08821662
5,473
lullabies-v3
Apache License 2.0
mediapicker/src/main/java/com/lijojoseph/mediapicker/FontsConstants.kt
klijojoseph
384,523,042
false
null
package com.lijojoseph.mediapicker object FontsConstants { const val SEMI_BOLD = "Inter-UI-Medium.otf" const val BOLD = "Inter-UI-SemiBold.otf" }
0
Kotlin
0
0
ee2739254e3e7568aa10ab2a95218632ee339eb4
154
MediaPicker
MIT License
nugu-login-kit/src/test/java/com/skt/nugu/sdk/platform/android/login/auth/NuguOAuthTest.kt
nugu-developers
214,067,023
false
null
/** * Copyright (c) 2021 SK Telecom Co., Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http:www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.skt.nugu.sdk.platform.android.login.auth import android.content.Intent import android.net.Uri import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import com.skt.nugu.sdk.client.configuration.ConfigurationStore import com.skt.nugu.sdk.core.interfaces.auth.AuthDelegate import com.skt.nugu.sdk.platform.android.login.exception.ClientUnspecifiedException import com.skt.nugu.sdk.platform.android.login.view.NuguOAuthCallbackActivity import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mockito import org.mockito.kotlin.never import org.mockito.kotlin.verify import java.lang.RuntimeException import java.util.* import java.util.concurrent.CountDownLatch @RunWith(AndroidJUnit4::class) class NuguOAuthTest { @Test fun testGetClient() { ConfigurationStore.configure("{\n" + " \"OAuthServerUrl\": \"https://api.sktnugu.com\",\n" + " \"OAuthClientId\": \"app.nugu.test\",\n" + " \"OAuthClientSecret\": \"12121212-eee-ddd-ccc-12121212\",\n" + " \"OAuthRedirectUri\": \"nugu.user.app.nugu.test://auth\",\n" + " \"PoCId\": \"app.nugu.test\",\n" + " \"DeviceTypeCode\": \"APP\"\n" + "}") NuguOAuth.create(options = NuguOAuthOptions.Builder() .deviceUniqueId("device1") .build()) val client = NuguOAuth.getClient() Assert.assertNotNull(client) } @Test fun testSetOptions() { ConfigurationStore.configure("{\n" + " \"OAuthServerUrl\": \"https://api.sktnugu.com\",\n" + " \"OAuthClientId\": \"app.nugu.test\",\n" + " \"OAuthClientSecret\": \"12121212-eee-ddd-ccc-12121212\",\n" + " \"OAuthRedirectUri\": \"nugu.user.app.nugu.test://auth\",\n" + " \"PoCId\": \"app.nugu.test\",\n" + " \"DeviceTypeCode\": \"APP\"\n" + "}") val client = NuguOAuth.create(options = NuguOAuthOptions.Builder() .deviceUniqueId("device1") .build()) val options = client.getOptions() Assert.assertNotNull(options) Assert.assertEquals(options?.clientId, "app.nugu.test") Assert.assertEquals(options?.clientSecret, "12121212-eee-ddd-ccc-12121212") Assert.assertEquals(options?.redirectUri, "nugu.user.app.nugu.test://auth") } @Test fun testSetOptions_MultipleTimes() { ConfigurationStore.configure("{\n" + " \"OAuthServerUrl\": \"https://api.sktnugu.com\",\n" + " \"OAuthClientId\": \"app.nugu.test\",\n" + " \"OAuthClientSecret\": \"12121212-eee-ddd-ccc-12121212\",\n" + " \"OAuthRedirectUri\": \"nugu.user.app.nugu.test://auth\",\n" + " \"PoCId\": \"app.nugu.test\",\n" + " \"DeviceTypeCode\": \"APP\"\n" + "}") val client = NuguOAuth.create(options = NuguOAuthOptions.Builder() .deviceUniqueId("device1") .build()) Assert.assertEquals(client.getOptions()?.deviceUniqueId, "device1") client.setOptions(options = NuguOAuthOptions.Builder() .deviceUniqueId("device2") .build()) val options = NuguOAuth.getClient().getOptions() Assert.assertNotNull(options) Assert.assertEquals(options?.deviceUniqueId, "device2") Assert.assertEquals(options?.clientId, "app.nugu.test") Assert.assertEquals(options?.clientSecret, "12121212-eee-ddd-ccc-12121212") Assert.assertEquals(options?.redirectUri, "nugu.user.app.nugu.test://auth") } @Test fun testOAuthServerUrl_MultipleTimes() { ConfigurationStore.configure("{\n" + " \"OAuthServerUrl\": \"https://1.sktnugu.com\",\n" + " \"OAuthClientId\": \"app.nugu.test\",\n" + " \"OAuthClientSecret\": \"12121212-eee-ddd-ccc-12121212\",\n" + " \"OAuthRedirectUri\": \"nugu.user.app.nugu.test://auth\",\n" + " \"PoCId\": \"app.nugu.test\",\n" + " \"DeviceTypeCode\": \"TEST\"\n" + "}") val client = NuguOAuth.create(options = NuguOAuthOptions.Builder() .deviceUniqueId("device1") .build()) Assert.assertEquals(client.baseUrl(), "https://1.sktnugu.com") ConfigurationStore.configure("{\n" + " \"OAuthServerUrl\": \"https://2.sktnugu.com\",\n" + " \"OAuthClientId\": \"app.nugu.test\",\n" + " \"OAuthClientSecret\": \"12121212-eee-ddd-ccc-12121212\",\n" + " \"OAuthRedirectUri\": \"nugu.user.app.nugu.test://auth\",\n" + " \"PoCId\": \"app.nugu.test\",\n" + " \"DeviceTypeCode\": \"TEST\"\n" + "}") Assert.assertEquals(client.baseUrl(), "https://2.sktnugu.com") } @Test fun testSetCredentials() { val client = NuguOAuth.create(options = NuguOAuthOptions.Builder() .deviceUniqueId("device1") .build()) client.setCredentials( Credentials( accessToken = "accessToken", refreshToken = "refreshToken", expiresIn = 10L, issuedTime = Date().time, tokenType = "", scope = "device:S.I.D." ) ) Assert.assertTrue(client.isTidLogin()) Assert.assertFalse(client.isAnonymouslyLogin()) Assert.assertTrue(client.isSidSupported()) Assert.assertFalse(client.isExpired()) } @Test fun testExpired() { val client = NuguOAuth.create(options = NuguOAuthOptions.Builder() .deviceUniqueId("device1") .build()) client.setCredentials( Credentials( accessToken = "accessToken", refreshToken = "refreshToken", expiresIn = 1L, issuedTime = Date().time, tokenType = "", scope = "device:S.I.D." ) ) Assert.assertFalse(client.isExpired()) client.setCredentials( Credentials( accessToken = "accessToken", refreshToken = "refreshToken", expiresIn = -1L, issuedTime = Date().time, tokenType = "", scope = "device:S.I.D." ) ) Assert.assertTrue(client.isExpired()) } @Test fun testIsSidSupported() { val client = NuguOAuth.create(options = NuguOAuthOptions.Builder() .deviceUniqueId("device1") .build()) client.setCredentials( Credentials( accessToken = "accessToken", refreshToken = "refreshToken", expiresIn = 1L, issuedTime = Date().time, tokenType = "", scope = "device:S.I.D." ) ) Assert.assertTrue(client.isSidSupported()) client.setCredentials( Credentials( accessToken = "accessToken", refreshToken = "refreshToken", expiresIn = 1L, issuedTime = Date().time, tokenType = "", scope = "" ) ) Assert.assertFalse(client.isSidSupported()) } @Test fun testAuthStateListener() { val client = NuguOAuth.create(options = NuguOAuthOptions.Builder() .deviceUniqueId("device1") .build()) client.setAuthState(AuthStateListener.State.REFRESHED) Assert.assertEquals(client.getAuthState(), AuthStateListener.State.REFRESHED) client.setAuthState(AuthStateListener.State.EXPIRED) Assert.assertEquals(client.getAuthState(), AuthStateListener.State.EXPIRED) client.setAuthState(AuthStateListener.State.UNRECOVERABLE_ERROR) Assert.assertEquals(client.getAuthState(), AuthStateListener.State.UNRECOVERABLE_ERROR) client.setAuthState(AuthStateListener.State.UNINITIALIZED) Assert.assertEquals(client.getAuthState(), AuthStateListener.State.UNINITIALIZED) } @Test fun testOnAuthStateChanged() { val latch = CountDownLatch(1) val client = NuguOAuth.create(options = NuguOAuthOptions.Builder() .deviceUniqueId("device1") .build()) val listener = object : AuthStateListener { override fun onAuthStateChanged(newState: AuthStateListener.State): Boolean { Assert.assertEquals(client.getAuthState(), newState) latch.countDown() return true } } client.addAuthStateListener(listener) client.setAuthState(AuthStateListener.State.REFRESHED) latch.await() client.removeAuthStateListener(listener) } @Test fun testOnceLoginListener() { val listener = OnceLoginListener(object : NuguOAuthInterface.OnLoginListener { override fun onSuccess(credentials: Credentials) { Assert.assertNotNull(credentials) } override fun onError(error: NuguOAuthError) { Assert.assertNotNull(error) } }) listener.onSuccess(Credentials.getDefault()) listener.onError(NuguOAuthError(throwable = RuntimeException())) } @Test fun testOnAccountListener() { val listener = OnceLoginListener(object : NuguOAuthInterface.OnAccountListener { override fun onSuccess(credentials: Credentials) { Assert.assertNotNull(credentials) } override fun onError(error: NuguOAuthError) { Assert.assertNotNull(error) Assert.assertEquals(error.throwable, RuntimeException::class) } }) listener.onSuccess(Credentials.getDefault()) listener.onError(NuguOAuthError(throwable = RuntimeException())) } @Test fun testMakeAuthorizeUri() { val client = NuguOAuth.create(options = NuguOAuthOptions.Builder() .deviceUniqueId("device1") .build(), "https://localhost") val uri = client.makeAuthorizeUri("{\"deviceSerialNumber\":\"deviceUniqueId\",\"theme\":\"dark\"}") Assert.assertNotNull(uri) } @Test fun testGenerateClientState() { val csrf = CSRFProtection() val clientState = csrf.generateState() Assert.assertTrue(csrf.verifyState(clientState)) } @Test fun testSetAuthorization() { val client = NuguOAuth.create(options = NuguOAuthOptions.Builder() .deviceUniqueId("device1") .build()) client.setCredentials( Credentials( accessToken = "accessToken", refreshToken = "refreshToken", expiresIn = 10L, issuedTime = Date().time, tokenType = "tokenType1", scope = "device:S.I.D." ) ) Assert.assertEquals(client.getCredentials().tokenType, "tokenType1") client.setAuthorization("tokenType2","accessToken") Assert.assertEquals(client.getCredentials().tokenType, "tokenType2") } @Test fun testClearAuthorization() { val client = NuguOAuth.create(options = NuguOAuthOptions.Builder() .deviceUniqueId("device1") .build()) client.setCredentials( Credentials( accessToken = "accessToken", refreshToken = "refreshToken", expiresIn = 10L, issuedTime = Date().time, tokenType = "tokenType1", scope = "device:S.I.D." ) ) Assert.assertEquals(client.getCredentials().tokenType, "tokenType1") client.clearAuthorization() Assert.assertEquals(client.getCredentials().tokenType, "") } @Test fun testTokens() { val client = NuguOAuth.create(options = NuguOAuthOptions.Builder() .deviceUniqueId("device1") .build()) client.setCredentials( Credentials( accessToken = "accessToken", refreshToken = "refreshToken", expiresIn = 10L, issuedTime = Date().time, tokenType = "tokenType1", scope = "device:S.I.D." ) ) Assert.assertEquals(client.getRefreshToken(), "refreshToken") Assert.assertEquals(client.getExpiresInMillis(), 10L * 1000) Assert.assertNotNull(client.getIssuedTime()) Assert.assertEquals(client.getScope(), "device:S.I.D.") } @Test fun testIsLogin() { val client = NuguOAuth.create(options = NuguOAuthOptions.Builder() .deviceUniqueId("device1") .build()) client.setCredentials( Credentials( accessToken = "accessToken", refreshToken = "refreshToken", expiresIn = 10L, issuedTime = Date().time, tokenType = "tokenType1", scope = "device:S.I.D." ) ) Assert.assertTrue(client.isLogin()) } @Test fun testIsAnonymouslyLogin() { val client = NuguOAuth.create(options = NuguOAuthOptions.Builder() .deviceUniqueId("device1") .build()) client.setCredentials( Credentials( accessToken = "accessToken", refreshToken = "", expiresIn = 10L, issuedTime = Date().time, tokenType = "tokenType1", scope = "device:S.I.D." ) ) Assert.assertTrue(client.isAnonymouslyLogin()) } @Test fun testIsTidLogin() { val client = NuguOAuth.create(options = NuguOAuthOptions.Builder() .deviceUniqueId("device1") .build()) client.setCredentials( Credentials( accessToken = "accessToken", refreshToken = "refreshToken", expiresIn = 10L, issuedTime = Date().time, tokenType = "tokenType1", scope = "device:S.I.D." ) ) Assert.assertTrue(client.isTidLogin()) } @Test fun testLoginWithTid() { val client = Mockito.mock(NuguOAuthInterface::class.java) verify(client, never()).loginWithTid(ApplicationProvider.getApplicationContext(), object : NuguOAuthInterface.OnLoginListener { override fun onSuccess(credentials: Credentials) { } override fun onError(error: NuguOAuthError) { } }) } @Test fun testAccountWithTid() { val client = Mockito.mock(NuguOAuthInterface::class.java) verify(client, never()).accountWithTid(ApplicationProvider.getApplicationContext(), object : NuguOAuthInterface.OnAccountListener { override fun onSuccess(credentials: Credentials) { } override fun onError(error: NuguOAuthError) { } }) } @Test fun testLoginAnonymously() { val client = Mockito.mock(NuguOAuthInterface::class.java) verify(client, never()).loginAnonymously(object : NuguOAuthInterface.OnLoginListener { override fun onSuccess(credentials: Credentials) { } override fun onError(error: NuguOAuthError) { } }) } @Test fun testLoginSilentlyWithTid() { val client = Mockito.mock(NuguOAuthInterface::class.java) verify(client, never()).loginSilentlyWithTid("refreshToken", object : NuguOAuthInterface.OnLoginListener { override fun onSuccess(credentials: Credentials) { } override fun onError(error: NuguOAuthError) { } }) } @Test fun testLoginWithAuthenticationCode() { val client = Mockito.mock(NuguOAuthInterface::class.java) verify(client, never()).loginWithAuthenticationCode("code", object : NuguOAuthInterface.OnLoginListener { override fun onSuccess(credentials: Credentials) { } override fun onError(error: NuguOAuthError) { } }) } @Test fun testLoginWithDeviceCode() { val client = Mockito.mock(NuguOAuthInterface::class.java) verify(client, never()).loginWithDeviceCode("code", object : NuguOAuthInterface.OnLoginListener { override fun onSuccess(credentials: Credentials) { } override fun onError(error: NuguOAuthError) { } }) } @Test fun testStartDeviceAuthorization() { val client = Mockito.mock(NuguOAuthInterface::class.java) verify(client, never()).startDeviceAuthorization("data", object : NuguOAuthInterface.OnDeviceAuthorizationListener { override fun onSuccess(result: DeviceAuthorizationResult) { } override fun onError(error: NuguOAuthError) { } }) } @Test fun testRequestMe() { val client = Mockito.mock(NuguOAuthInterface::class.java) verify(client, never()).requestMe(object : NuguOAuthInterface.OnMeResponseListener { override fun onSuccess(response: MeResponse) { } override fun onError(error: NuguOAuthError) { } }) } @Test fun testIntrospect() { val client = Mockito.mock(NuguOAuthInterface::class.java) verify(client, never()).introspect(object : NuguOAuthInterface.OnIntrospectResponseListener { override fun onSuccess(response: IntrospectResponse) { } override fun onError(error: NuguOAuthError) { } }) } @Test fun testRevoke() { val client = Mockito.mock(NuguOAuthInterface::class.java) verify(client, never()).revoke(object : NuguOAuthInterface.OnRevokeListener { override fun onSuccess() { } override fun onError(error: NuguOAuthError) { } }) } @Test fun testAuthDelegate() { val delegate = Mockito.mock(AuthDelegate::class.java) verify(delegate, never()).getAuthorization() } @Test fun testGetDeviceUniqueId() { val client = NuguOAuth.create(options = NuguOAuthOptions.Builder() .deviceUniqueId("device1") .build()) client.setCredentials( Credentials( accessToken = "accessToken", refreshToken = "refreshToken", expiresIn = 10L, issuedTime = Date().time, tokenType = "tokenType1", scope = "device:S.I.D." ) ) Assert.assertEquals(client.deviceUniqueId(), "device1") } @Test(expected = ClientUnspecifiedException::class) fun testCheckClientId() { val client = NuguOAuth.create(options = NuguOAuthOptions.Builder() .deviceUniqueId("device1") .clientId("YOUR_CLIENT_ID_HERE") .build()) client.checkClientId() } @Test(expected = ClientUnspecifiedException::class) fun testCheckClientSecret() { val client = NuguOAuth.create(options = NuguOAuthOptions.Builder() .deviceUniqueId("device1") .clientSecret("YOUR_CLIENT_SECRET_HERE") .build()) client.checkClientSecret() } @Test(expected = ClientUnspecifiedException::class) fun testCheckRedirectUri() { val client = NuguOAuth.create(options = NuguOAuthOptions.Builder() .deviceUniqueId("device1") .redirectUri("YOUR REDIRECT URI SCHEME://YOUR REDIRECT URI HOST") .build()) client.checkRedirectUri() } @Test fun testSetResult() { val client = NuguOAuth.create(options = NuguOAuthOptions.Builder() .deviceUniqueId("device1") .build()) client.setCredentials( Credentials( accessToken = "accessToken", refreshToken = "refreshToken", expiresIn = 10L, issuedTime = Date().time, tokenType = "tokenType1", scope = "device:S.I.D." ) ) client.onceLoginListener = OnceLoginListener(object : NuguOAuthInterface.OnLoginListener { override fun onSuccess(credentials: Credentials) { Assert.assertNotNull(credentials) } override fun onError(error: NuguOAuthError) { Assert.assertNotNull(error) } }) client.setResult(true) client.setResult(false, NuguOAuthError(throwable = RuntimeException())) } @Test fun testCodeFromIntent() { ConfigurationStore.configure("{\n" + " \"OAuthServerUrl\": \"https://api.sktnugu.com\",\n" + " \"OAuthClientId\": \"app.nugu.test\",\n" + " \"OAuthClientSecret\": \"12121212-eee-ddd-ccc-12121212\",\n" + " \"OAuthRedirectUri\": \"nugu.user.app.nugu.test://auth\",\n" + " \"PoCId\": \"app.nugu.test\",\n" + " \"DeviceTypeCode\": \"APP\"\n" + "}") val client = NuguOAuth.create(options = NuguOAuthOptions.Builder() .deviceUniqueId("device1") .build()) client.setCredentials( Credentials( accessToken = "accessToken", refreshToken = "refreshToken", expiresIn = 10L, issuedTime = Date().time, tokenType = "tokenType1", scope = "device:S.I.D." ) ) val intent = Intent( ApplicationProvider.getApplicationContext(), NuguOAuthCallbackActivity::class.java ).apply { data = Uri.parse("https://dummy.com?code=testcode") } Assert.assertNotNull(client.codeFromIntent(intent)) } @Test fun testGetLoginUri() { ConfigurationStore.configure( "{\n" + " \"OAuthServerUrl\": \"https://api.sktnugu.com\",\n" + " \"OAuthClientId\": \"app.nugu.test\",\n" + " \"OAuthClientSecret\": \"12121212-eee-ddd-ccc-12121212\",\n" + " \"OAuthRedirectUri\": \"nugu.user.app.nugu.test://auth\",\n" + " \"PoCId\": \"app.nugu.test\",\n" + " \"DeviceTypeCode\": \"APP\"\n" + "}" ) val client = NuguOAuth.create( options = NuguOAuthOptions.Builder() .deviceUniqueId("device1") .build() ) client.setCredentials( Credentials( accessToken = "accessToken", refreshToken = "refreshToken", expiresIn = 10L, issuedTime = Date().time, tokenType = "tokenType1", scope = "device:S.I.D." ) ) Assert.assertNotNull( client.getLoginUri("{\"deviceSerialNumber\":\"deviceUniqueId\",\"theme\":\"dark\"}") ) } }
3
null
18
27
53ebf6b8b17afeff6fdb3a8741f345f2fbe0d649
24,307
nugu-android
Apache License 2.0
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/SirenOn.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Outline.SirenOn: ImageVector get() { if (_sirenOn != null) { return _sirenOn!! } _sirenOn = Builder(name = "SirenOn", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveToRelative(21.0f, 18.0f) horizontalLineToRelative(-0.031f) lineToRelative(-1.148f, -8.496f) curveToRelative(-0.25f, -1.998f, -1.957f, -3.504f, -3.969f, -3.504f) horizontalLineToRelative(-7.703f) curveToRelative(-2.013f, 0.0f, -3.719f, 1.506f, -3.968f, 3.494f) lineToRelative(-1.149f, 8.506f) horizontalLineToRelative(-0.031f) curveToRelative(-1.654f, 0.0f, -3.0f, 1.346f, -3.0f, 3.0f) verticalLineToRelative(3.0f) horizontalLineToRelative(24.0f) verticalLineToRelative(-3.0f) curveToRelative(0.0f, -1.654f, -1.346f, -3.0f, -3.0f, -3.0f) close() moveTo(6.164f, 9.752f) curveToRelative(0.125f, -0.999f, 0.979f, -1.752f, 1.985f, -1.752f) horizontalLineToRelative(7.703f) curveToRelative(1.006f, 0.0f, 1.86f, 0.753f, 1.986f, 1.762f) lineToRelative(1.113f, 8.238f) lineTo(5.05f, 18.0f) lineToRelative(1.114f, -8.248f) close() moveTo(22.0f, 22.0f) lineTo(2.0f, 22.0f) verticalLineToRelative(-1.0f) curveToRelative(0.0f, -0.551f, 0.449f, -1.0f, 1.0f, -1.0f) horizontalLineToRelative(18.0f) curveToRelative(0.551f, 0.0f, 1.0f, 0.449f, 1.0f, 1.0f) verticalLineToRelative(1.0f) close() moveTo(8.148f, 10.0f) horizontalLineToRelative(3.852f) verticalLineToRelative(2.0f) horizontalLineToRelative(-2.104f) lineToRelative(-0.27f, 2.0f) horizontalLineToRelative(-2.018f) lineToRelative(0.54f, -4.0f) close() moveTo(3.136f, 6.317f) lineTo(0.389f, 3.687f) lineToRelative(1.384f, -1.444f) lineToRelative(2.747f, 2.631f) lineToRelative(-1.384f, 1.444f) close() moveTo(6.453f, 4.125f) lineToRelative(-0.538f, -3.792f) lineTo(7.896f, 0.052f) lineToRelative(0.538f, 3.792f) lineToRelative(-1.98f, 0.281f) close() moveTo(17.546f, 4.125f) lineToRelative(-1.98f, -0.281f) lineTo(16.104f, 0.052f) lineToRelative(1.98f, 0.281f) lineToRelative(-0.538f, 3.792f) close() moveTo(20.863f, 6.317f) lineToRelative(-1.384f, -1.444f) lineToRelative(2.747f, -2.631f) lineToRelative(1.384f, 1.444f) lineToRelative(-2.747f, 2.631f) close() } } .build() return _sirenOn!! } private var _sirenOn: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
4,101
icons
MIT License
src/main/Main.kt
Clausr
575,584,811
false
{"Kotlin": 67769}
import com.github.kittinunf.fuel.Fuel import com.github.kittinunf.fuel.core.Headers import com.github.kittinunf.result.Result import java.io.File import java.nio.file.Files import java.nio.file.Paths fun main(args: Array<String>) { val year = 2023 val day = 3 readInputFileFromInternet(year, day) createDayClassFile(year, day) createTestFile(year, day) } fun Int.padWithStartingZero(): String = toString().padStart(2, '0') fun readInputFileFromInternet(year: Int, day: Int) { val fileName = "day${day.padWithStartingZero()}.txt" val directory = "src/test/resources/aoc$year" val path = "$directory/$fileName" // Create directory Files.createDirectories(Paths.get(directory)) val file = File(path).also { if (it.exists()) { println("Input file download aborted, file already exists") return } } val sessionCookie = resourceAsString("session_cookie.txt") Fuel.get("https://adventofcode.com/$year/day/$day/input") .header(Headers.USER_AGENT to "github.com/Clausr/advent_of_code/tree/main/src/main.kt by clausr") .header(Headers.COOKIE to "session=${sessionCookie.trimIndent()}") .responseString { _, response, result -> when (result) { is Result.Failure -> { println("Failed to download input: ${response.statusCode} ${response.responseMessage}") } is Result.Success -> { // Make sure to use same line separators as the system result.value .replace("\n", System.lineSeparator()) .also { file.writeText(it) } println("$path downloaded successfully") } } } .join() } fun createTestFile(year: Int, day: Int) { val fileName = "Day${day.padWithStartingZero()}Test.kt" val directory = "src/test/aoc$year" Files.createDirectories(Paths.get(directory)) val path = "$directory/$fileName" File(path) .takeIf { !it.exists() } ?.writeText(getTestCaseContent(year, day)) ?.also { println("$path created") } } fun createDayClassFile(year: Int, day: Int) { val directory = "src/main/aoc$year" val fileName = "Day${day.padWithStartingZero()}.kt" Files.createDirectories(Paths.get(directory)) val path = "$directory/$fileName" File(path) .takeIf { !it.exists() } ?.writeText(getDayClassContent(year, day)) ?.also { println("$path created") } } fun getTestCaseContent(year: Int, day: Int): String { val doubleTriple = "\"\"\"\"\"\"" val dayPadded = day.padWithStartingZero() return """package aoc$year import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import resourceAsList class Day${dayPadded}Test { private val exampleInput = $doubleTriple.trimIndent().split("\n") @Test fun testPartOneExample1() { val day$day = Day$dayPadded(exampleInput) assertEquals(0, day$day.solvePart1()) } @Test fun partOneRealInput() { val day$day = Day$dayPadded(resourceAsList("aoc${year}/day${dayPadded}.txt")) assertEquals(0, day$day.solvePart1()) } @Test fun testPartTwoExample1() { val day$day = Day$dayPadded(exampleInput) assertEquals(0, day$day.solvePart2()) } @Test fun partTwoRealInput() { val day$day = Day$dayPadded(resourceAsList("aoc${year}/day${dayPadded}.txt")) assertEquals(0, day$day.solvePart2()) } }""".replace("\n", System.lineSeparator()) } fun getDayClassContent(year: Int, day: Int): String { return """package aoc${year} class Day${day.padWithStartingZero()}(input: List<String>) { fun solvePart1(): Int { return -1 } fun solvePart2(): Int { return -1 } }""".replace("\n", System.lineSeparator()) }
3
Kotlin
0
0
cc82ab4bc58b1491baf8c3c918386f739762def7
3,939
advent_of_code
Apache License 2.0
beagle-noop/src/main/java/com/pandulapeter/beagle/BeagleNetworkInterceptor.kt
yexseven
221,888,935
true
{"Kotlin": 127153}
package com.pandulapeter.beagle import com.pandulapeter.beagleCore.contracts.BeagleNetworkInterceptorContract import okhttp3.Interceptor import okhttp3.Response object BeagleNetworkInterceptor : BeagleNetworkInterceptorContract { override fun intercept(chain: Interceptor.Chain): Response = chain.proceed(chain.request()) }
0
null
0
0
f6f1d2c2372349c69c89fa4795d7682ad29c15bb
330
beagle
Apache License 2.0
10-building-a-dynamic-feature/projects/starter/features/sharing/src/main/java/com/raywenderlich/android/petsave/sharing/presentation/SharingFragmentViewModel.kt
raywenderlich
279,673,021
false
null
package com.raywenderlich.android.petsave.sharing.presentation import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.raywenderlich.android.petsave.common.domain.usecases.GetAnimalDetails import com.raywenderlich.android.petsave.common.utils.DispatchersProvider import com.raywenderlich.android.petsave.sharing.presentation.model.mappers.UiAnimalToShareMapper import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import javax.inject.Inject @HiltViewModel class SharingFragmentViewModel @Inject constructor( private val getAnimalDetails: GetAnimalDetails, private val uiAnimalToShareMapper: UiAnimalToShareMapper, private val dispatchersProvider: DispatchersProvider ): ViewModel() { val viewState: StateFlow<SharingViewState> get() = _viewState private val _viewState = MutableStateFlow(SharingViewState()) fun onEvent(event: SharingEvent) { when (event) { is SharingEvent.GetAnimalToShare -> getAnimalToShare(event.animalId) } } private fun getAnimalToShare(animalId: Long) { viewModelScope.launch { val animal = withContext(dispatchersProvider.io()) { getAnimalDetails(animalId) } _viewState.value = viewState.value.copy( animalToShare = uiAnimalToShareMapper.mapToView(animal) ) } } }
1
Kotlin
35
97
a9d68daf38a4d5e093c44ef382be3d76d9dc7e74
1,460
adva-materials
Apache License 2.0
src/main/kotlin/com/github/sukhinin/kflow/sink/FlowSink.kt
sukhinin
250,091,757
false
null
package com.github.sukhinin.kflow.sink import com.github.sukhinin.kflow.Flow interface FlowSink { fun write(flow: Flow) }
0
Kotlin
0
1
f5e78100a5d9b9f53db30467ce6901f0a225b5ab
128
kflow
Apache License 2.0
utils/src/org/jetbrains/android/generator/test/generatorUtils.kt
fossabot
106,286,350
true
{"Kotlin": 1437454, "Java": 39912, "HTML": 1615}
/* * Copyright 2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.android.generator.test import java.io.File import org.jetbrains.android.anko.utils.Buffer import org.jetbrains.android.anko.config.AnkoFile import org.jetbrains.android.anko.config.ConfigurationTune private fun Context.functionalDslTests(init: Buffer.(version: String) -> Unit) { val dir = File("./dsl/test/" + basePackage.replace('.', '/'), "/functional") for (version in testVersions) { val testFile = File(dir, "FunctionalTestsFor$version.kt") if (!testFile.exists()) { testFile.writeText(buffer { line("package $basePackage.functional\n") line("import $basePackage.*") line("import $basePackage.config.*") line("import org.junit.Test\n") line("public class FunctionalTestsFor$version : AbstractFunctionalTest() {") line("val version = \"$version\"\n").nl() init(version) line("}") }.toString()) println("File $testFile written") } } } private fun Buffer.functionalDslTest(name: String, mainAnkoFile: AnkoFile, configInit: TestConfiguration.() -> Unit = {}) { val testConfiguration = TestConfiguration() testConfiguration.configInit() line("@Test public fun test$name() {") line("runFunctionalTest(\"$name.kt\", AnkoFile.${mainAnkoFile.name()}, version) {") for (file in testConfiguration.files) { line("files.add(AnkoFile.${file.name()})") } for (tune in testConfiguration.tunes) { line("tunes.add(ConfigurationTune.${tune.name()})") } line("}") line("}").nl() } private fun Context.dslCompileTests(files: List<String>, category: String) { val dir = File("./dsl/test/" + basePackage.replace('.', '/'), "/${category.toLowerCase()}") val testFile = File(dir, "Generated${category}Test.kt") if (!testFile.exists()) { testFile.writeText(buffer { line("package $basePackage.${category.toLowerCase()}\n").nl() line("import $basePackage.*") line("import $basePackage.compile.CompileTestFixture") line("import org.junit.*\n") line("import kotlin.platform.platformStatic").nl() line("public class Generated${category}Test : Abstract${category}Test() {") for (file in files) { for (version in versions) { line("@Test public fun test${file}For$version() {") line("run${category}Test(\"$file.kt\", \"$version\")") line("}").nl() } } line("}") }.toString()) println("File $testFile written") } } fun main(args: Array<String>) { val versions = File("./workdir/original/") .listFiles { it.isDirectory() && it.name.matches("\\d+s?".toRegex()) } ?.map { it.name } ?: listOf() val testVersions = File("./dsl/testData/functional/") .listFiles { it.isDirectory() && it.name.matches("\\d+s?".toRegex()) } ?.map { it.name } ?: listOf() Context(versions, testVersions, "org.jetbrains.android.anko").generate() } private fun buffer(init: Buffer.() -> Unit) = Buffer(" ", 0, init) private class Context(val versions: List<String>, val testVersions: List<String>, val basePackage: String) private class TestConfiguration { val files = hashSetOf<AnkoFile>() val tunes = hashSetOf<ConfigurationTune>() fun tune(tune: ConfigurationTune) { tunes.add(tune) } fun file(file: AnkoFile) { files.add(file) } }
0
Kotlin
0
0
37622fc1714cde2b5e81717bbb7b64344abe9b6f
4,226
anko
Apache License 2.0
node/src/integration-test/kotlin/net/corda/node/flows/AsymmetricCorDappsTests.kt
amangale
166,518,885
false
{"Gradle": 71, "INI": 27, "Markdown": 84, "Shell": 24, "Text": 13, "Ignore List": 10, "Java Properties": 3, "Batchfile": 5, "XML": 103, "Java": 130, "Kotlin": 1649, "YAML": 5, "Makefile": 2, "Python": 7, "Gherkin": 3, "Groovy": 2, "Dockerfile": 1, "RPM Spec": 1, "CSS": 10, "SVG": 4, "PowerShell": 1, "JSON": 2, "AppleScript": 1, "HTML": 7, "JavaScript": 17, "reStructuredText": 139, "TeX": 6, "BibTeX": 1}
package net.corda.node.flows import co.paralleluniverse.fibers.Suspendable import net.corda.core.flows.* import net.corda.core.identity.Party import net.corda.core.internal.concurrent.transpose import net.corda.core.messaging.startFlow import net.corda.core.utilities.getOrThrow import net.corda.core.utilities.unwrap import net.corda.testing.core.ALICE_NAME import net.corda.testing.core.BOB_NAME import net.corda.testing.core.singleIdentity import net.corda.testing.driver.DriverParameters import net.corda.testing.driver.NodeParameters import net.corda.testing.driver.driver import net.corda.testing.node.internal.cordappForClasses import org.junit.Test import kotlin.test.assertEquals class AsymmetricCorDappsTests { @StartableByRPC @InitiatingFlow class Ping(private val pongParty: Party, val times: Int) : FlowLogic<Unit>() { @Suspendable override fun call() { val pongSession = initiateFlow(pongParty) pongSession.sendAndReceive<Unit>(times) for (i in 1..times) { val j = pongSession.sendAndReceive<Int>(i).unwrap { it } assertEquals(i, j) } } } @InitiatedBy(Ping::class) class Pong(private val pingSession: FlowSession) : FlowLogic<Unit>() { @Suspendable override fun call() { val times = pingSession.sendAndReceive<Int>(Unit).unwrap { it } for (i in 1..times) { val j = pingSession.sendAndReceive<Int>(i).unwrap { it } assertEquals(i, j) } } } @Test fun `no shared cordapps with asymmetric specific classes`() { driver(DriverParameters(startNodesInProcess = false, cordappsForAllNodes = emptySet())) { val nodeA = startNode(NodeParameters( providedName = ALICE_NAME, additionalCordapps = setOf(cordappForClasses(Ping::class.java)) )).getOrThrow() val nodeB = startNode(NodeParameters( providedName = BOB_NAME, additionalCordapps = setOf(cordappForClasses(Ping::class.java, Pong::class.java)) )).getOrThrow() nodeA.rpc.startFlow(::Ping, nodeB.nodeInfo.singleIdentity(), 1).returnValue.getOrThrow() } } @Test fun `shared cordapps with asymmetric specific classes`() { val sharedCordapp = cordappForClasses(Ping::class.java) val cordappForNodeB = cordappForClasses(Pong::class.java) driver(DriverParameters(startNodesInProcess = false, cordappsForAllNodes = setOf(sharedCordapp))) { val (nodeA, nodeB) = listOf( startNode(NodeParameters(providedName = ALICE_NAME)), startNode(NodeParameters(providedName = BOB_NAME, additionalCordapps = setOf(cordappForNodeB))) ).transpose().getOrThrow() nodeA.rpc.startFlow(::Ping, nodeB.nodeInfo.singleIdentity(), 1).returnValue.getOrThrow() } } @Test fun `shared cordapps with asymmetric specific classes in process`() { val sharedCordapp = cordappForClasses(Ping::class.java) val cordappForNodeB = cordappForClasses(Pong::class.java) driver(DriverParameters(startNodesInProcess = true, cordappsForAllNodes = setOf(sharedCordapp))) { val (nodeA, nodeB) = listOf( startNode(NodeParameters(providedName = ALICE_NAME)), startNode(NodeParameters(providedName = BOB_NAME, additionalCordapps = setOf(cordappForNodeB))) ).transpose().getOrThrow() nodeA.rpc.startFlow(::Ping, nodeB.nodeInfo.singleIdentity(), 1).returnValue.getOrThrow() } } }
1
null
1
1
4059966ccb15883022b4a069f9e8fedce7849dde
3,716
corda
Apache License 2.0
plugins/liquid/arrow-refined-types/src/commonMain/kotlin/arrow/refinement/digests/SHA512.kt
pstinghua
409,558,986
true
{"Kotlin": 1937232, "Java": 7034, "Shell": 195}
package arrow.refinement.digests import arrow.refinement.Refined import arrow.refinement.strings.HexString import arrow.refinement.strings.Size import kotlin.jvm.JvmInline @JvmInline value /** * [SHA512] constrains [String] to be a valid hexadecimal [String] of length 128 * * # Safe nullable construction * * ```kotlin:ank * import arrow.refinement.digests.SHA512 * * SHA512.orNull("ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f8819a5d4940e0db27ac185f8a0e1d5f84f88bc887fd67b143732c304cc5fa9ad8e6f57f50028a8ff") * ``` * * ```kotlin:ank * SHA512.orNull("not-sha512") * ``` * * # Resolved constraints * * ```kotlin:ank * SHA512.constraints("ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f8819a5d4940e0db27ac185f8a0e1d5f84f88bc887fd67b143732c304cc5fa9ad8e6f57f50028a8ff") * ``` * * ```kotlin:ank * SHA512.constraints("not-sha512") * ``` * * ```kotlin:ank * SHA512.isValid("ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f8819a5d4940e0db27ac185f8a0e1d5f84f88bc887fd67b143732c304cc5fa9ad8e6f57f50028a8ff") * ``` * * ```kotlin:ank * SHA512.isValid("not-sha512") * ``` * * # Folding validation * * ```kotlin:ank * SHA512.fold("ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f8819a5d4940e0db27ac185f8a0e1d5f84f88bc887fd67b143732c304cc5fa9ad8e6f57f50028a8ff", { "failed: $it" }, { "success: $it" }) * ``` * * ```kotlin:ank * SHA512.fold("not-sha512", { "failed: $it" }, { "success: $it" }) * ``` * * # Unsafe require * * ```kotlin:ank * SHA512.require("ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f8819a5d4940e0db27ac185f8a0e1d5f84f88bc887fd67b143732c304cc5fa9ad8e6f57f50028a8ff") * ``` * * ```kotlin:ank * try { SHA512.require("not-sha512") } catch (e: IllegalArgumentException) { e.message } * ``` * */ class SHA512 private constructor(val value: String) { companion object : Refined<String, SHA512>(::SHA512, HexString and Size.N(128u)) }
2
null
0
0
9adbd026e54349e26f3987b97b3165241f5f282d
1,898
arrow-meta
Apache License 2.0
px-checkout/src/main/java/com/mercadopago/android/px/internal/features/checkout/PostPaymentUrlsMapper.kt
mercadopago
49,529,486
false
null
package com.mercadopago.android.px.internal.features.checkout import android.net.Uri import com.mercadopago.android.px.internal.extensions.isNotNullNorEmpty import com.mercadopago.android.px.internal.mappers.Mapper import com.mercadopago.android.px.model.IPaymentDescriptor import com.mercadopago.android.px.model.Payment import com.mercadopago.android.px.preferences.CheckoutPreference import com.mercadopago.android.px.preferences.PostPaymentUrls internal object PostPaymentUrlsMapper : Mapper<PostPaymentUrlsMapper.Model, PostPaymentUrlsMapper.Response>() { override fun map(model: Model): Response { return Response( getUrl(model.redirectUrl, model.preference.redirectUrls, model), getUrl(model.backUrl, model.preference.backUrls, model) ) } private fun getUrl(url: String?, postPaymentUrls: PostPaymentUrls?, model: Model): String? { with(model) { return url.takeIf { it.isNotNullNorEmpty() } ?: payment?.let { payment -> getUrlFromPostPayment(postPaymentUrls, payment.paymentStatus).takeIf { it.isNotNullNorEmpty() }?.let { appendDataToUrl(it, payment, preference, siteId) } } } } private fun getUrlFromPostPayment(postPaymentUrls: PostPaymentUrls?, paymentStatus: String): String? { return postPaymentUrls?.let { when(paymentStatus) { Payment.StatusCodes.STATUS_APPROVED -> it.success Payment.StatusCodes.STATUS_REJECTED -> it.failure else -> it.pending } } } private fun appendDataToUrl(url: String, payment: IPaymentDescriptor, preference: CheckoutPreference, siteId: String): String { return Uri.parse(url).buildUpon() .appendQueryParameter("collection_id", payment.id.toString()) .appendQueryParameter("collection_status", payment.paymentStatus) .appendQueryParameter("payment_id", payment.id.toString()) .appendQueryParameter("status", payment.paymentStatus) .appendQueryParameter("payment_type", payment.paymentTypeId) .appendQueryParameter("preference_id", preference.id) .appendQueryParameter("external_reference", preference.externalReference) .appendQueryParameter("site_id", siteId) .toString() } data class Model( val redirectUrl: String?, val backUrl: String?, val payment: IPaymentDescriptor?, val preference: CheckoutPreference, val siteId: String ) data class Response( val redirectUrl: String?, val backUrl: String? ) }
38
null
69
94
f5cfa00ea5963f9153a237c3f329af5d2d6cd87f
2,692
px-android
MIT License
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/apigatewayv2/CfnIntegrationTlsConfigPropertyDsl.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress( "RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION" ) package cloudshift.awscdk.dsl.services.apigatewayv2 import cloudshift.awscdk.common.CdkDslMarker import kotlin.String import software.amazon.awscdk.services.apigatewayv2.CfnIntegration /** * The `TlsConfig` property specifies the TLS configuration for a private integration. * * If you specify a TLS configuration, private integration traffic uses the HTTPS protocol. * Supported only for HTTP APIs. * * Example: * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.apigatewayv2.*; * TlsConfigProperty tlsConfigProperty = TlsConfigProperty.builder() * .serverNameToVerify("serverNameToVerify") * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigatewayv2-integration-tlsconfig.html) */ @CdkDslMarker public class CfnIntegrationTlsConfigPropertyDsl { private val cdkBuilder: CfnIntegration.TlsConfigProperty.Builder = CfnIntegration.TlsConfigProperty.builder() /** * @param serverNameToVerify If you specify a server name, API Gateway uses it to verify the * hostname on the integration's certificate. The server name is also included in the TLS * handshake to support Server Name Indication (SNI) or virtual hosting. */ public fun serverNameToVerify(serverNameToVerify: String) { cdkBuilder.serverNameToVerify(serverNameToVerify) } public fun build(): CfnIntegration.TlsConfigProperty = cdkBuilder.build() }
3
null
0
3
c59c6292cf08f0fc3280d61e7f8cff813a608a62
1,790
awscdk-dsl-kotlin
Apache License 2.0
src/main/kotlin/org/teamvoided/nullium/data/gen/loot/InjectionLootTablesProvider.kt
TeamVoided
788,995,006
false
{"Kotlin": 61140, "Java": 18442}
package org.teamvoided.nullium.data.gen.loot import net.fabricmc.fabric.api.datagen.v1.FabricDataOutput import net.fabricmc.fabric.api.datagen.v1.provider.SimpleFabricLootTableProvider import net.minecraft.block.Blocks import net.minecraft.block.CakeBlock import net.minecraft.item.Items import net.minecraft.loot.LootTable import net.minecraft.loot.context.LootContextType import net.minecraft.loot.context.LootContextTypes import net.minecraft.registry.HolderLookup import net.minecraft.registry.RegistryKey import org.teamvoided.nullium.data.loot.NulliumInjections import org.teamvoided.nullium.util.blockStateProperty import org.teamvoided.nullium.util.lootTable import org.teamvoided.nullium.util.randomChance import org.teamvoided.nullium.util.survivesExplosion import java.util.concurrent.CompletableFuture import java.util.function.BiConsumer typealias SimpleLootProviderFactory = (o: FabricDataOutput, r: CompletableFuture<HolderLookup.Provider>) -> SimpleFabricLootTableProvider object InjectionLootTablesProvider { fun lootTables(): List<SimpleLootProviderFactory> { return listOf( simpleLootTableProvider(LootContextTypes.BLOCK) { gen -> gen.accept( NulliumInjections.CAKE_DROPS, lootTable { pool { item(Items.CAKE) { conditionally( blockStateProperty(Blocks.CAKE) { exactMatch(CakeBlock.BITES, 0) } ) } conditionally(survivesExplosion()) } } ) }, simpleLootTableProvider(LootContextTypes.BARTER) { gen -> gen.accept( NulliumInjections.BARTER_UPGRADES, lootTable { pool { item(Items.NETHERITE_UPGRADE_SMITHING_TEMPLATE) { // 1 in 3.3 stacks of golden ingots conditionally(randomChance(0.006f)) } } } ) } ) } fun simpleLootTableProvider( c: LootContextType, fn: (gen: BiConsumer<RegistryKey<LootTable>, LootTable.Builder>) -> Unit ): SimpleLootProviderFactory { return { o, r -> object : SimpleFabricLootTableProvider(o, r, c) { override fun generate(gen: BiConsumer<RegistryKey<LootTable>, LootTable.Builder>) { fn(gen) } override fun getName(): String = "Injection|${super.getName()}" } } } }
0
Kotlin
0
1
7423e7769d8888995d4129f6d329535ea809854b
2,872
Nullium
MIT License
app/src/main/java/com/diplom/map/mvp/config/retrofit/backstage/GeoserverClientModule.kt
DonGlebon
175,883,786
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 2, "Ignore List": 2, "Batchfile": 1, "Git Attributes": 1, "Proguard": 1, "XML": 55, "Kotlin": 78, "Java": 1}
package com.diplom.map.mvp.config.retrofit.backstage import com.diplom.map.mvp.config.retrofit.GeoserverClient import com.google.gson.GsonBuilder import dagger.Module import dagger.Provides import io.reactivex.schedulers.Schedulers import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import javax.inject.Singleton @Module class GeoserverClientModule { @Singleton @Provides fun provideGeoserverClient(): GeoserverClient = GeoserverClient( Retrofit.Builder() .baseUrl("http://nuolh.belstu.by:4201/geoserver/") .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io())) .addConverterFactory(GsonConverterFactory.create(GsonBuilder().create())) .build() ) }
1
null
1
1
45f2e59eed6f228f42d0b2b45ad374746a7dc9d3
874
Diplom
MIT License
plugin/src/main/kotlin/io/github/addoncommunity/galactifun/api/objects/planet/PlanetaryWorld.kt
Slimefun-Addon-Community
624,085,324
false
{"Kotlin": 165422}
package io.github.addoncommunity.galactifun.api.objects.planet import io.github.addoncommunity.galactifun.api.objects.PlanetaryObject import io.github.addoncommunity.galactifun.impl.managers.PlanetManager import org.bukkit.World import org.bukkit.inventory.ItemStack /** * A planetary object that has a world. This is for adapting vanilla or plugin worlds to the Galactifun API. * If you want to create a custom world, use [AlienWorld] * * @author Seggan */ abstract class PlanetaryWorld( name: String, baseItem: ItemStack ) : PlanetaryObject(name, baseItem) { lateinit var world: World private set fun register() { orbit.parent.addOrbiter(this) world = loadWorld() PlanetManager.register(this) } abstract fun loadWorld(): World }
1
Kotlin
2
5
1d1f713bb22786b614d28058079e9da643665b2d
797
Galactifun2
Apache License 2.0
app/src/main/java/com/kuneosu/mintoners/ui/fragments/ProfileMainFragment.kt
Kuneosu
823,904,157
false
{"Kotlin": 199162}
package com.kuneosu.mintoners.ui.fragments import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import androidx.navigation.fragment.findNavController import com.kuneosu.mintoners.R import com.kuneosu.mintoners.databinding.FragmentProfileMainBinding class ProfileMainFragment : Fragment() { private var _binding: FragmentProfileMainBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentProfileMainBinding.inflate(inflater, container, false) binding.profileKakaoLogin.setOnClickListener { Toast.makeText(context, getString(R.string.beta_feature_message), Toast.LENGTH_SHORT).show() // binding.profileMainGuest.visibility = View.GONE // binding.profileMainMember.visibility = View.VISIBLE } binding.profileNaverLogin.setOnClickListener { Toast.makeText(context, getString(R.string.beta_feature_message), Toast.LENGTH_SHORT).show() // findNavController().navigate(R.id.action_profileMainFragment_to_profileRegisterFragment) } binding.profileSettingLogout.setOnClickListener { binding.profileMainMember.visibility = View.GONE binding.profileMainGuest.visibility = View.VISIBLE } binding.profileSettingPersonal.setOnClickListener { findNavController().navigate(R.id.action_profileMainFragment_to_profilePersonalFragment) } return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
0
Kotlin
0
0
3a290dcc803aa1d5ce1ad300c7cb3789280b1c74
1,900
Mintoners
MIT License
relateddigital-google/src/main/java/com/relateddigital/relateddigital_google/inapp/jackpot/JackpotCopyToClipboardInterface.kt
relateddigital
570,038,292
false
null
package com.relateddigital.relateddigital_google.inapp.jackpot interface JackpotCopyToClipboardInterface { fun copyToClipboard(couponCode: String?, link: String?) }
0
Kotlin
0
2
29e00b28a1a267ac43e992e626666f0ae4cc8df9
169
relateddigital-google
Amazon Digital Services License
platform/inspect/src/com/intellij/codeInspection/inspectionProfile/YamlInspectionProfileImpl.kt
ingokegel
72,937,917
false
null
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.codeInspection.inspectionProfile import com.intellij.codeHighlighting.HighlightDisplayLevel import com.intellij.codeInspection.GlobalInspectionTool import com.intellij.codeInspection.ex.* import com.intellij.codeInspection.inspectionProfile.YamlProfileUtils.createProfileCopy import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.util.io.toCanonicalPath import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.profile.codeInspection.BaseInspectionProfileManager import com.intellij.profile.codeInspection.InspectionProfileManager import com.intellij.profile.codeInspection.PROFILE_DIR import com.intellij.profile.codeInspection.ProjectInspectionProfileManager import com.intellij.psi.PsiElement import com.intellij.psi.search.scope.packageSet.* import org.jdom.Element import java.io.File import java.io.Reader import java.nio.file.FileSystems import java.nio.file.Path import java.nio.file.Paths import kotlin.io.path.exists import kotlin.io.path.reader private const val SCOPE_PREFIX = "scope#" private val LOG = logger<YamlInspectionProfileImpl>() class YamlInspectionConfigImpl(override val inspection: String, override val enabled: Boolean?, override val severity: String?, override val ignore: List<String>, override val options: Map<String, String>) : YamlInspectionConfig class YamlGroupConfigImpl(override val group: String, override val enabled: Boolean?, override val severity: String?, override val ignore: List<String>) : YamlGroupConfig class YamlInspectionGroupImpl(override val groupId: String, val inspections: Set<String>) : YamlInspectionGroup { override fun includesInspection(tool: InspectionToolWrapper<*, *>): Boolean { return tool.shortName in inspections } } class YamlCompositeGroupImpl(override val groupId: String, private val groupProvider: InspectionGroupProvider, private val groupRules: List<String>) : YamlInspectionGroup { override fun includesInspection(tool: InspectionToolWrapper<*, *>): Boolean { for (groupRule in groupRules.asReversed().filter { it.isNotEmpty() }) { val groupId = groupRule.removePrefix("!") if (groupProvider.findGroup(groupId).includesInspection(tool)) { return groupId == groupRule } } return false } } class CompositeGroupProvider : InspectionGroupProvider { private val providers = mutableListOf<InspectionGroupProvider>() fun addProvider(groupProvider: InspectionGroupProvider) { providers.add(groupProvider) } override fun findGroup(groupId: String): YamlInspectionGroup? { return providers.firstNotNullOfOrNull { it.findGroup(groupId) } } } class YamlInspectionProfileImpl private constructor(override val profileName: String?, override val inspectionToolsSupplier: InspectionToolsSupplier, override val inspectionProfileManager: BaseInspectionProfileManager, override val baseProfile: InspectionProfileImpl, override val configurations: List<YamlBaseConfig>, override val groups: List<YamlInspectionGroup>, private val groupProvider: InspectionGroupProvider) : YamlInspectionProfile, InspectionGroupProvider { companion object { @JvmStatic fun loadFrom(reader: Reader, includeReaders: (Path) -> Reader, toolsSupplier: InspectionToolsSupplier, profileManager: BaseInspectionProfileManager ): YamlInspectionProfileImpl { val profile = readConfig(reader, includeReaders) val baseProfile = findBaseProfile(profileManager, profile.baseProfile) val configurations = profile.inspections.map(::createInspectionConfig) val groupProvider = CompositeGroupProvider() groupProvider.addProvider(InspectionGroupProvider.createDynamicGroupProvider()) val groups = profile.groups.map { group -> createGroup(groupProvider, group) } val customGroupProvider = object : InspectionGroupProvider { val groupMap = groups.associateBy { group -> group.groupId } override fun findGroup(groupId: String): YamlInspectionGroup? { return groupMap[groupId] } } groupProvider.addProvider(customGroupProvider) return YamlInspectionProfileImpl( profile.name, toolsSupplier, profileManager, baseProfile, configurations, groups, groupProvider) } @JvmStatic fun loadFrom(project: Project, filePath: String = "${getDefaultProfileDirectory(project)}/profile.yaml", toolsSupplier: InspectionToolsSupplier = InspectionToolRegistrar.getInstance(), profileManager: BaseInspectionProfileManager = ProjectInspectionProfileManager.getInstance(project) ): YamlInspectionProfileImpl { val configFile = File(filePath).absoluteFile require(configFile.exists()) { "File does not exist: ${configFile.canonicalPath}" } val includeProvider: (Path) -> Reader = { val includePath = Path.of(configFile.parent).resolve(it) require(includePath.exists()) { "File does not exist: ${includePath.toCanonicalPath()}" } includePath.reader() } return configFile.reader().use { reader -> loadFrom(reader, includeProvider, toolsSupplier, profileManager) } } private fun findBaseProfile(profileManager: InspectionProfileManager, profileName: String?): InspectionProfileImpl { val name = profileName ?: "Default" return profileManager.getProfile(name, false) ?: throw IllegalArgumentException("Can't find base profile '$name'") } @JvmStatic fun isYamlFile(filepath: String): Boolean { val extension = File(filepath).extension return extension == "yaml" || extension == "yml" } private fun createGroup(groupProvider: InspectionGroupProvider, group: YamlInspectionGroupRaw): YamlInspectionGroup { return if (group.groups.isNotEmpty()) { YamlCompositeGroupImpl(group.groupId, groupProvider, group.groups) } else { YamlInspectionGroupImpl(group.groupId, group.inspections.toSet()) } } private fun getDefaultProfileDirectory(project: Project): String = "${project.basePath}/${Project.DIRECTORY_STORE_FOLDER}/$PROFILE_DIR" private fun createInspectionConfig(config: YamlInspectionConfigRaw): YamlBaseConfig { val inspectionId = config.inspection if (inspectionId != null) { return YamlInspectionConfigImpl(inspectionId, config.enabled, config.severity, config.ignore, config.options ?: emptyMap()) } val groupId = config.group if (groupId != null) { return YamlGroupConfigImpl(groupId, config.enabled, config.severity, config.ignore) } throw IllegalArgumentException("Missing group or inspection id in the inspection configuration.") } } fun buildEffectiveProfile(): InspectionProfileImpl { val effectiveProfile: InspectionProfileImpl = createProfileCopy(baseProfile, inspectionToolsSupplier, inspectionProfileManager) effectiveProfile.name = profileName ?: "Default" val scopesToApply = mutableMapOf<String, MutableList<Pair<PackageSet, Boolean>>>() configurations.forEach { configuration -> val tools = findTools(configuration) val scopes = configuration.ignore.map { pattern -> createScope(pattern) } tools.asSequence().mapNotNull { tool -> effectiveProfile.getToolsOrNull(tool.shortName, null) }.forEach { inspectionTools -> val enabled = configuration.enabled if (enabled != null) { inspectionTools.isEnabled = enabled if (inspectionTools.tools.all { !it.isEnabled }) { inspectionTools.defaultState.isEnabled = enabled } } val severity = HighlightDisplayLevel.find(configuration.severity) if (severity != null) { inspectionTools.tools.forEach { it.level = severity } } val options = (configuration as? YamlInspectionConfig)?.options if (!options.isNullOrEmpty()) { val element = Element("tool") YamlProfileUtils.writeXmlOptions(element, options) inspectionTools.defaultState.tool.tool.readSettings(element) } val toApply = scopesToApply.getOrPut(inspectionTools.shortName) { mutableListOf() } toApply.addAll(scopes) } } effectiveProfile.tools.forEach { tool -> val enabled = tool.isEnabled val toApply = scopesToApply[tool.shortName] if (toApply != null) { if (tool.isGlobalTool()) { // for global inspections yaml profile are creating only one enabled scope, it doesn't support several scopes with different severities/params. val oldScopes = collectOldScopes(tool) tool.defaultState.isEnabled = false tool.removeAllScopes() val scope = HierarchyPackageSet(toApply.reversed() + oldScopes) tool.prependTool(NamedScope.UnnamedScope(scope), tool.defaultState.tool, true, tool.level) } else { toApply.forEach { (packageSet, enabled) -> tool.prependTool(NamedScope.UnnamedScope(packageSet), tool.defaultState.tool, enabled, tool.level) } } tool.isEnabled = enabled // because prependTool is modifying isEnabled } } return effectiveProfile } private fun collectOldScopes(tool: ToolsImpl): List<Pair<PackageSet, Boolean>> { return tool.tools.mapNotNull { val packageSet = it.getScope(null)?.value if (packageSet is HierarchyPackageSet) { packageSet.packages } else if (packageSet != null) { listOf( packageSet to it.isEnabled) } else null }.flatten() } private fun ToolsImpl.isGlobalTool(): Boolean { return this.tool.tool is GlobalInspectionTool } private fun createScope(pattern: String): Pair<PackageSet, Boolean> { return if (pattern.startsWith("!")) { Pair(parsePattern(pattern.drop(1)), true) } else { Pair(parsePattern(pattern), false) } } private fun parsePattern(pattern: String): PackageSet { if (pattern.startsWith(SCOPE_PREFIX)) { val scope = pattern.drop(SCOPE_PREFIX.length) try { return PackageSetFactory.getInstance().compile(scope) } catch (e: ParsingException) { LOG.warn("Unknown scope format: $scope", e) } } return getGlobScope(pattern) } private fun getGlobScope(pattern: String): PackageSet { val matcher = FileSystems.getDefault().getPathMatcher("glob:$pattern") val packageSet = object : AbstractPackageSet("glob:$pattern") { override fun contains(file: VirtualFile, project: Project, holder: NamedScopesHolder?): Boolean { val root = holder?.projectBaseDir ?: return false val relativePath = VfsUtilCore.getRelativePath(file, root, File.separatorChar) ?: return false return matcher.matches(Paths.get(relativePath)) } } return packageSet } private fun findTools(configuration: YamlBaseConfig): List<InspectionToolWrapper<*, *>> { return when (configuration) { is YamlGroupConfig -> baseProfile.getInspectionTools(null).filter { findGroup(configuration.group).includesInspection(it) } is YamlInspectionConfig -> listOfNotNull(baseProfile.getInspectionTool(configuration.inspection, null as PsiElement?)) } } override fun findGroup(groupId: String): YamlInspectionGroup? { return groupProvider.findGroup(groupId) } private class HierarchyPackageSet(val packages: List<Pair<PackageSet, Boolean>>) : AbstractPackageSet("Hierarchy:$packages") { override fun contains(file: VirtualFile, project: Project, holder: NamedScopesHolder?): Boolean { packages.forEach {(packageSet, enabled) -> if (packageSet is PackageSetBase) { if (packageSet.contains(file, project, holder)) return enabled } else { val psiFile = getPsiFile(file, project) if (psiFile != null && packageSet.contains(psiFile, holder)) return enabled } } return false } override fun hashCode(): Int = packages.hashCode() override fun equals(other: Any?): Boolean { return packages == (other as? HierarchyPackageSet)?.packages } } }
284
null
5162
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
13,071
intellij-community
Apache License 2.0
sources/gradle-e2e-test/testData/projects/cli-jvm-hello-world/src/main.kt
JetBrains
709,379,874
false
{"Kotlin": 1917051, "Java": 288926, "Shell": 107894, "Batchfile": 66223, "Lex": 16216, "Swift": 14457, "Ruby": 4736, "Dockerfile": 1327}
/* * Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. */ fun main() { println("Hello, World!") }
0
Kotlin
30
988
6a2c7f0b86b36c85e9034f3de9bfe416516b323b
173
amper
Apache License 2.0
app/src/main/java/com/taqucinco/pokemon_sample/ui/route/home/HomeScreenUiState.kt
taqucinco-com
735,229,218
false
{"Kotlin": 113444}
package com.taqucinco.pokemon_sample.ui.route.home import com.taqucinco.pokemon_sample.feature.pokemon.PokemonResource data class HomeScreenUiState( val pokemons: List<PokemonResource> = emptyList(), val offset: Int = 0, val loading: Boolean = false, val remaining: Boolean = true, val error: Throwable? = null, )
6
Kotlin
0
1
c8e1ac968c331b832312ed36292855a097d54014
336
pokemon_sample
Apache License 2.0
src/main/kotlin/com/github/czyzby/setup/config/configuration.kt
czyzby
58,057,083
false
null
package com.github.czyzby.setup.config import com.badlogic.gdx.Gdx import com.badlogic.gdx.scenes.scene2d.Actor import com.github.czyzby.autumn.annotation.Component import com.github.czyzby.autumn.annotation.Initiate import com.github.czyzby.autumn.mvc.component.i18n.LocaleService import com.github.czyzby.autumn.mvc.component.ui.InterfaceService import com.github.czyzby.autumn.mvc.component.ui.SkinService import com.github.czyzby.autumn.mvc.config.AutumnActionPriority import com.github.czyzby.autumn.mvc.stereotype.preference.* import com.github.czyzby.lml.parser.LmlParser import com.github.czyzby.lml.parser.tag.LmlAttribute import com.github.czyzby.lml.parser.tag.LmlTag import com.github.czyzby.lml.vis.parser.impl.VisLmlSyntax import com.github.czyzby.lml.vis.parser.impl.nongwt.ExtendedVisLml import com.github.czyzby.setup.views.widgets.ScrollableTextArea import com.kotcrab.vis.ui.Locales import com.kotcrab.vis.ui.VisUI import com.kotcrab.vis.ui.widget.Tooltip import com.kotcrab.vis.ui.widget.VisLabel import com.kotcrab.vis.ui.widget.file.FileChooser /** * Configures Autumn MVC application. * @author MJ */ @Component class Configuration { companion object { const val VERSION = "1.9.11.2" const val WIDTH = 600 const val HEIGHT = 700 const val PREFERENCES_PATH = "gdx-liftoff-prefs" } @LmlParserSyntax val syntax = VisLmlSyntax() @LmlMacro val macro = "templates/macros.lml" @I18nBundle val bundle = "i18n/nls" @I18nLocale(propertiesPath = PREFERENCES_PATH, defaultLocale = "en") val localePreference = "locale" @AvailableLocales val availableLocales = arrayOf("en") @Preference val preferencesPath = PREFERENCES_PATH; @Initiate(priority = AutumnActionPriority.TOP_PRIORITY) fun initiate(skinService: SkinService, interfaceService: InterfaceService, localeService: LocaleService) { VisUI.setSkipGdxVersionCheck(true) VisUI.load(Gdx.files.internal("skin/tinted.json")) skinService.addSkin("default", VisUI.getSkin()) FileChooser.setDefaultPrefsName(PREFERENCES_PATH) // Adding tags and attributes related to the file chooser: ExtendedVisLml.registerFileChooser(syntax) ExtendedVisLml.registerFileValidators(syntax) // Adding custom ScrollableTextArea widget: syntax.addTagProvider(ScrollableTextArea.ScrollableTextAreaLmlTagProvider(), "console") // Changing FileChooser locale bundle: interfaceService.setActionOnBundlesReload { Locales.setFileChooserBundle(localeService.i18nBundle) } // Adding custom tooltip tag attribute: interfaceService.parser.syntax.addAttributeProcessor(object : LmlAttribute<Actor> { override fun getHandledType(): Class<Actor> = Actor::class.java override fun process(parser: LmlParser, tag: LmlTag, actor: Actor, rawAttributeData: String) { val tooltip = Tooltip() val label = VisLabel(parser.parseString(rawAttributeData, actor), "small") label.setWrap(true) tooltip.clear() tooltip.add(label).width(200f) tooltip.pad(3f) tooltip.setTarget(actor) tooltip.pack() } }, "tooltip") } }
7
null
13
129
da82263e56f671327d69b872a6a2fca1050b719a
3,312
gdx-setup
The Unlicense
app/src/main/java/com/androgynousis/messenger/view/activities/Conversation.kt
kumarguaraw989
237,062,235
true
{"Kotlin": 27709}
package com.androgynousis.messenger.view.activities import android.os.Bundle import android.view.Menu import android.view.View import android.widget.Button import android.widget.EditText import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.androgynousis.messenger.R import com.androgynousis.messenger.model.ChatData import com.androgynousis.messenger.view.adapter.ConversationRecyclerView import java.util.* class Conversation : BaseActivity() { private var mRecyclerView: RecyclerView? = null private var mAdapter: ConversationRecyclerView? = null private var text: EditText? = null private var send: Button? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_conversation) setupToolbarWithUpNav(R.id.toolbar, "<NAME>", R.drawable.ic_action_back) mRecyclerView = findViewById<View>(R.id.recyclerView) as RecyclerView mRecyclerView!!.setHasFixedSize(true) mRecyclerView!!.layoutManager = LinearLayoutManager(this) mAdapter = ConversationRecyclerView(this, setData() as MutableList<ChatData>) mRecyclerView!!.adapter = mAdapter mRecyclerView!!.postDelayed({ mRecyclerView!!.smoothScrollToPosition(mRecyclerView!!.adapter!!.itemCount - 1) }, 1000) text = findViewById<View>(R.id.et_message) as EditText text!!.setOnClickListener { mRecyclerView!!.postDelayed({ mRecyclerView!!.smoothScrollToPosition(mRecyclerView!!.adapter!!.itemCount - 1) }, 500) } send = findViewById<View>(R.id.bt_send) as Button send!!.setOnClickListener { if (text!!.text.toString() != "") { val data: MutableList<ChatData?> = ArrayList() val item = ChatData() item.time = "6:00pm" item.type = "2" item.text = text!!.text.toString() data.add(item) mAdapter!!.addItem(data) mRecyclerView!!.smoothScrollToPosition(mRecyclerView!!.adapter!!.itemCount - 1) text!!.setText("") } } } private fun setData(): List<ChatData> { val data: MutableList<ChatData> = ArrayList() val text = arrayOf("15 September", "Hi, Julia! How are you?", "Hi, Joe, looks great! :) ", "I'm fine. Wanna go out somewhere?", "Yes! Coffe maybe?", "Great idea! You can come 9:00 pm? :)))", "Ok!", "Ow my good, this Kit is totally awesome", "Can you provide other kit?", "I don't have much time, :`(") val time = arrayOf("", "5:30pm", "5:35pm", "5:36pm", "5:40pm", "5:41pm", "5:42pm", "5:40pm", "5:41pm", "5:42pm") val type = arrayOf("0", "2", "1", "1", "2", "1", "2", "2", "2", "1") for (i in text.indices) { val item = ChatData() item.type = type[i] item.text = text[i] item.time = time[i] data.add(item) } return data } override fun onCreateOptionsMenu(menu: Menu): Boolean { val inflater = menuInflater inflater.inflate(R.menu.menu_userphoto, menu) return true } override fun onPointerCaptureChanged(hasCapture: Boolean) {} }
0
null
0
1
01ab4b3839a2e7ecb56c0eeb4f4cfa0428a2a12a
3,275
messenger-design
MIT License
2018/src/five/InventoryManagementChallengeTest.kt
Mattias1
116,139,424
false
null
package five import junit.framework.Assert import junit.framework.TestCase import org.junit.Test class InventoryManagementChallengeTest : TestCase() { private val challenge: InventoryManagementChallenge = InventoryManagementChallenge() @Test fun testChecksum() { val input = listOf( "abcdef", "bababc", "abbcde", "abcccd", "aabcdd", "abcdee", "ababab" ) val result = challenge.checksum(input) Assert.assertEquals(12, result) } @Test fun testCommonLetters() { val input = listOf( "abcde", "fghij", "klmno", "pqrst", "fguij", "axcye", "wvxyz" ) val result = challenge.commonLetters(input) Assert.assertEquals("fgij", result) } }
0
Kotlin
0
0
6bcd889c6652681e243d493363eef1c2e57d35ef
891
advent-of-code
MIT License
FreeLocationProvider/src/main/java/dev/pwar/freelocationprovider/mapper/SensorDataModelFromLogLine.kt
fcuringa
619,291,328
false
null
package dev.pwar.freelocationprovider.mapper import dev.pwar.freelocationprovider.domain.SensorDataModel import dev.pwar.freelocationprovider.domain.SensorType import java.time.LocalDateTime fun sensorDataModelFromLogLine(line: String): SensorDataModel { if (line.contains("android.sensor")){ val elements = line.split(";") val timestamp = elements[1].let { timeString -> LocalDateTime.parse(timeString) } val type = elements[2].let { when(it) { "android.sensor.gravity" -> SensorType.GRAVITY "android.sensor.gyroscope" -> SensorType.GYROSCOPE "android.sensor.linear_acceleration" -> SensorType.LINEAR_ACCELERATION "android.sensor.accelerometer" -> SensorType.ACCELEROMETER "android.sensor.game_rotation_vector" -> SensorType.GAME_ROTATION_VECTOR else -> SensorType.UNKNOWN } } val x = elements[3].toDouble() val y = elements[4].toDouble() val z = elements[5].toDouble() var extra = 0.0 if (type == SensorType.GAME_ROTATION_VECTOR){ extra = elements[6].toDouble() } return SensorDataModel(timestamp, type, x, y, z, extra) } else { throw Error("Invalid log line, must be a sensor data log line") } }
0
Kotlin
0
2
632b713d9f7795394dfe148396f9b3b3fae5148a
1,353
FreeLocationProvider
Apache License 2.0
app/src/main/java/com/arcadone/pokestorie/presentation/HomeViewModel.kt
ArcaDone
804,002,329
false
{"Kotlin": 88338}
package com.arcadone.pokestorie.presentation import android.util.Log import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.arcadone.pokestorie.domain.model.PokemonInfo import com.arcadone.pokestorie.domain.model.PokemonListPreview import com.arcadone.pokestorie.domain.model.PokemonLoader import com.arcadone.pokestorie.domain.usecase.GetPokemonListByUrlUseCase import com.arcadone.pokestorie.domain.usecase.GetPokemonListUseCase import com.arcadone.pokestorie.domain.usecase.GetSinglePokemonUseCase import com.arcadone.pokestorie.domain.model.PokeUseCaseData import com.arcadone.pokestorie.domain.model.PokemonData import com.arcadone.pokestorie.networkconnection.NetworkConnection import com.arcadone.pokestorie.rest.model.ApiResult import com.arcadone.pokestorie.rest.model.onFailure import com.arcadone.pokestorie.rest.model.onSuccess import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class HomeViewModel @Inject constructor( private val pokemonListUseCase: GetPokemonListUseCase, private val pokemonListByUrlUseCase: GetPokemonListByUrlUseCase, private val getSinglePokemonUseCase: GetSinglePokemonUseCase, private val networkConnection: NetworkConnection ) : ViewModel() { private var nextPage: String = "" private var isLoadingNextPage = false private val _pokemonDetails = mutableStateOf<PokemonInfo?>(null) val pokemonDetails: State<PokemonInfo?> = _pokemonDetails private val _pokemonBySearch = mutableStateOf<PokemonInfo?>(null) val pokemonBySearch: State<PokemonInfo?> = _pokemonBySearch private val _pokemonList = mutableStateOf<List<PokemonListPreview>>(listOf()) val pokemonList: State<List<PokemonListPreview>> = _pokemonList private val _uiState = mutableStateOf<HomeUiState>(HomeUiState.Loading(networkConnection.isOnline())) val uiState: State<HomeUiState> = _uiState private val _isSearching = mutableStateOf(false) val isSearching: State<Boolean> = _isSearching private val _searchError = mutableStateOf<String?>(null) val searchError: State<String?> = _searchError init { getPokemonList(PokeUseCaseData()) } private fun getPokemonList(params: PokeUseCaseData) { _uiState.value = HomeUiState.Loading(networkConnection.isOnline()) viewModelScope.launch(Dispatchers.IO + CoroutineExceptionHandler { _, exception -> Log.d(HomeViewModel::class.java.simpleName, "Exception: ${exception.stackTrace}") }) { handleResult(pokemonListUseCase.invoke(params)) } } fun getPokemonByUrlList() { if (isLoadingNextPage) return isLoadingNextPage = true updateListWithLoader(true) viewModelScope.launch(Dispatchers.IO + CoroutineExceptionHandler { _, exception -> Log.d(HomeViewModel::class.java.simpleName, "Exception: ${exception.stackTrace}") }) { handleResult(pokemonListByUrlUseCase.invoke(nextPage), append = true) updateListWithLoader(false) } } private fun handleResult(result: ApiResult<PokemonData>, append: Boolean = false) { result.onSuccess { pokemonData -> if (append) { _pokemonList.value = _pokemonList.value.filter { it !is PokemonLoader } + pokemonData.pokemonInfo } else { _pokemonList.value = pokemonData.pokemonInfo } nextPage = pokemonData.next _uiState.value = HomeUiState.ShowSuccess(Unit) }.onFailure { _uiState.value = HomeUiState.ShowError(it.message ?: "An Error Occurred") }.also { isLoadingNextPage = false } } private fun updateListWithLoader(showLoader: Boolean) { val currentList = _pokemonList.value.toMutableList() if (showLoader) { currentList.add(PokemonLoader()) } else { currentList.removeAll { it is PokemonLoader } } _pokemonList.value = currentList } fun openModalBottomSheet(pokemonDetails: PokemonInfo) { _pokemonDetails.value = pokemonDetails } fun searchPokemon(query: String) { if (query.isEmpty()) return _isSearching.value = true _searchError.value = null viewModelScope.launch(Dispatchers.IO + CoroutineExceptionHandler { _, exception -> Log.d(HomeViewModel::class.java.simpleName, "Exception: ${exception.stackTrace}") }) { getSinglePokemonUseCase.invoke(query).onSuccess { _pokemonBySearch.value = it _isSearching.value = false }.onFailure { _searchError.value = it.message _isSearching.value = false } } } fun cleanSearch() { _pokemonBySearch.value = null } fun retry() { getPokemonList(PokeUseCaseData()) } }
0
Kotlin
0
0
b5cdf21b656222931531755081f9a5a68ea7ceb1
5,159
pokeStorie
MIT License
app/src/main/kotlin/io/wax911/challenge/koin/Modules.kt
wax911
457,808,380
false
{"Kotlin": 140698}
package io.wax911.challenge.koin import io.wax911.challenge.core.koin.helper.FeatureModuleHelper import org.koin.androidx.fragment.dsl.fragment import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.dsl.module private val contentModule = module { } private val viewModelModule = module { } internal val appModules = FeatureModuleHelper( listOf(contentModule, viewModelModule) )
0
Kotlin
0
0
b975c8bbc266bd7a19abeadd585f94407bbb95ec
398
android-tech-task
Apache License 2.0
app/src/main/java/com/xtensolutions/weatherapp/ui/viewmodel/BaseViewModel.kt
riontech-xten
345,582,958
false
null
package com.xtensolutions.weatherapp.ui.viewmodel import androidx.hilt.lifecycle.ViewModelInject import androidx.lifecycle.ViewModel import androidx.lifecycle.asLiveData import com.xtensolutions.weatherapp.R import com.xtensolutions.weatherapp.core.DataResult import kotlinx.coroutines.flow.flow import retrofit2.Response /** * Created by <NAME> on 18/02/21. * <EMAIL> */ open class BaseViewModel @ViewModelInject constructor() : ViewModel() { fun <T> getDataResult(call: suspend () -> Response<T>) = flow<DataResult<T>> { emit(DataResult.Loading()) val response = call.invoke() if (response.isSuccessful) { emit(DataResult.Success(response.body()!!)) } else { emit(DataResult.Fail(response.errorBody().toString())) } }.asLiveData() fun <T> getAssetResult(call: suspend () -> T) = flow<DataResult<T>> { emit(DataResult.Loading()) val response = call.invoke() if (response != null) { emit(DataResult.Success(response)) } else { emit(DataResult.Fail("No data found")) } }.asLiveData() }
0
Kotlin
0
0
baea739eb9789d3d803a4bb29084965f15cdae83
1,135
Weather
Apache License 2.0
remix/src/commonMain/kotlin/com/woowla/compose/icon/collections/remix/remix/document/FileCheckLine.kt
walter-juan
868,046,028
false
{"Kotlin": 34345428}
package com.woowla.compose.icon.collections.remix.remix.document import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.woowla.compose.icon.collections.remix.remix.DocumentGroup public val DocumentGroup.FileCheckLine: ImageVector get() { if (_fileCheckLine != null) { return _fileCheckLine!! } _fileCheckLine = Builder(name = "FileCheckLine", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(12.0f, 20.0f) verticalLineTo(22.0f) horizontalLineTo(3.993f) curveTo(3.445f, 22.0f, 3.0f, 21.545f, 3.0f, 21.008f) verticalLineTo(2.992f) curveTo(3.0f, 2.444f, 3.447f, 2.0f, 3.999f, 2.0f) horizontalLineTo(16.0f) lineTo(21.0f, 7.0f) verticalLineTo(14.0f) horizontalLineTo(19.0f) verticalLineTo(8.0f) horizontalLineTo(15.0f) verticalLineTo(4.0f) horizontalLineTo(5.0f) verticalLineTo(20.0f) horizontalLineTo(12.0f) close() moveTo(14.465f, 19.465f) lineTo(18.0f, 23.0f) lineTo(22.95f, 18.051f) lineTo(21.536f, 16.636f) lineTo(18.0f, 20.172f) lineTo(15.879f, 18.051f) lineTo(14.465f, 19.465f) close() } } .build() return _fileCheckLine!! } private var _fileCheckLine: ImageVector? = null
0
Kotlin
0
3
eca6c73337093fbbfbb88546a88d4546482cfffc
2,303
compose-icon-collections
MIT License
shared/src/commonMain/kotlin/screens/create/AddTaskSheet.kt
big-jared
721,852,180
false
{"Kotlin": 79505, "Swift": 687, "Shell": 228}
package screens.create import BottomSheetScreen import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.core.animateDpAsState import androidx.compose.animation.core.animateFloatAsState import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.clickable import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.defaultMinSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.DateRange import androidx.compose.material.icons.filled.KeyboardArrowRight import androidx.compose.material.icons.rounded.Add import androidx.compose.material.icons.rounded.Close import androidx.compose.material3.Button import androidx.compose.material3.Divider import androidx.compose.material3.FilledTonalIconButton import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.rotate import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.rememberVectorPainter import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import blue import cafe.adriel.voyager.navigator.bottomSheet.LocalBottomSheetNavigator import darkGrey import dev.gitlive.firebase.firestore.QuerySnapshot import green import kotlinx.coroutines.flow.Flow import lightBlue import lightGreen import lightGrey import lightNavy import lightOrange import lightPurple import lightRed import lightYellow import models.Task import models.User import navy import orange import purple import red import screens.uid import services.TaskService import services.UserService import utils.ColorHintCircle import utils.HighlightBox import utils.ProfileIcon import yellow data class TaskSheetData( val types: Flow<QuerySnapshot> ) class TaskSheet(task: Task? = null) : BottomSheetScreen { @Composable override fun ColumnScope.BottomSheetContent() { val navigator = LocalBottomSheetNavigator.current var title by remember { mutableStateOf("") } var selectedColor by remember { mutableStateOf<Color?>(null) } var usingAdvanced by remember { mutableStateOf(false) } var user: User? by remember { mutableStateOf(null) } LaunchedEffect(null) { user = UserService.getUser(uid ?: return@LaunchedEffect) val types = TaskService.getTaskTypes() } val horizontalPadding = Modifier.padding(horizontal = 16.dp) Column(modifier = Modifier.padding(vertical = 16.dp).verticalScroll(rememberScrollState())) { Row(modifier = horizontalPadding) { Text( modifier = Modifier.weight(1f).align(Alignment.CenterVertically), text = "Create new task", style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.SemiBold ) FilledTonalIconButton(modifier = Modifier.align(Alignment.CenterVertically), onClick = { navigator.hide() }) { Icon(Icons.Rounded.Close, "") } } Text(modifier = horizontalPadding.padding(top = 16.dp), text = "Title") OutlinedTextField(modifier = horizontalPadding.fillMaxWidth().padding(top = 8.dp), shape = RoundedCornerShape(8.dp), value = title, onValueChange = { title = it }, placeholder = { Text("Redesign this app") }) Row(modifier = horizontalPadding.padding(top = 32.dp)) { Text( "Project", Modifier.weight(1f).align(Alignment.CenterVertically).padding(vertical = 8.dp) ) HighlightBox(modifier = Modifier.align(Alignment.CenterVertically), text = "Sani Mobile", backgroundColor = lightGrey, color = darkGrey, frontIcon = { ColorHintCircle(Modifier.size(24.dp), blue) }) FilledTonalIconButton(modifier = Modifier.align(Alignment.CenterVertically), onClick = { navigator.hide() }) { Icon(Icons.Rounded.Add, "") } } Divider(modifier = horizontalPadding.padding(top = 8.dp)) Row(modifier = horizontalPadding.padding(top = 16.dp)) { Text( modifier = Modifier.align(Alignment.CenterVertically).weight(1f) .padding(vertical = 8.dp), text = "Due Date" ) HighlightBox( modifier = Modifier.align(Alignment.CenterVertically), text = "Today", color = red, backgroundColor = lightRed, frontIcon = { Icon( painter = rememberVectorPainter( Icons.Default.DateRange ), contentDescription = "", tint = red ) }) } Divider(modifier = horizontalPadding.padding(top = 8.dp)) Text(modifier = horizontalPadding.padding(top = 16.dp), text = "Color") Row(modifier = Modifier.padding(top = 16.dp).height(84.dp).horizontalScroll(rememberScrollState())) { Spacer(modifier = Modifier.width(16.dp)) listOf( red, lightRed, orange, lightOrange, yellow, lightYellow, blue, lightBlue, green, lightGreen, purple, lightPurple, navy, lightNavy ).forEach { ColorHintCircle( modifier = Modifier.size(animateDpAsState(if (selectedColor == it) 84.dp else 64.dp).value) .padding(8.dp) .clip(CircleShape) .clickable { selectedColor = it } .align(Alignment.CenterVertically) , it ) } Spacer(modifier = Modifier.width(16.dp)) } Text(modifier = horizontalPadding.padding(top = 16.dp), text = "Assignee") Row(modifier = horizontalPadding.padding(top = 16.dp)) { ProfileIcon(modifier = Modifier.size(64.dp)) FilledTonalIconButton(modifier = Modifier.align(Alignment.CenterVertically) .padding(start = 16.dp).size(64.dp), onClick = { navigator.hide() }) { Icon(Icons.Rounded.Add, "") } } TextButton( modifier = horizontalPadding.padding(top = 16.dp).align(Alignment.End), onClick = { usingAdvanced = usingAdvanced.not() }) { Row { Text( "Advanced Settings", color = blue, style = MaterialTheme.typography.bodyLarge ) Icon( modifier = Modifier.rotate(animateFloatAsState(if (usingAdvanced) 270f else 90f).value), painter = rememberVectorPainter( Icons.Default.KeyboardArrowRight ), contentDescription = "", tint = blue, ) } } AnimatedVisibility (usingAdvanced) { Column { Text(modifier = horizontalPadding.padding(top = 16.dp), text = "Notes") OutlinedTextField(modifier = horizontalPadding.fillMaxWidth().padding(top = 8.dp).defaultMinSize(minHeight = 120.dp), shape = RoundedCornerShape(8.dp), value = title, onValueChange = { title = it }, placeholder = { Text("Redesign this app") }) } } Button( modifier = horizontalPadding.fillMaxWidth().height(64.dp).padding(top = 16.dp), onClick = {}, shape = RoundedCornerShape(32.dp), ) { Text("Done", style = MaterialTheme.typography.bodyLarge) } } } }
0
Kotlin
0
0
38e7ba115d706a8022e72071c47721e8ef1eeabb
9,938
Lolito
Apache License 2.0
app/src/main/java/cn/wthee/pcrtool/ui/tool/TweetList.kt
wthee
277,015,110
false
null
package cn.wthee.pcrtool.ui.tool import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.text.ClickableText import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.unit.sp import androidx.hilt.navigation.compose.hiltViewModel import androidx.paging.LoadState import androidx.paging.compose.collectAsLazyPagingItems import androidx.paging.compose.itemContentType import androidx.paging.compose.itemKey import cn.wthee.pcrtool.R import cn.wthee.pcrtool.data.db.entity.TweetData import cn.wthee.pcrtool.data.enums.KeywordType import cn.wthee.pcrtool.data.enums.MainIconType import cn.wthee.pcrtool.ui.components.BottomSearchBar import cn.wthee.pcrtool.ui.components.CenterTipText import cn.wthee.pcrtool.ui.components.CircularProgressCompose import cn.wthee.pcrtool.ui.components.CommonSpacer import cn.wthee.pcrtool.ui.components.DateRange import cn.wthee.pcrtool.ui.components.DateRangePickerCompose import cn.wthee.pcrtool.ui.components.IconTextButton import cn.wthee.pcrtool.ui.components.MainCard import cn.wthee.pcrtool.ui.components.MainContentText import cn.wthee.pcrtool.ui.components.MainImage import cn.wthee.pcrtool.ui.components.MainTitleText import cn.wthee.pcrtool.ui.components.VerticalGrid import cn.wthee.pcrtool.ui.theme.CombinedPreviews import cn.wthee.pcrtool.ui.theme.Dimen import cn.wthee.pcrtool.ui.theme.ExpandAnimation import cn.wthee.pcrtool.ui.theme.FadeAnimation import cn.wthee.pcrtool.ui.theme.PreviewLayout import cn.wthee.pcrtool.utils.BrowserUtil import cn.wthee.pcrtool.viewmodel.CommonApiViewModel import cn.wthee.pcrtool.viewmodel.TweetViewModel import java.util.regex.Pattern /** * 推特列表 */ @Composable fun TweetList( tweetViewModel: TweetViewModel = hiltViewModel(), commonAPIViewModel: CommonApiViewModel = hiltViewModel(), ) { val scrollState = rememberLazyListState() //关键词输入 val keywordInputState = remember { mutableStateOf("") } //关键词查询 val keywordState = remember { mutableStateOf("") } //时间范围 val dateRange = remember { mutableStateOf(DateRange()) } //获取分页数据 val tweetPager = remember(keywordState.value, dateRange.value) { tweetViewModel.getTweet(keywordState.value, dateRange.value) } val tweetItems = tweetPager.flow.collectAsLazyPagingItems() //获取关键词 val keywordFlow = remember { commonAPIViewModel.getKeywords(KeywordType.TWEET) } val keywordList by keywordFlow.collectAsState(initial = arrayListOf()) Box( modifier = Modifier .fillMaxSize() .background(MaterialTheme.colorScheme.surface) ) { LazyColumn(state = scrollState) { //头部加载中提示 item { ExpandAnimation(tweetItems.loadState.refresh == LoadState.Loading) { Box( modifier = Modifier .fillMaxWidth() .padding(Dimen.largePadding) ) { CircularProgressCompose(Modifier.align(Alignment.Center)) } } } items( count = tweetItems.itemCount, key = tweetItems.itemKey( key = { it.id } ), contentType = tweetItems.itemContentType() ) { index -> val item = tweetItems[index] TweetItem(item ?: TweetData()) } //暂无更多提示 if (tweetItems.loadState.refresh != LoadState.Loading) { item { FadeAnimation(tweetItems.loadState.append is LoadState.NotLoading) { CenterTipText(stringResource(id = R.string.no_more)) } } } items(2) { CommonSpacer() } } //日期选择 DateRangePickerCompose(dateRange = dateRange) //搜索栏 BottomSearchBar( modifier = Modifier .align(Alignment.BottomEnd), labelStringId = R.string.tweet, keywordInputState = keywordInputState, keywordState = keywordState, leadingIcon = MainIconType.TWEET, scrollState = scrollState, defaultKeywordList = keywordList, onResetClick = { //同时重置时间筛选 dateRange.value = DateRange() } ) } } /** * 推特内容 */ @Composable private fun TweetItem(data: TweetData) { val photos = data.getImageList() Column( modifier = Modifier.padding( horizontal = Dimen.largePadding, vertical = Dimen.mediumPadding ) ) { Row( modifier = Modifier .padding(bottom = Dimen.mediumPadding) .fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { MainTitleText(text = data.date) } MainCard { Column { //来源 val jpInfoUrl = stringResource(id = R.string.jp_info_url) IconTextButton( text = "@" + stringResource(id = R.string.title_jp_info), contentColor = MaterialTheme.colorScheme.primary ) { BrowserUtil.open(jpInfoUrl) } //文本 if (data.tweet.contains("http")) { val annotatedLinkString: AnnotatedString = buildAnnotatedString { val str = data.getFormatTweet() val urlIndexList = clickableLink(str) urlIndexList.forEachIndexed { i, it -> val startIndex = it.first val endIndex = it.second //多个url时 只添加一次 if (i == 0) { append(str) } addStyle( style = SpanStyle( color = MaterialTheme.colorScheme.primary, fontSize = 16.sp, textDecoration = TextDecoration.Underline ), start = startIndex, end = endIndex ) addStringAnnotation( tag = "URL", annotation = str.substring(startIndex, endIndex), start = startIndex, end = endIndex ) } } ClickableText( modifier = Modifier.padding( start = Dimen.smallPadding, end = Dimen.smallPadding, bottom = Dimen.mediumPadding, ), text = annotatedLinkString, onClick = { annotatedLinkString .getStringAnnotations("URL", it, it) .firstOrNull()?.let { stringAnnotation -> BrowserUtil.open(stringAnnotation.item) } } ) } else { MainContentText( text = data.getFormatTweet(), textAlign = TextAlign.Start, selectable = true, modifier = Modifier.padding( start = Dimen.smallPadding, end = Dimen.smallPadding, bottom = Dimen.mediumPadding, ), ) } //相关链接跳转 IconTextButton( icon = MainIconType.BROWSER, text = stringResource(id = R.string.twitter), modifier = Modifier .padding(bottom = Dimen.smallPadding, end = Dimen.smallPadding) .align(Alignment.End) ) { BrowserUtil.open(data.link) } //图片 if (photos.isNotEmpty()) { if (photos.size > 1) { VerticalGrid(fixCount = 3, contentPadding = Dimen.mediumPadding) { photos.forEach { MainImage( data = it, ratio = -1f, modifier = Modifier .fillMaxWidth() .height(Dimen.tweetImgHeight), contentScale = ContentScale.Crop ) } } } else { MainImage( data = photos[0], ratio = -1f, modifier = Modifier.fillMaxWidth(), contentScale = ContentScale.Crop ) } } } } } } private val urlPattern: Pattern = Pattern.compile( "(?:^|[\\W])((ht|f)tp(s?):\\/\\/|www\\.)" + "(([\\w\\-]+\\.){1,}?([\\w\\-.~]+\\/?)*" + "[\\p{Alnum}.,%_=?&#\\-+()\\[\\]\\*$~@!:/{};']*)", Pattern.CASE_INSENSITIVE or Pattern.MULTILINE or Pattern.DOTALL ) private fun clickableLink(longText: String): ArrayList<Pair<Int, Int>> { val urlList = arrayListOf<Pair<Int, Int>>() try { val matcher = urlPattern.matcher(longText) var matchStart: Int var matchEnd: Int while (matcher.find()) { matchStart = matcher.start(1) matchEnd = matcher.end() urlList.add(Pair(matchStart, matchEnd)) } } catch (e: Exception) { e.printStackTrace() } return urlList } @CombinedPreviews @Composable private fun TweetItemPreview() { PreviewLayout { TweetItem(data = TweetData(id = 1, tweet = "???")) } }
0
null
2
53
73b9331c3e15e9718177c64ef6725eea8582abe6
11,795
pcr-tool
Apache License 2.0
domain/src/main/java/com/nyinyihtunlwin/domain/exception/NetworkException.kt
nyinyihtunlwin-codigo
368,728,828
false
{"Kotlin": 37585}
package com.nyinyihtunlwin.domain.exception object NetworkException: Exception()
0
Kotlin
0
1
daf51d2c563325b57a56211b87d14bd2556666b3
81
my-movies
Apache License 2.0
components/link-manager/src/test/kotlin/net/corda/p2p/linkmanager/sessions/StateManagerWrapperTest.kt
corda
346,070,752
false
null
package net.corda.p2p.linkmanager.sessions import net.corda.libs.statemanager.api.MetadataFilter import net.corda.libs.statemanager.api.State import net.corda.libs.statemanager.api.StateManager import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.verify import org.mockito.kotlin.whenever class StateManagerWrapperTest { private val keys = setOf("key1", "key2") private val state = mock<State>() private val filter = mock<MetadataFilter>() private val filters = listOf(filter) private val keysToStates = mapOf("key1" to state) private val stateManager = mock<StateManager> { on { get(keys) } doReturn keysToStates on { findByMetadataMatchingAny(filters) } doReturn keysToStates } private val sessionCache = mock<SessionCache> { on { validateStatesAndScheduleExpiry(keysToStates) } doReturn keysToStates } private val wrapper = StateManagerWrapper( stateManager, sessionCache, ) @Test fun `get calls the state manager`() { wrapper.get(keys) verify(stateManager).get(keys) } @Test fun `get calls the scheduler`() { wrapper.get(keys) verify(sessionCache).validateStatesAndScheduleExpiry(keysToStates) } @Test fun `get returns the correct value`() { val ret = wrapper.get(keys) assertThat(ret).isEqualTo(keysToStates) } @Test fun `findStatesMatchingAny calls the state manager`() { wrapper.findStatesMatchingAny(filters) verify(stateManager).findByMetadataMatchingAny(filters) } @Test fun `findStatesMatchingAny calls the scheduler`() { wrapper.findStatesMatchingAny(filters) verify(sessionCache).validateStatesAndScheduleExpiry(keysToStates) } @Test fun `findStatesMatchingAny returns the correct value`() { val ret = wrapper.findStatesMatchingAny(filters) assertThat(ret).isEqualTo(keysToStates) } @Test fun `upsert with update will set the beforeUpdate to true`() { val update = UpdateAction(state) wrapper.upsert(listOf(update)) verify(sessionCache).validateStateAndScheduleExpiry(state, true) } @Test fun `upsert with create will set the beforeUpdate to false`() { val create = CreateAction(state) wrapper.upsert(listOf(create)) verify(sessionCache).validateStateAndScheduleExpiry(state, false) } @Test fun `upsert with update will not update expired sessions`() { val update = UpdateAction(state) wrapper.upsert(listOf(update)) verify(stateManager, never()).update(any()) } @Test fun `upsert with update will update valid sessions`() { whenever(sessionCache.validateStateAndScheduleExpiry(state, true)).doReturn(state) val update = UpdateAction(state) wrapper.upsert(listOf(update)) verify(stateManager).update(listOf(state)) } @Test fun `upsert with create will not create expired sessions`() { val create = CreateAction(state) wrapper.upsert(listOf(create)) verify(stateManager, never()).create(any()) } @Test fun `upsert with create will create valid sessions`() { whenever(sessionCache.validateStateAndScheduleExpiry(state, false)).doReturn(state) val create = CreateAction(state) wrapper.upsert(listOf(create)) verify(stateManager).create(listOf(state)) } @Test fun `upsert with return the failures of the updates and creates`() { whenever(sessionCache.validateStateAndScheduleExpiry(any(), any())).doReturn(state) whenever(stateManager.create(any())).doReturn(setOf("key3", "key4")) whenever(stateManager.update(any())).doReturn(mapOf("key1" to state, "key2" to state)) val update = UpdateAction(state) val create = CreateAction(state) val failed = wrapper.upsert(listOf(update, create)) assertThat(failed) .containsEntry("key1", state) .containsEntry("key2", state) .containsEntry("key3", null) .containsEntry("key4", null) .hasSize(4) } }
50
null
25
55
00630a76507ef4610a50058480a911b3b77ca603
4,376
corda-runtime-os
Apache License 2.0
v16/src/jvmMain/kotlin/com/monta/ocpp/emulator/chargepoint/view/createchargepoint/ChargePointForm.kt
monta-app
789,343,716
false
null
package com.monta.ocpp.emulator.v16.view.createchargepoint import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.Button import androidx.compose.material.ButtonDefaults import androidx.compose.material.Card import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.monta.ocpp.emulator.common.components.FormInput import com.monta.ocpp.emulator.common.components.LabelledCheckBox import com.monta.ocpp.emulator.common.components.MontaIcon import com.monta.ocpp.emulator.common.components.PasswordField import com.monta.ocpp.emulator.common.components.Spinner import com.monta.ocpp.emulator.common.components.getButtonStateColor import com.monta.ocpp.emulator.common.components.getCardStyle import com.monta.ocpp.emulator.common.model.UrlChoice import com.monta.ocpp.emulator.common.util.injectAnywhere import com.monta.ocpp.emulator.v16.data.entity.ChargePointDAO import com.monta.ocpp.emulator.v16.data.entity.ChargePointTable import com.monta.ocpp.emulator.v16.data.model.OcppVersion import com.monta.ocpp.emulator.v16.data.service.ChargePointService import com.monta.ocpp.emulator.v16.view.NavigationViewModel import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq import org.jetbrains.exposed.sql.transactions.transaction import org.koin.core.annotation.Factory @Composable fun ChargePointForm(viewModel: ChargePointFormViewModel, chargePoint: ChargePointDAO?) { chargePoint?.let { if (!viewModel.initialized) { viewModel.form.updateFromDAO(it) viewModel.form = viewModel.form.copy() viewModel.initialized = true viewModel.isUpdating = true } } Box( modifier = Modifier.fillMaxSize() .verticalScroll( state = rememberScrollState() ) ) { Card( modifier = getCardStyle() .align(Alignment.Center) .padding( top = 32.dp, bottom = 32.dp ), shape = RoundedCornerShape(20.dp) ) { Column( modifier = Modifier.padding(16.dp) .width(400.dp), verticalArrangement = Arrangement.spacedBy(5.dp) ) { Text( text = (if (viewModel.isUpdating) "Edit" else "Create") + " Charge Point", style = MaterialTheme.typography.h5, modifier = Modifier.padding(8.dp) .align(Alignment.Start) .fillMaxWidth() ) FormInput( modifier = Modifier.fillMaxWidth(), label = "Charge Point Name", value = viewModel.form.chargePointName, onValueChange = { newValue -> viewModel.form = viewModel.form.copy( chargePointName = newValue ) }, helperText = "Name used for identifying the charge point locally in the app, not largely important mostly for your convenience" ) FormInput( modifier = Modifier.fillMaxWidth(), label = "Charge Point Identity", value = viewModel.form.chargePointIdentity, onValueChange = { newValue -> viewModel.form = viewModel.form.copy( chargePointIdentity = newValue ) viewModel.validateForm() }, enabled = !viewModel.isUpdating, isError = viewModel.formErrors.contains("identity"), helperText = viewModel.formErrors.getOrDefault("identity", null) ?: "The identity used for connecting to the OCPP server, cannot be empty or contain spaces, and must be unique" ) Spinner( modifier = Modifier.fillMaxWidth(), label = "OCPP Server", value = viewModel.form.urlChoice, values = UrlChoice.entries, render = { urlChoice -> urlChoice.name } ) { newUrlChoice -> viewModel.form = viewModel.form.copy( urlChoice = newUrlChoice, ocppUrl = newUrlChoice.ocppUrl, apiUrl = newUrlChoice.apiUrl ) } FormInput( modifier = Modifier.fillMaxWidth(), label = "Ocpp Url", value = viewModel.form.ocppUrl, onValueChange = { newValue -> viewModel.form = viewModel.form.copy( ocppUrl = newValue ) }, enabled = viewModel.form.urlChoice == UrlChoice.Other ) Row( verticalAlignment = Alignment.CenterVertically ) { Text( text = "Connectors", style = MaterialTheme.typography.subtitle1, modifier = Modifier.padding(end = 8.dp) ) MontaIcon( iconName = "help", tooltipText = "Allows you to select how many connectors this charge point will be configured with" ) } Row { Button( modifier = Modifier.fillMaxWidth() .weight(1f) .padding(end = 4.dp), colors = ButtonDefaults.buttonColors( backgroundColor = getButtonStateColor(viewModel.form.connectorCount == 1) ), onClick = { viewModel.form = viewModel.form.copy( connectorCount = 1 ) } ) { Text("1") } Button( modifier = Modifier.fillMaxWidth() .weight(1f) .padding(start = 4.dp), colors = ButtonDefaults.buttonColors( backgroundColor = getButtonStateColor(viewModel.form.connectorCount == 2) ), onClick = { viewModel.form = viewModel.form.copy( connectorCount = 2 ) } ) { Text("2") } } LabelledCheckBox( modifier = Modifier.fillMaxWidth(), checked = viewModel.form.showAdvanceSettings, onCheckedChange = { viewModel.form = viewModel.form.copy( showAdvanceSettings = it ) }, label = "Show Advanced Settings" ) if (viewModel.form.showAdvanceSettings) { FormInput( modifier = Modifier.fillMaxWidth(), label = "Api Url", value = viewModel.form.apiUrl, onValueChange = { newValue -> viewModel.form = viewModel.form.copy( apiUrl = newValue ) } ) PasswordField( modifier = Modifier.fillMaxWidth(), password = viewModel.form.password, passwordVisibility = viewModel.form.passwordVisibility, passwordListener = { newValue -> viewModel.form = viewModel.form.copy( password = newValue ) }, passwordVisibilityListener = { newValue -> viewModel.form = viewModel.form.copy( passwordVisibility = newValue ) } ) Spinner( modifier = Modifier.fillMaxWidth(), label = "Max charging rate", value = viewModel.form.maxKw, values = listOf(22, 150, 250, 350), render = { "$it kW" }, onSelectionChanged = { newMaxKw -> viewModel.form = viewModel.form.copy( maxKw = newMaxKw.toDouble() ) } ) Spinner( modifier = Modifier.fillMaxWidth(), label = "OCPP version", value = viewModel.form.ocppVersion, values = OcppVersion.entries, render = { ocppVersionChoice -> ocppVersionChoice.version } ) { newOcppChoice -> viewModel.form = viewModel.form.copy( ocppVersion = newOcppChoice ) } FormInput( modifier = Modifier.fillMaxWidth(), label = "Firmware Version", value = viewModel.form.firmware, onValueChange = { newValue -> viewModel.form = viewModel.form.copy( firmware = newValue ) } ) } Button( enabled = viewModel.formErrors.isEmpty(), modifier = Modifier.align(Alignment.Start), onClick = { connect(viewModel) } ) { if (viewModel.isUpdating) { Text("Save") } else { Text("Create") } } } } } } private fun connect( viewModel: ChargePointFormViewModel ) { val navigationViewModel: NavigationViewModel by injectAnywhere() val chargePointService: ChargePointService by injectAnywhere() if (viewModel.validateForm()) { return } chargePointService.upsert( name = viewModel.form.chargePointName, identity = viewModel.form.chargePointIdentity, password = viewModel.form.password, ocppUrl = viewModel.form.ocppUrl, apiUrl = viewModel.form.apiUrl, firmware = viewModel.form.firmware, maxKw = viewModel.form.maxKw, connectorCount = viewModel.form.connectorCount ) navigationViewModel.navigateTo( screen = NavigationViewModel.Screen.ChargePoints ) } @Factory class ChargePointFormViewModel { var form by mutableStateOf(Form()) var initialized by mutableStateOf(false) var isUpdating by mutableStateOf(false) val formErrors = mutableStateMapOf<String, String>() fun validateForm(): Boolean { var hasErrors = false if (form.ocppUrl.isBlank()) { formErrors["ocppUrl"] = "URL cannot be blank or empty" hasErrors = true } else if (!form.ocppUrl.isWebsocketUrl()) { formErrors["ocppUrl"] = "URL not a valid web socket url" hasErrors = true } if (form.chargePointIdentity.isBlank()) { formErrors["identity"] = "Cannot be blank or empty" hasErrors = true } else if (!isUpdating && transaction { ChargePointDAO.count( ChargePointTable.identity eq form.chargePointIdentity.trim().uppercase() ) != 0L } ) { formErrors["identity"] = "Identity already in use" hasErrors = true } else if (form.urlChoice == UrlChoice.Production && !form.chargePointIdentity.trim().uppercase().startsWith("MEM_")) { formErrors["identity"] = "On production identity must begin with MEM_" hasErrors = true } else { formErrors.remove("identity") } return hasErrors } data class Form( var chargePointName: String = "", var chargePointIdentity: String = "", var password: String = "", var passwordVisibility: Boolean = false, var urlChoice: UrlChoice = UrlChoice.Staging, var ocppUrl: String = UrlChoice.Staging.ocppUrl, var apiUrl: String = UrlChoice.Staging.apiUrl, var connectorCount: Int = 1, var showAdvanceSettings: Boolean = false, var firmware: String = "1.0.0", var maxKw: Double = 22.0, var ocppVersion: OcppVersion = OcppVersion.V16 ) { fun updateFromDAO(chargePoint: ChargePointDAO) { this.chargePointName = chargePoint.name this.chargePointIdentity = chargePoint.identity this.password = chargePoint.basicAuthPassword ?: this.password this.urlChoice = UrlChoice.fromUrl(chargePoint.ocppUrl) this.ocppUrl = chargePoint.ocppUrl this.apiUrl = chargePoint.apiUrl this.connectorCount = transaction { chargePoint.connectors.count().toInt() } this.firmware = chargePoint.firmware this.maxKw = chargePoint.maxKw this.ocppVersion = chargePoint.ocppVersion } } private fun String.isWebsocketUrl(): Boolean { return startsWith("wss://") || startsWith("ws://") } }
7
null
4
89
3ec9445ca517e97a0dba2f0a05b7ed38ac37faf5
15,243
ocpp-emulator
Apache License 2.0
src/main/kotlin/one/digitalinnovation/digionebank/teste/TesteAutenticacao.kt
lucasgoncalvesbt
425,162,689
false
null
package one.digitalinnovation.digionebank.teste import one.digitalinnovation.digionebank.Logavel class TesteAutenticacao { fun autentica(logavel: Logavel) = println(logavel.login()) }
0
Kotlin
0
0
4bfb3f1e1bd2630ac16644e52f8753270cbd569d
189
dio-kotlin-oo
MIT License
hexagon_core/src/test/kotlin/com/hexagonkt/helpers/JvmTest.kt
wanglaibao
182,938,373
true
{"Kotlin": 294183, "HTML": 22186, "Scala": 3558, "JavaScript": 2701, "Groovy": 2022, "Dockerfile": 1701, "CSS": 613}
package com.hexagonkt.helpers import org.testng.annotations.Test import java.net.Inet4Address @Test class JvmTest { @Test fun `'hostname' and 'ip' contains valid values` () { assert(Jvm.hostname.isNotBlank()) assert(Jvm.ip.matches(Regex("\\d{1,3}(\\.\\d{1,3}){3}"))) assert(Inet4Address.getAllByName(Jvm.hostname).isNotEmpty()) assert(Inet4Address.getAllByName(Jvm.ip).isNotEmpty()) } @Test fun `JVM metrics have valid values` () { val numberRegex = Regex("[\\d.,]+") assert(Jvm.initialMemory().matches(numberRegex)) assert(Jvm.usedMemory().matches(numberRegex)) assert(Jvm.uptime().matches(numberRegex)) } }
0
Kotlin
0
0
69b24328adcb32cca1b038128f544b437e324525
693
hexagon
MIT License
middleware/sisyphus-jdbc/src/main/kotlin/com/bybutter/sisyphus/middleware/jdbc/support/proto/filter/TableSqlBuilder.kt
ButterCam
264,589,207
false
null
package com.bybutter.sisyphus.middleware.jdbc.support.proto.filter import com.bybutter.sisyphus.dsl.filtering.grammar.FilterParser import com.bybutter.sisyphus.string.toCamelCase import org.jooq.Condition import org.jooq.DSLContext import org.jooq.Field import org.jooq.OrderField import org.jooq.Record import org.jooq.SelectConditionStep import org.jooq.SelectJoinStep import org.jooq.Table open class TableSqlBuilder<T : Record>(private val table: Table<T>) : SqlBuilder<T>() { private val fieldMapping = mutableMapOf<String, Any>() final override var runtime: FilterRuntime = FilterRuntime() private set override fun buildSelect( dsl: DSLContext, expressions: List<Any?>, vararg fields: Field<*>, ): SelectConditionStep<T> { val selectedFields = if (fields.isEmpty()) { table.fields() } else { fields } val conditions = expressions.flatMap { when (it) { is Condition -> listOf(it) is ConditionProvider -> it.provideConditions() else -> listOf() } } val joins = expressions.flatMap { when (it) { is JoinProvider -> it.provideJoins() is Join -> listOf(it) else -> listOf() } }.distinctBy { it.javaClass } return dsl.select(*selectedFields).from(table).run { joins.fold(this as SelectJoinStep<*>) { step, join -> join.joinTable(step) } }.where(conditions) as SelectConditionStep<T> } override fun member(member: FilterParser.MemberContext): Any? { return fieldMapping[member.text] } fun field( member: String, field: Field<*>, converter: ((Any?) -> Any?)? = null, ) { val camelCaseMember = toCamelCase(member) val fieldOrHandle = FieldHandle.wrap(field, converter) fieldMapping[member] = fieldOrHandle fieldMapping[camelCaseMember] = fieldOrHandle } fun runtime(runtime: FilterRuntime) { this.runtime = runtime } fun library(library: FilterStandardLibrary) { this.runtime = FilterRuntime(library) } private fun toCamelCase(field: String): String { return field.split(".").map { it.toCamelCase() }.joinToString(".") } } fun <T : Record> sqlBuilder( table: Table<T>, block: TableSqlBuilder<T>.() -> Unit, ): TableSqlBuilder<T> { return TableSqlBuilder(table).apply(block) } fun Condition.withJoin(join: Join): SqlFilterPart { return SqlFilterPart(this, listOf(join), listOf()) } fun Condition.orderBy(vararg orderBy: OrderField<*>): SqlFilterPart { return SqlFilterPart(this, listOf(), orderBy.toList()) } fun Condition.filterPart(): SqlFilterPart { return SqlFilterPart(this, listOf(), listOf()) }
9
null
10
92
1f9851c7c45030fa08e018e961110851e029f940
3,000
sisyphus
MIT License
plugin/src/main/java/com/bumble/devicefarm/plugin/device/farm/DeviceFarm.kt
bumble-tech
575,789,291
false
{"Kotlin": 24616}
package com.bumble.devicefarm.plugin.device.farm import com.android.build.api.dsl.Device import org.gradle.api.provider.Property import org.gradle.api.tasks.Input interface DeviceFarm : Device { @get:Input val shards: Property<Int> }
0
Kotlin
3
6
9c0548344983d652d1c80af2f128b85d60403429
245
Article_GradleManagedDevices
Apache License 2.0
app/src/main/java/com/amtgreenberg/thegame/MainApplication.kt
AdamMTGreenberg
324,944,552
false
null
package com.amtgreenberg.thegame import android.app.Application import com.amtgreenberg.thegame.di.component.AppComponent import com.amtgreenberg.thegame.di.component.DaggerAppComponent import com.amtgreenberg.thegame.di.module.AppModule import com.amtgreenberg.thegame.di.module.LocalStorageModule import com.facebook.stetho.Stetho import timber.log.Timber class MainApplication : Application() { companion object { lateinit var appComponent: AppComponent } override fun onCreate() { super.onCreate() appComponent = initDagger(this) initStetho() initTimber() } private fun initDagger(mainApplication: MainApplication): AppComponent { return DaggerAppComponent.builder() .appModule(AppModule(application = mainApplication)) .localStorageModule(LocalStorageModule(application = mainApplication)) .build() } private fun initStetho() { if (BuildConfig.DEBUG) { Stetho.initializeWithDefaults(this) } } private fun initTimber() { if (BuildConfig.DEBUG) { Timber.plant(Timber.DebugTree()) } } }
0
Kotlin
0
0
ce8a3f510639cdd1c58cffd339f454b24e50d178
1,156
thegame
MIT License
mbingresskit/src/main/java/com/daimler/mbingresskit/implementation/network/LdssoAgreementTask.kt
Daimler
199,818,813
false
{"Gradle": 9, "Markdown": 6, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Proguard": 2, "Java": 7, "Kotlin": 220, "JSON": 7, "XML": 14}
package com.daimler.mbingresskit.implementation.network import com.daimler.mbingresskit.common.LdssoUserAgreement import com.daimler.mbingresskit.common.UserAgreementContentType import com.daimler.mbingresskit.implementation.network.model.agreement.ApiAgreementsResponse import com.daimler.mbingresskit.implementation.network.model.agreement.ApiLdssoAgreement internal class LdssoAgreementTask( locale: String, country: String, api: UserApi, callback: Callback<LdssoUserAgreement>? ) : BaseAgreementTask<ApiLdssoAgreement, LdssoUserAgreement>("", locale, country, api, callback) { override fun getAgreements(agreements: ApiAgreementsResponse): List<ApiLdssoAgreement> = agreements.ldsso ?: emptyList() override fun fetchAgreementContent(agreement: ApiLdssoAgreement): LdssoUserAgreement { val url = agreement.href val type = if (url.endsWith(".pdf")) { UserAgreementContentType.PDF } else { UserAgreementContentType.WEB } val call = api.fetchPdfAgreementsContent(agreement.href) val response = call.execute() return if (response.isSuccessful) { ldssoAgreement(agreement, response.body()?.bytes(), type) } else { ldssoAgreement(agreement, null, type) } } private fun ldssoAgreement(apiAgreement: ApiLdssoAgreement, bytes: ByteArray?, contentType: UserAgreementContentType) = LdssoUserAgreement( documentId = apiAgreement.id, originalUrl = apiAgreement.href, documentVersion = apiAgreement.version, displayName = apiAgreement.displayName, locale = locale, countryCode = country, filePath = null, acceptedByUser = mapApiAcceptanceStateToAcceptanceState(apiAgreement.acceptedByUser), implicitConsent = apiAgreement.implicitConsent == true, fileContent = bytes, position = apiAgreement.position, contentType = contentType ) }
0
Kotlin
0
0
472fe1cdf4ae45989c9d0f1a9628292f5432b103
2,161
MBSDK-IngressKit-Android
MIT License
plugins/kotlin/idea/tests/testData/quickfix/convertToAnonymousObject/typeArgument2.kt
ingokegel
72,937,917
false
null
// "Convert to anonymous object" "true" interface B<X, Y, Z> { fun bar(a: Z, b: Y): X } val b = <caret>B { a: Int, b: Long -> "" } // FUS_QUICKFIX_NAME: org.jetbrains.kotlin.idea.quickfix.ConvertToAnonymousObjectFix
233
null
4912
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
220
intellij-community
Apache License 2.0
app/src/main/java/com/example/news/ui/home/main/adapter/item/NewsTextItem.kt
KotezMorovez
756,865,346
false
{"Kotlin": 237052}
package com.example.news.ui.home.main.adapter.item import com.example.news.ui.common.delegate_adapter.IDelegateAdapterItem class NewsTextItem (val ui: NewsUi) : IDelegateAdapterItem { override fun id(): String { return ui.id } override fun content(): NewsUi { return ui } }
0
Kotlin
0
0
fde8a39b0ef6b6642261fcfe406d00ae3a5a2131
308
News
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsaccreditedprogrammesapi/course/repositories/JpaCourseRepository.kt
ministryofjustice
615,402,552
false
{"Kotlin": 215257, "Shell": 10680, "Dockerfile": 1397}
package uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.course.repositories import org.hibernate.Hibernate import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Component import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.course.domain.Audience import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.course.domain.CourseEntity import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.course.domain.CourseRepository import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.course.domain.Offering import java.util.UUID import kotlin.jvm.optionals.getOrNull @Component class JpaCourseRepository @Autowired constructor( private val courseRepository: CourseEntityRepository, private val offeringRepository: OfferingRepository, private val audienceRepository: AudienceRepository, ) : CourseRepository { override fun allCourses(): List<CourseEntity> = courseRepository .findAll() .onEach { Hibernate.initialize(it.audiences) Hibernate.initialize(it.prerequisites) } override fun course(courseId: UUID): CourseEntity? = courseRepository .findById(courseId) .getOrNull() ?.also { Hibernate.initialize(it.audiences) Hibernate.initialize(it.prerequisites) } override fun findCourseByOfferingId(offeringId: UUID): CourseEntity? = courseRepository .findByMutableOfferings_id(offeringId) ?.also { Hibernate.initialize(it.audiences) Hibernate.initialize(it.prerequisites) } override fun allOfferings(): List<Offering> = offeringRepository .findAll() .onEach { Hibernate.initialize(it.course) } override fun offeringsForCourse(courseId: UUID): List<Offering> = courseRepository .findById(courseId) .getOrNull() ?.offerings ?.toList() ?: emptyList() override fun courseOffering(courseId: UUID, offeringId: UUID): Offering? = offeringsForCourse(courseId).find { it.id == offeringId } override fun courseOffering(offeringId: UUID): Offering? = offeringRepository.findById(offeringId).getOrNull() override fun allAudiences(): Set<Audience> = audienceRepository.findAll().toSet() override fun saveCourse(courseEntity: CourseEntity) { courseRepository.save(courseEntity) } override fun saveAudiences(audiences: Set<Audience>) { audienceRepository.saveAll(audiences) } }
0
Kotlin
0
0
f15f6d5030a8bd93970c82afd832c821de3f2c1e
2,393
hmpps-accredited-programmes-api
MIT License
app/src/main/java/com/binlly/gankee/service/Services.kt
binlly
110,812,581
false
null
package com.binlly.gankee.service import android.os.Handler import android.os.Looper import com.binlly.gankee.app.App import com.binlly.gankee.service.account.AccountService import com.binlly.gankee.service.account.AccountServiceImpl import com.binlly.gankee.service.remoteconfig.RemoteConfigService import com.binlly.gankee.service.remoteconfig.RemoteConfigServiceImpl object Services { lateinit var app: App private val mHandler = Handler(Looper.getMainLooper()) fun remove(callbacks: Runnable) { mHandler.removeCallbacks(callbacks) } fun post(post: Runnable) { mHandler.post(post) } fun postDelayed(post: Runnable, delayMillis: Long) { mHandler.postDelayed(post, delayMillis) } fun postDelayed(delayMillis: Long = 0L, post: () -> Unit) { mHandler.postDelayed(post, delayMillis) } fun removeRunnable(post: (() -> Unit)?): Boolean { post ?: return false post.let { mHandler.removeCallbacks(post) return true } } private val accountService: AccountService by lazy { AccountServiceImpl.registerInstance() } private val remoteConfigService: RemoteConfigService by lazy { RemoteConfigServiceImpl.registerInstance() } fun app(): App { return App.app } fun account(): AccountService { return accountService } fun remoteConfig(): RemoteConfigService { return remoteConfigService } }
1
null
1
1
fd315ad794de22e6213fbcb8c4fa45af1c24c8d4
1,475
Gankee
MIT License
app/src/main/java/in/developingdeveloper/timeline/settings/ui/SettingsContent.kt
5AbhishekSaxena
624,931,376
false
null
package `in`.developingdeveloper.timeline.settings.ui import android.content.res.Configuration import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import `in`.developingdeveloper.timeline.R import `in`.developingdeveloper.timeline.core.ui.components.BackNavigationIcon import `in`.developingdeveloper.timeline.core.ui.components.TimelineStartAlignedTopAppBar import `in`.developingdeveloper.timeline.core.ui.models.UiText import `in`.developingdeveloper.timeline.core.ui.theme.TimelineTheme import `in`.developingdeveloper.timeline.settings.ui.components.SettingsList import `in`.developingdeveloper.timeline.settings.ui.models.UiSetting @Composable fun SettingsContent( settings: List<UiSetting>, onBackNavigationIconClick: () -> Unit, ) { Scaffold( topBar = { TimelineStartAlignedTopAppBar( title = stringResource(id = R.string.settings), navigationIcon = { BackNavigationIcon(onBackNavigationIconClick) }, ) }, ) { contentPadding -> SettingsList( settings = settings, modifier = Modifier .padding(contentPadding) .fillMaxSize(), ) } } @Preview( name = "Night Mode", uiMode = Configuration.UI_MODE_NIGHT_YES, ) @Preview( name = "Day Mode", uiMode = Configuration.UI_MODE_NIGHT_NO, ) @Composable @Suppress("UnusedPrivateMember", "MagicNumber") private fun SettingsContentPreview() { val settings = (1..10).map { UiSetting( label = UiText.StringText("Label #$it"), onClick = {}, ) } TimelineTheme { Surface { SettingsContent( settings = settings, onBackNavigationIconClick = {}, ) } } }
9
null
3
18
44cbc20a430e0d012d982b4adb11ae626af1c404
2,148
Timeline
Apache License 2.0
educational-core/src/com/jetbrains/edu/coursecreator/stepik/StepikCourseUploader.kt
JetBrains
43,696,115
false
null
package com.jetbrains.edu.coursecreator.stepik import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.Project import com.jetbrains.edu.coursecreator.CCNotificationUtils.showNotification import com.jetbrains.edu.coursecreator.stepik.CCStepikConnector.* import com.jetbrains.edu.learning.EduBrowser.Companion.getInstance import com.jetbrains.edu.learning.courseFormat.EduCourse import com.jetbrains.edu.learning.marketplace.MARKETPLACE_COURSES_HELP import com.jetbrains.edu.learning.messages.EduCoreBundle.message import com.jetbrains.edu.learning.stepik.api.StepikConnector import com.jetbrains.edu.learning.stepik.api.StepikCourseLoader class StepikCourseUploader(val project: Project, val course: EduCourse) { fun updateCourse() { val remoteCourse = StepikConnector.getInstance().getCourseInfo(course.id) ?: return StepikCourseLoader.loadCourseStructure(remoteCourse) remoteCourse.init(null, null, false) pushChanges(remoteCourse) } private fun pushChanges(remoteCourse: EduCourse) { val changeRetriever = StepikChangeRetriever(project, course, remoteCourse) val changedItems = changeRetriever.getChangedItems() if (changedItems.isEmpty()) { showNotification(project, "Nothing to update", null) return } var success = processCourse(changedItems) success = processTopLevelSection(changedItems) && success success = processSections(changedItems) && success success = processLessons(changedItems) && success success = processTasks(changedItems) && success if (!success) { showNotification(project, "Failed to update the course", null) } else { course.updateDate = remoteCourse.updateDate showNotification(project, object: AnAction(message("course.dialog.learn.more")) { override fun actionPerformed(e: AnActionEvent) { getInstance().browse(MARKETPLACE_COURSES_HELP) } }, message("stepik.course.updated.notification.title"), message("stepik.course.updated.notification.message")) } } private fun processCourse(changedItems: StepikChangesInfo): Boolean { var success = true if (changedItems.isCourseInfoChanged) { success = updateCourseInfo(project, course) && success } if (changedItems.isCourseAdditionalInfoChanged) { success = updateCourseAdditionalInfo(project, course) && success } return success } private fun processTopLevelSection(changedItems: StepikChangesInfo): Boolean { var success = true if (changedItems.isTopLevelSectionRemoved) { StepikConnector.getInstance().deleteSection(course.sectionIds[0]) course.sectionIds = emptyList() } if (changedItems.isTopLevelSectionNameChanged) { success = updateSectionForTopLevelLessons(course) && success } if (changedItems.isTopLevelSectionAdded) { val sectionId = postSectionForTopLevelLessons(project, course) success = sectionId != -1 && success } return success } private fun processSections(changedItems: StepikChangesInfo): Boolean { var success = true // delete old section changedItems.sectionsToDelete.forEach { StepikConnector.getInstance().deleteSection(it.id) } // post new section changedItems.newSections.forEach { it.position = it.index success = postSection(project, it) && success } // update section for (localSection in changedItems.sectionInfosToUpdate) { localSection.position = localSection.index success = updateSectionInfo(localSection) && success } return success } private fun processLessons(changedItems: StepikChangesInfo): Boolean { var success = true // delete old lesson changedItems.lessonsToDelete.forEach { StepikConnector.getInstance().deleteLesson(it.id) StepikConnector.getInstance().deleteUnit(it.unitId) } // post new lesson changedItems.newLessons.forEach { val section = it.section?.id ?: course.sectionIds.first() success = postLesson(project, it, it.index, section) && success } // update lesson for (localLesson in changedItems.lessonsInfoToUpdate) { val section = localLesson.section?.id ?: course.sectionIds.first() val lesson = updateLessonInfo(project, localLesson, false, section) success = lesson != null && success } changedItems.lessonAdditionalInfosToUpdate.forEach { success = updateLessonAdditionalInfo(it, project) && success } return success } private fun processTasks(changedItems: StepikChangesInfo): Boolean { var success = true // delete old task changedItems.tasksToDelete.forEach { StepikConnector.getInstance().deleteTask(it.id) } // post new task changedItems.newTasks.forEach { success = postTask(project, it, it.lesson.id) && success } // update tasks for (localTask in changedItems.tasksToUpdate) { success = updateTask(project, localTask) && success } return success } }
0
null
37
98
4b4b8b51517cd0fd1452bec9250a4c414b051caa
5,095
educational-plugin
Apache License 2.0
src/main/kotlin/no/nav/dagpenger/manuell/behandling/avklaring/AvklaringBehandling.kt
navikt
767,735,518
false
{"Kotlin": 30061, "Dockerfile": 213}
package no.nav.dagpenger.manuell.behandling.avklaring import mu.KotlinLogging import mu.withLoggingContext import no.nav.dagpenger.manuell.behandling.hendelse.ManuellBehandlingAvklaring import no.nav.helse.rapids_rivers.JsonMessage import no.nav.helse.rapids_rivers.MessageContext import java.time.LocalDateTime import java.util.UUID internal data class AvklaringBehandling( val avklaring: Avklaring, val kode: String, val behandlingId: UUID, val ident: String, val søknadId: UUID, val context: MessageContext, val opprettet: LocalDateTime = LocalDateTime.now(), ) { companion object { private val logger = KotlinLogging.logger { } } fun lagInformasjonsbehov(manuellBehandlingAvklaring: ManuellBehandlingAvklaring) { val behov = JsonMessage .newNeed( behov = listOf(avklaring.behov.name), avklaring.behovKontekst(manuellBehandlingAvklaring) + mapOf( "avklaringId" to avklaring.id.toString(), "søknadId" to søknadId.toString(), "behandlingId" to behandlingId.toString(), "ident" to ident, ), ) behov.interestedIn("@behovId") withLoggingContext( "behovId" to behov["@behovId"].asText(), "avklaringId" to avklaring.id.toString(), "behandlingId" to behandlingId.toString(), ) { logger.info { "Publisere behov for ${avklaring.behov.name} for avklaring $kode" } context.publish( ident, behov.toJson(), ) } } fun publiserIkkeRelevant() { context.publish( ident, JsonMessage .newMessage( "AvklaringIkkeRelevant", mutableMapOf( "avklaringId" to avklaring.id.toString(), "kode" to kode, "behandlingId" to behandlingId.toString(), "ident" to ident, ), ).toJson(), ) withLoggingContext( "avklaringId" to avklaring.id.toString(), "behandlingId" to behandlingId.toString(), ) { logger.info { "Publisert AvklaringIkkeRelevant for avklaring $kode" } } } }
1
Kotlin
0
0
f2cd3232ce5a21d75eea4c43b757d6f34ebaf020
2,480
dp-manuell-behandling
MIT License
project/core-bukkit/src/main/kotlin/io/github/itsflicker/sync/bukkit/core/PlayerDataHandler.kt
MeowRealms
680,412,955
false
null
package io.github.itsflicker.sync.bukkit.core import io.github.itsflicker.sync.common.data.PlayerData import org.bukkit.entity.Player import taboolib.common.platform.Platform import taboolib.common.platform.PlatformSide import taboolib.module.configuration.ConfigNode import java.util.* import java.util.concurrent.ConcurrentHashMap @PlatformSide([Platform.BUKKIT]) object PlayerDataHandler { @ConfigNode("sync", "config_bukkit.yml") var syncConf = emptyMap<String, Boolean>() private set val currentPlayerData = ConcurrentHashMap<UUID, PlayerData>() fun generatePlayerData(player: Player): PlayerData { val data = PlayerData(player.uniqueId, player.name) return data } fun applyPlayerData(player: Player, data: PlayerData) { } }
1
Kotlin
0
0
a0a9e1d2053590eec95bec51951b718f9e778918
789
ItsSync
Creative Commons Zero v1.0 Universal
project/core-bukkit/src/main/kotlin/io/github/itsflicker/sync/bukkit/core/PlayerDataHandler.kt
MeowRealms
680,412,955
false
null
package io.github.itsflicker.sync.bukkit.core import io.github.itsflicker.sync.common.data.PlayerData import org.bukkit.entity.Player import taboolib.common.platform.Platform import taboolib.common.platform.PlatformSide import taboolib.module.configuration.ConfigNode import java.util.* import java.util.concurrent.ConcurrentHashMap @PlatformSide([Platform.BUKKIT]) object PlayerDataHandler { @ConfigNode("sync", "config_bukkit.yml") var syncConf = emptyMap<String, Boolean>() private set val currentPlayerData = ConcurrentHashMap<UUID, PlayerData>() fun generatePlayerData(player: Player): PlayerData { val data = PlayerData(player.uniqueId, player.name) return data } fun applyPlayerData(player: Player, data: PlayerData) { } }
1
Kotlin
0
0
a0a9e1d2053590eec95bec51951b718f9e778918
789
ItsSync
Creative Commons Zero v1.0 Universal
app/src/main/java/fr/chatavion/client/db/entity/Community.kt
Minibuz
596,173,565
false
null
package fr.chatavion.client.db.entity import androidx.room.Entity import androidx.room.Index import androidx.room.PrimaryKey @Entity( tableName = "community", indices = [ Index(value = ["name", "address"], unique = true) ] ) data class Community( val name: String, val address: String, var pseudo: String, var idLastMessage: Int, @PrimaryKey(autoGenerate = true) val communityId: Int = 0 )
0
Kotlin
1
1
dbac7c48ee5ce52f01c0327809bc82bf1c2faac2
437
ChatAvion-Client
MIT License
app/src/main/java/com/polar/androidblesdk/HeartRateActivity.kt
LetMarq
801,298,442
false
{"Kotlin": 29140}
package com.polar.androidblesdk import android.Manifest import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.os.Build import android.os.Bundle import android.util.Log import android.view.View import android.widget.Button import android.widget.TextView import android.widget.Toast import androidx.annotation.StringRes import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.core.graphics.drawable.DrawableCompat import androidx.core.util.Pair import com.google.android.material.snackbar.Snackbar import com.polar.sdk.api.PolarBleApi import com.polar.sdk.api.PolarBleApiCallback import com.polar.sdk.api.PolarBleApiDefaultImpl import com.polar.sdk.api.PolarH10OfflineExerciseApi import com.polar.sdk.api.errors.PolarInvalidArgument import com.polar.sdk.api.model.* import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.core.Flowable import io.reactivex.rxjava3.core.Single import io.reactivex.rxjava3.disposables.Disposable import java.util.* import android.media.AudioManager import android.media.ToneGenerator import android.widget.ImageButton class HeartRateActivity : AppCompatActivity() { companion object { private const val TAG = "MainActivity" private const val API_LOGGER_TAG = "API LOGGER" private const val PERMISSION_REQUEST_CODE = 1 } // ATTENTION! Replace with the device ID from your device. private var deviceId = "C3E38426" private var toneGenerator: ToneGenerator? = null private var metronomeTimer: Timer? = null private val api: PolarBleApi by lazy { // Notice all features are enabled PolarBleApiDefaultImpl.defaultImplementation( applicationContext, setOf( PolarBleApi.PolarBleSdkFeature.FEATURE_HR, PolarBleApi.PolarBleSdkFeature.FEATURE_POLAR_SDK_MODE, PolarBleApi.PolarBleSdkFeature.FEATURE_BATTERY_INFO, PolarBleApi.PolarBleSdkFeature.FEATURE_POLAR_H10_EXERCISE_RECORDING, PolarBleApi.PolarBleSdkFeature.FEATURE_POLAR_OFFLINE_RECORDING, PolarBleApi.PolarBleSdkFeature.FEATURE_POLAR_ONLINE_STREAMING, PolarBleApi.PolarBleSdkFeature.FEATURE_POLAR_DEVICE_TIME_SETUP, PolarBleApi.PolarBleSdkFeature.FEATURE_DEVICE_INFO, PolarBleApi.PolarBleSdkFeature.FEATURE_POLAR_LED_ANIMATION ) ) } private var scanDisposable: Disposable? = null private var autoConnectDisposable: Disposable? = null private var hrDisposable: Disposable? = null private var ecgDisposable: Disposable? = null private var accDisposable: Disposable? = null private var gyrDisposable: Disposable? = null private var magDisposable: Disposable? = null private var ppgDisposable: Disposable? = null private var isMetronomeActive = false private var deviceConnected = false private var bluetoothEnabled = false private lateinit var broadcastButton: ImageButton private lateinit var startButton: ImageButton private lateinit var switchToConfigActivity: ImageButton private lateinit var hrDisplayTextView: TextView private lateinit var maxHrEditText: TextView private lateinit var minHrEditText: TextView private lateinit var startButtonText: TextView private var currentInterval: Long? = null //Verity Sense offline recording use private val entryCache: MutableMap<String, MutableList<PolarOfflineRecordingEntry>> = mutableMapOf() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_heart_rate) Log.d(TAG, "version: " + PolarBleApiDefaultImpl.versionInfo()) broadcastButton = findViewById(R.id.broadcast_button) startButton = findViewById(R.id.start_button) hrDisplayTextView = findViewById(R.id.hr_display) maxHrEditText = findViewById(R.id.edit_text_max_hr) minHrEditText = findViewById(R.id.edit_text_min_hr) // Recuperando o valor do deviceId das preferências compartilhadas val sharedPref = getSharedPreferences("AppPreferences", Context.MODE_PRIVATE) deviceId = sharedPref.getString("deviceId", deviceId) ?: deviceId // Registrando uma mensagem de log para verificar o valor recuperado showToast("Device ID: $deviceId") startButtonText = findViewById(R.id.text_stop_begin_button) // Initialize your TextView setupStartButton() // frequencyDisplayText = findViewById(R.id.frequency_display_text) // timeDisplayText = findViewById(R.id.time_display_text) toneGenerator = ToneGenerator(AudioManager.STREAM_ALARM, 100) // Adjust the volume level (100 is maximum) switchToConfigActivity = findViewById(R.id.configButton) switchToConfigActivity.setOnClickListener { startActivity(Intent(this@HeartRateActivity, ConfigurationActivity::class.java)) } api.setPolarFilter(false) // If there is need to log what is happening inside the SDK, it can be enabled like this: val enableSdkLogs = false if(enableSdkLogs) { api.setApiLogger { s: String -> Log.d(API_LOGGER_TAG, s) } } api.setApiCallback(object : PolarBleApiCallback() { override fun blePowerStateChanged(powered: Boolean) { Log.d(TAG, "BLE power: $powered") bluetoothEnabled = powered if (powered) { enableAllButtons() showToast("Phone Bluetooth on") } else { disableAllButtons() showToast("Phone Bluetooth off") } } override fun deviceConnected(polarDeviceInfo: PolarDeviceInfo) { Log.d(TAG, "CONNECTED: ${polarDeviceInfo.deviceId}") deviceId = polarDeviceInfo.deviceId deviceConnected = true val buttonText = getString(R.string.disconnect_from_device, deviceId) // toggleButtonDown(connectButton, buttonText) } override fun deviceConnecting(polarDeviceInfo: PolarDeviceInfo) { Log.d(TAG, "CONNECTING: ${polarDeviceInfo.deviceId}") } override fun deviceDisconnected(polarDeviceInfo: PolarDeviceInfo) { Log.d(TAG, "DISCONNECTED: ${polarDeviceInfo.deviceId}") deviceConnected = false val buttonText = getString(R.string.connect_to_device, deviceId) // toggleButtonUp(connectButton, buttonText) // toggleButtonUp(toggleSdkModeButton, R.string.enable_sdk_mode) } private var toneTimer: Timer? = null override fun hrNotificationReceived(identifier: String, data: PolarHrData.PolarHrSample) { val hr = data.hr runOnUiThread { hrDisplayTextView.text = "Frequência cardíaca: $hr" } if (!isMetronomeActive) return val maxHr = maxHrEditText.text.toString().toIntOrNull() val minHr = minHrEditText.text.toString().toIntOrNull() if (maxHr != null && minHr != null) { val targetHr = when { hr > maxHr -> minHr hr < minHr -> maxHr else -> hr } val interval = 60000L / targetHr if (hr !in minHr..maxHr) { startMetronome(interval) } else { stopMetronome() } } else { Log.e(TAG, "Invalid max or min heart rate value") } } override fun disInformationReceived(identifier: String, uuid: UUID, value: String) { Log.d(TAG, "DIS INFO uuid: $uuid value: $value") } override fun batteryLevelReceived(identifier: String, level: Int) { Log.d(TAG, "BATTERY LEVEL: $level") } }) broadcastButton.setOnClickListener { connectToDevice { isConnected -> if (isConnected) { autoConnectToDevice { isAutoConnected -> if (isAutoConnected) { scanForDevices { isScanComplete -> if (isScanComplete) { startHrStreaming() } } } } } } } startButton.setOnClickListener { isMetronomeActive = !isMetronomeActive if (isMetronomeActive) { startButtonText.text = "Parar" // Change text to 'Stop' showToast("Metronome monitoring activated.") } else { stopMetronome() startButtonText.text = "Iniciar" // Change text back to 'Start' showToast("Metronome monitoring deactivated.") } } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { requestPermissions(arrayOf(Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_CONNECT), PERMISSION_REQUEST_CODE) } else { requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), PERMISSION_REQUEST_CODE) } } else { requestPermissions(arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION), PERMISSION_REQUEST_CODE) } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == PERMISSION_REQUEST_CODE) { for (index in 0..grantResults.lastIndex) { if (grantResults[index] == PackageManager.PERMISSION_DENIED) { disableAllButtons() Log.w(TAG, "No sufficient permissions") showToast("No sufficient permissions") return } } Log.d(TAG, "Needed permissions are granted") enableAllButtons() } } private fun startMetronome(interval: Long) { // Only start or adjust the metronome if the interval has changed if (currentInterval != interval) { stopMetronome() // Stop existing timer if running currentInterval = interval metronomeTimer = Timer().apply { scheduleAtFixedRate(object : TimerTask() { override fun run() { toneGenerator?.startTone(ToneGenerator.TONE_CDMA_ALERT_CALL_GUARD, 100) // Short beep } }, 0, interval) } } } private fun stopMetronome() { if (currentInterval != null) { metronomeTimer?.cancel() metronomeTimer = null currentInterval = null } } public override fun onPause() { super.onPause() } public override fun onResume() { super.onResume() api.foregroundEntered() } public override fun onDestroy() { super.onDestroy() api.shutDown() toneGenerator?.release() } private fun toggleButtonDown(button: Button, text: String? = null) { toggleButton(button, true, text) } private fun toggleButtonDown(button: Button, @StringRes resourceId: Int) { toggleButton(button, true, getString(resourceId)) } private fun toggleButtonUp(button: Button, text: String? = null) { toggleButton(button, false, text) } private fun toggleButtonUp(button: Button, @StringRes resourceId: Int) { toggleButton(button, false, getString(resourceId)) } private fun toggleButton(button: Button, isDown: Boolean, text: String? = null) { if (text != null) button.text = text var buttonDrawable = button.background buttonDrawable = DrawableCompat.wrap(buttonDrawable!!) if (isDown) { DrawableCompat.setTint(buttonDrawable, resources.getColor(R.color.primaryDarkColor)) } else { DrawableCompat.setTint(buttonDrawable, resources.getColor(R.color.primaryColor)) } button.background = buttonDrawable } private fun showToast(message: String) { val toast = Toast.makeText(applicationContext, message, Toast.LENGTH_LONG) toast.show() } private fun showDialog(title: String, message: String) { AlertDialog.Builder(this) .setTitle(title) .setMessage(message) .setPositiveButton("OK") { _, _ -> // Respond to positive button press } .show() } private fun disableAllButtons() { broadcastButton.isEnabled = false } private fun enableAllButtons() { broadcastButton.isEnabled = true } private fun disposeAllStreams() { ecgDisposable?.dispose() accDisposable?.dispose() gyrDisposable?.dispose() magDisposable?.dispose() ppgDisposable?.dispose() ppgDisposable?.dispose() } private fun connectToDevice(completion: (Boolean) -> Unit) { if (!deviceConnected) { try { api.connectToDevice(deviceId) completion(true) // Simulate a successful connection } catch (e: PolarInvalidArgument) { Log.e(TAG, "Failed to connect. Reason: ${e.message}") completion(false) } } else { Log.d(TAG, "Device already connected.") completion(true) } } private fun autoConnectToDevice(completion: (Boolean) -> Unit) { if (autoConnectDisposable == null || autoConnectDisposable?.isDisposed == true) { autoConnectDisposable = api.autoConnectToDevice(-60, "180D", null) .subscribe( { Log.d(TAG, "Auto-connect search complete") completion(true) }, { throwable -> Log.e(TAG, "Auto-connect failed: ${throwable.message}") completion(false) } ) } else { Log.d(TAG, "Auto-connect already in progress.") completion(false) } } private fun scanForDevices(completion: (Boolean) -> Unit) { val isDisposed = scanDisposable?.isDisposed ?: true if (isDisposed) { scanDisposable = api.searchForDevice() .observeOn(AndroidSchedulers.mainThread()) .subscribe( { polarDeviceInfo: PolarDeviceInfo -> Log.d(TAG, "Polar device found: id=${polarDeviceInfo.deviceId}, address=${polarDeviceInfo.address}") completion(true) }, { error -> Log.e(TAG, "Device scan failed. Reason: ${error.message}") completion(false) }, { Log.d(TAG, "Device scan complete") completion(true) } ) } else { Log.d(TAG, "Scanning already in progress.") completion(false) } } private fun startHrStreaming() { val isDisposed = hrDisposable?.isDisposed ?: true if (isDisposed) { hrDisposable = api.startHrStreaming(deviceId) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { hrData: PolarHrData -> Log.d(TAG, "HR Data received: bpm=${hrData.samples.map { it.hr }}") }, { error -> Log.e(TAG, "HR streaming failed. Reason: ${error.message}") }, { Log.d(TAG, "HR streaming complete") } ) } else { Log.d(TAG, "HR streaming already in progress.") } } private fun setupStartButton() { startButton.setOnClickListener { isMetronomeActive = !isMetronomeActive if (isMetronomeActive) { startButtonText.text = "Parar" // Change text to 'Stop' showToast("Metronome monitoring activated.") } else { stopMetronome() startButtonText.text = "Iniciar" // Change text back to 'Start' showToast("Metronome monitoring deactivated.") } } } }
0
Kotlin
0
0
9f295e65a0e7a578f332517e8cc8fbc0ee0bc685
17,204
MoveApp
MIT License
core/ui/src/main/java/ru/aleshin/core/ui/views/CategoryMonogram.kt
v1tzor
638,022,252
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 ru.aleshin.core.ui.views import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box 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.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.text.intl.Locale import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.toUpperCase import androidx.compose.ui.unit.dp import ru.aleshin.core.ui.theme.material.badge @Composable fun CategoryIconMonogram( modifier: Modifier = Modifier, icon: Painter, iconDescription: String?, iconColor: Color, badgeEnabled: Boolean = false, backgroundColor: Color, ) = Box( modifier = modifier.size(40.dp), contentAlignment = Alignment.Center, ) { Box( modifier = Modifier.fillMaxSize().clip(RoundedCornerShape(40.dp)).background(backgroundColor), contentAlignment = Alignment.Center, ) { Icon( modifier = Modifier.size(24.dp), painter = icon, contentDescription = iconDescription, tint = iconColor, ) } if (badgeEnabled) { ImportanceBadge( modifier = Modifier.align(Alignment.TopEnd), color = badge, ) } } @Composable fun CategoryTextMonogram( modifier: Modifier = Modifier, text: String, textColor: Color, backgroundColor: Color, badgeEnabled: Boolean = false, ) = Box( modifier = modifier.size(40.dp), contentAlignment = Alignment.Center, ) { Box( modifier = Modifier.fillMaxSize().clip(RoundedCornerShape(40.dp)).background(backgroundColor), contentAlignment = Alignment.Center, ) { Text( text = text.toUpperCase(Locale.current), modifier = Modifier.align(Alignment.Center), color = textColor, textAlign = TextAlign.Center, style = MaterialTheme.typography.titleMedium, ) } if (badgeEnabled) { ImportanceBadge( modifier = Modifier.align(Alignment.TopEnd), color = badge, ) } } @Composable fun ImportanceBadge( modifier: Modifier = Modifier, color: Color = badge, ) { Box( modifier = modifier .padding(vertical = 4.dp, horizontal = 2.dp) .size(7.dp) .clip(RoundedCornerShape(100.dp)) .background(color), ) }
3
null
4
99
0762559e4dabea2971df1573472216f554ab8577
3,470
TimePlanner
Apache License 2.0
app/src/main/java/org/xtras/daggerviewmodelfactory/viewmodel/TestViewModel.kt
victor5171
250,354,171
false
null
package org.xtras.daggerviewmodelfactory.viewmodel import androidx.lifecycle.ViewModel import javax.inject.Inject class TestViewModel @Inject constructor() : ViewModel()
0
Kotlin
1
1
20d47f8632a39429e01f3e8e68ac188f5209caa1
172
dagger-viewmodelfactory
MIT License
ktor-client/ktor-client-okhttp/jvm/src/io/ktor/client/engine/okhttp/OkHttpConfig.kt
RuiDTLima
190,507,625
true
{"Kotlin": 2537833, "Lua": 280, "HTML": 112}
/* * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.engine.okhttp import io.ktor.client.engine.* import okhttp3.* import java.util.concurrent.* /** * Configuration for [OkHttp] client engine. */ class OkHttpConfig : HttpClientEngineConfig() { internal var config: OkHttpClient.Builder.() -> Unit = {} /** * Preconfigured [OkHttpClient] instance instead of configuring one. */ var preconfigured: OkHttpClient? = null /** * Configure [OkHttpClient] using [OkHttpClient.Builder]. */ fun config(block: OkHttpClient.Builder.() -> Unit) { val oldConfig = config config = { oldConfig() block() } } /** * Add [Interceptor] to [OkHttp] client. */ fun addInterceptor(interceptor: Interceptor) { config { addInterceptor(interceptor) } } /** * Add network [Interceptor] to [OkHttp] client. */ fun addNetworkInterceptor(interceptor: Interceptor) { config { addNetworkInterceptor(interceptor) } } }
0
Kotlin
0
1
e0525a274d2c9958778fb649df39d59c44341b2b
1,186
ktor
Apache License 2.0
compiler/tests/org/jetbrains/kotlin/jvm/compiler/AbstractWriteSignatureTest.kt
staltz
421,687,586
true
{"Markdown": 34, "XML": 687, "Ant Build System": 40, "Ignore List": 8, "Git Attributes": 1, "Kotlin": 18510, "Java": 4307, "Protocol Buffer": 4, "Text": 4085, "JavaScript": 63, "JAR Manifest": 3, "Roff": 30, "Roff Manpage": 10, "INI": 7, "HTML": 135, "Groovy": 20, "Maven POM": 50, "Gradle": 71, "Java Properties": 10, "CSS": 3, "Proguard": 1, "JFlex": 2, "Shell": 9, "Batchfile": 8, "ANTLR": 1}
/* * Copyright 2010-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.jvm.compiler import com.google.common.io.Closeables import com.google.common.io.Files import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.io.FileUtil import org.jetbrains.kotlin.cli.common.output.outputUtils.writeAllTo import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment import org.jetbrains.kotlin.codegen.GenerationUtils import org.jetbrains.kotlin.cli.jvm.compiler.JvmPackagePartProvider import org.jetbrains.kotlin.test.JetTestUtils import org.jetbrains.kotlin.test.TestCaseWithTmpdir import org.jetbrains.kotlin.utils.join import org.jetbrains.org.objectweb.asm.* import org.junit.Assert import java.io.File import java.io.FileInputStream import java.nio.charset.Charset import java.util.* import java.util.regex.MatchResult import java.util.regex.Pattern import kotlin.text.Regex public abstract class AbstractWriteSignatureTest : TestCaseWithTmpdir() { private var jetCoreEnvironment: KotlinCoreEnvironment? = null override fun setUp() { super.setUp() jetCoreEnvironment = JetTestUtils.createEnvironmentWithMockJdkAndIdeaAnnotations(myTestRootDisposable) } override fun tearDown() { jetCoreEnvironment = null super.tearDown() } protected fun doTest(ktFileName: String) { val ktFile = File(ktFileName) val text = FileUtil.loadFile(ktFile, true) val psiFile = JetTestUtils.createFile(ktFile.getName(), text, jetCoreEnvironment!!.project) val outputFiles = GenerationUtils.compileFileGetClassFileFactoryForTest(psiFile, jetCoreEnvironment!!) outputFiles.writeAllTo(tmpdir) Disposer.dispose(myTestRootDisposable) val expectations = parseExpectations(ktFile) expectations.check() } private class SignatureExpectation(val header: String, val name: String, expectedJvmSignature: String, expectedGenericSignature: String) { private var checked = false private val expectedSignature = formatSignature(header, expectedJvmSignature, expectedGenericSignature) fun isChecked(): Boolean = checked fun check(name: String, actualJvmSignature: String, actualGenericSignature: String) { if (this.name == name) { checked = true val actualSignature = formatSignature(header, actualJvmSignature, actualGenericSignature) Assert.assertEquals(expectedSignature, actualSignature) } } } private inner class PackageExpectationsSuite() { private val classSuitesByClassName = LinkedHashMap<String, ClassExpectationsSuite>() fun getOrCreateClassSuite(className: String): ClassExpectationsSuite = classSuitesByClassName.getOrPut(className) { ClassExpectationsSuite(className) } fun check() { classSuitesByClassName.values().forEach { it.check() } } } private inner class ClassExpectationsSuite(val className: String) { val classExpectations = ArrayList<SignatureExpectation>() val methodExpectations = ArrayList<SignatureExpectation>() val fieldExpectations = ArrayList<SignatureExpectation>() fun check() { val checker = Checker() val classFileName = "$tmpdir/${className.replace('.', '/')}.class" val classFile = File(classFileName) checkClassFile(checker, classFile) if (className.endsWith("Package")) { // This class is a package facade. We should also check package parts. checkPackageParts(checker, classFile) } assertAllChecked() } private fun checkPackageParts(checker: Checker, classFile: File) { // Look for package parts in the same directory. // Package part file names for package SomePackage look like SomePackage$<hash>.class. val classDir = classFile.getParentFile() val classLastName = classFile.getName() val packageFacadePrefix = classLastName.replace(".class", "\$") classDir.listFiles { dir, lastName -> lastName.startsWith(packageFacadePrefix) && lastName.endsWith(".class") } forEach { packageFacadeFile -> checkClassFile(checker, packageFacadeFile) } } private fun assertAllChecked() { val uncheckedExpectations = ArrayList<SignatureExpectation>() classExpectations.filterNotTo(uncheckedExpectations) { it.isChecked() } methodExpectations.filterNotTo(uncheckedExpectations) { it.isChecked() } fieldExpectations.filterNotTo(uncheckedExpectations) { it.isChecked() } Assert.assertTrue( "Unchecked expectations (${uncheckedExpectations.size()} total):\n " + uncheckedExpectations.join("\n "), uncheckedExpectations.isEmpty()) } private fun checkClassFile(checker: Checker, classFile: File) { val classInputStream = FileInputStream(classFile) try { ClassReader(classInputStream).accept(checker, ClassReader.SKIP_CODE or ClassReader.SKIP_DEBUG or ClassReader.SKIP_FRAMES) } finally { Closeables.closeQuietly(classInputStream) } } private inner class Checker : ClassVisitor(Opcodes.ASM5) { override fun visit(version: Int, access: Int, name: String, signature: String?, superName: String?, interfaces: Array<out String>?) { classExpectations forEach { it.check(name, name, signature?:"null") } super.visit(version, access, name, signature, superName, interfaces) } override fun visitMethod(access: Int, name: String, desc: String, signature: String?, exceptions: Array<out String>?): MethodVisitor? { methodExpectations forEach { it.check(name, desc, signature?:"null") } return super.visitMethod(access, name, desc, signature, exceptions) } override fun visitField(access: Int, name: String, desc: String, signature: String?, value: Any?): FieldVisitor? { fieldExpectations forEach { it.check(name, desc, signature?:"null") } return super.visitField(access, name, desc, signature, value) } } fun addClassExpectation(name: String, jvmSignature: String, genericSignature: String) { classExpectations.add(SignatureExpectation("class: $name", name, jvmSignature, genericSignature)) } fun addFieldExpectation(className: String, memberName: String, jvmSignature: String, genericSignature: String) { fieldExpectations.add(SignatureExpectation("field: $className::$memberName", memberName, jvmSignature, genericSignature)) } fun addMethodExpectation(className: String, memberName: String, jvmSignature: String, genericSignature: String) { methodExpectations.add(SignatureExpectation("method: $className::$memberName", memberName, jvmSignature, genericSignature)) } } fun parseExpectations(ktFile: File): PackageExpectationsSuite { val expectations = PackageExpectationsSuite() val lines = Files.readLines(ktFile, Charset.forName("utf-8")) var lineNo = 0 while (lineNo < lines.size()) { val line = lines[lineNo] val expectationMatch = expectationRegex.matchExact(line) if (expectationMatch != null) { val kind = expectationMatch.group(1)!! val className = expectationMatch.group(2)!! val memberName = expectationMatch.group(4) if (kind == "class" && memberName != null) { throw AssertionError("$ktFile:${lineNo+1}: use $className\$$memberName to denote inner class") } else if (memberName == null) { throw AssertionError("$ktFile:${lineNo+1}: '$kind' requires member name (after $className::)") } val jvmSignatureMatch = jvmSignatureRegex.matchExact(lines[lineNo+1]) val genericSignatureMatch = genericSignatureRegex.matchExact(lines[lineNo+2]) if (jvmSignatureMatch != null && genericSignatureMatch != null) { val jvmSignature = jvmSignatureMatch.group(1) val genericSignature = genericSignatureMatch.group(1) val classSuite = expectations.getOrCreateClassSuite(className) when (kind) { "class" -> classSuite.addClassExpectation(className, jvmSignature, genericSignature) "field" -> classSuite.addFieldExpectation(className, memberName, jvmSignature, genericSignature) "method" -> classSuite.addMethodExpectation(className, memberName, jvmSignature, genericSignature) else -> throw AssertionError("$ktFile:${lineNo+1}: unsupported expectation kind: $kind") } // Expectation, skip the following 'jvm signature' and 'generic signature' lines lineNo += 3 } else { throw AssertionError("$ktFile:${lineNo+1}: '$kind' should be followed by 'jvm signature' and 'generic signature'") } } else { ++lineNo } } return expectations } companion object { fun formatSignature(header: String, jvmSignature: String, genericSignature: String): String = """// $header // jvm signature: $jvmSignature // generic signature: $genericSignature""" val expectationRegex = Regex("^// (class|method|field): *([^:]+)(::(.+)) *(//.*)?") val jvmSignatureRegex = Regex("^// jvm signature: *(.+) *(//.*)?") val genericSignatureRegex = Regex("^// generic signature: *(.+) *(//.*)?") fun Regex.matchExact(input: String): MatchResult? { val matcher = this.toPattern().matcher(input) if (matcher.matches()) { return matcher.toMatchResult() } else { return null } } } }
1
Java
0
1
ff00bde607d605c4eba2d98fbc9e99af932accb6
11,015
kotlin
Apache License 2.0
library/renetik-android-ui/src/main/java/renetik/android/ui/extensions/view/View+Visibility.kt
rene-dohan
69,289,476
false
null
package renetik.android.ui.extensions.view import android.view.View import android.view.View.* import androidx.appcompat.widget.ContentFrameLayout import renetik.android.event.registration.CSMultiRegistration import renetik.android.event.registration.CSRegistration import renetik.android.ui.protocol.CSVisibility import renetik.android.event.property.CSProperty import renetik.android.core.kotlin.primitives.isTrue fun <T : View> T.visible(animated: Boolean = false) = apply { if (animated) fadeIn() else { visibility = VISIBLE updateVisibility() } } fun <T : View> T.invisible(animated: Boolean = false) = apply { if (animated) fadeOut(invisible = true) else { visibility = INVISIBLE updateVisibility() } } fun <T : View> T.updateVisibility() { (tag as? CSVisibility)?.updateVisibility() } fun <T : View> T.gone(animated: Boolean = false) = apply { if (animated) fadeOut() else { visibility = GONE updateVisibility() } } val <T : View> T.isVisible get() = visibility == VISIBLE val <T : View> T.isInvisible get() = visibility == INVISIBLE val <T : View> T.isGone get() = visibility == GONE fun <T : View> T.show(animated: Boolean = false) = apply { visible(animated) } fun <T : View> T.hide(animated: Boolean = false) = apply { gone(animated) } fun <T : View> T.visibleIf(condition: Boolean, animated: Boolean = false) = apply { if (condition) visible(animated) else invisible(animated) } fun <T : View> T.invisibleIf(condition: Boolean, animated: Boolean = false) = visibleIf(!condition, animated) fun <T : View> T.shownIf(condition: Boolean, animated: Boolean = false) = apply { if (condition) show(animated) else gone(animated) } fun <T : View> T.goneIf(condition: Boolean, animated: Boolean = false) = shownIf(!condition, animated) fun <T> View.shownIf(property: CSProperty<T>, animated: Boolean = false, condition: (T) -> Boolean): CSRegistration { shownIf(condition(property.value)) return property.onChange { shownIf(condition(property.value), animated) } } fun View.shownIf(property: CSProperty<Boolean>, animated: Boolean = false) = shownIf(property, animated) { it } fun View.shownIfNot(property: CSProperty<Boolean>, animated: Boolean = false) = shownIf(property, animated) { !it } fun <T> View.shownIf(property1: CSProperty<T>, property2: CSProperty<*>, animated: Boolean = false, condition: (T) -> Boolean) = shownIf(property1, property2, animated) { first, _ -> condition(first) } fun <T, V> View.shownIf(property1: CSProperty<T>, property2: CSProperty<V>, animated: Boolean = false, condition: (T, V) -> Boolean): CSRegistration { fun update(animated: Boolean) = shownIf(condition(property1.value, property2.value), animated) update(animated = false) return CSMultiRegistration( property1.onChange { update(animated) }, property2.onChange { update(animated) }) } fun <T, V, X> View.shownIf(property1: CSProperty<T>, property2: CSProperty<V>, property3: CSProperty<X>, animated: Boolean = false, condition: (T, V, X) -> Boolean): CSRegistration { fun update(animated: Boolean) = shownIf(condition(property1.value, property2.value, property3.value), animated) update(animated = false) return CSMultiRegistration( property1.onChange { update(animated) }, property2.onChange { update(animated) }, property3.onChange { update(animated) }, ) } fun View.goneIf(property1: CSProperty<Boolean>, property2: CSProperty<Boolean>, animated: Boolean = false): CSRegistration { return goneIf(property1, property2, animated) { value1, value2 -> value1.isTrue || value2.isTrue } } fun <T, V> View.goneIf(property1: CSProperty<T>, property2: CSProperty<V>, animated: Boolean = false, condition: (T, V) -> Boolean): CSRegistration { fun update() = goneIf(condition(property1.value, property2.value), animated) update() return CSMultiRegistration( property1.onChange { update() }, property2.onChange { update() }) } fun <T> View.goneIf(property: CSProperty<T>, animated: Boolean = false, condition: (T) -> Boolean): CSRegistration { goneIf(condition(property.value)) return property.onChange { goneIf(condition(property.value), animated) } } fun View.goneIf(property: CSProperty<Boolean>, animated: Boolean = false) = goneIf(property, animated) { it } fun <T> View.visibleIf(property1: CSProperty<T>, property2: CSProperty<*>, animated: Boolean = false, condition: (T) -> Boolean) = visibleIf(property1, property2, animated) { first, _ -> condition(first) } fun <T, V> View.visibleIf(property1: CSProperty<T>, property2: CSProperty<V>, animated: Boolean = false, condition: (T, V) -> Boolean): CSRegistration { fun update() = visibleIf(condition(property1.value, property2.value), animated) update() return CSMultiRegistration( property1.onChange { update() }, property2.onChange { update() }) } fun <T> View.visibleIf(property: CSProperty<T>, animated: Boolean = false, condition: (T) -> Boolean): CSRegistration { visibleIf(condition(property.value)) return property.onChange { visibleIf(condition(property.value), animated) } } fun View.visibleIf(property: CSProperty<Boolean>, animated: Boolean = false) = visibleIf(property, animated) { it } fun View.visibleIfNot(property: CSProperty<Boolean>, animated: Boolean = false) = visibleIf(property, animated) { !it } fun <T> View.invisibleIf(property: CSProperty<T>, animated: Boolean = false, condition: (T) -> Boolean): CSRegistration { invisibleIf(condition(property.value)) return property.onChange { invisibleIf(condition(property.value), animated) } } fun View.invisibleIf(property: CSProperty<Boolean>, animated: Boolean = false) = invisibleIf(property, animated) { it } // This had be done because isShown return false in on Resume // for main activity view when created // because it has not yet attached its DecorView.class to window // DecorView is internal class so we cant identify it by class just className DecorView // Other solution is to identify ContentFrameLayout instead as top view // Previous simple "solution": view.parent?.parent?.parent?.parent != null fun View.isShowing(): Boolean { if (!isVisible) return false var view: View = this while (true) { val parent = view.parent when { parent == null -> return false parent !is View -> return true parent is ContentFrameLayout -> return true // parent.className == "DecorView" -> return true !parent.isVisible -> return false else -> view = parent } } }
0
Kotlin
3
2
e5bb388e7f2b0fb87585994283334dcce0371637
7,252
renetik-library-android
MIT License
model/src/main/java/com/freshdigitable/udonroad2/model/MediaEntity.kt
akihito104
149,869,805
false
{"YAML": 4, "Gradle Kotlin DSL": 7, "JSON": 1, "Kotlin": 263, "Java Properties": 10, "Shell": 1, "Text": 1, "Ignore List": 17, "Batchfile": 1, "EditorConfig": 1, "Gradle": 12, "Proguard": 17, "XML": 147, "Java": 3, "INI": 7, "PlantUML": 3}
/* * Copyright (c) 2019. Matsuda, Akihit (akihito104) * * 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.freshdigitable.udonroad2.model interface TweetMediaItem : UrlItem { val id: MediaId val mediaUrl: String val type: MediaType val order: Int override val displayUrl: String get() = "" override val expandedUrl: String get() = "" } val TweetMediaItem.thumbMediaUrl: String get() = "$mediaUrl:thumb" interface MediaEntity : UrlItem, TweetMediaItem { val largeSize: Size? val mediumSize: Size? val smallSize: Size? val thumbSize: Size? val videoAspectRatioWidth: Int? val videoAspectRatioHeight: Int? val videoDurationMillis: Long? val videoValiantItems: List<VideoValiant> interface Size { val width: Int val height: Int val resizeType: Int } interface VideoValiant { val bitrate: Int val contentType: String val url: String } } enum class MediaType(val value: String) { PHOTO("photo"), VIDEO("video"), ANIMATED_GIF("animated_gif"); companion object { fun find(value: String): MediaType = values().first { it.value == value } } }
22
null
1
1
7ec50f204fda79cf222b24623f22e80d05301555
1,747
UdonRoad2
Apache License 2.0
app/src/main/java/com/example/medellinplaces/ui/view/SplashScreenActivity.kt
sachih1ro
428,084,945
false
{"Kotlin": 18767}
package com.example.medellinplaces.ui.view import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Handler import android.os.Looper import com.example.medellinplaces.databinding.ActivityPlacesMainBinding import com.example.medellinplaces.databinding.ActivitySplashScreenBinding class SplashScreenActivity : AppCompatActivity() { private lateinit var binding: ActivitySplashScreenBinding //Handler and runnable definition private lateinit var handler : Handler private lateinit var runnable: Runnable override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivitySplashScreenBinding.inflate(layoutInflater) setContentView(binding.root) //Splash Screen Runnable init runnable = Runnable { val intent = android.content.Intent( this, com.example.medellinplaces.ui.view.PlacesMainActivity::class.java ) startActivity(intent) finish() //Destroy actual activity - (Splash Screen) } handler = Handler(Looper.getMainLooper()) handler.postDelayed(runnable,800) } //Data leak prevention override fun onDestroy() { //handler.removeCallbacksAndMessages(null) handler.removeCallbacks(runnable) super.onDestroy() } }
0
Kotlin
0
0
b201f088e0f2f1b112c1f67969ff064c836c8cd1
1,393
MedellinPlacesApp-4MisionTIC2022
MIT License
camera/camera-camera2-pipe-integration/src/main/java/androidx/camera/camera2/pipe/integration/adapter/CameraControlAdapter.kt
androidx
256,589,781
false
null
/* * Copyright 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 androidx.camera.camera2.pipe.integration.adapter import android.annotation.SuppressLint import android.graphics.Rect import android.hardware.camera2.CameraCharacteristics import androidx.arch.core.util.Function import androidx.camera.camera2.pipe.CameraPipe import androidx.camera.camera2.pipe.core.Log.warn import androidx.camera.camera2.pipe.integration.config.CameraScope import androidx.camera.camera2.pipe.integration.impl.CameraProperties import androidx.camera.camera2.pipe.integration.impl.EvCompControl import androidx.camera.camera2.pipe.integration.impl.FlashControl import androidx.camera.camera2.pipe.integration.impl.FocusMeteringControl import androidx.camera.camera2.pipe.integration.impl.StillCaptureRequestControl import androidx.camera.camera2.pipe.integration.impl.TorchControl import androidx.camera.camera2.pipe.integration.impl.UseCaseCamera import androidx.camera.camera2.pipe.integration.impl.ZoomControl import androidx.camera.camera2.pipe.integration.interop.Camera2CameraControl import androidx.camera.camera2.pipe.integration.interop.CaptureRequestOptions import androidx.camera.camera2.pipe.integration.interop.ExperimentalCamera2Interop import androidx.camera.core.FocusMeteringAction import androidx.camera.core.FocusMeteringResult import androidx.camera.core.ImageCapture import androidx.camera.core.ImageCapture.FLASH_MODE_AUTO import androidx.camera.core.ImageCapture.FLASH_MODE_ON import androidx.camera.core.impl.CameraControlInternal import androidx.camera.core.impl.CaptureConfig import androidx.camera.core.impl.Config import androidx.camera.core.impl.SessionConfig import androidx.camera.core.impl.utils.executor.CameraXExecutors import androidx.camera.core.impl.utils.futures.FutureChain import androidx.camera.core.impl.utils.futures.Futures import com.google.common.util.concurrent.ListenableFuture import javax.inject.Inject import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.ExperimentalCoroutinesApi /** * Adapt the [CameraControlInternal] interface to [CameraPipe]. * * This controller class maintains state as use-cases are attached / detached from the camera as * well as providing access to other utility methods. The primary purpose of this class it to * forward these interactions to the currently configured [UseCaseCamera]. */ @SuppressLint("UnsafeOptInUsageError") @CameraScope @OptIn(ExperimentalCoroutinesApi::class, ExperimentalCamera2Interop::class) public class CameraControlAdapter @Inject constructor( private val cameraProperties: CameraProperties, private val evCompControl: EvCompControl, private val flashControl: FlashControl, private val focusMeteringControl: FocusMeteringControl, private val stillCaptureRequestControl: StillCaptureRequestControl, private val torchControl: TorchControl, private val zoomControl: ZoomControl, private val zslControl: ZslControl, public val camera2cameraControl: Camera2CameraControl, ) : CameraControlInternal { override fun getSensorRect(): Rect { return cameraProperties.metadata[CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE]!! } override fun addInteropConfig(config: Config) { camera2cameraControl.addCaptureRequestOptions( CaptureRequestOptions.Builder.from(config).build() ) } override fun clearInteropConfig() { camera2cameraControl.clearCaptureRequestOptions() } override fun getInteropConfig(): Config { return camera2cameraControl.getCaptureRequestOptions() } override fun enableTorch(torch: Boolean): ListenableFuture<Void> = Futures.nonCancellationPropagating( FutureChain.from(torchControl.setTorchAsync(torch).asListenableFuture()) .transform( Function { return@Function null }, CameraXExecutors.directExecutor() ) ) override fun startFocusAndMetering( action: FocusMeteringAction ): ListenableFuture<FocusMeteringResult> = Futures.nonCancellationPropagating(focusMeteringControl.startFocusAndMetering(action)) override fun cancelFocusAndMetering(): ListenableFuture<Void> { return Futures.nonCancellationPropagating( CompletableDeferred<Void?>() .also { // Convert to null once the task is done, ignore the results. focusMeteringControl.cancelFocusAndMeteringAsync().propagateTo(it) { null } } .asListenableFuture() ) } override fun setZoomRatio(ratio: Float): ListenableFuture<Void> = zoomControl.setZoomRatio(ratio) override fun setLinearZoom(linearZoom: Float): ListenableFuture<Void> = zoomControl.setLinearZoom(linearZoom) override fun getFlashMode(): Int { return flashControl.flashMode } override fun setFlashMode(@ImageCapture.FlashMode flashMode: Int) { flashControl.setFlashAsync(flashMode) zslControl.setZslDisabledByFlashMode( flashMode == FLASH_MODE_ON || flashMode == FLASH_MODE_AUTO ) } override fun setScreenFlash(screenFlash: ImageCapture.ScreenFlash?) { flashControl.setScreenFlash(screenFlash) } override fun setExposureCompensationIndex(exposure: Int): ListenableFuture<Int> = Futures.nonCancellationPropagating(evCompControl.updateAsync(exposure).asListenableFuture()) override fun setZslDisabledByUserCaseConfig(disabled: Boolean) { zslControl.setZslDisabledByUserCaseConfig(disabled) } override fun isZslDisabledByByUserCaseConfig(): Boolean { return zslControl.isZslDisabledByUserCaseConfig() } override fun addZslConfig(sessionConfigBuilder: SessionConfig.Builder) { zslControl.addZslConfig(sessionConfigBuilder) } override fun submitStillCaptureRequests( captureConfigs: List<CaptureConfig>, @ImageCapture.CaptureMode captureMode: Int, @ImageCapture.FlashType flashType: Int, ): ListenableFuture<List<Void?>> = stillCaptureRequestControl.issueCaptureRequests(captureConfigs, captureMode, flashType) override fun getSessionConfig(): SessionConfig { warn { "TODO: getSessionConfig is not yet supported" } return SessionConfig.defaultEmptySessionConfig() } }
29
null
983
5,321
98b929d303f34d569e9fd8a529f022d398d1024b
7,018
androidx
Apache License 2.0
font-awesome/src/commonMain/kotlin/compose/icons/fontawesomeicons/solid/FunnelDollar.kt
DevSrSouza
311,134,756
false
{"Kotlin": 36719092}
package compose.icons.fontawesomeicons.solid import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Butt import androidx.compose.ui.graphics.StrokeJoin.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import compose.icons.fontawesomeicons.SolidGroup public val SolidGroup.FunnelDollar: ImageVector get() { if (_funnelDollar != null) { return _funnelDollar!! } _funnelDollar = Builder(name = "FunnelDollar", defaultWidth = 640.0.dp, defaultHeight = 512.0.dp, viewportWidth = 640.0f, viewportHeight = 512.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(433.46f, 165.94f) lineToRelative(101.2f, -111.87f) curveTo(554.61f, 34.12f, 540.48f, 0.0f, 512.26f, 0.0f) lineTo(31.74f, 0.0f) curveTo(3.52f, 0.0f, -10.61f, 34.12f, 9.34f, 54.07f) lineTo(192.0f, 256.0f) verticalLineToRelative(155.92f) curveToRelative(0.0f, 12.59f, 5.93f, 24.44f, 16.0f, 32.0f) lineToRelative(79.99f, 60.0f) curveToRelative(20.86f, 15.64f, 48.47f, 6.97f, 59.22f, -13.57f) curveTo(310.8f, 455.38f, 288.0f, 406.35f, 288.0f, 352.0f) curveToRelative(0.0f, -89.79f, 62.05f, -165.17f, 145.46f, -186.06f) close() moveTo(480.0f, 192.0f) curveToRelative(-88.37f, 0.0f, -160.0f, 71.63f, -160.0f, 160.0f) reflectiveCurveToRelative(71.63f, 160.0f, 160.0f, 160.0f) reflectiveCurveToRelative(160.0f, -71.63f, 160.0f, -160.0f) reflectiveCurveToRelative(-71.63f, -160.0f, -160.0f, -160.0f) close() moveTo(496.0f, 431.88f) lineTo(496.0f, 448.0f) curveToRelative(0.0f, 4.42f, -3.58f, 8.0f, -8.0f, 8.0f) horizontalLineToRelative(-16.0f) curveToRelative(-4.42f, 0.0f, -8.0f, -3.58f, -8.0f, -8.0f) verticalLineToRelative(-16.29f) curveToRelative(-11.29f, -0.58f, -22.27f, -4.52f, -31.37f, -11.35f) curveToRelative(-3.9f, -2.93f, -4.1f, -8.77f, -0.57f, -12.14f) lineToRelative(11.75f, -11.21f) curveToRelative(2.77f, -2.64f, 6.89f, -2.76f, 10.13f, -0.73f) curveToRelative(3.87f, 2.42f, 8.26f, 3.72f, 12.82f, 3.72f) horizontalLineToRelative(28.11f) curveToRelative(6.5f, 0.0f, 11.8f, -5.92f, 11.8f, -13.19f) curveToRelative(0.0f, -5.95f, -3.61f, -11.19f, -8.77f, -12.73f) lineToRelative(-45.0f, -13.5f) curveToRelative(-18.59f, -5.58f, -31.58f, -23.42f, -31.58f, -43.39f) curveToRelative(0.0f, -24.52f, 19.05f, -44.44f, 42.67f, -45.07f) lineTo(463.99f, 256.0f) curveToRelative(0.0f, -4.42f, 3.58f, -8.0f, 8.0f, -8.0f) horizontalLineToRelative(16.0f) curveToRelative(4.42f, 0.0f, 8.0f, 3.58f, 8.0f, 8.0f) verticalLineToRelative(16.29f) curveToRelative(11.29f, 0.58f, 22.27f, 4.51f, 31.37f, 11.35f) curveToRelative(3.9f, 2.93f, 4.1f, 8.77f, 0.57f, 12.14f) lineToRelative(-11.75f, 11.21f) curveToRelative(-2.77f, 2.64f, -6.89f, 2.76f, -10.13f, 0.73f) curveToRelative(-3.87f, -2.43f, -8.26f, -3.72f, -12.82f, -3.72f) horizontalLineToRelative(-28.11f) curveToRelative(-6.5f, 0.0f, -11.8f, 5.92f, -11.8f, 13.19f) curveToRelative(0.0f, 5.95f, 3.61f, 11.19f, 8.77f, 12.73f) lineToRelative(45.0f, 13.5f) curveToRelative(18.59f, 5.58f, 31.58f, 23.42f, 31.58f, 43.39f) curveToRelative(0.0f, 24.53f, -19.04f, 44.44f, -42.67f, 45.07f) close() } } .build() return _funnelDollar!! } private var _funnelDollar: ImageVector? = null
17
Kotlin
25
571
a660e5f3033e3222e3553f5a6e888b7054aed8cd
4,502
compose-icons
MIT License
work/work-runtime/src/main/java/androidx/work/ListenableFuture.kt
androidx
256,589,781
false
{"Kotlin": 95878258, "Java": 67276414, "C++": 9121933, "AIDL": 629410, "Python": 308602, "Shell": 191832, "TypeScript": 40586, "HTML": 26377, "Svelte": 20307, "ANTLR": 19860, "C": 16935, "CMake": 14401, "Groovy": 13532, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019}
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("NOTHING_TO_INLINE") package androidx.work import androidx.annotation.RestrictTo import androidx.concurrent.futures.CallbackToFutureAdapter import androidx.work.impl.utils.futures.SettableFuture import com.google.common.util.concurrent.ListenableFuture import java.util.concurrent.CancellationException import java.util.concurrent.ExecutionException import java.util.concurrent.Executor import java.util.concurrent.atomic.AtomicBoolean import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException import kotlinx.coroutines.Job import kotlinx.coroutines.suspendCancellableCoroutine /** * Awaits for the completion of the [ListenableFuture] without blocking a thread. * * @return R The result from the [ListenableFuture] * */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public suspend inline fun <R> ListenableFuture<R>.await(): R { // Fast path if (isDone) { try { return get() } catch (e: ExecutionException) { throw e.cause ?: e } } return suspendCancellableCoroutine { cancellableContinuation -> addListener( Runnable { try { cancellableContinuation.resume(get()) } catch (throwable: Throwable) { val cause = throwable.cause ?: throwable when (throwable) { is CancellationException -> cancellableContinuation.cancel(cause) else -> cancellableContinuation.resumeWithException(cause) } } }, DirectExecutor.INSTANCE ) cancellableContinuation.invokeOnCancellation { cancel(false) } } } /** * A special [Job] to [ListenableFuture] wrapper. */ internal class JobListenableFuture<R>( private val job: Job, private val underlying: SettableFuture<R> = SettableFuture.create() ) : ListenableFuture<R> by underlying { public fun complete(result: R) { underlying.set(result) } init { job.invokeOnCompletion { throwable: Throwable? -> when (throwable) { null -> require(underlying.isDone) is CancellationException -> underlying.cancel(true) else -> underlying.setException(throwable.cause ?: throwable) } } } } internal fun <V> Executor.executeAsync(debugTag: String, block: () -> V): ListenableFuture<V> = CallbackToFutureAdapter.getFuture { completer -> val cancelled = AtomicBoolean(false) completer.addCancellationListener({ cancelled.set(true) }, DirectExecutor.INSTANCE) execute { if (cancelled.get()) return@execute try { completer.set(block()) } catch (t: Throwable) { completer.setException(t) } } debugTag }
27
Kotlin
901
4,898
e7c7c42655aba3f04cb7672f2eb02744bd24ce7f
3,542
androidx
Apache License 2.0
math-hammer-40k/src/main/kotlin/io/hsar/mathhammer/model/UnitProfile.kt
HSAR
382,069,316
false
null
package io.hsar.mathhammer.model /** * Each unit configuration makes multiple distinct offensive profiles, one per attacker type. */ data class UnitProfile( val unitName: String, val totalPointsCost: Double, val offensiveProfiles: List<OffensiveProfile> )
0
Kotlin
0
0
6a51110c3158a61a0c5874a68214b0f51f566be2
270
MathHammer
Apache License 2.0
WorkManagerSample/app/src/main/java/com/example/background/FilterActivity.kt
android
90,792,131
false
null
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.background import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.View import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.work.WorkInfo import com.bumptech.glide.Glide import com.example.background.databinding.ActivityFilterBinding /** The [android.app.Activity] where the user picks filters to be applied on an image. */ class FilterActivity : AppCompatActivity() { private val viewModel: FilterViewModel by viewModels { FilterViewModelFactory(application) } private var outputImageUri: Uri? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) ActivityFilterBinding.inflate(layoutInflater).run { setContentView(root) bindViews(this) // Check to see if we have output. viewModel.workInfo.observe(this@FilterActivity) { info -> onStateChange(info, this) } } } private fun bindViews(binding: ActivityFilterBinding) { with(binding) { val imageUri: Uri = Uri.parse(intent.getStringExtra(Constants.KEY_IMAGE_URI)) Glide.with(this@FilterActivity).load(imageUri).into(imageView) // Only show output options if a Imgur client id is set. val multipleDestinationsPossible = Constants.IMGUR_CLIENT_ID.isNotEmpty() if (!multipleDestinationsPossible) { destinationsGroup.visibility = View.GONE } apply.setOnClickListener { val applyWaterColor = filterWatercolor.isChecked val applyGrayScale = filterGrayscale.isChecked val applyBlur = filterBlur.isChecked val save = save.isChecked val imageOperations = ImageOperations( applicationContext, imageUri, applyWaterColor, applyGrayScale, applyBlur, save ) viewModel.apply(imageOperations) } output.setOnClickListener { if (outputImageUri != null) { val viewOutput = Intent(Intent.ACTION_VIEW, outputImageUri) if (viewOutput.resolveActivity(packageManager) != null) { startActivity(viewOutput) } } } cancel.setOnClickListener { viewModel.cancel() } } } private fun onStateChange(info: WorkInfo, binding: ActivityFilterBinding) { val finished = info.state.isFinished with(binding) { if (!finished) { progressBar.visibility = View.VISIBLE cancel.visibility = View.VISIBLE apply.visibility = View.GONE output.visibility = View.GONE } else { progressBar.visibility = View.GONE cancel.visibility = View.GONE apply.visibility = View.VISIBLE } } val outputData = info.outputData outputData.getString(Constants.KEY_IMAGE_URI)?.let { outputImageUri = Uri.parse(it) binding.output.visibility = View.VISIBLE } } companion object { /** * Creates a new intent which can be used to start [FilterActivity]. * * @param context the application [Context]. * @param imageUri the input image [Uri]. * @return the instance of [Intent]. */ internal fun newIntent(context: Context, imageUri: Uri) = Intent(context, FilterActivity::class.java).putExtra( Constants.KEY_IMAGE_URI, imageUri.toString() ) } }
193
null
8331
23,109
e849ce3004ccd1132a121cf513bbcb7996d95c30
4,453
architecture-components-samples
Apache License 2.0
app/src/main/java/com/sirisdevelopment/swiftly/viewmodel/MainViewModel.kt
jim-spa
301,162,871
false
null
package com.sirisdevelopment.swiftly.viewmodel import com.sirisdevelopment.swiftly.SwiftlyExample import com.sirisdevelopment.swiftly.data.SwiftlyGrocerAPI import com.sirisdevelopment.swiftly.data.SwiftlyRepository import com.sirisdevelopment.swiftly.data.SwiftlyServiceGenerator import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.async import timber.log.Timber class MainViewModel { val context by lazy { SwiftlyExample.context } fun getSwiftlyGrocerManagersSpecialsAsync() = GlobalScope.async { Timber.d("getSwiftlyGrocerManagersSpecials: started...") val swiftlyRepository = SwiftlyRepository.instance.getInstance(context).swiftlyGrocerApi.retrieveSwiftlyGroverManagerSpecials() Timber.d("getSwiftlyGrocerManagersSpecials: retrieveSwiftlyGroverManagerSpecials started..") } }
0
Kotlin
0
0
f3885b1c28c18e6cac7cdd1cf8d33d4a7d30b3e9
844
swiftly-example
MIT License
app/src/main/java/com/sirisdevelopment/swiftly/viewmodel/MainViewModel.kt
jim-spa
301,162,871
false
null
package com.sirisdevelopment.swiftly.viewmodel import com.sirisdevelopment.swiftly.SwiftlyExample import com.sirisdevelopment.swiftly.data.SwiftlyGrocerAPI import com.sirisdevelopment.swiftly.data.SwiftlyRepository import com.sirisdevelopment.swiftly.data.SwiftlyServiceGenerator import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.async import timber.log.Timber class MainViewModel { val context by lazy { SwiftlyExample.context } fun getSwiftlyGrocerManagersSpecialsAsync() = GlobalScope.async { Timber.d("getSwiftlyGrocerManagersSpecials: started...") val swiftlyRepository = SwiftlyRepository.instance.getInstance(context).swiftlyGrocerApi.retrieveSwiftlyGroverManagerSpecials() Timber.d("getSwiftlyGrocerManagersSpecials: retrieveSwiftlyGroverManagerSpecials started..") } }
0
Kotlin
0
0
f3885b1c28c18e6cac7cdd1cf8d33d4a7d30b3e9
844
swiftly-example
MIT License
compiler-plugin-utils/src/main/kotlin/com/rnett/plugin/naming/FunctionFilter.kt
rnett
334,825,195
false
null
package com.rnett.plugin.naming import org.jetbrains.kotlin.ir.declarations.IrFunction import org.jetbrains.kotlin.ir.declarations.IrValueParameter import org.jetbrains.kotlin.ir.util.isVararg /** * A filter for resolving IR functions */ @Deprecated("Will be superseded by reference generator") public interface IFunctionFilter { public var numParameters: Int? public var numTypeParameters: Int? public var parameters: MutableMap<Int, (IrValueParameter) -> Boolean> public var hasExtensionReceiver: Boolean? public var extensionReceiver: ((IrValueParameter) -> Boolean)? public var hasDispatchReceiver: Boolean? public var hasVararg: Boolean? public var isExpect: Boolean? public fun matches(function: IrFunction): Boolean public fun filter(filter: (IrFunction) -> Boolean) public operator fun Int.invoke(filter: (IrValueParameter) -> Boolean) { parameters[this] = filter } } /** * Implementation of [IFunctionFilter] */ @Deprecated("Will be superseded by reference generator") public open class FunctionFilter internal constructor() : IFunctionFilter { override var numParameters: Int? = null override var numTypeParameters: Int? = null override var parameters: MutableMap<Int, (IrValueParameter) -> Boolean> = mutableMapOf() override var hasExtensionReceiver: Boolean? = null override var extensionReceiver: ((IrValueParameter) -> Boolean)? = null override var hasDispatchReceiver: Boolean? = null override var hasVararg: Boolean? = null override var isExpect: Boolean? = null internal var filter: (IrFunction) -> Boolean = { true } override fun matches(function: IrFunction): Boolean { val params = function.valueParameters numParameters?.let { if (params.size != it) return false } numTypeParameters?.let { if (function.typeParameters.size != it) return false } parameters.forEach { (i, it) -> if (i > params.lastIndex) return false if (!it(params[i])) return false } hasExtensionReceiver?.let { if (it != (function.extensionReceiverParameter != null)) return false } hasDispatchReceiver?.let { if (it != (function.dispatchReceiverParameter != null)) return false } extensionReceiver?.let { if (function.extensionReceiverParameter == null) return false if (!it(function.extensionReceiverParameter!!)) return false } hasVararg?.let { if (it != function.valueParameters.any { it.isVararg }) return false } isExpect?.let { if (it != function.isExpect) return false } return filter(function) } override fun filter(filter: (IrFunction) -> Boolean) { val old = this.filter this.filter = { old(it) && filter(it) } } } /** * Add a lambda filter */ public fun <T : IFunctionFilter> T.withFilter(filter: (IrFunction) -> Boolean): T = apply { filter(filter) } /** * Only select functions with a matching (lazily resolved) extension receiver */ public fun <T : IFunctionFilter> T.withExtensionReceiverType(classRef: () -> ClassRef): T = apply { val ref = lazy(classRef) extensionReceiver = { it.type.isClassifierOf(ref.value) } } public inline operator fun <T : IFunctionFilter> T.invoke(builder: IFunctionFilter.() -> Unit): T = apply(builder)
0
Kotlin
0
6
e74bd3c52b82a4f3bcce9aefd1b06d656b927c67
3,630
compiler-plugin-utils
Apache License 2.0
easyResult/src/main/java/com/yupfeg/result/permission/config/RequestPermissionConfig.kt
yuPFeG1819
447,441,136
false
{"Kotlin": 108800}
package com.yupfeg.result.permission.config import com.yupfeg.result.permission.dialog.PermissionRationaleDialogFragment /** * 动态权限请求dsl配置类 * @author yuPFeG * @date 2021/10/15 */ open class RequestPermissionConfig{ /** * 请求的权限集合,集合为空则不会发起权限请求 * */ @JvmField var permissions : Array<String>? = null /** * 是否在权限请求拒绝后,显示权限请求原因的弹窗, * * 需要配合[rationaleDialogFragment],该弹窗会在允许后,再次请求权限 * * 配合[forwardSettingDialogFragment],该弹窗会在允许后,跳转到系统应用权限页 * */ @JvmField var isShowRationalDialogAfterDefined : Boolean = false /** * 权限请求理由说明弹窗,默认为null * * 推荐外部不需要每次创建新对象,可以通过非空判断,在视图作用域范围内创建一次'单例', * 在视图声明周期结束时,将其dismiss与置空 * */ @JvmField var rationaleDialogFragment : PermissionRationaleDialogFragment? = null /** * 导航到系统设置页说明弹窗,仅在所拒绝的权限都为永久拒绝时生效,默认为null * * 在遇到永久拒绝的权限时,会弹出提示弹窗,并在确认后跳转到系统设置页 * * 推荐外部不需要每次创建新对象,可以通过非空判断,在视图作用域范围内创建一个'单例', * 在视图声明周期结束时,将其dismiss与置空 * */ @JvmField var forwardSettingDialogFragment : PermissionRationaleDialogFragment? = null /** * 设置需要请求的权限 * @param permission 需要请求的权限 * */ @Suppress("unused") fun setRequestPermissions(vararg permission : String){ permissions = arrayOf(*permission) } }
0
Kotlin
0
0
611597eeb69760ed0b855f60f1943d0e2435b5d9
1,275
EasyResutAPI
Apache License 2.0
boxicons/src/commonMain/kotlin/com/woowla/compose/icon/collections/boxicons/boxicons/regular/BxDetail.kt
walter-juan
868,046,028
false
{"Kotlin": 34345428}
package com.woowla.compose.icon.collections.boxicons.boxicons.regular import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.woowla.compose.icon.collections.boxicons.boxicons.RegularGroup public val RegularGroup.BxDetail: ImageVector get() { if (_bxDetail != null) { return _bxDetail!! } _bxDetail = Builder(name = "BxDetail", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(20.0f, 3.0f) horizontalLineTo(4.0f) curveToRelative(-1.103f, 0.0f, -2.0f, 0.897f, -2.0f, 2.0f) verticalLineToRelative(14.0f) curveToRelative(0.0f, 1.103f, 0.897f, 2.0f, 2.0f, 2.0f) horizontalLineToRelative(16.0f) curveToRelative(1.103f, 0.0f, 2.0f, -0.897f, 2.0f, -2.0f) verticalLineTo(5.0f) curveToRelative(0.0f, -1.103f, -0.897f, -2.0f, -2.0f, -2.0f) close() moveTo(4.0f, 19.0f) verticalLineTo(5.0f) horizontalLineToRelative(16.0f) lineToRelative(0.002f, 14.0f) horizontalLineTo(4.0f) close() } path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(6.0f, 7.0f) horizontalLineToRelative(12.0f) verticalLineToRelative(2.0f) lineTo(6.0f, 9.0f) close() moveTo(6.0f, 11.0f) horizontalLineToRelative(12.0f) verticalLineToRelative(2.0f) lineTo(6.0f, 13.0f) close() moveTo(6.0f, 15.0f) horizontalLineToRelative(6.0f) verticalLineToRelative(2.0f) lineTo(6.0f, 17.0f) close() } } .build() return _bxDetail!! } private var _bxDetail: ImageVector? = null
0
Kotlin
0
3
eca6c73337093fbbfbb88546a88d4546482cfffc
2,982
compose-icon-collections
MIT License
compiler/ir/ir.tree/src/org/jetbrains/kotlin/ir/expressions/impl/IrFunctionExpressionImpl.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2019 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.ir.expressions.impl import org.jetbrains.kotlin.ir.declarations.IrSimpleFunction import org.jetbrains.kotlin.ir.expressions.IrFunctionExpression import org.jetbrains.kotlin.ir.expressions.IrStatementOrigin import org.jetbrains.kotlin.ir.types.IrType import org.jetbrains.kotlin.ir.visitors.IrElementTransformer import org.jetbrains.kotlin.ir.visitors.IrElementVisitor class IrFunctionExpressionImpl( startOffset: Int, endOffset: Int, type: IrType, override var function: IrSimpleFunction, override val origin: IrStatementOrigin ) : IrExpressionBase(startOffset, endOffset, type), IrFunctionExpression { override fun <R, D> accept(visitor: IrElementVisitor<R, D>, data: D): R { return visitor.visitFunctionExpression(this, data) } override fun <D> acceptChildren(visitor: IrElementVisitor<Unit, D>, data: D) { function.accept(visitor, data) } override fun <D> transformChildren(transformer: IrElementTransformer<D>, data: D) { function = function.transform(transformer, data) as IrSimpleFunction } }
125
null
4903
39,894
0ad440f112f353cd2c72aa0a0619f3db2e50a483
1,318
kotlin
Apache License 2.0
src/main/kotlin/no/nav/familie/ba/sak/ekstern/restDomene/RestUtvidetBehandling.kt
navikt
224,639,942
false
null
package no.nav.familie.ba.sak.ekstern.restDomene import no.nav.familie.ba.sak.kjerne.behandling.domene.BehandlingKategori import no.nav.familie.ba.sak.kjerne.behandling.domene.BehandlingResultat import no.nav.familie.ba.sak.kjerne.behandling.domene.BehandlingStatus import no.nav.familie.ba.sak.kjerne.behandling.domene.BehandlingType import no.nav.familie.ba.sak.kjerne.behandling.domene.BehandlingUnderkategori import no.nav.familie.ba.sak.kjerne.behandling.domene.BehandlingÅrsak import no.nav.familie.ba.sak.kjerne.steg.StegType import no.nav.familie.ba.sak.kjerne.vedtak.vedtaksperiode.Utbetalingsperiode import java.time.LocalDateTime data class RestUtvidetBehandling( val behandlingId: Long, val steg: StegType, val stegTilstand: List<RestBehandlingStegTilstand>, val status: BehandlingStatus, val resultat: BehandlingResultat, val skalBehandlesAutomatisk: Boolean, val type: BehandlingType, val kategori: BehandlingKategori, val underkategori: BehandlingUnderkategori, val årsak: BehandlingÅrsak, val opprettetTidspunkt: LocalDateTime, val endretAv: String, val arbeidsfordelingPåBehandling: RestArbeidsfordelingPåBehandling, val søknadsgrunnlag: SøknadDTO?, val personer: List<RestPerson>, val personResultater: List<RestPersonResultat>, val fødselshendelsefiltreringResultater: List<RestFødselshendelsefiltreringResultat>, val utbetalingsperioder: List<Utbetalingsperiode>, val personerMedAndelerTilkjentYtelse: List<RestPersonMedAndeler>, val endretUtbetalingAndeler: List<RestEndretUtbetalingAndel>, val tilbakekreving: RestTilbakekreving?, val vedtak: RestVedtak?, val totrinnskontroll: RestTotrinnskontroll?, )
8
Kotlin
0
7
d4a7ef6bc7ba6f0dfdbea1e0d7c7413a97891d55
1,719
familie-ba-sak
MIT License
src/jvmMain/kotlin/controller/ig/IgController.kt
hapifhir
285,363,653
false
null
package controller.ig import model.PackageInfo interface IgController { suspend fun listIgs(): MutableList<PackageInfo> }
10
Kotlin
4
4
f702b7432facec00c97ab72ee41f463cc2444974
127
org.hl7.fhir.validator-wrapper
Apache License 2.0
app/src/main/java/me/hegj/wandroid/mvp/model/share/ShareByIdModel.kt
hegaojian
206,478,384
false
null
package me.hegj.wandroid.mvp.model.share import android.app.Application import com.google.gson.Gson import com.jess.arms.integration.IRepositoryManager import com.jess.arms.mvp.BaseModel import com.jess.arms.di.scope.ActivityScope import io.reactivex.Observable import javax.inject.Inject import me.hegj.wandroid.mvp.contract.share.ShareByIdContract import me.hegj.wandroid.mvp.model.api.Api import me.hegj.wandroid.mvp.model.entity.ApiResponse import me.hegj.wandroid.mvp.model.entity.ShareResponse /** * ================================================ * Description: * <p> * Created by MVPArmsTemplate on 10/09/2019 13:20 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a> * <a href="https://github.com/JessYanCoding">Follow me</a> * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a> * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a> * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a> * ================================================ */ @ActivityScope class ShareByIdModel @Inject constructor(repositoryManager: IRepositoryManager) : BaseModel(repositoryManager), ShareByIdContract.Model { override fun getShareData(pageNo: Int,id:Int): Observable<ApiResponse<ShareResponse>> { return mRepositoryManager.obtainRetrofitService(Api::class.java) .getShareByidData(pageNo,id) } //取消收藏 override fun uncollect(id: Int): Observable<ApiResponse<Any>> { return mRepositoryManager .obtainRetrofitService(Api::class.java) .uncollect(id) } //收藏 override fun collect(id: Int): Observable<ApiResponse<Any>> { return mRepositoryManager .obtainRetrofitService(Api::class.java) .collect(id) } @Inject lateinit var mGson: Gson; @Inject lateinit var mApplication: Application; override fun onDestroy() { super.onDestroy(); } }
1
null
100
713
622016c9695c01f3a134a23c4af1f76686aad6f1
1,964
WanAndroid
Apache License 2.0
src/main/kotlin/org/plan/research/tga/coverage/CoverageInfo.kt
plan-research
762,333,893
false
{"Kotlin": 29709, "Python": 21144}
package org.plan.research.tga.coverage data class CoverageInfo<T : Any>( val coverage: Map<T, Boolean> ) { val covered: UInt = coverage.count { it.value }.toUInt() val total: UInt = coverage.size.toUInt() val ratio = covered / total } data class LineId(val fileName: String, val lineNumber: UInt) data class InstructionId(val line: LineId, val number: UInt) data class BranchId(val line: LineId, val number: UInt) interface CodeCoverageInfo { val instructions: CoverageInfo<InstructionId> val lines: CoverageInfo<LineId> val branches: CoverageInfo<BranchId> } data class MethodCoverageInfo( val name: String, val descriptor: String, override val instructions: CoverageInfo<InstructionId>, override val lines: CoverageInfo<LineId>, override val branches: CoverageInfo<BranchId> ) : CodeCoverageInfo data class ClassCoverageInfo( val name: String, val methods: Set<MethodCoverageInfo> ) : CodeCoverageInfo { override val instructions = CoverageInfo<InstructionId>(methods.fold(mutableMapOf()) { a, b -> a.putAll(b.instructions.coverage) a }) override val lines = CoverageInfo<LineId>(methods.fold(mutableMapOf()) { a, b -> a.putAll(b.lines.coverage) a }) override val branches = CoverageInfo<BranchId>(methods.fold(mutableMapOf()) { a, b -> a.putAll(b.branches.coverage) a }) }
0
Kotlin
0
0
7b8042b0de65d5dbf3da60f1dc121f4b33660184
1,409
tga-pipeline
Apache License 2.0
network/src/test/java/com/bintang/network/ApiAbstract.kt
PiaggiPutra
273,506,057
false
null
package com.bintang.network import androidx.arch.core.executor.testing.InstantTaskExecutorRule import java.io.IOException import java.nio.charset.StandardCharsets import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import okhttp3.mockwebserver.RecordedRequest import okio.buffer import okio.source import org.hamcrest.CoreMatchers import org.hamcrest.MatcherAssert import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.runner.RunWith import org.junit.runners.JUnit4 import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory @RunWith(JUnit4::class) abstract class ApiAbstract<T> { @Rule @JvmField val instantExecutorRule: InstantTaskExecutorRule = InstantTaskExecutorRule() private lateinit var mockWebServer: MockWebServer @Throws(IOException::class) @Before fun mockServer() { mockWebServer = MockWebServer() mockWebServer.start() } @Throws(IOException::class) @After fun stopServer() { mockWebServer.shutdown() } @Throws(IOException::class) fun enqueueResponse(fileName: String) { enqueueResponse(fileName, emptyMap()) } @Throws(IOException::class) private fun enqueueResponse(fileName: String, headers: Map<String, String>) { val inputStream = javaClass.classLoader!!.getResourceAsStream("api-response/$fileName") val source = inputStream.source().buffer() val mockResponse = MockResponse() for ((key, value) in headers) { mockResponse.addHeader(key, value) } mockWebServer.enqueue(mockResponse.setBody(source.readString(StandardCharsets.UTF_8))) } fun createService(clazz: Class<T>): T { return Retrofit.Builder() .baseUrl(mockWebServer.url("/")) .addConverterFactory(GsonConverterFactory.create()) .build() .create(clazz) } fun assertRequestPath(path: String) { val request: RecordedRequest = mockWebServer.takeRequest() MatcherAssert.assertThat(request.path, CoreMatchers.`is`(path)) } }
0
Kotlin
0
0
641770f129f649d144370639831c407b9903e87b
2,016
TestKitaBisaAndroid
Apache License 2.0
core/testing/src/main/java/io/github/droidkaigi/confsched/testing/data/TestDispatcherModule.kt
DroidKaigi
776,354,672
false
{"Kotlin": 1119401, "Swift": 211686, "Shell": 2954, "Makefile": 1314, "Ruby": 386}
package io.github.droidkaigi.confsched.testing.data import dagger.Module import dagger.Provides import dagger.hilt.components.SingletonComponent import dagger.hilt.testing.TestInstallIn import io.github.droidkaigi.confsched.di.DispatcherModule import io.github.droidkaigi.confsched.di.IoDispatcher import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.TestDispatcher import javax.inject.Singleton @Module @TestInstallIn(components = [SingletonComponent::class], replaces = [DispatcherModule::class]) class TestDispatcherModule { @Provides @Singleton fun provideTestDispatcher(): TestDispatcher = StandardTestDispatcher() @Provides @IoDispatcher fun provideIoDispatcher(): CoroutineDispatcher = StandardTestDispatcher() }
49
Kotlin
201
438
57c38a76beb5b75edc9220833162e1257f40ac06
826
conference-app-2024
Apache License 2.0
src/main/kotlin/io/luxus/jda/FileUtils.kt
Luxusio
756,409,398
false
{"Kotlin": 11869, "Java": 1260}
package io.luxus.jda import java.io.File val File.allFiles: List<File> get() { return if (isDirectory) { listFiles()?.flatMap { it.allFiles } ?: listOf() } else { listOf(this) } }
1
Kotlin
0
1
e1a99086f60c25bebc2f2d97bd323a4386bea947
238
Java-Dependency-Analyzer
Apache License 2.0
src/test/kotlin/xyz/magentaize/dynamicdata/list/DynamicOrFixture.kt
Magentaize
290,133,754
false
null
package xyz.magentaize.dynamicdata.list import xyz.magentaize.dynamicdata.list.test.asAggregator import io.reactivex.rxjava3.core.Observable import org.amshove.kluent.shouldBeEqualTo import kotlin.test.Test internal class DynamicOrFixture { private val source1 = SourceList<Int>() private val source2 = SourceList<Int>() private val source3 = SourceList<Int>() private val source = SourceList<Observable<ChangeSet<Int>>>() private val result = source.or().asAggregator() @Test fun itemIsReplaced() { source1.add(0) source2.add(1) source.add(source1.connect()) source.add(source2.connect()) source1.replaceAt(0, 9) result.data.size shouldBeEqualTo 2 result.messages.size shouldBeEqualTo 3 result.data.items.toList() shouldBeEqualTo listOf(1, 9) } @Test fun clearSource() { source1.add(0) source2.add(1) source.add(source1.connect()) source.add(source2.connect()) source.clear() result.data.size shouldBeEqualTo 0 } @Test fun includedWhenItemIsInOneSource() { source.add(source1.connect()) source.add(source2.connect()) source1.add(1) result.data.size shouldBeEqualTo 1 result.data.items.first() shouldBeEqualTo 1 } @Test fun includedWhenItemIsInTwoSources() { source.add(source1.connect()) source.add(source2.connect()) source1.add(1) source2.add(1) result.data.size shouldBeEqualTo 1 result.data.items.first() shouldBeEqualTo 1 } @Test fun removedWhenNoLongerInEither() { source.add(source1.connect()) source.add(source2.connect()) source1.add(1) source1.remove(1) result.data.size shouldBeEqualTo 0 } @Test fun combineRange() { source.add(source1.connect()) source.add(source2.connect()) source1.addRange(1..10) source2.addRange(6..10) result.data.size shouldBeEqualTo 10 result.data.items.toList() shouldBeEqualTo (1..10).toList() } @Test fun clearOnlyClearsOneSource() { source.add(source1.connect()) source.add(source2.connect()) source1.addRange(1..5) source2.addRange(6..10) source1.clear() result.data.size shouldBeEqualTo 5 result.data.items.toList() shouldBeEqualTo (6..10).toList() } @Test fun addAndRemoveLists() { source1.addRange(1..5) source2.addRange(6..10) source3.addRange(100..104) source.add(source1.connect()) source.add(source2.connect()) source.add(source3.connect()) var ex = (1..5).union(6..10).union(100..104).toList() result.data.size shouldBeEqualTo 15 result.data.toList() shouldBeEqualTo ex source.removeAt(1) result.data.size shouldBeEqualTo 10 ex = (1..5).union(100..104).toList() result.data.items.toList() shouldBeEqualTo ex } // // @Test // fun refreshPassesThrough(){ // source1.add() // } }
0
Kotlin
0
3
dda522f335a6ab3847cc90ff56e8429c15834800
3,129
dynamicdata-kotlin
MIT License
app/src/main/java/com/example/swd_application/Admin/Activities/EventAdminActivity.kt
Anirudhk07
336,242,117
false
null
package com.example.swd_application.Admin.Activities import android.app.DatePickerDialog import android.content.Intent import android.net.Uri import android.os.Bundle import android.util.Log import android.webkit.MimeTypeMap import android.widget.* import androidx.appcompat.app.AppCompatActivity import com.example.swd_application.Authentication.Admin.AdminHomeActivity import com.example.swd_application.R import com.example.swd_application.Models.EventModel import com.google.android.gms.tasks.Task import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.QuerySnapshot import com.google.firebase.firestore.ktx.firestore import com.google.firebase.ktx.Firebase import com.google.firebase.storage.FirebaseStorage import com.google.firebase.storage.StorageReference import com.google.firebase.storage.UploadTask import com.google.firebase.storage.ktx.storage import java.util.* class EventAdminActivity : AppCompatActivity() { companion object { private const val TAG = "Event-Admin" private const val IMAGE_PICK_CODE = 999 const val COLLECTION_PATH = "EVENTS" const val ROOT_EVENT_IMAGE_REF = "Events-Images" const val IMAGE_URL_FIELD = "eventImageUrl" } private lateinit var et_admin_event_name: TextView private lateinit var et_admin_event_description: TextView private lateinit var btnChoose: Button private lateinit var et_event_name_head_1: TextView private lateinit var et_event_name_head_2: TextView private lateinit var et_event_link: TextView private lateinit var et_event_number_of_seats_value: TextView private lateinit var btn_date_picker_start: Button private lateinit var tv_start_event: TextView private lateinit var btn_date_picker_end: Button private lateinit var tv_end_event: TextView private lateinit var imageView: ImageView private var imageUri: Uri? = null private var imageUriAsString: String? = null private lateinit var radioGroup: RadioGroup private lateinit var radioButtonYes: RadioButton private lateinit var radioButtonNo: RadioButton private lateinit var btn_add_event: Button private var isEventFlagship = false private var startDate: String? = null private var endDate: String? = null private val eventsDb: FirebaseFirestore = Firebase.firestore private val storageReference: FirebaseStorage = Firebase.storage private val imageStorageRootRef: StorageReference = storageReference.reference override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_event_admin) et_admin_event_name = findViewById<TextView>(R.id.et_admin_event_name) et_admin_event_description = findViewById<TextView>(R.id.et_admin_event_description) et_event_number_of_seats_value = findViewById<TextView>(R.id.et_admin_event_number_of_seats_value) btnChoose = findViewById<Button>(R.id.btnChoose) imageView = findViewById<ImageView>(R.id.iv_admin_event_image) btn_date_picker_start = findViewById<Button>(R.id.btn_date_picker_start) tv_start_event = findViewById<TextView>(R.id.tv_start_event) btn_date_picker_end = findViewById<Button>(R.id.btn_date_picker_end) tv_end_event = findViewById<TextView>(R.id.tv_end_event) et_event_name_head_1 = findViewById<TextView>(R.id.et_event_name_head_1) et_event_name_head_2 = findViewById<TextView>(R.id.et_event_name_head_2) et_event_link = findViewById<TextView>(R.id.et_event_link) btn_add_event = findViewById<Button>(R.id.btn_add_event) radioGroup = findViewById<RadioGroup>(R.id.rg_admin_event_flagship) radioButtonYes = findViewById<RadioButton>(R.id.rb_admin_event_yes) radioButtonNo = findViewById<RadioButton>(R.id.rb_admin_event_no) //Calender val calender: Calendar = Calendar.getInstance() val day: Int = calender.get(Calendar.DAY_OF_MONTH) val month: Int = calender.get(Calendar.MONTH) val year: Int = calender.get(Calendar.YEAR) btn_date_picker_start.setOnClickListener { val dpd = DatePickerDialog( this, DatePickerDialog.OnDateSetListener { view, year, month, dayOfMonth -> startDate = "${dayOfMonth}-${month + 1}-${year}" tv_start_event.text = startDate }, year, month, day ) dpd.show() } btn_date_picker_end.setOnClickListener { val dpd = DatePickerDialog( this, DatePickerDialog.OnDateSetListener { view, year, month, dayOfMonth -> endDate = "${dayOfMonth}-${month + 1}-${year}" tv_end_event.text = endDate }, year, month, day ) dpd.show() } radioButtonYes.setOnClickListener { isEventFlagship = true } radioButtonNo.setOnClickListener { isEventFlagship = false } btnChoose.setOnClickListener { launchGallery() } btn_add_event.setOnClickListener { val areAllFieldsFilled:Boolean = checkWhetherAllFieldsFilled() // If all the fields are not filled if(!areAllFieldsFilled){ return@setOnClickListener } val eventModel: EventModel = createEventModel() Log.d(TAG, "Show Data $eventModel") // This function will check firestore and if event exists it does not allow user to post event // but if event does not exist it add the events to firestore checkWhetherThisEventExistsInFireStore(eventModel) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == RESULT_OK && requestCode == IMAGE_PICK_CODE) { imageUri = data?.data if (imageUri != null) { imageView.setImageURI(imageUri) imageUriAsString = data?.dataString } } } private fun uploadImageToFirebaseStorage(eventId: String) { val eventImageRef: StorageReference = imageStorageRootRef.child( "${ROOT_EVENT_IMAGE_REF}/${eventId}.${ getFileExtension(imageUri!!) }" ) val path: String = eventImageRef.path val imageName: String = eventImageRef.name Log.d(TAG, "path is $path and imagename is $imageName") val uploadTask: UploadTask = eventImageRef.putFile(imageUri!!) uploadTask.addOnSuccessListener { Log.d(TAG, "uploadImageToFirebaseStorage: Your image got successfully uploaded") }.addOnFailureListener { Log.d(TAG, "uploadImageToFirebaseStorage: ${it.message}") Toast.makeText( this@EventAdminActivity, "Your image did not got successfully uploaded.Please contact the administration team", Toast.LENGTH_SHORT ).show() } val urlTask = uploadTask.continueWithTask { task -> if (!task.isSuccessful) { task.exception?.let { throw it } } eventImageRef.downloadUrl } urlTask.addOnCompleteListener { task: Task<Uri> -> if (task.isSuccessful) { val downloadUri: Uri? = task.result if (downloadUri != null) { // We are here updating the event updateEventDataWithImageUrl(eventId, IMAGE_URL_FIELD, downloadUri) } } } } private fun updateEventDataWithImageUrl(eventId: String, fieldName: String, downloadUri: Uri) { eventsDb.collection(COLLECTION_PATH).document(eventId) .update(mapOf(fieldName to downloadUri.toString())) .addOnSuccessListener { Log.d(TAG, "DocumentSnapshot successfully updated! path name is ${downloadUri}") } .addOnFailureListener { ex -> Log.w(TAG, "Error updating document", ex) } } // This functions adds the event data to firestore private fun addEventDataToFirestore(eventModel: EventModel) { val eventId = "${eventModel.eventName.toUpperCase(Locale.ROOT)}-${eventModel.eventConductedYear}" eventsDb.collection(COLLECTION_PATH) .document(eventId) .set(eventModel) .addOnCompleteListener { Toast.makeText( this@EventAdminActivity, "The Event Data Got Uploaded", Toast.LENGTH_LONG ).show() // To add data into sub collections of the particular event document use below lines // eventsDb.collection(COLLECTION_PATH).document(eventId).collection("COORDINATORS") // eventsDb.collection(COLLECTION_PATH).document(eventId).collection("HEADS") // eventsDb.collection(COLLECTION_PATH).document(eventId).collection("VOLUNTEERS").add(mapOf("hello" to "Anubhav")) val intent = Intent(this@EventAdminActivity, AdminHomeActivity::class.java) startActivity(intent) finish() }.addOnFailureListener { Toast.makeText( this@EventAdminActivity, "The Event Data did not got uploaded.Try Again !!", Toast.LENGTH_LONG ).show() } } // This will check whether event already exists in firestore or not // If events exist it will not allow user to create an event // If event does not exist first it creates an event and send it to firebase without image and image url // Then it uploads the image and the update the event data with image Url private fun checkWhetherThisEventExistsInFireStore(eventModel: EventModel) { val eventId = "${eventModel.eventName.toUpperCase(Locale.ROOT)}-${eventModel.eventConductedYear}" eventsDb.collection(COLLECTION_PATH) .get() .addOnSuccessListener { documents: QuerySnapshot -> for (document in documents) { Log.d(TAG, "DocumentSnapshot id: ${document.id}") if (document.id == eventId) { Toast.makeText(this@EventAdminActivity,"This event already exists in database",Toast.LENGTH_LONG).show() return@addOnSuccessListener } } Log.d(TAG, "No such document exists.So we insert this event document") // This function assume that image-Uri is null and uploads the event data without image addEventDataToFirestore(eventModel) // This function uploads the image and also update the event document with the image URL uploadImageToFirebaseStorage(eventId) } } private fun launchGallery() { val intent = Intent(Intent.ACTION_GET_CONTENT) intent.type = "image/*" startActivityForResult(intent, IMAGE_PICK_CODE) } private fun getFileExtension(uri: Uri): String { val contentResolver = contentResolver val mimeType = MimeTypeMap.getSingleton() return mimeType.getExtensionFromMimeType(contentResolver.getType(uri)).toString() } // It is used to create eventModel datatype from data provided by user private fun createEventModel(): EventModel { val calender: Calendar = Calendar.getInstance() val year: Int = calender.get(Calendar.YEAR) val eventModel: EventModel = EventModel( year.toString(), et_admin_event_description.text.toString(), endDate!!, isEventFlagship, listOf<String>( et_event_name_head_1.text.toString(), et_event_name_head_2.text.toString() ), null, et_event_link.text.toString(), et_admin_event_name.text.toString().trim().toUpperCase(Locale.ROOT), 0, startDate!!, et_event_number_of_seats_value.text.toString().toInt() ) return eventModel } private fun checkWhetherAllFieldsFilled(): Boolean{ if (et_admin_event_name.text.isEmpty() || et_admin_event_name.text.isBlank()) { Toast.makeText(this@EventAdminActivity, "You have not provided an event name.So provide event name to proceed", Toast.LENGTH_SHORT).show() return false } else if (et_admin_event_description.text.isEmpty() || et_admin_event_description.text.isBlank()) { Toast.makeText(this@EventAdminActivity,"You have not provided an event description.So provide an event description to proceed",Toast.LENGTH_SHORT).show() return false } else if (imageUri == null) { Toast.makeText(this@EventAdminActivity,"You have not provided an event image.So provide an event image to proceed", Toast.LENGTH_SHORT).show() return false } else if (et_event_number_of_seats_value.text.isEmpty() || et_event_number_of_seats_value.text.isBlank()) { Toast.makeText(this@EventAdminActivity,"You have not provided the number of seats for an event.So provide the number of seats for event to proceed",Toast.LENGTH_SHORT).show() return false } else if (tv_start_event.text == getString(R.string.event_start_date_and_time)) { Toast.makeText(this@EventAdminActivity,"You have not provided an event start date.So provide an event start date to proceed", Toast.LENGTH_SHORT).show() return false } else if (tv_end_event.text == getString(R.string.event_end_date_and_time)) { Toast.makeText(this@EventAdminActivity,"You have not provided an event end date.So provide an event end date to proceed",Toast.LENGTH_SHORT).show() return false } else if (et_event_link.text.isEmpty() || et_event_link.text.isBlank()) { Toast.makeText(this@EventAdminActivity,"You have not provided an event form link.So provide an event form link to proceed",Toast.LENGTH_SHORT).show() return false } return true } }
0
Kotlin
0
2
75a89d52dc9fa9d8b39e54f0b115323df08aac3d
14,634
SWD-Application
MIT License
app/src/main/java/com/lodz/android/agiledevkt/modules/keyboard/KeyboardTestActivity.kt
LZ9
137,967,291
false
{"Kotlin": 2174504}
package com.lodz.android.agiledevkt.modules.keyboard import android.content.Context import android.content.Intent import android.os.Bundle import android.view.View import com.lodz.android.agiledevkt.databinding.ActivityKeyboardTestBinding import com.lodz.android.agiledevkt.modules.main.MainActivity import com.lodz.android.corekt.anko.toastShort import com.lodz.android.corekt.utils.IdCardUtils import com.lodz.android.pandora.base.activity.BaseActivity import com.lodz.android.pandora.utils.viewbinding.bindingLayout /** * 自定义键盘测试类 * @author zhouL * @date 2021/2/22 */ class KeyboardTestActivity : BaseActivity() { companion object { fun start(context: Context){ val intent = Intent(context, KeyboardTestActivity::class.java) context.startActivity(intent) } } private val mBinding: ActivityKeyboardTestBinding by bindingLayout(ActivityKeyboardTestBinding::inflate) override fun getViewBindingLayout(): View = mBinding.root override fun findViews(savedInstanceState: Bundle?) { super.findViews(savedInstanceState) getTitleBarLayout().setTitleName(intent.getStringExtra(MainActivity.EXTRA_TITLE_NAME) ?: "") mBinding.idcardKeyboardView.initView(window, mBinding.idcardCltedt.getEditText()) mBinding.carplateKeyboardView.initView(window, mBinding.carplateCltedt.getEditText()) mBinding.commonCertKeyboardView.initView(window, mBinding.commonCertCltedt.getEditText()) } override fun onClickBackBtn() { super.onClickBackBtn() finish() } override fun setListeners() { super.setListeners() // 身份证键盘 mBinding.idcardKeyboardView.setOnClickFinishListener { if (it.isNotEmpty()) { val tips = if (IdCardUtils.validateIdCard(it)) "合法身份证:$it" else "身份证号不合法" toastShort(tips) } } // 车牌键盘 mBinding.carplateKeyboardView.setOnClickFinishListener{ if (it.isNotEmpty()){ toastShort(it) } } // 全键盘 mBinding.commonCertKeyboardView.setOnClickFinishListener{ if (it.isNotEmpty()){ toastShort(it) } } } override fun initData() { super.initData() showStatusCompleted() } }
0
Kotlin
3
11
926b9f968a984c42ade94371714ef4caf3ffbccf
2,339
AgileDevKt
Apache License 2.0
src/main/kotlin/io/datawire/loom/proto/model/NodeGroup.kt
datawire
85,326,195
false
{"Kotlin": 83440, "HCL": 12785, "Python": 3826, "Shell": 3210}
package io.datawire.loom.proto.model data class NodeGroup(val name: String, val nodeCount: Int = 1, val nodeType: String = "t2.nano")
16
Kotlin
5
52
bccc8254fb0fca1746cf23857ab49aa924e7b4c4
135
loom
Apache License 2.0
team/teamapi/src/main/java/it/laface/team/api/Const.kt
carlaf92
249,497,287
false
null
package it.laface.team.api import it.laface.domain.model.Team object Const { val teams: List<Team> by lazy { listOf( Team( id = "1610612749", key = "Milwaukee", cityName = "Milwaukee", code = "bucks", nickname = "Bucks", rgbColor = "#00471b", tricode = "MIL" ), Team( id = "1610612761", key = "Toronto", cityName = "Toronto", code = "raptors", nickname = "Raptors", rgbColor = "#ce1141", tricode = "TOR" ), Team( id = "1610612738", key = "Boston", cityName = "Boston", code = "celtics", nickname = "Celtics", rgbColor = "#007A33", tricode = "BOS" ), Team( id = "1610612748", key = "Miami", cityName = "Miami", code = "heat", nickname = "Heat", rgbColor = "#98002e", tricode = "MIA" ), Team( id = "1610612754", key = "Indiana", cityName = "Indiana", code = "pacers", nickname = "Pacers", rgbColor = "#00275d", tricode = "IND" ), Team( id = "1610612755", key = "Philadelphia", cityName = "Philadelphia", code = "sixers", nickname = "76ers", rgbColor = "#ed174c", tricode = "PHI" ), Team( id = "1610612751", key = "Brooklyn", cityName = "Brooklyn", code = "nets", nickname = "Nets", rgbColor = "#000000", tricode = "BKN" ), Team( id = "1610612753", key = "Orlando", cityName = "Orlando", code = "magic", nickname = "Magic", rgbColor = "#0077C0", tricode = "ORL" ), Team( id = "1610612764", key = "Washington", cityName = "Washington", code = "wizards", nickname = "Wizards", rgbColor = "#002b5c", tricode = "WAS" ), Team( id = "1610612766", key = "Charlotte", cityName = "Charlotte", code = "hornets", nickname = "Hornets", rgbColor = "#00848E", tricode = "CHA" ), Team( id = "1610612741", key = "Chicago", cityName = "Chicago", code = "bulls", nickname = "Bulls", rgbColor = "#ce1141", tricode = "CHI" ), Team( id = "1610612752", key = "New York", cityName = "New York", code = "knicks", nickname = "Knicks", rgbColor = "#f58426", tricode = "NYK" ), Team( id = "1610612765", key = "Detroit", cityName = "Detroit", code = "pistons", nickname = "Pistons", rgbColor = "#C8102E", tricode = "DET" ), Team( id = "1610612737", key = "Atlanta", cityName = "Atlanta", code = "hawks", nickname = "Hawks", rgbColor = "#E13A3E", tricode = "ATL" ), Team( id = "1610612739", key = "Cleveland", cityName = "Cleveland", code = "cavaliers", nickname = "Cavaliers", rgbColor = "#860038", tricode = "CLE" ), Team( id = "1610612747", key = "Los Angeles", cityName = "Los Angeles", code = "lakers", nickname = "Lakers", rgbColor = "#fdba33", tricode = "LAL" ), Team( id = "1610612746", key = "LA", cityName = "Los Angeles", code = "clippers", nickname = "Clippers", rgbColor = "#ed174c", tricode = "LAC" ), Team( id = "1610612743", key = "Denver", cityName = "Denver", code = "nuggets", nickname = "Nuggets", rgbColor = "#0E2240", tricode = "DEN" ), Team( id = "1610612762", key = "Utah", cityName = "Utah", code = "jazz", nickname = "Jazz", rgbColor = "#00275d", tricode = "UTA" ), Team( id = "1610612760", key = "Oklahoma City", cityName = "Oklahoma City", code = "thunder", nickname = "Thunder", rgbColor = "#007AC1", tricode = "OKC" ), Team( id = "1610612745", key = "Houston", cityName = "Houston", code = "rockets", nickname = "Rockets", rgbColor = "#ce1138", tricode = "HOU" ), Team( id = "1610612742", key = "Dallas", cityName = "Dallas", code = "mavericks", nickname = "Mavericks", rgbColor = "#006BB6", tricode = "DAL" ), Team( id = "1610612763", key = "Memphis", cityName = "Memphis", code = "grizzlies", nickname = "Grizzlies", rgbColor = "#5D76A9", tricode = "MEM" ), Team( id = "1610612757", key = "Portland", cityName = "Portland", code = "blazers", nickname = "<NAME>", rgbColor = "#e43a3e", tricode = "POR" ), Team( id = "1610612740", key = "New Orleans", cityName = "New Orleans", code = "pelicans", nickname = "Pelicans", rgbColor = "#0C2340", tricode = "NOP" ), Team( id = "1610612758", key = "Sacramento", cityName = "Sacramento", code = "kings", nickname = "Kings", rgbColor = "#5A2D81", tricode = "SAC" ), Team( id = "1610612759", key = "San Antonio", cityName = "San Antonio", code = "spurs", nickname = "Spurs", rgbColor = "#788287", tricode = "SAS" ), Team( id = "1610612756", key = "Phoenix", cityName = "Phoenix", code = "suns", nickname = "Suns", rgbColor = "#e56020", tricode = "PHX" ), Team( id = "1610612750", key = "Minnesota", cityName = "Minnesota", code = "timberwolves", nickname = "Timberwolves", rgbColor = "#005083", tricode = "MIN" ), Team( id = "1610612744", key = "Golden State", cityName = "Golden State", code = "warriors", nickname = "Warriors", rgbColor = "#1D428A", tricode = "GSW" ) ) } }
1
Kotlin
0
5
ece5ed250b5f188b985fb546d24981077ef99866
8,621
nba-app
MIT License
packages/graalvm-js/src/main/kotlin/elide/runtime/gvm/globals.kt
elide-dev
506,113,888
false
null
package elide.runtime.gvm import elide.runtime.js.require /** * */ internal val globalThis: dynamic = js("globalThis") /** * */ internal fun assign(name: String, target: dynamic) { globalThis[name] = target } /** * */ internal fun mount(pkg: String, path: String, name: String) { var target: dynamic = require(pkg) if (path.isNotEmpty()) { target = target[path] } assign(name, target) } /** * */ internal fun mount(pkg: String, name: String) { mount( pkg, "", name, ) }
36
Kotlin
4
33
91800dbbf291e65a91d451ed50c9673d82efd174
513
elide
MIT License
projects/workforce-allocations-to-delius/src/dev/kotlin/uk/gov/justice/digital/hmpps/data/generator/UserGenerator.kt
ministryofjustice
500,855,647
false
{"Kotlin": 4318635, "HTML": 70066, "D2": 42781, "Ruby": 25921, "Shell": 19356, "SCSS": 6370, "HCL": 2712, "Dockerfile": 2447, "JavaScript": 1372, "Python": 268}
package uk.gov.justice.digital.hmpps.data.generator import uk.gov.justice.digital.hmpps.integrations.delius.user.LdapUser import uk.gov.justice.digital.hmpps.integrations.delius.user.StaffUser import uk.gov.justice.digital.hmpps.user.AuditUser import javax.naming.ldap.LdapName object UserGenerator { val AUDIT_USER = generate("HMPPSAllocations") val LIMITED_ACCESS_USER = generate("LimitedAccess") fun generate(username: String, id: Long = IdGenerator.getAndIncrement()) = AuditUser(id, username) } object StaffUserGenerator { val DEFAULT = generate("JoeBloggs") fun generate( username: String, id: Long = IdGenerator.getAndIncrement() ) = StaffUser(id, username) } object LdapUserGenerator { val DEFAULT = generate(StaffUserGenerator.DEFAULT.username, "<EMAIL>") fun generate( username: String, email: String ) = LdapUser(LdapName("cn=$username"), username, email) }
7
Kotlin
0
2
de3de53279e92b0ce8ae8639fe16cc0462b329be
943
hmpps-probation-integration-services
MIT License
src/main/java/com/mineinabyss/mobzy/ecs/components/initialization/Equipment.kt
Paul1365972
327,421,137
true
{"Kotlin": 160952}
package com.mineinabyss.mobzy.ecs.components.initialization import com.mineinabyss.geary.ecs.api.autoscan.AutoscanComponent import com.mineinabyss.idofront.serialization.SerializableItemStack import kotlinx.serialization.Serializable /** * A component for adding equipment to spawned mobs. */ @Serializable @AutoscanComponent data class Equipment( val helmet: SerializableItemStack? = null, val chestplate: SerializableItemStack? = null, val leggings: SerializableItemStack? = null, val boots: SerializableItemStack? = null )
0
Kotlin
0
0
ba1cec1b06421bbfe67ea2c90bc7422a425f8a5a
546
Mobzy
MIT License
src/behavioral/mediator/ChatRoom.kt
daolq3012
96,442,903
false
null
package behavioral.mediator import java.util.* /** * Created by framgia on 10/07/2017. */ class ChatRoom { val users = arrayListOf<User>() fun sendMessage(user: User, message: String) { print("${Date()} [${user.name}]: Sending $message\n") users .filter { user != it } .forEach { receiveMessage(it, message) } } private fun receiveMessage(user: User, message: String) { print("[${user.name}]: Received $message\n") } fun addUser(user: User) { users.add(user) } }
0
Kotlin
1
5
9c0e6a5f20e8297bf10f32e92048ff8704bea43b
562
KotlinDesignPattern
Creative Commons Attribution 4.0 International
src/main/kotlin/strumbot/utils.kt
MinnDevelopment
226,680,624
false
null
/* * Copyright 2019-present <NAME> and the Strumbot 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 strumbot import dev.minn.jda.ktx.scope import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.launch import net.dv8tion.jda.api.JDA import net.dv8tion.jda.api.entities.Guild import kotlin.time.Duration // Convert role type to role id private val rankByType: MutableMap<String, String> = mutableMapOf() fun filterId(guild: Guild, id: Long) = guild.idLong == id || id == 0L fun JDA.getRoleByType(config: DiscordConfig, type: String): String { val roleName = config.ranks[type] ?: "0" if (type !in rankByType) { // Find role by name val roleId = getRolesByName(roleName, true) .firstOrNull { filterId(it.guild, config.guildId) } // filter by server id (if applicable) ?.id ?: return "0" // take id or return "0" as fallback rankByType[type] = roleId } return rankByType[type] ?: "0" } inline fun JDA.repeatUntilShutdown(rate: Duration, initDelay: Duration = rate, crossinline task: suspend CoroutineScope.() -> Unit): Job { return scope.launch { delay(initDelay) while (status != JDA.Status.SHUTDOWN) { task() delay(rate) } } }
1
Kotlin
4
9
53422fa7e3764f060e469a783a6568d09ed8c18b
1,860
strumbot
Apache License 2.0
app/src/main/java/com/stevdzasan/diaryapp/data/repository/MongoDB.kt
stevdza-san
592,279,912
false
null
package com.arzhang.mongo.repository import android.annotation.SuppressLint import android.os.Build import androidx.annotation.RequiresApi import com.arzhang.util.model.Diary import com.arzhang.lifediary.model.RequestState import com.arzhang.util.Constants.APP_ID import com.arzhang.util.toInstant import io.realm.kotlin.Realm import io.realm.kotlin.ext.query import io.realm.kotlin.log.LogLevel import io.realm.kotlin.mongodb.App import io.realm.kotlin.mongodb.sync.SyncConfiguration import io.realm.kotlin.query.Sort import io.realm.kotlin.types.RealmInstant import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.map import org.mongodb.kbson.ObjectId import java.time.LocalDateTime import java.time.LocalTime import java.time.ZoneId import java.time.ZonedDateTime object MongoDB : MongoRepository { private val app = App.create(APP_ID) private val user = app.currentUser private lateinit var realm: Realm init { configureTheRealm() } override fun configureTheRealm() { if (user != null) { val config = SyncConfiguration.Builder(user, setOf(Diary::class)) .initialSubscriptions { sub -> add( query = sub.query<Diary>("ownerId == $0", user.id), name = "User's Diaries" ) } .log(LogLevel.ALL) .build() realm = Realm.open(config) } } @SuppressLint("NewApi") override fun getAllDiaries(): Flow<Diaries> { return if (user != null) { try { realm.query<Diary>(query = "ownerId == $0", user.id) .sort(property = "date", sortOrder = Sort.DESCENDING) .asFlow() .map { result -> RequestState.Success( data = result.list.groupBy { it.date.toInstant() .atZone(ZoneId.systemDefault()) .toLocalDate() } ) } } catch (e: Exception) { flow { emit(RequestState.Error(e)) } } } else { flow { emit(RequestState.Error(UserNotAuthenticatedException())) } } } @SuppressLint("NewApi") override fun getFilteredDiaries(zonedDateTime: ZonedDateTime): Flow<Diaries> { return if (user != null) { try { realm.query<Diary>( "ownerId == $0 AND date < $1 AND date > $2", user.id, LocalDateTime.of( zonedDateTime.toLocalDate().plusDays(1), LocalTime.MIDNIGHT ).toEpochSecond(zonedDateTime.offset), LocalDateTime.of( zonedDateTime.toLocalDate(), LocalTime.MIDNIGHT ).toEpochSecond(zonedDateTime.offset), ).asFlow().map {result -> RequestState.Success( data = result.list.groupBy { it.date.toInstant() .atZone(ZoneId.systemDefault()) .toLocalDate() } ) } } catch (e: Exception) { flow { emit(RequestState.Error(e)) } } } else { flow { emit(RequestState.Error(UserNotAuthenticatedException())) } } } override fun getSelectedDiary(diaryId: ObjectId): Flow<RequestState<Diary>> { return if (user != null) { try { realm.query<Diary>(query = "_id == $0", diaryId).asFlow().map { RequestState.Success(it.list.first()) } } catch (e: Exception) { flow {emit(RequestState.Error(e))} } } else { flow { emit(RequestState.Error(UserNotAuthenticatedException())) } } } override suspend fun insertDiary(diary: Diary): RequestState<Diary> { return if (user != null) { realm.write { try { val addedDiary = copyToRealm(diary.apply { ownerId = user.id }) RequestState.Success(data = addedDiary) } catch (e: Exception) { RequestState.Error(e) } } } else { RequestState.Error(UserNotAuthenticatedException()) } } override suspend fun updateDiary(diary: Diary): RequestState<Diary> { return if (user != null) { realm.write { val queriedDiary = query<Diary>(query = "_id == $0", diary._id).first().find() if(queriedDiary != null) { queriedDiary.title = diary.title queriedDiary.description = diary.description queriedDiary.mood = diary.mood queriedDiary.images = diary.images queriedDiary.date = diary.date RequestState.Success(data = queriedDiary) } else { RequestState.Error(error = Exception("Queried Diary does not exist.")) } } } else { RequestState.Error(UserNotAuthenticatedException()) } } override suspend fun deleteDiary(id: ObjectId): RequestState<Diary> { return if (user != null) { realm.write { val diary = query<Diary>(query = "_id == $0 AND ownerId == $1", id, user.id).first().find() if(diary != null) { try { delete(diary) RequestState.Success(data = diary) } catch (e: Exception) { RequestState.Error(Exception(e)) } } else { RequestState.Error(Exception("Diary does not exist")) } } } else { RequestState.Error(UserNotAuthenticatedException()) } } override suspend fun deleteAllDiaries(): RequestState<Boolean> { return if (user != null) { realm.write { val diaries = this.query<Diary>("ownerId == $0", user.id) .find() try { delete(diaries) RequestState.Success(data=true) } catch (e: Exception) { RequestState.Error(e) } } } else { RequestState.Error(UserNotAuthenticatedException()) } } } private class UserNotAuthenticatedException : Exception("User is not Logged in.")
0
null
30
86
55b54448d80e082cbf54e324d9616896a8da8622
6,962
DiaryApp
The Unlicense
app/src/main/java/good/damn/clientsocket/utils/ByteUtils.kt
GoodDamn
780,553,871
false
{"Kotlin": 38180}
package good.damn.clientsocket.utils import java.io.ByteArrayOutputStream import java.nio.charset.Charset class ByteUtils { companion object { fun stringList( list: List<String>, charset: Charset, offset: Int = 0 ): ByteArray { val baos = ByteArrayOutputStream() val factCount = list.size - offset if (factCount == 0) { return ByteArray(0) } if (factCount != 1) { baos.write( // List count (0-255) factCount ) } for (i in offset until list.size) { val bytes = list[i].toByteArray( charset ) baos.write( // Length (0-255) bytes.size ) baos.write( // Content bytes ) } val result = baos.toByteArray() baos.close() return result } fun integer(i: Int): ByteArray { return byteArrayOf( ((i shr 24) and 0xff).toByte(), (((i shr 16) and 0xff).toByte()), ((i shr 8) and 0xff).toByte(), (i and 0xff).toByte() ) } fun integer( buf: ByteArray, off: Int ): Int { return (buf[off].toInt() and 0xff shl 24) or (buf[off+1].toInt() and 0xff shl 16) or (buf[off+2].toInt() and 0xff shl 8) or (buf[off+3].toInt() and 0xff) } } }
0
Kotlin
0
0
dcd5474810b2a15eab373214c9e04a4ed591f8d9
1,674
SocketClient
MIT License
src/main/kotlin/application/controller/manager/PatientDigitalTwinManager.kt
SmartOperatingBlock
614,385,819
false
null
/* * Copyright (c) 2023. Smart Operating Block * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ package application.controller.manager import entity.patient.Patient import entity.patient.PatientData /** This interface model the operation on Patients Digital Twins. */ interface PatientDigitalTwinManager { /** * Create the digital twin of a [Patient] given its [patientId]. */ fun createPatientDT( patientId: PatientData.PatientId, ): Patient? /** * Delete the digital twin of a [Patient] given its [patientId]. */ fun deletePatientDT( patientId: PatientData.PatientId, ): Boolean /** * Get the [Patient] tax code given its [patientId]. */ fun getPatientTaxCode( patientId: PatientData.PatientId, ): PatientData.TaxCode? }
1
Kotlin
0
1
a1db7e3a036354fe2c2c501c32f3f6b0dd218289
928
surgical-process-monitoring-microservice
MIT License
login/src/main/java/com/fuusy/login/ui/LoginActivity.kt
fuusy
362,828,165
false
null
package com.fuusy.login.ui import android.view.View import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import com.alibaba.android.arouter.facade.annotation.Route import com.alibaba.android.arouter.launcher.ARouter import com.fuusy.common.base.BaseVmActivity import com.fuusy.common.network.net.IStateObserver import com.fuusy.common.support.Constants import com.fuusy.common.support.Constants.Companion.KEY_LIVEDATA_BUS_LOGIN import com.fuusy.common.support.Constants.Companion.SP_KEY_USER_INFO_NAME import com.fuusy.common.support.LiveDataBus import com.fuusy.common.utils.SpUtils import com.fuusy.login.R import com.fuusy.login.databinding.ActivityLoginBinding import com.fuusy.login.viewmodel.LoginViewModel import com.fuusy.service.repo.LoginResp private const val TAG = "LoginActivity" @Route(path = Constants.PATH_LOGIN) class LoginActivity : BaseVmActivity<ActivityLoginBinding, LoginViewModel>() { override fun initData() { initToolbar() initListener() registerObserve() } private fun initToolbar() { mBinding?.run { setToolbarBackIcon(llToolbarLogin.ivBack, R.drawable.ic_back_clear) setToolbarTitle(llToolbarLogin.tvTitle, "登录") llToolbarLogin.ivBack.setOnClickListener { finish() } } } private fun registerObserve() { mViewModel.loginLiveData.observe(this, Observer { }) mViewModel.loginLiveData.observe(this,object :IStateObserver<LoginResp>(null){ override fun onDataChange(data: LoginResp?) { showToast("登录成功") SpUtils.put(SP_KEY_USER_INFO_NAME, data?.nickname) //DbHelper.insertUserInfo(this, it) LiveDataBus.get().with(KEY_LIVEDATA_BUS_LOGIN) .postValue(data) finish() } override fun onReload(v: View?) { TODO("Not yet implemented") } }) } private fun initListener() { mBinding?.run { tvToRegister.setOnClickListener { ARouter.getInstance().build(Constants.PATH_REGISTER) .navigation() } btLogin.setOnClickListener { mViewModel.login(etUserName.text.toString(), etPassword.text.toString()) } } } override fun getLayoutId(): Int = R.layout.activity_login override fun getViewModel(): LoginViewModel = ViewModelProviders.of(this).get(LoginViewModel::class.java) }
3
null
98
545
9582767b442ed282dddb8b1b159350d0223c7246
2,586
component-jetpack-mvvm
MIT License
app/src/main/java/com/github/nytimesnewsapp/base/presentation/BaseViewHolder.kt
Edydaoud
320,500,193
false
null
package com.github.nytimesnewsapp.base.presentation import android.view.View import androidx.recyclerview.widget.RecyclerView import com.github.nytimesnewsapp.base.presentation.model.BaseUIModel import kotlinx.android.extensions.LayoutContainer abstract class BaseViewHolder<in T : BaseUIModel>( itemView: View ) : LayoutContainer, RecyclerView.ViewHolder(itemView) { override val containerView: View? = itemView abstract fun bindView(position: Int, item: T) abstract fun bindViewPayloads(position: Int, item: T, diffSet: Set<String>) }
0
Kotlin
0
0
5ca2ca1156b37b5cff8e7a8d0daa84b70e6c5d96
557
NYTimeNews
Apache License 2.0
app/src/main/java/com/puntogris/recap/feature_recap/presentation/create_recap/CreateRecapViewModel.kt
puntogris
398,389,151
false
null
package com.puntogris.recap.feature_recap.presentation.create_recap import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.puntogris.recap.feature_recap.domain.model.Recap import com.puntogris.recap.feature_recap.domain.use_case.PublishRecapUseCase import com.puntogris.recap.feature_recap.domain.use_case.SaveRecapDraftUseCase import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import javax.inject.Inject @HiltViewModel class CreateRecapViewModel @Inject constructor( private val saveRecapDraftUseCase: SaveRecapDraftUseCase, private val publishRecapUseCase: PublishRecapUseCase ) : ViewModel() { private val _showMenu = MutableLiveData(false) val showMenu: LiveData<Boolean> = _showMenu fun toggleMenu() { _showMenu.value = !_showMenu.value!! } private val _recap = MutableStateFlow(Recap()) val recap: StateFlow<Recap> = _recap.asStateFlow() fun updateRecap(title: String, season: Int, episode: Int) { _recap.value.apply { this.title = title this.season = season this.episode = episode } } fun updateRecapBody(body: String) { _recap.value.body = body } suspend fun saveRecapLocally() = saveRecapDraftUseCase(recap.value) fun setRecap(recap: Recap) { _recap.value = recap } suspend fun publishRecap() = publishRecapUseCase(recap.value) }
0
Kotlin
0
0
960f3f6f3c876289cfc6e7edc76778af05dcdcd0
1,591
recap
MIT License
app/src/test/kotlin/pl/allegro/devskiller/domain/assessments/NotifierServiceTest.kt
Mixonn
463,822,686
false
{"Kotlin": 48184}
package pl.allegro.devskiller.domain.assessments import io.mockk.every import io.mockk.mockk import io.mockk.slot import io.mockk.verify import pl.allegro.devskiller.config.simpleJavaApplicationConfig import pl.allegro.devskiller.domain.assessments.notifier.AssessmentsInEvaluation import pl.allegro.devskiller.domain.assessments.notifier.AssessmentsNotifier import pl.allegro.devskiller.domain.assessments.notifier.AssessmentsSummary import pl.allegro.devskiller.domain.assessments.provider.AssessmentsProvider import pl.allegro.devskiller.domain.assessments.provider.assessmentAlmostTwoHoursAgo import pl.allegro.devskiller.domain.assessments.provider.assessmentOverTwoHoursAgo import pl.allegro.devskiller.domain.assessments.provider.assessmentTwoHoursAgo import pl.allegro.devskiller.domain.assessments.provider.simpleEmptyAssessmentSummary import pl.allegro.devskiller.domain.time.FixedTimeProvider.Companion.overTwoHoursAgo import pl.allegro.devskiller.domain.time.FixedTimeProvider.Companion.twoHoursAgo import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertTrue import kotlin.test.fail class NotifierServiceTest { private val provider = mockk<AssessmentsProvider>() private val notifier = mockk<AssessmentsNotifier>(relaxed = true) private val notifierService = NotifierService(notifier, provider, simpleJavaApplicationConfig()) private val assessmentsSummary = slot<AssessmentsSummary>() @Test fun `should notify when no assessments provided`() { // given no assessments provided every { provider.getAssessmentsToEvaluate() } returns listOf() // when notifierService.notifyAboutAssessmentsToCheck() // then verify(exactly = 1) { notifier.notify(capture(assessmentsSummary)) } assertTrue(assessmentsSummary.isCaptured) assessmentsSummary.captured.also { assertEquals(simpleEmptyAssessmentSummary(), it) } } @Test fun `should notify when there are assessments in evaluation`() { // given there is an assessment in evaluation val assessments = listOf(assessmentTwoHoursAgo) every { provider.getAssessmentsToEvaluate() } returns assessments // when notifierService.notifyAboutAssessmentsToCheck() // then verify(exactly = 1) { notifier.notify(capture(assessmentsSummary)) } assertTrue(assessmentsSummary.isCaptured) assessmentsSummary.captured.also { if (it !is AssessmentsInEvaluation) fail("Assessments should not be empty") assertEquals(1, it.remaining) assertEquals(twoHoursAgo, it.oldest) } } @Test fun `should notify about the oldest assessment if there are multiple of them`() { // given there are multiple assessments in evaluation val assessments = listOf(assessmentTwoHoursAgo, assessmentOverTwoHoursAgo, assessmentAlmostTwoHoursAgo) every { provider.getAssessmentsToEvaluate() } returns assessments // when notifierService.notifyAboutAssessmentsToCheck() // then notified about the oldest one of them verify(exactly = 1) { notifier.notify(capture(assessmentsSummary)) } assertTrue(assessmentsSummary.isCaptured) assessmentsSummary.captured.also { if (it !is AssessmentsInEvaluation) fail() assertEquals(3, it.remaining) assertEquals(overTwoHoursAgo, it.oldest) } } }
4
Kotlin
0
0
1bbd41bec8af3748e19e0d8673188eaf0b700e5a
3,490
devskiller-slack-plugin
Apache License 2.0
src/Day01.kt
ianredman26
572,914,381
false
null
fun main() { fun part1(input: List<String>): List<Pair<Int, Int>> { val elves: MutableMap<Int, Int> = mutableMapOf() var total = 0 input.map { total = if (it.isEmpty()) { elves[elves.size.plus(1)] = total 0 } else { total.plus(it.toInt()) } } return elves.toList().sortedByDescending { (_, value) -> value } } fun part2(input: List<Pair<Int, Int>>): Int { val total = input[0].second.plus(input[1].second).plus(input[3].second) return total } val testInput = readInput("Day01_part1") // test if implementation meets criteria from the description, like: // check(part1(testInput) == 4) // val input = readInput("Day01") println(part1(testInput)) println(part2(part1(testInput))) }
0
Kotlin
0
0
dcd9fae4531622cc974d2eb3d5ded94bf268ad1e
864
advent-of-code-2022
Apache License 2.0
native/native.tests/testData/codegen/cinterop/kt63048.kt
JetBrains
3,432,266
false
null
// TARGET_BACKEND: NATIVE // MODULE: cinterop_kt63048 // FILE: kt63048.def language = Objective-C headers = kt63048.h // FILE: kt63048.h #import "Foundation/NSString.h" #import "Foundation/NSObject.h" @interface WithClassProperty : NSObject -(instancetype) init; @property (class, readonly, copy) NSString * stringProperty; @end // FILE: kt63048.m #import "kt63048.h" @implementation WithClassProperty : NSObject -(instancetype) init {} + (NSString *) stringProperty { return @"153"; } @end // MODULE: main(cinterop_kt63048) // FILE: main.kt @file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class, kotlin.experimental.ExperimentalObjCName::class) import kt63048.* import kotlin.test.assertEquals @ObjCName("KotlinImplWithCompanionPropertyOverride") class Impl : WithClassProperty() { companion object : WithClassPropertyMeta() { override fun stringProperty(): String? = "42" } } @ObjCName("KotlinImplWithoutCompanionPropertyOverride") class ImplWithoutOverride : WithClassProperty() { companion object : WithClassPropertyMeta() { } } fun box(): String { assertEquals("42", Impl.stringProperty()) assertEquals("153", ImplWithoutOverride.stringProperty()) return "OK" }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
1,219
kotlin
Apache License 2.0
app/src/main/java/com/zzr/jetpacktest/kotlin_test/TrimDelegate.kt
zrzhong
288,220,143
false
{"Gradle Kotlin DSL": 2, "Java Properties": 2, "Gradle": 3, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Kotlin": 173, "XML": 104, "Java": 22, "HTML": 3, "INI": 1}
package com.zzr.jetpacktest.kotlin_test import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty /** * @Author zzr * @Desc * @Date 2020/9/27 */ class TrimDelegate : ReadWriteProperty<Any?, String> { private var trimmedValue: String = "" override fun getValue(thisRef: Any?, property: KProperty<*>): String { return trimmedValue } override fun setValue(thisRef: Any?, property: KProperty<*>, value: String) { trimmedValue = value.trim() } }
1
null
1
1
7765544fd6df3d615dadbe03f7df1daaac7aa1ab
502
JetpackTest
Apache License 2.0
data/src/main/java/com/eoyeongbooyeong/data/dto/response/BookMarkDto.kt
Booyoungee
819,817,364
false
{"Kotlin": 333090}
package com.eoyeongbooyeong.data.dto.response import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class BookMarkDto( @SerialName("bookmarkId") val bookmarkId: Int, )
1
Kotlin
0
1
7e78e32a86aa36af068475b0730128ce9baa03dc
224
booyoungee-android
Apache License 2.0
src/test/kotlin/br/com/zup/lucasmiguins/pix/enums/EnumTipoDeChaveTest.kt
miguins
385,259,217
true
{"Kotlin": 84040, "Smarty": 2172, "Dockerfile": 171}
package br.com.zup.lucasmiguins.pix.enums import io.micronaut.test.extensions.junit5.annotation.MicronautTest import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test @MicronautTest internal class EnumTipoDeChaveTest { @Nested inner class CPF { @Test internal fun `deve retornar false para um cpf invalido ou nao informado`() { with(EnumTipoDeChave.CPF) { assertFalse(valida(chave = "12345678")) assertFalse(valida(chave = "")) assertFalse(valida(chave = null)) } } @Test internal fun `deve retornar true para um cpf valido`() { with(EnumTipoDeChave.CPF) { assertTrue(valida(chave = "42812084022")) assertTrue(valida(chave = "428.120.840-22")) } } } @Nested inner class CELULAR { @Test fun `deve retornar true para um celular valido`() { with(EnumTipoDeChave.CELULAR) { assertTrue(valida(chave = "+55 91 912345678".replace(" ", ""))) } } @Test fun `deve retornar false para um celular invalido ou nao preenchido`() { with(EnumTipoDeChave.CELULAR) { assertFalse(valida(chave = "91912345678")) assertFalse(valida(chave = "+55abc1234")) assertFalse(valida(chave = "")) assertFalse(valida(chave = null)) } } } @Nested inner class EMAIL { @Test fun `deve retornar true para um email valido`() { with(EnumTipoDeChave.EMAIL) { assertTrue(valida(chave = "<EMAIL>")) } } @Test fun `deve retornar false para um email valido`() { with(EnumTipoDeChave.EMAIL) { assertTrue(valida(chave = "<EMAIL>")) } } } @Nested inner class ALEATORIA { @Test fun `deve retornar true quando a chave for nula ou vazia`() { with(EnumTipoDeChave.ALEATORIA) { assertTrue(valida(chave = "")) assertTrue(valida(chave = null)) } } @Test fun `deve retornar false quando a chave for preenchida`() { with(EnumTipoDeChave.ALEATORIA) { assertFalse(valida(chave = "valor")) } } } }
0
Kotlin
0
0
40b9662f4983c779a2cc88a4914e6f7e9eb1287c
2,478
orange-talents-05-template-pix-keymanager-grpc
Apache License 2.0