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
src/main/kotlin/no/nav/tilgangsmaskin/populasjonstilgangskontroll/rest/Tilgangskontroll.kt
navikt
843,415,610
false
{"Kotlin": 2033, "Dockerfile": 170}
package no.nav.tilgangsmaskin.populasjonstilgangskontroll.rest import no.nav.tilgangsmaskin.populasjonstilgangskontroll.service.TilgangsService import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController @RestController @RequestMapping("/api/v1") class Tilgangskontroll { val tilgangsService = TilgangsService() @PostMapping("sjekkTilgang") fun sjekkTilgang(brukerIdent: String): String { val harTilgang = tilgangsService.validerTilgang(brukerIdent) return harTilgang.toString() } }
0
Kotlin
0
0
4c1437929d190d281601ae8b68e534459c7b33a4
642
populasjonstilgangskontroll
MIT License
app/src/main/java/com/hitanshudhawan/popcorn2/network/ApiKeyInterceptor.kt
hitanshu-dhawan
214,371,969
false
null
package com.hitanshudhawan.popcorn2.network import okhttp3.Interceptor import okhttp3.Response class ApiKeyInterceptor(private val apiKey: String) : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val originalRequest = chain.request() val originalUrl = originalRequest.url() val newRequest = originalRequest.newBuilder() .url( originalUrl.newBuilder() .addQueryParameter("api_key", apiKey) .build() ) .build() return chain.proceed(newRequest) } }
3
null
4
20
b6b6ca8051ba3b2b50fb908a5c1e68d281454a5d
611
PopCorn2
Apache License 2.0
bittrader-candle-api/src/main/kotlin/org/kentunc/bittrader/candle/api/BittraderCandleApiApplication.kt
ken-tunc
430,691,495
false
null
package org.kentunc.bittrader.candle.api import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication @SpringBootApplication class BittraderCandleApiApplication fun main(args: Array<String>) { runApplication<BittraderCandleApiApplication>(*args) }
2
Kotlin
0
0
757c83fd604e5758a5e67bbfd98b33c1d9cc1961
309
bittrader
MIT License
android/src/main/java/com/jpiasecki/spatialsdk/ScaleView.kt
j-piasecki
868,164,718
false
{"Kotlin": 44340, "TypeScript": 15591, "Ruby": 3166, "Objective-C": 2527, "JavaScript": 1429, "Objective-C++": 1204, "C": 103, "Swift": 62}
package com.jpiasecki.spatialsdk import com.facebook.react.bridge.ReactContext import com.facebook.react.views.view.ReactViewGroup import com.meta.spatial.core.Vector3 import com.meta.spatial.toolkit.Scale class ScaleView(reactContext: ReactContext) : ReactViewGroup(reactContext), ComponentHolder { override var component = Scale(1f) private set fun setScale(x: Float, y: Float, z: Float) = tryReattachAfter { component.scale = Vector3(x, y, z) } override fun onAttachedToWindow() = tryReattachAfter { super.onAttachedToWindow() } override fun onDetachedFromWindow() { tryReattachAfter { component = Scale(1f) } super.onDetachedFromWindow() } }
0
Kotlin
0
6
b1b15e35935e24f1b70a790beca04710285860ee
700
react-native-spatial-sdk
MIT License
kotlin-mui-icons/src/main/generated/mui/icons/material/DensitySmallRounded.kt
JetBrains
93,250,841
false
null
// Automatically generated - do not modify! @file:JsModule("@mui/icons-material/DensitySmallRounded") @file:JsNonModule package mui.icons.material @JsName("default") external val DensitySmallRounded: SvgIconComponent
10
Kotlin
5
983
7ef1028ba3e0982dc93edcdfa6ee1edb334ddf35
220
kotlin-wrappers
Apache License 2.0
src/main/kotlin/me/xiaozhangup/ostrich/OstrichPlayer.kt
xiaozhangup
841,522,776
false
{"Kotlin": 13980, "Shell": 128}
package me.xiaozhangup.ostrich import me.xiaozhangup.ostrich.video.ImageResizer import me.xiaozhangup.ostrich.video.ImageToColorBlockConverter import me.xiaozhangup.ostrich.video.VideoFrameExtractor import net.kyori.adventure.text.Component import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer import org.bukkit.command.CommandSender import org.bukkit.entity.Display import org.bukkit.entity.EntityType import org.bukkit.entity.Player import org.bukkit.entity.TextDisplay import taboolib.common.env.RuntimeDependencies import taboolib.common.env.RuntimeDependency import taboolib.common.io.newFile import taboolib.common.platform.Plugin import taboolib.common.platform.command.PermissionDefault import taboolib.common.platform.command.command import taboolib.common.platform.function.getDataFolder import taboolib.common.platform.function.submit import taboolib.common.platform.function.submitAsync import java.io.File @RuntimeDependencies( RuntimeDependency( "ink.pmc.advkt:core:1.0.0", test = "ink.pmc.advkt.sound.SoundKt", relocate = ["!kotlin.", "!kotlin1822."], repository = "https://maven.nostal.ink/repository/maven-public", transitive = false ) ) object OstrichPlayer : Plugin() { private val videoDir by lazy { newFile( getDataFolder(), "video", folder = true ) } private val cacheDir by lazy { newFile( getDataFolder(), "cache", folder = true ) } private val cache: MutableMap<String, List<Component>> = mutableMapOf() override fun onEnable() { videoDir cacheDir.listFiles()?.forEach { it.delete() } command("play") { dynamic { suggestion<CommandSender> { _, _ -> getDataFolder().listFiles()?.filter { it.name.endsWith(".cideo") }?.map { it.name }?.toList() ?: emptyList() } execute<Player> { sender, _, arg -> submitAsync { val cached = cache[arg] val frames = if (cached != null) { sender.sendMessage("视频文件已缓存") cached } else { val video = File(getDataFolder(), arg) sender.sendMessage("正在加载视频文件中...") val frames = video.readLines().map { GsonComponentSerializer.gson().deserialize(it) } sender.sendMessage("视频文件加载完成") cache[arg] = frames frames }.toMutableList() submit { val entity = sender.world.spawnEntity( sender.location.apply { yaw = 0f pitch = 0f }, EntityType.TEXT_DISPLAY ).apply { this as TextDisplay isShadowed = true lineWidth = Int.MAX_VALUE alignment = TextDisplay.TextAlignment.CENTER billboard = Display.Billboard.VERTICAL } as TextDisplay sender.sendMessage("视频开始播放") playerVideo(frames, entity, true) } } } } } command("video", permissionDefault = PermissionDefault.TRUE) { literal("extractor") { dynamic { suggestion<CommandSender> { _, _ -> videoDir.listFiles()?.map { it.name }?.toList() ?: emptyList() } execute<CommandSender> { sender, _, args -> submitAsync { val video = File(videoDir, args) if (video.exists()) { VideoFrameExtractor.extractFrames( video, File(cacheDir, video.nameWithoutExtension + "_frames") ) } else { sender.sendMessage("视频文件不存在") } } } } } literal("resize") { dynamic("x") { dynamic("y") { dynamic("file") { suggestion<CommandSender> { _, _ -> cacheDir.listFiles()?.map { it.name }?.toList() ?: emptyList() } execute<CommandSender> { sender, args, _ -> submitAsync { val x = args["x"].toInt() val y = args["y"].toInt() ImageResizer.resizeImages( File(cacheDir, args["file"]), File(cacheDir, args["file"] + "_${x}_${y}_resize"), x, y ) sender.sendMessage("图片已缩放") } } } } } } literal("convert") { dynamic("file") { suggestion<CommandSender> { _, _ -> cacheDir.listFiles()?.map { it.name }?.toList() ?: emptyList() } execute<CommandSender> { sender, args, _ -> submitAsync { val file = File(cacheDir, args["file"]) ImageToColorBlockConverter.convertImagesToColorBlocksList( file, 2, newFile( getDataFolder(), "${file.name}.cideo" ) ) sender.sendMessage("图片已转换") } } } } } } private fun playerVideo( frames: MutableList<Component>, entity: TextDisplay, repeat: Boolean ) { var clone = frames.toMutableList() submit(period = 1) { if (clone.isEmpty()) { if (repeat) { clone = frames.toMutableList() } else { entity.remove() cancel() return@submit } } entity.text(clone.removeFirst()) } } }
0
Kotlin
0
0
87897e32e432a4abbc98f6d7d57f5cbb4735ff02
7,384
OstrichPlayer
Creative Commons Zero v1.0 Universal
client/src/main/java/com/bookstore/repository/TransactionRepository.kt
ezralazuardy
271,148,211
false
null
package com.bookstore.repository import com.bookstore.dao.remote.RemoteTransactionDAO import com.bookstore.model.request.transaction.CheckoutRequest import com.bookstore.model.request.transaction.PaymentRequest import com.bookstore.model.response.transaction.Transaction import com.bookstore.utils.SessionHelper import com.bookstore.utils.SessionHelper.asBearer class TransactionRepository( private val userRepository: UserRepository, private val transactionDAO: RemoteTransactionDAO ) { suspend fun performCheckout(checkoutRequest: CheckoutRequest) : Transaction = userRepository.checkSession().let { if (it != null) return transactionDAO.performCheckout(it.asBearer(), checkoutRequest) else throw SessionHelper.unauthorizedException } suspend fun performPayment(paymentRequest: PaymentRequest): Transaction = userRepository.checkSession().let { if (it != null) return transactionDAO.performPayment(it.asBearer(), paymentRequest) else throw SessionHelper.unauthorizedException } suspend fun getCheckoutHistory(): List<Transaction> = userRepository.checkSession().let { if (it != null) return transactionDAO.getCheckoutHistory(it.asBearer()) else throw SessionHelper.unauthorizedException } }
0
Kotlin
0
7
d2f7dce513588e1797fa379bf43b70ec87759f29
1,317
bookstore
MIT License
sheetselection/src/main/java/com/khoben/sheetselection/SelectionDiffCallback.kt
khoben
405,875,392
false
null
package com.khoben.sheetselection import androidx.recyclerview.widget.DiffUtil class SelectionDiffCallback( private val oldList: List<SheetSelectionItem>, private val newList: List<SheetSelectionItem> ) : DiffUtil.Callback() { override fun getOldListSize(): Int = oldList.size override fun getNewListSize(): Int = newList.size override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return oldList[oldItemPosition].key == newList[newItemPosition].key } override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return oldList[oldItemPosition].isChecked == newList[newItemPosition].isChecked } }
0
Kotlin
0
0
eeb0085cfb1cb91982d1d06f93cfdc51288abaa9
705
sheetselection
MIT License
mobile_app/src/main/kotlin/dev/marlonlom/apps/bookbar/settings/SettingsFragment.kt
marlonlom
384,998,032
false
null
/* * Copyright (c) 2021 marlonlom. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.marlonlom.apps.bookbar.settings import android.os.Bundle import androidx.appcompat.app.AppCompatDelegate import androidx.core.content.edit import androidx.preference.ListPreference import androidx.preference.PreferenceFragmentCompat import dev.marlonlom.apps.bookbar.R import dev.marlonlom.apps.bookbar.utils.ThemeManager import timber.log.Timber /** * Application settings fragment class. * * @author marlonlom */ class SettingsFragment : PreferenceFragmentCompat() { override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { setPreferencesFromResource(R.xml.bookbar_preferences, rootKey) setupThemeSelectionList(findPreference("preference_key_dark_theme")!!) } private fun setupThemeSelectionList(themePreference: ListPreference) { Timber.d("setupThemeSelectionList") themePreference.setDefaultValue( themePreference.sharedPreferences.getString( "pref_theme_value", "default" ) ) themePreference.setOnPreferenceChangeListener { preference, newValue -> Timber.d("themePreference.setOnPreferenceChangeListener(${preference.key}, $newValue)") val themeModesArray = requireContext().resources.getStringArray(R.array.entry_values_for_dark_theme_setting) val selectedDefaultValue = ThemeManager.getSelectedDefaultValue(themeModesArray, newValue.toString()) val selectedUiMode = ThemeManager.getSelectedUiMode(themeModesArray, newValue.toString()) preference.preferenceManager.sharedPreferences.edit(commit = true) { putString("pref_theme_value", selectedDefaultValue) } Timber.d("Values(selectedDefaultValue=$selectedDefaultValue, selectedUiMode=$selectedUiMode)") preference.setDefaultValue(selectedDefaultValue) AppCompatDelegate.setDefaultNightMode(selectedUiMode) requireActivity().recreate() true } } }
0
Kotlin
0
0
7a8d956a136d3eb93e1813a9cbfed466052e6330
2,674
bookbar
Apache License 2.0
feature/wallpaper-picker/data/src/main/kotlin/ru/maksonic/beresta/feature/wallpaper_picker/data/store/WallpapersStore.kt
maksonic
580,058,579
false
{"Kotlin": 1587340, "Assembly": 374}
package ru.maksonic.beresta.feature.wallpaper_picker.data.store import androidx.compose.ui.graphics.Color import ru.maksonic.beresta.feature.wallpaper_picker.data.store.gradient.WallpaperGradientsStore import ru.maksonic.beresta.feature.wallpaper_picker.data.store.texture.WallpaperTexturesStore import ru.maksonic.beresta.feature.wallpaper_picker.domain.WallpaperParams import ru.maksonic.beresta.feature.wallpaper_picker.domain.WallpaperType import ru.maksonic.beresta.feature.wallpaper_picker.domain.WallpapersDataContainer import ru.maksonic.beresta.feature.wallpaper_picker.domain.wallpaper.BaseWallpaper import ru.maksonic.beresta.feature.wallpaper_picker.domain.wallpaper.WallpaperGradient /** * @Author maksonic on 30.10.2023 */ class WallpapersStore( private val colorsStore: WallpaperColorsStore, private val gradientsStore: WallpaperGradientsStore, private val texturesStore: WallpaperTexturesStore, private val imagesStore: WallpaperImagesStore ) { fun fetchAllWallpapers() = WallpapersDataContainer( colorsStore.data, gradientsStore.data, texturesStore.data, imagesStore.data ) fun fetchWallpaperColors() = colorsStore.data fun fetchWallpaperGradients(): List<WallpaperGradient<Color>> = gradientsStore.data fun fetchWallpaperTextures() = texturesStore.data fun fetchWallpaperImages() = imagesStore.data fun fetchTexturesReadyStyles() = texturesStore.styles fun fetchTexturesTintColors() = texturesStore.tintColors fun fetchTexturesBackgroundColors() = texturesStore.backgroundColors fun findWallpaper(params: WallpaperParams): BaseWallpaper<Color> = when (params.type) { WallpaperType.Value.COLOR -> colorsStore.findByParams(params) WallpaperType.Value.GRADIENT -> gradientsStore.findByParams(params) WallpaperType.Value.TEXTURE -> texturesStore.findByParams(params) WallpaperType.Value.IMAGE -> imagesStore.findByParams(params) else -> BaseWallpaper.empty() } }
0
Kotlin
0
0
d9a53cc50c6e149923fc5bc6fc2c38013bfadb9d
1,996
Beresta
MIT License
matrix-sdk-android/src/test/java/org/matrix/android/sdk/test/fakes/FakeWorkManagerProvider.kt
tchapgouv
340,329,238
false
null
/* * Copyright (c) 2022 The Matrix.org Foundation C.I.C. * * 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.matrix.android.sdk.test.fakes import io.mockk.every import io.mockk.mockk import org.matrix.android.sdk.internal.di.WorkManagerProvider internal class FakeWorkManagerProvider( val fakeWorkManager: FakeWorkManager = FakeWorkManager(), ) { val instance = mockk<WorkManagerProvider>().also { every { it.workManager } returns fakeWorkManager.instance every { it.tag } returns "Tag" } }
91
null
6
9
a2c060c687b0aa69af681138c5788d6933d19860
1,050
tchap-android
Apache License 2.0
domain/src/main/java/pl/kubisiak/dataflow/models/FavouritePosts.kt
szymonkubisiak
222,223,106
false
null
package pl.kubisiak.dataflow.models data class FavouritePosts(val favPostid: Post.ID?)
0
Kotlin
0
0
d498fe5d18d7a02b87e8240a0429a32de2845614
87
demo-android
MIT License
shared/src/commonMain/kotlin/com/prof18/feedflow/shared/domain/feed/retriever/FeedRetrieverRepository.kt
prof18
600,257,020
false
{"Kotlin": 746513, "HTML": 182777, "Swift": 163455, "SCSS": 161629, "CSS": 16810, "Shell": 2392, "JavaScript": 1214}
package com.prof18.feedflow.shared.domain.feed.retriever import co.touchlab.kermit.Logger import com.prof18.feedflow.core.model.FeedFilter import com.prof18.feedflow.core.model.FeedItem import com.prof18.feedflow.core.model.FeedItemId import com.prof18.feedflow.core.model.FeedSource import com.prof18.feedflow.core.model.FeedSourceCategory import com.prof18.feedflow.core.model.ParsedFeedSource import com.prof18.feedflow.core.utils.DispatcherProvider import com.prof18.feedflow.database.DatabaseHelper import com.prof18.feedflow.db.Search import com.prof18.feedflow.feedsync.database.domain.toFeedSource import com.prof18.feedflow.shared.data.SettingsHelper import com.prof18.feedflow.shared.domain.DateFormatter import com.prof18.feedflow.shared.domain.feed.FeedSourceLogoRetriever import com.prof18.feedflow.shared.domain.feed.FeedUrlRetriever import com.prof18.feedflow.shared.domain.feedsync.FeedSyncRepository import com.prof18.feedflow.shared.domain.mappers.RssChannelMapper import com.prof18.feedflow.shared.domain.mappers.toFeedItem import com.prof18.feedflow.shared.domain.model.AddFeedResponse import com.prof18.feedflow.shared.domain.model.FeedUpdateStatus import com.prof18.feedflow.shared.domain.model.FinishedFeedUpdateStatus import com.prof18.feedflow.shared.domain.model.InProgressFeedUpdateStatus import com.prof18.feedflow.shared.domain.model.NoFeedSourcesStatus import com.prof18.feedflow.shared.domain.model.StartedFeedUpdateStatus import com.prof18.feedflow.shared.presentation.model.DatabaseError import com.prof18.feedflow.shared.presentation.model.ErrorState import com.prof18.feedflow.shared.presentation.model.FeedErrorState import com.prof18.feedflow.shared.utils.executeWithRetry import com.prof18.feedflow.shared.utils.getNumberOfConcurrentParsingRequests import com.prof18.rssparser.RssParser import com.prof18.rssparser.model.RssChannel import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf import kotlinx.collections.immutable.toImmutableList import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flatMapMerge import kotlinx.coroutines.flow.update import kotlinx.coroutines.withContext @OptIn(ExperimentalCoroutinesApi::class) internal class FeedRetrieverRepository( private val parser: RssParser, private val databaseHelper: DatabaseHelper, private val dispatcherProvider: DispatcherProvider, private val logger: Logger, private val dateFormatter: DateFormatter, private val settingsHelper: SettingsHelper, private val feedSourceLogoRetriever: FeedSourceLogoRetriever, private val rssChannelMapper: RssChannelMapper, private val feedUrlRetriever: FeedUrlRetriever, private val feedSyncRepository: FeedSyncRepository, ) { private val updateMutableState: MutableStateFlow<FeedUpdateStatus> = MutableStateFlow( FinishedFeedUpdateStatus, ) val updateState = updateMutableState.asStateFlow() private val errorMutableState: MutableStateFlow<ErrorState?> = MutableStateFlow(null) val errorState = errorMutableState.asStateFlow() private val feedToUpdate = hashSetOf<String>() private val mutableFeedState: MutableStateFlow<ImmutableList<FeedItem>> = MutableStateFlow(persistentListOf()) val feedState = mutableFeedState.asStateFlow() private val currentFeedFilterMutableState: MutableStateFlow<FeedFilter> = MutableStateFlow(FeedFilter.Timeline) val currentFeedFilter: StateFlow<FeedFilter> = currentFeedFilterMutableState.asStateFlow() private var currentPage: Int = 0 private var isFeedSyncDone = true private val knownUrlSuffix = listOf( "", "feed", "rss", "atom.xml", "feed.xml", "rss.xml", "index.xml", "atom.json", "feed.json", "rss.json", "index.json", ) suspend fun getFeeds() { try { val feeds = executeWithRetry { databaseHelper.getFeedItems( feedFilter = currentFeedFilterMutableState.value, pageSize = PAGE_SIZE, offset = 0, showReadItems = settingsHelper.getShowReadArticlesTimeline(), ) } currentPage = 1 mutableFeedState.update { feeds.map { it.toFeedItem(dateFormatter) }.toImmutableList() } } catch (e: Throwable) { logger.e(e) { "Something wrong while getting data from Database" } errorMutableState.update { DatabaseError } } } suspend fun loadMoreFeeds() { // Stop loading if there are no more items if (mutableFeedState.value.size % PAGE_SIZE != 0L) { return } try { val feeds = executeWithRetry { databaseHelper.getFeedItems( feedFilter = currentFeedFilterMutableState.value, pageSize = PAGE_SIZE, offset = currentPage * PAGE_SIZE, showReadItems = settingsHelper.getShowReadArticlesTimeline(), ) } currentPage += 1 mutableFeedState.update { currentItems -> val newList = feeds.map { it.toFeedItem(dateFormatter) }.toImmutableList() (currentItems + newList).toImmutableList() } } catch (e: Throwable) { logger.e(e) { "Something wrong while getting data from Database" } errorMutableState.update { DatabaseError } } } suspend fun updateFeedFilter(feedFilter: FeedFilter) { currentFeedFilterMutableState.update { feedFilter } getFeeds() } fun getUnreadFeedCountFlow(): Flow<Long> = currentFeedFilter.flatMapLatest { feedFilter -> databaseHelper.getUnreadFeedCountFlow( feedFilter = feedFilter, ) } suspend fun clearReadFeeds() { getFeeds() } suspend fun markAsRead(itemsToUpdates: HashSet<FeedItemId>) { mutableFeedState.update { currentItems -> currentItems.map { feedItem -> if (FeedItemId(feedItem.id) in itemsToUpdates) { feedItem.copy(isRead = true) } else { feedItem } }.toImmutableList() } databaseHelper.markAsRead(itemsToUpdates.toList()) feedSyncRepository.setIsSyncUploadRequired() } suspend fun fetchFeeds( forceRefresh: Boolean = false, isFirstLaunch: Boolean = false, ) { return withContext(dispatcherProvider.io) { updateMutableState.update { StartedFeedUpdateStatus } feedSyncRepository.syncFeedSources() val feedSourceUrls = databaseHelper.getFeedSources() feedToUpdate.clear() feedToUpdate.addAll(feedSourceUrls.map { it.url }) if (feedSourceUrls.isEmpty()) { updateMutableState.update { NoFeedSourcesStatus } } else { updateMutableState.emit( InProgressFeedUpdateStatus( refreshedFeedCount = 0, totalFeedCount = feedSourceUrls.size, ), ) if (!isFirstLaunch) { getFeeds() } isFeedSyncDone = false parseFeeds( feedSourceUrls = feedSourceUrls, forceRefresh = forceRefresh, ) feedSyncRepository.syncFeedItems() isFeedSyncDone = true updateRefreshCount() getFeeds() } } } suspend fun markAllFeedAsRead() { val currentFilter = currentFeedFilterMutableState.value databaseHelper.markAllFeedAsRead(currentFilter) feedSyncRepository.setIsSyncUploadRequired() getFeeds() } suspend fun fetchSingleFeed( url: String, category: FeedSourceCategory?, ): AddFeedResponse = withContext(dispatcherProvider.io) { val addResult = guessLinkAndParseFeed(url) ?: return@withContext AddFeedResponse.NotRssFeed val rssChannel = addResult.channel val urlToSave = addResult.usedUrl logger.d { "<- Got back ${rssChannel.title}" } val title = rssChannel.title if (title != null) { val logoUrl = feedSourceLogoRetriever.getFeedSourceLogoUrl(rssChannel) val parsedFeedSource = ParsedFeedSource( id = urlToSave.hashCode().toString(), url = urlToSave, title = title, category = category, logoUrl = logoUrl, ) return@withContext AddFeedResponse.FeedFound( rssChannel = rssChannel, parsedFeedSource = parsedFeedSource, ) } else { return@withContext AddFeedResponse.EmptyFeed } } suspend fun addFeedSource(feedFound: AddFeedResponse.FeedFound) = withContext(dispatcherProvider.io) { val rssChannel = feedFound.rssChannel val parsedFeedSource = feedFound.parsedFeedSource val currentTimestamp = dateFormatter.currentTimeMillis() val feedSource = FeedSource( id = parsedFeedSource.url.hashCode().toString(), url = parsedFeedSource.url, title = parsedFeedSource.title, lastSyncTimestamp = currentTimestamp, category = parsedFeedSource.category, logoUrl = parsedFeedSource.logoUrl, ) val feedItems = rssChannelMapper.getFeedItems( rssChannel = rssChannel, feedSource = feedSource, ) databaseHelper.insertFeedSource( listOf( parsedFeedSource, ), ) databaseHelper.insertFeedItems(feedItems, currentTimestamp) feedSyncRepository.insertSyncedFeedSource(listOf(parsedFeedSource.toFeedSource())) feedSyncRepository.performBackup() updateMutableState.update { FinishedFeedUpdateStatus } getFeeds() } @Suppress("MagicNumber") suspend fun deleteOldFeeds() { // One week // (((1 hour in seconds) * 24 hours) * 7 days) val oneWeekInMillis = (((60 * 60) * 24) * 7) * 1000L val threshold = dateFormatter.currentTimeMillis() - oneWeekInMillis val oldFeedIds = databaseHelper.getOldFeedItem(threshold) databaseHelper.deleteOldFeedItems(threshold) feedSyncRepository.deleteFeedItems(oldFeedIds) getFeeds() } suspend fun updateBookmarkStatus(feedItemId: FeedItemId, isBookmarked: Boolean) { mutableFeedState.update { currentItems -> currentItems.mapNotNull { feedItem -> if (feedItem.id == feedItemId.id) { if (currentFeedFilter.value == FeedFilter.Bookmarks && !isBookmarked) { null } else { feedItem.copy(isBookmarked = isBookmarked) } } else { feedItem } }.toImmutableList() } databaseHelper.updateBookmarkStatus(feedItemId, isBookmarked) feedSyncRepository.setIsSyncUploadRequired() } suspend fun updateReadStatus(feedItemId: FeedItemId, isRead: Boolean) { mutableFeedState.update { currentItems -> currentItems.mapNotNull { feedItem -> if (feedItem.id == feedItemId.id) { if (currentFeedFilter.value == FeedFilter.Read && !isRead) { null } else { feedItem.copy(isRead = isRead) } } else { feedItem } }.toImmutableList() } databaseHelper.updateReadStatus(feedItemId, isRead) feedSyncRepository.setIsSyncUploadRequired() } private suspend fun parseFeeds( feedSourceUrls: List<FeedSource>, forceRefresh: Boolean, ) = feedSourceUrls .mapNotNull { feedSource -> val shouldRefresh = shouldRefreshFeed(feedSource, forceRefresh) if (shouldRefresh) { feedSource } else { logger.d { "One hour is not passed, skipping: ${feedSource.url}}" } feedToUpdate.remove(feedSource.url) updateRefreshCount() null } } .asFlow() .flatMapMerge(concurrency = getNumberOfConcurrentParsingRequests()) { feedSource -> suspend { logger.d { "-> Getting ${feedSource.url}" } try { val rssChannel = parser.getRssChannel(feedSource.url) logger.d { "<- Got back ${rssChannel.title}" } feedToUpdate.remove(feedSource.url) updateRefreshCount() val items = rssChannelMapper.getFeedItems( rssChannel = rssChannel, feedSource = feedSource, ) databaseHelper.insertFeedItems(items, dateFormatter.currentTimeMillis()) } catch (e: Throwable) { logger.e(e) { "Something went wrong, skipping: ${feedSource.url}}" } errorMutableState.update { FeedErrorState( failingSourceName = feedSource.title, ) } feedToUpdate.remove(feedSource.url) updateRefreshCount() } }.asFlow() }.collect() fun search(query: String): Flow<List<Search>> = databaseHelper.search( searchQuery = query, ) @Suppress("MagicNumber") private fun shouldRefreshFeed( feedSource: FeedSource, forceRefresh: Boolean, ): Boolean { val lastSyncTimestamp = feedSource.lastSyncTimestamp val oneHourInMillis = (60 * 60) * 1000 val currentTime = dateFormatter.currentTimeMillis() return forceRefresh || lastSyncTimestamp == null || currentTime - lastSyncTimestamp >= oneHourInMillis } private fun updateRefreshCount() { updateMutableState.update { oldUpdate -> val refreshedFeedCount = oldUpdate.refreshedFeedCount + 1 val totalFeedCount = oldUpdate.totalFeedCount if (feedToUpdate.isEmpty() && isFeedSyncDone) { FinishedFeedUpdateStatus } else { InProgressFeedUpdateStatus( refreshedFeedCount = refreshedFeedCount, totalFeedCount = totalFeedCount, ) } } } private fun String.buildUrl(originalUrl: String) = if (originalUrl.endsWith("/")) { "$originalUrl$this" } else { "$originalUrl/$this" } private suspend fun guessLinkAndParseFeed(originalUrl: String): AddResult? { for (suffix in knownUrlSuffix) { val actualUrl = suffix.buildUrl(originalUrl) logger.d { "Trying with actualUrl: $actualUrl" } try { val channel = parser.getRssChannel(actualUrl) return AddResult( channel = channel, usedUrl = actualUrl, ) } catch (_: Throwable) { // Do nothing } } logger.d { "Trying to get: $originalUrl" } val url = feedUrlRetriever.getFeedUrl(originalUrl) ?: return null logger.d { "Found url: $url" } return try { val channel = parser.getRssChannel(url) AddResult( channel = channel, usedUrl = url, ) } catch (_: Throwable) { // Do nothing null } } private data class AddResult( val channel: RssChannel, val usedUrl: String, ) private companion object { private const val PAGE_SIZE = 40L } }
27
Kotlin
18
332
60c15c24c157e46625e05158c5d048d4ca4b7217
16,952
feed-flow
Apache License 2.0
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/outline/Externaldrive.kt
Tlaster
560,394,734
false
{"Kotlin": 25133302}
package moe.tlaster.icons.vuesax.vuesaxicons.outline 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 moe.tlaster.icons.vuesax.vuesaxicons.OutlineGroup public val OutlineGroup.Externaldrive: ImageVector get() { if (_externaldrive != null) { return _externaldrive!! } _externaldrive = Builder(name = "Externaldrive", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(16.0f, 22.75f) horizontalLineTo(9.0f) curveTo(5.56f, 22.75f, 3.25f, 20.44f, 3.25f, 17.0f) verticalLineTo(7.0f) curveTo(3.25f, 3.56f, 5.56f, 1.25f, 9.0f, 1.25f) horizontalLineTo(16.0f) curveTo(19.44f, 1.25f, 21.75f, 3.56f, 21.75f, 7.0f) verticalLineTo(17.0f) curveTo(21.75f, 20.44f, 19.44f, 22.75f, 16.0f, 22.75f) close() moveTo(9.0f, 2.75f) curveTo(6.42f, 2.75f, 4.75f, 4.42f, 4.75f, 7.0f) verticalLineTo(17.0f) curveTo(4.75f, 19.58f, 6.42f, 21.25f, 9.0f, 21.25f) horizontalLineTo(16.0f) curveTo(18.58f, 21.25f, 20.25f, 19.58f, 20.25f, 17.0f) verticalLineTo(7.0f) curveTo(20.25f, 4.42f, 18.58f, 2.75f, 16.0f, 2.75f) horizontalLineTo(9.0f) close() } path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(21.0f, 15.75f) horizontalLineTo(4.0f) curveTo(3.59f, 15.75f, 3.25f, 15.41f, 3.25f, 15.0f) curveTo(3.25f, 14.59f, 3.59f, 14.25f, 4.0f, 14.25f) horizontalLineTo(21.0f) curveTo(21.41f, 14.25f, 21.75f, 14.59f, 21.75f, 15.0f) curveTo(21.75f, 15.41f, 21.41f, 15.75f, 21.0f, 15.75f) close() } path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(8.0f, 12.75f) horizontalLineTo(7.0f) curveTo(6.59f, 12.75f, 6.25f, 12.41f, 6.25f, 12.0f) curveTo(6.25f, 11.59f, 6.59f, 11.25f, 7.0f, 11.25f) horizontalLineTo(8.0f) curveTo(8.41f, 11.25f, 8.75f, 11.59f, 8.75f, 12.0f) curveTo(8.75f, 12.41f, 8.41f, 12.75f, 8.0f, 12.75f) close() } path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(8.0f, 10.25f) horizontalLineTo(7.0f) curveTo(6.59f, 10.25f, 6.25f, 9.91f, 6.25f, 9.5f) curveTo(6.25f, 9.09f, 6.59f, 8.75f, 7.0f, 8.75f) horizontalLineTo(8.0f) curveTo(8.41f, 8.75f, 8.75f, 9.09f, 8.75f, 9.5f) curveTo(8.75f, 9.91f, 8.41f, 10.25f, 8.0f, 10.25f) close() } path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(8.0f, 7.75f) horizontalLineTo(7.0f) curveTo(6.59f, 7.75f, 6.25f, 7.41f, 6.25f, 7.0f) curveTo(6.25f, 6.59f, 6.59f, 6.25f, 7.0f, 6.25f) horizontalLineTo(8.0f) curveTo(8.41f, 6.25f, 8.75f, 6.59f, 8.75f, 7.0f) curveTo(8.75f, 7.41f, 8.41f, 7.75f, 8.0f, 7.75f) close() } path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(17.0f, 19.4999f) curveTo(16.74f, 19.4999f, 16.48f, 19.3899f, 16.29f, 19.2099f) curveTo(16.11f, 19.0199f, 16.0f, 18.7599f, 16.0f, 18.4999f) curveTo(16.0f, 18.2299f, 16.11f, 17.9799f, 16.29f, 17.7899f) curveTo(16.57f, 17.5099f, 17.01f, 17.4199f, 17.38f, 17.5799f) curveTo(17.5f, 17.6299f, 17.61f, 17.6999f, 17.71f, 17.7899f) curveTo(17.89f, 17.9799f, 18.0f, 18.2399f, 18.0f, 18.4999f) curveTo(18.0f, 18.7599f, 17.89f, 19.0199f, 17.71f, 19.2099f) curveTo(17.61f, 19.2999f, 17.51f, 19.3699f, 17.38f, 19.4199f) curveTo(17.26f, 19.4699f, 17.13f, 19.4999f, 17.0f, 19.4999f) close() } } .build() return _externaldrive!! } private var _externaldrive: ImageVector? = null
0
Kotlin
0
2
b8a8231e6637c2008f675ae76a3423b82ee53950
5,999
VuesaxIcons
MIT License
platform/vcs-impl/src/com/intellij/openapi/vcs/checkin/ReformatBeforeCheckinHandler.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.checkin import com.intellij.codeInsight.actions.AbstractLayoutCodeProcessor import com.intellij.codeInsight.actions.ReformatCodeProcessor import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.CheckinProjectPanel import com.intellij.openapi.vcs.VcsBundle.message import com.intellij.openapi.vcs.VcsConfiguration import com.intellij.openapi.vcs.changes.CommitContext import com.intellij.openapi.vcs.changes.ui.BooleanCommitOption import com.intellij.openapi.vcs.checkin.CheckinHandlerUtil.getPsiFiles import com.intellij.openapi.vcs.ui.RefreshableOnComponent import com.intellij.psi.formatter.FormatterUtil.getReformatBeforeCommitCommandName import com.intellij.vcs.commit.isBackgroundCommitChecks import com.intellij.vcs.commit.isNonModalCommit open class ReformatCheckinHandlerFactory : CheckinHandlerFactory() { override fun createHandler(panel: CheckinProjectPanel, commitContext: CommitContext): CheckinHandler = if (isBackgroundCommitChecks() && panel.isNonModalCommit) BackgroundReformatCheckinHandler(panel) else ReformatBeforeCheckinHandler(panel.project, panel) } open class ReformatBeforeCheckinHandler( @JvmField protected val myProject: Project, private val panel: CheckinProjectPanel ) : CheckinHandler(), CheckinMetaHandler { private val settings get() = VcsConfiguration.getInstance(myProject) override fun getBeforeCheckinConfigurationPanel(): RefreshableOnComponent = BooleanCommitOption(panel, message("checkbox.checkin.options.reformat.code"), true, settings::REFORMAT_BEFORE_PROJECT_COMMIT) override fun runCheckinHandlers(runnable: Runnable) { val saveAndContinue = { FileDocumentManager.getInstance().saveAllDocuments() runnable.run() } if (settings.REFORMAT_BEFORE_PROJECT_COMMIT && !DumbService.isDumb(myProject)) { ReformatCodeProcessor(myProject, getPsiFiles(myProject, panel.virtualFiles), getReformatBeforeCommitCommandName(), saveAndContinue, true).run() } else { saveAndContinue() // TODO just runnable.run()? } } } private class BackgroundReformatCheckinHandler(commitPanel: CheckinProjectPanel) : CodeProcessorCheckinHandler(commitPanel) { override fun getBeforeCheckinConfigurationPanel(): RefreshableOnComponent = ReformatBeforeCheckinHandler(project, commitPanel).beforeCheckinConfigurationPanel override fun isEnabled(): Boolean = settings.REFORMAT_BEFORE_PROJECT_COMMIT override fun createCodeProcessor(): AbstractLayoutCodeProcessor = ReformatCodeProcessor(project, getPsiFiles(project, commitPanel.virtualFiles), getReformatBeforeCommitCommandName(), null, true) }
191
null
4372
13,319
4d19d247824d8005662f7bd0c03f88ae81d5364b
2,935
intellij-community
Apache License 2.0
lifecycle/src/commonMain/kotlin/com/erolc/lifecycle/LifecycleEventObserver.kt
ErolC
786,106,502
false
{"Kotlin": 205561, "Swift": 620, "HTML": 304}
package com.erolc.lifecycle interface LifecycleEventObserver:LifecycleObserver { fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) }
0
Kotlin
0
0
dacbb74a8c2e60359438c7b593c7d50027c06ede
155
MRouter
Apache License 2.0
app/src/main/java/com/sethchhim/kuboo_client/ui/main/downloads/DownloadsFragmentImpl1_Content.kt
befora
137,512,422
false
null
package com.sethchhim.kuboo_client.ui.main.downloads import androidx.lifecycle.Observer import com.google.android.material.tabs.TabLayout import com.sethchhim.kuboo_client.Extensions.compressFavorite import com.sethchhim.kuboo_client.Extensions.downloadListToBookList import com.sethchhim.kuboo_client.Settings import com.sethchhim.kuboo_client.ui.main.downloads.adapter.DownloadListAdapter import com.sethchhim.kuboo_remote.KubooRemote import com.sethchhim.kuboo_remote.model.Book import com.tonyodev.fetch2.Download import com.tonyodev.fetch2.Error import com.tonyodev.fetch2.FetchListener import com.tonyodev.fetch2.Status import com.tonyodev.fetch2core.DownloadBlock import timber.log.Timber import javax.inject.Inject open class DownloadsFragmentImpl1_Content : DownloadsFragmentImpl0_View() { @Inject lateinit var kubooRemote: KubooRemote protected fun populateDownloads(enableLoading: Boolean = true) { if (enableLoading) { setNumberProgressBar() setStateLoading() resetDownloads() contentRecyclerView.saveState() } viewModel.getDownloadListLiveData().observe(this, Observer { result -> result?.let { viewModel.getFetchDownloads().observe(this, Observer { fetchDownloads -> fetchDownloads?.let { handleResult(result.downloadListToBookList(), fetchDownloads) } }) } }) } private fun handleResult(result: List<Book>, fetchDownloads: List<Download>) { val compressedList = result.compressFavorite() val nonCompressedList = result.filter { !compressedList.contains(it) } val filteredList = when (Settings.DOWNLOAD_TRACKING_HIDE_FINISHED) { true -> compressedList.filter { val isAnyCompletedDownloadsFromSameXmlId = nonCompressedList.any { item -> val isMatchXmlId = item.getXmlId() == it.getXmlId() val isCompleted = fetchDownloads.any { it.tag == item.getIdString() && it.group == item.getXmlId() && it.status == Status.COMPLETED } isMatchXmlId && isCompleted } return@filter !it.isFavorite || it.isFavorite && !it.isFinished || it.isFavorite && it.isFinished && isAnyCompletedDownloadsFromSameXmlId } false -> compressedList } when (filteredList.isEmpty()) { true -> onPopulateContentEmpty() false -> onPopulateContentSuccess(filteredList) } } private fun onPopulateContentSuccess(result: List<Book>) { Timber.i("onPopulateDownloadsSuccess result: ${result.size}") setStateConnected() (contentRecyclerView.adapter as DownloadListAdapter).submitList(result as MutableList<Book>) contentRecyclerView.restoreState() } protected val onTabSelectedListener = object : TabLayout.OnTabSelectedListener { override fun onTabReselected(tab: TabLayout.Tab) { handleTab(tab.position) } override fun onTabUnselected(tab: TabLayout.Tab) {} override fun onTabSelected(tab: TabLayout.Tab) { handleTab(tab.position) } private fun handleTab(position: Int) { when (position) { 0 -> kubooRemote.pauseAll() 1 -> mainActivity.trackingService.startTrackingServiceSingle(viewModel.getActiveLogin()) } } } protected val fetchListener = object : FetchListener { override fun onAdded(download: Download) {} override fun onStarted(download: Download, downloadBlocks: List<DownloadBlock>, totalBlocks: Int) {} override fun onCancelled(download: Download) { updateContent(download) } override fun onCompleted(download: Download) { updateContent(download) populateDownloads(enableLoading = false) } override fun onDeleted(download: Download) { updateContent(download) setNumberProgressBar() } override fun onError(download: Download, error: Error, throwable: Throwable?) { updateContent(download) } override fun onPaused(download: Download) { updateContent(download) } override fun onProgress(download: Download, etaInMilliSeconds: Long, downloadedBytesPerSecond: Long) { updateContent(download) } override fun onQueued(download: Download, waitingOnNetwork: Boolean) { updateContent(download) } override fun onRemoved(download: Download) { updateContent(download) } override fun onResumed(download: Download) { updateContent(download) } override fun onDownloadBlockUpdated(download: Download, downloadBlock: DownloadBlock, totalBlocks: Int) {} override fun onWaitingNetwork(download: Download) {} } private fun resetDownloads() { (contentRecyclerView.adapter as DownloadListAdapter).submitList(mutableListOf()) } }
1
Kotlin
39
81
33e456344172eab96b136e30130c4125096f253d
5,214
Kuboo
Apache License 2.0
src/main/kotlin/com/chattriggers/ctjs/utils/config/ConfigBoolean.kt
qkleinfelter
146,530,916
false
{"Proguard": 1, "Text": 3, "INI": 1, "Markdown": 5, "Gradle": 2, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "YAML": 1, "Java Properties": 1, "JSON": 2, "JavaScript": 5, "Java": 1, "HAProxy": 1, "Kotlin": 113}
package com.chattriggers.ctjs.utils.config import com.chattriggers.ctjs.minecraft.libs.ChatLib import com.chattriggers.ctjs.minecraft.libs.renderer.Rectangle import com.chattriggers.ctjs.minecraft.libs.renderer.Renderer import com.chattriggers.ctjs.minecraft.libs.renderer.Text import com.chattriggers.ctjs.minecraft.wrappers.Client import net.minecraft.client.gui.GuiButton import kotlin.properties.Delegates import kotlin.reflect.KMutableProperty class ConfigBoolean (private val prop: KMutableProperty<Boolean>, override val name: String = "", x: Int = 0, y: Int = 0) : ConfigOption() { private var value: Boolean by Delegates.observable(prop.getter.call(Config)) { _, _, new -> prop.setter.call(Config, new) } private val initial: Boolean = value init { this.x = x this.y = y } private var button: GuiButton = GuiButton( 0, Renderer.screen.getWidth() / 2 - 100 + this.x, this.y + 15, stringValue ) private val stringValue: String get() = if (this.value) ChatLib.addColor("&aTrue") else ChatLib.addColor("&cFalse") override fun draw(mouseX: Int, mouseY: Int, partialTicks: Float) { if (this.hidden) return val middle = Renderer.screen.getWidth() / 2 Rectangle(-0x80000000, (middle - 105 + this.x).toFloat(), (this.y - 5).toFloat(), 210f, 45f) .setShadow(-0x30000000, 3f, 3f) .draw() Text(this.name, (middle - 100 + this.x).toFloat(), this.y.toFloat()).draw() //#if MC<=10809 this.button.xPosition = middle - 100 + this.x this.button.drawButton(Client.getMinecraft(), mouseX, mouseY) //#else //$$ this.button.x = middle - 100 + this.x; //$$ this.button.drawButton(Client.getMinecraft(), mouseX, mouseY, partialTicks); //#endif super.draw(mouseX, mouseY, partialTicks) } override fun mouseClicked(mouseX: Int, mouseY: Int) { if (this.hidden) return if (this.button.mousePressed(Client.getMinecraft(), mouseX, mouseY)) { this.value = (!this.value) this.button.playPressSound(Client.getMinecraft().soundHandler) } if (this.resetButton.mousePressed(Client.getMinecraft(), mouseX, mouseY)) { this.value = this.initial this.resetButton.playPressSound(Client.getMinecraft().soundHandler) } this.button.displayString = stringValue } }
1
null
1
1
2f55ec379cbf17f64991b10fd3dd8a1aac94fe14
2,480
ct.js
MIT License
bbfgradle/tmp/results/diffABI/wegyxbg_FILE.kt
DaniilStepanov
346,008,310
false
{"Markdown": 122, "Gradle": 762, "Gradle Kotlin DSL": 649, "Java Properties": 23, "Shell": 49, "Ignore List": 20, "Batchfile": 26, "Git Attributes": 8, "Kotlin": 82508, "Protocol Buffer": 12, "Java": 6674, "Proguard": 12, "XML": 1698, "Text": 13298, "INI": 221, "JavaScript": 294, "JAR Manifest": 2, "Roff": 217, "Roff Manpage": 38, "JSON": 199, "HTML": 2429, "AsciiDoc": 1, "YAML": 21, "EditorConfig": 1, "OpenStep Property List": 19, "C": 79, "Objective-C": 68, "C++": 169, "Swift": 68, "Pascal": 1, "Python": 4, "CMake": 2, "Objective-C++": 12, "Groovy": 45, "Dockerfile": 3, "Diff": 1, "EJS": 1, "CSS": 6, "Ruby": 6, "SVG": 50, "JFlex": 3, "Maven POM": 107, "JSON with Comments": 9, "Ant Build System": 53, "Graphviz (DOT)": 78, "Scala": 1}
// Bug happens on JVM , JVM -Xuse-ir // FILE: tmp0.kt package wegyxbg import kotlin.reflect.* import kotlin.collections.* import kotlin.sequences.* import kotlin.text.* fun foo(p: Int?): Boolean =TODO() fun foo2(p: Int?): Boolean =TODO() class M<T: Any>(val z: T?) { fun nulled(): T? = TODO() } fun box(): String =TODO() internal interface Bri : Map<Char, M<String>>, MatchNamedGroupCollection{ override fun containsKey(key: kotlin.Char): kotlin.Boolean = TODO() override fun get(key: kotlin.Char): M<kotlin.String>? = TODO() override fun isEmpty(): kotlin.Boolean = TODO() var dpwj: ArrayDeque<M<M<Double>>> val ygon: Collection<M<Byte>> val xodg: Double val mmvq: List<M<Long>> var lyap: UShort val Double.wyka: Char get() = TODO() var ywdz: Triple<LinkedHashSet<Char>, Double, UInt> val cjhg: Set<Short> var wbud: UByte }
1
null
1
1
e772ef1f8f951873ebe7d8f6d73cf19aead480fa
865
kotlinWithFuzzer
Apache License 2.0
android/src/main/java/com/simplereactnativelibrary/SimpleReactNativeLibraryModule.kt
jannik-feuerhahn
500,572,969
false
{"Java": 6360, "Objective-C": 3492, "Kotlin": 1576, "TypeScript": 1532, "JavaScript": 1472, "Ruby": 1221, "Swift": 639, "Shell": 149, "C": 103}
package com.simplereactnativelibrary import com.facebook.react.bridge.* import android.util.Log class SimpleReactNativeLibraryModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) { override fun getName(): String { return "SimpleReactNativeLibrary" } // Example method // See https://reactnative.dev/docs/native-modules-android @ReactMethod fun launchSDK(url: String, callback: Callback) { // val intent = Intent(reactApplicationContext, AdaModalActivity::class.java) // val params = AdaParameters( // url = url, // locale = "en-US" // ) // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) // intent.putExtra("adaParameters", params) // reactApplicationContext.startActivity(intent) val msg = "Launched SDK with url: $url" Log.d(SimpleReactNativeLibraryModule::class.simpleName, msg) callback.invoke(null, msg) } }
1
null
1
1
c0dfcfad7c67f64fa15b63d9190807a7dd889692
981
simple-react-native-library
MIT License
platform/configuration-store-impl/src/RestoreDefaultSettingsAction.kt
hieuprogrammer
284,920,751
false
null
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.configurationStore import com.intellij.CommonBundle import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.* import com.intellij.openapi.application.ex.ApplicationEx import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.ui.Messages import java.nio.file.Path class RestoreDefaultSettingsAction : DumbAwareAction() { override fun actionPerformed(e: AnActionEvent) { if (!confirmRestoreSettings(e, ConfigImportHelper.getBackupPath())) { return; } CustomConfigMigrationOption.writeCustomConfigMigrationFile(null) invokeLater { (ApplicationManager.getApplication() as ApplicationEx).restart(true) } } private fun confirmRestoreSettings(e: AnActionEvent, backupPath: Path?): Boolean { val restartButtonText = if (ApplicationManager.getApplication().isRestartCapable) ConfigurationStoreBundle.message("restore.default.settings.confirmation.button.restart") else ConfigurationStoreBundle.message("restore.default.settings.confirmation.button.shutdown") return Messages.YES == Messages.showYesNoDialog( e.project, ConfigurationStoreBundle.message("restore.default.settings.confirmation.message", backupPath), ConfigurationStoreBundle.message("restore.default.settings.confirmation.title"), restartButtonText, CommonBundle.getCancelButtonText(), Messages.getWarningIcon() ) } }
1
null
1
2
dc846ecb926c9d9589c1ed8a40fdb20e47874db9
1,604
intellij-community
Apache License 2.0
appmonet-sdk/appmonet-sdk-core/src/main/java/com/monet/bidder/adview/AdViewClient.kt
AppMonet
299,708,730
false
{"Java": 446521, "Kotlin": 285931, "Shell": 83}
package com.monet.bidder.adview import android.graphics.Bitmap import android.net.Uri import android.os.Build import android.webkit.WebResourceRequest import android.webkit.WebResourceResponse import android.webkit.WebView import com.monet.bidder.* class AdViewClient internal constructor(private val adViewManagerCallback: AdViewManagerCallback) : BaseWebViewClient() { private var mListener: AdServerBannerListener? = null fun setListener(listener: AdServerBannerListener?) { mListener = listener } override fun onPageStartedInner(view: WebView, url: String, favicon: Bitmap) { super.onPageStartedInner(view, url, favicon) adViewManagerCallback.handleAdInteraction(view, url) } override fun onPageFinished(view: WebView, url: String) { adViewManagerCallback.isLoaded = true super.onPageFinished(view, url) } override fun shouldInterceptRequestInner(view: WebView, url: String): WebResourceResponse { return adViewManagerCallback.shouldInterceptRequest(view, url) ?: super.shouldInterceptRequestInner(view, url) } override fun shouldInterceptRequestInner(view: WebView, request: WebResourceRequest): WebResourceResponse { return adViewManagerCallback.shouldInterceptRequest(view, request) ?: super.shouldInterceptRequestInner(view, request) } override fun shouldOverrideUrlLoadingInner(view: WebView, url: String): Boolean { return adViewManagerCallback.checkOverride(view, Uri.parse(url)) } override fun shouldOverrideUrlLoadingInner(view: WebView, request: WebResourceRequest): Boolean { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // note that in older webviews, we can only stop loading // we can't control the initial redirect which sucks :/ adViewManagerCallback.shouldOverrideUrlLoading(view, request) } else { super.shouldOverrideUrlLoadingInner(view, request) } } }
1
null
1
1
1af1e9d2d20508496cb14d7cf12930a0727a277c
2,039
appmonet-android-sdk
Freetype Project License
app/src/main/java/org/stepik/android/presentation/step_content_text/TextStepContentPresenter.kt
StepicOrg
42,045,161
false
null
package org.stepik.android.presentation.step_content_text import io.reactivex.Scheduler import io.reactivex.rxkotlin.plusAssign import io.reactivex.rxkotlin.subscribeBy import org.stepic.droid.di.qualifiers.BackgroundScheduler import org.stepic.droid.di.qualifiers.MainScheduler import ru.nobird.android.domain.rx.emptyOnErrorStub import org.stepik.android.domain.step_content_text.interactor.TextContentFontInteractor import org.stepik.android.presentation.base.PresenterBase import javax.inject.Inject class TextStepContentPresenter @Inject constructor( private val textContentFontInteractor: TextContentFontInteractor, @BackgroundScheduler private val backgroundScheduler: Scheduler, @MainScheduler private val mainScheduler: Scheduler ) : PresenterBase<TextStepContentView>() { fun onSetTextContentSize() { compositeDisposable += textContentFontInteractor .fetchTextContentFontSize() .subscribeOn(backgroundScheduler) .observeOn(mainScheduler) .subscribeBy( onSuccess = { view?.setTextContentFontSize(it) }, onError = emptyOnErrorStub ) } }
13
null
54
189
dd12cb96811a6fc2a7addcd969381570e335aca7
1,175
stepik-android
Apache License 2.0
plugins/kotlin/idea/tests/testData/gradle/multiplatform/core/features/compositeBuild/libraryWithRootProjectName/includedLibrary/utils/src/nativeMain/kotlin/LibraryNativeMain.kt
ingokegel
72,937,917
false
null
object LibraryUtilsNativeMain { fun call() = LibraryNativeMain.call() }
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
75
intellij-community
Apache License 2.0
app/src/main/java/dev/igokoro/moshi_enum/ModelKt.kt
igokoro
306,720,802
false
null
package dev.igokoro.moshi_enum import com.squareup.moshi.JsonClass enum class DoomedEnumKt{ B } @JsonClass(generateAdapter = true) data class ModelKt( val value: DoomedEnumKt )
1
null
1
1
04c1296529e6bc08702887397c39fca9a4091e6a
187
moshi-obfuscated-enums
Apache License 2.0
plugins/full-line/src/org/jetbrains/completion/full/line/services/TabSelectedItemStorageImpl.kt
xGreat
182,651,778
false
null
package org.jetbrains.completion.full.line.services import org.jetbrains.completion.full.line.AnalyzedFullLineProposal class TabSelectedItemStorageImpl : TabSelectedItemStorage { private var head: String? = null private var selectedProposal: AnalyzedFullLineProposal? = null override fun saveTabSelected(head: String, proposal: AnalyzedFullLineProposal) { this.head = head selectedProposal = proposal } override fun getSavedProposal(): AnalyzedFullLineProposal? { val result = selectedProposal selectedProposal = null head = null return result } override fun prefixFromPreviousSession(): String { return head ?: "" } }
1
null
1
1
fb5f23167ce9cc53bfa3ee054b445cf4d8f1ce98
670
intellij-community
Apache License 2.0
library_base/src/main/java/com/ckz/baselibrary/binding/ViewBinding.kt
c786909486
514,179,909
false
{"Gradle": 9, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 8, "Batchfile": 1, "Markdown": 1, "INI": 5, "Proguard": 6, "Kotlin": 80, "XML": 48, "Java": 56}
package com.ckz.baselibrary.binding import android.graphics.drawable.Drawable import android.view.View import androidx.databinding.BindingAdapter import androidx.viewpager.widget.PagerAdapter import androidx.viewpager.widget.ViewPager /** *@packageName com.ckz.baselibrary.binding *@author kzcai *@date 11/25/20 */ object ViewBinding { @BindingAdapter("bgDrawable") @JvmStatic fun bgDrawable(view: View, drawable: Drawable){ view.background = drawable } @BindingAdapter("isShow") @JvmStatic fun isShow(view: View,isShow:Boolean){ view.visibility = if (isShow) View.VISIBLE else View.GONE } @BindingAdapter("isVisibility") @JvmStatic fun isVisibility(view: View,isShow:Boolean){ view.visibility = if (isShow) View.VISIBLE else View.INVISIBLE } @BindingAdapter("isSelected") @JvmStatic fun isSelected(view:View,isSelected:Boolean){ view.isSelected = isSelected } }
0
Java
0
0
de2681d4b6a0ed9459cea57b78ea7efa5a49f702
968
BaseMvvmModel
Apache License 2.0
app/src/main/java/com/foreveross/atwork/modules/group/module/SelectToHandleAction.kt
AoEiuV020
421,650,297
false
{"Java": 8618305, "Kotlin": 1733509, "JavaScript": 719597, "CSS": 277438, "HTML": 111559}
package com.foreveross.atwork.modules.group.module import android.os.Parcelable import com.foreveross.atwork.modules.route.action.RouteAction abstract class SelectToHandleAction(open var max: Int = -1) : RouteAction(), Parcelable
1
null
1
1
1c4ca5bdaea6d5230d851fb008cf2578a23b2ce5
231
w6s_lite_android
MIT License
src/test/kotlin/org/web3j/quorum/enclave/http/ResponseParserTest.kt
cgf4j
159,775,791
false
null
package org.web3j.quorum.enclave.http import org.assertj.core.api.Assertions.* import org.junit.Test import org.junit.Assert.assertTrue class ResponseParserTest { val httpOkChunkedResponse = """ HTTP/1.1 200 OK Transfer-Encoding: chunked Date: Wed, 02 Aug 2017 21:48:33 GMT Server: Warp/3.2.12 0062 {"key":"<KEY>} 0 """.trimIndent() val httpOkCHunkedResponseEmpty = """ HTTP/1.1 200 OK Transfer-Encoding: chunked Date: Wed, 09 Aug 2017 21:04:54 GMT Server: Warp/3.2.12 0 """.trimIndent() val httpBadRequestResponse = """ HTTP/1.1 400 Bad Request Transfer-Encoding: chunked Date: Thu, 03 Aug 2017 07:44:11 GMT Server: Warp/3.2.12 000B Bad Request 0 """.trimIndent() val httpInternalServerErrorResponse = """ HTTP/1.0 500 Internal Server Error Date: Thu, 03 Aug 2017 07:51:11 GMT Server: Warp/3.2.12 Content-Type: text/plain; charset=utf-8 Something went wrong """.trimIndent() @Test fun testParseHttpResponse() { val expected = Response( StatusCode(200, "OK"), hashMapOf( Pair("Transfer-Encoding", "chunked"), Pair("Server", "Warp/3.2.12"), Pair("Date", "Wed, 02 Aug 2017 21:48:33 GMT")), """ 0062 {"key":"<KEY>} 0 """.trimIndent()) val result = ResponseParser.parseResponse(httpOkChunkedResponse) assertTrue(result == expected) } @Test fun testParseHttpResponseBadRequest() { val expected = Response( StatusCode(400, "Bad Request"), hashMapOf( Pair("Transfer-Encoding", "chunked"), Pair("Server", "Warp/3.2.12"), Pair("Date", "Thu, 03 Aug 2017 07:44:11 GMT")), """ 000B Bad Request 0 """.trimIndent() ) val result = ResponseParser.parseResponse(httpBadRequestResponse) assertTrue(result == expected) } @Test fun testParseHttpResponseInternalServerError() { val expected = Response( StatusCode(500, "Internal Server Error"), hashMapOf( Pair("Content-Type", "text/plain; charset=utf-8"), Pair("Server", "Warp/3.2.12"), Pair("Date", "Thu, 03 Aug 2017 07:51:11 GMT")), """ Something went wrong """.trimIndent() ) val result = ResponseParser.parseResponse(httpInternalServerErrorResponse) assertTrue(result == expected) } @Test fun testParseHttpTextResponse() { val response = ResponseParser.parseResponse(httpInternalServerErrorResponse) val text = ResponseParser.parseTextPlainBody(response) assertThat(text).isEqualTo("Something went wrong") } @Test fun testParseHttpChunkedResponse() { val chunk = ResponseParser.parseChunkedResponse(httpOkChunkedResponse) assertThat(chunk).isEqualTo( """ {"key":"<KEY>} """.trim() ) } @Test fun testParseHttpEmptyChunkedResponse() { val chunk = ResponseParser.parseChunkedResponse(httpOkCHunkedResponseEmpty) assertThat(chunk).isEqualTo("") } }
1
null
1
1
67bb6522d7c93154c3173a3634b8b537f8d5632f
3,739
quorum
Apache License 2.0
plugins/groovy/src/org/jetbrains/plugins/groovy/console/GroovyConsoleView.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.console import com.intellij.execution.impl.ConsoleState import com.intellij.execution.impl.ConsoleState.NotStartedStated import com.intellij.execution.impl.ConsoleViewImpl import com.intellij.execution.impl.ConsoleViewRunningState import com.intellij.execution.process.ProcessHandler import com.intellij.execution.ui.ConsoleViewContentType import com.intellij.openapi.project.Project import com.intellij.psi.search.GlobalSearchScope class GroovyConsoleView(project: Project) : ConsoleViewImpl( project, GlobalSearchScope.allScope(project), true, object : NotStartedStated() { override fun attachTo(console: ConsoleViewImpl, processHandler: ProcessHandler): ConsoleState { return ConsoleViewRunningState(console, processHandler, this, true, false) } }, true) { companion object { private const val RESULT_MARKER = "ee2d5778-e2f4-4705-84ef-0847535c32f4" } override fun print(text: String, contentType: ConsoleViewContentType) { if (text.startsWith(RESULT_MARKER)) { super.print("Result: ", ConsoleViewContentType.SYSTEM_OUTPUT) super.print(text.substring(RESULT_MARKER.length), contentType) } else { super.print(text, contentType) } } }
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
1,389
intellij-community
Apache License 2.0
utils-ktx/src/main/java/me/shouheng/utils/ktx/NoDoubleClickListener.kt
Shouheng88
214,335,640
false
{"Markdown": 2, "Text": 1, "YAML": 2, "Gradle": 5, "Shell": 1, "Ignore List": 5, "Batchfile": 1, "INI": 1, "Proguard": 3, "Kotlin": 35, "XML": 66, "Java": 72}
package me.shouheng.utils.ktx import android.view.View /** Avoid to click twice in short time. */ abstract class NoDoubleClickListener : View.OnClickListener { private var lastClickTime: Long = 0 override fun onClick(v: View) { val currentTime = System.currentTimeMillis() if (currentTime - lastClickTime > MIN_CLICK_DELAY_TIME) { lastClickTime = currentTime onNoDoubleClick(v) } } protected abstract fun onNoDoubleClick(v: View) companion object { var MIN_CLICK_DELAY_TIME = 500L } } /** Add function to View to avoid click twice */ fun View.onDebouncedClick(click: (view: View) -> Unit) { setOnClickListener(object : NoDoubleClickListener() { override fun onNoDoubleClick(v: View) { click(v) } }) }
1
Java
31
118
f4189fec9f7d8941d6e5550b1c42d46c68e825c3
845
utils-android
Apache License 2.0
analysis/analysis-api/testData/components/scopeProvider/staticDeclaredMemberScope/scriptWithClassDeclaration.kts
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
// DO_NOT_CHECK_NON_PSI_SYMBOL_RESTORE // script abstract class Person { abstract val name: String } fun foo(action: () -> Int) { action() } foo { 42 + 42 }
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
171
kotlin
Apache License 2.0
feature-walletconnect-api/src/main/java/co/jp/soramitsu/walletconnect/domain/WalletConnectInteractor.kt
soramitsu
278,060,397
false
{"Kotlin": 5738291, "Java": 18796}
package co.jp.soramitsu.walletconnect.domain import com.walletconnect.web3.wallet.client.Wallet import jp.co.soramitsu.core.models.ChainId import jp.co.soramitsu.runtime.multiNetwork.chain.model.Chain @Suppress("ComplexInterface") interface WalletConnectInteractor { suspend fun getChains(): List<Chain> suspend fun checkChainsSupported(proposal: Wallet.Model.SessionProposal): Result<Boolean> suspend fun approveSession( proposal: Wallet.Model.SessionProposal, selectedWalletIds: Set<Long>, selectedOptionalChainIds: Set<String>, onSuccess: (Wallet.Params.SessionApprove) -> Unit = {}, onError: (Wallet.Model.Error) -> Unit ) fun rejectSession( proposal: Wallet.Model.SessionProposal, onSuccess: (Wallet.Params.SessionReject) -> Unit = {}, onError: (Wallet.Model.Error) -> Unit ) fun silentRejectSession( proposal: Wallet.Model.SessionProposal, onSuccess: (Wallet.Params.SessionReject) -> Unit = {}, onError: (Wallet.Model.Error) -> Unit ) suspend fun handleSignAction( chain: Chain, topic: String, recentSession: Wallet.Model.SessionRequest, onSignError: (Exception) -> Unit, onRequestSuccess: (operationHash: String?, chainId: ChainId?) -> Unit, onRequestError: (Wallet.Model.Error) -> Unit ) fun rejectSessionRequest( sessionTopic: String, requestId: Long, onSuccess: (Wallet.Params.SessionRequestResponse) -> Unit = {}, onError: (Wallet.Model.Error) -> Unit ) fun getActiveSessionByTopic(topic: String): Wallet.Model.Session? fun getPendingListOfSessionRequests(topic: String): List<Wallet.Model.SessionRequest> fun disconnectSession( topic: String, onSuccess: (Wallet.Params.SessionDisconnect) -> Unit = {}, onError: (Wallet.Model.Error) -> Unit ) fun pair( pairingUri: String, onSuccess: (Wallet.Params.Pair) -> Unit = {}, onError: (Wallet.Model.Error) -> Unit = {} ) }
15
Kotlin
30
89
812c6ed5465d19a0616865cbba3e946d046720a1
2,077
fearless-Android
Apache License 2.0
meta-resource/src/main/java/com/rarible/core/meta/resource/resolver/GatewayProvider.kt
rarible
357,923,214
false
null
package com.rarible.core.meta.resource.resolver import java.util.Random interface GatewayProvider { fun getGateway(): String } class RandomGatewayProvider( private val gateways: List<String> ) : GatewayProvider { override fun getGateway(): String = gateways[Random().nextInt(gateways.size)] } class ConstantGatewayProvider( private val gateway: String ) : GatewayProvider { override fun getGateway(): String = gateway }
0
Kotlin
3
9
fb72de3228c224daf7e8ec2e09becc4dee602733
446
service-core
MIT License
app/src/main/java/com/benny/openlauncher/preference/ColorPreferenceSupport.kt
penglu20
129,922,039
true
{"Java": 449795, "Kotlin": 224558}
/* * Copyright (C) 2017 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.benny.openlauncher.preference import android.app.Activity import android.content.Context import android.content.res.TypedArray import android.graphics.Color import android.support.annotation.ColorInt import android.support.v7.preference.Preference import android.support.v7.preference.PreferenceManager import android.support.v7.preference.PreferenceViewHolder import android.util.AttributeSet import android.view.ContextThemeWrapper import com.jaredrummler.android.colorpicker.R import com.jaredrummler.android.colorpicker.ColorPanelView import com.jaredrummler.android.colorpicker.ColorPickerDialog import com.jaredrummler.android.colorpicker.ColorPickerDialogListener import com.jaredrummler.android.colorpicker.ColorShape /** * A Preference to select a color */ class ColorPreferenceSupport : Preference, ColorPickerDialogListener { private var onShowDialogListener: OnShowDialogListener? = null private var color = Color.BLACK private var showDialog: Boolean = false @ColorPickerDialog.DialogType private var dialogType: Int = 0 private var colorShape: Int = 0 private var allowPresets: Boolean = false private var allowCustom: Boolean = false private var showAlphaSlider: Boolean = false private var showColorShades: Boolean = false private var previewSize: Int = 0 /** * Get the colors that will be shown in the [ColorPickerDialog]. * * @return An array of color ints */ /** * Set the colors shown in the [ColorPickerDialog]. * * @param presets An array of color ints */ var presets: IntArray? = null private var dialogTitle: Int = 0 /** * The tag used for the [ColorPickerDialog]. * * @return The tag */ val fragmentTag: String get() = "color_" + key constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { init(attrs) } constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) { init(attrs) } private fun init(attrs: AttributeSet) { isPersistent = true val a = context.obtainStyledAttributes(attrs, R.styleable.ColorPreference) showDialog = a.getBoolean(R.styleable.ColorPreference_cpv_showDialog, true) dialogType = a.getInt(R.styleable.ColorPreference_cpv_dialogType, ColorPickerDialog.TYPE_PRESETS) colorShape = a.getInt(R.styleable.ColorPreference_cpv_colorShape, ColorShape.CIRCLE) allowPresets = a.getBoolean(R.styleable.ColorPreference_cpv_allowPresets, true) allowCustom = a.getBoolean(R.styleable.ColorPreference_cpv_allowCustom, true) showAlphaSlider = a.getBoolean(R.styleable.ColorPreference_cpv_showAlphaSlider, false) showColorShades = a.getBoolean(R.styleable.ColorPreference_cpv_showColorShades, true) previewSize = a.getInt(R.styleable.ColorPreference_cpv_previewSize, SIZE_NORMAL) val presetsResId = a.getResourceId(R.styleable.ColorPreference_cpv_colorPresets, 0) dialogTitle = a.getResourceId(R.styleable.ColorPreference_cpv_dialogTitle, R.string.cpv_default_title) if (presetsResId != 0) { presets = context.resources.getIntArray(presetsResId) } else { presets = ColorPickerDialog.MATERIAL_COLORS } if (colorShape == ColorShape.CIRCLE) { widgetLayoutResource = if (previewSize == SIZE_LARGE) R.layout.cpv_preference_circle_large else R.layout.cpv_preference_circle } else { widgetLayoutResource = if (previewSize == SIZE_LARGE) R.layout.cpv_preference_square_large else R.layout.cpv_preference_square } a.recycle() } override fun onClick() { super.onClick() if (onShowDialogListener != null) { onShowDialogListener!!.onShowColorPickerDialog(title as String, color) } else if (showDialog) { val dialog = ColorPickerDialog.newBuilder() .setDialogType(dialogType) .setDialogTitle(dialogTitle) .setColorShape(colorShape) .setPresets(presets!!) .setAllowPresets(allowPresets) .setAllowCustom(allowCustom) .setShowAlphaSlider(showAlphaSlider) .setShowColorShades(showColorShades) .setColor(color) .create() dialog.setColorPickerDialogListener(this@ColorPreferenceSupport) val activity = getPrefActivity(this) dialog.show(activity!!.fragmentManager, fragmentTag) } } override fun onAttachedToHierarchy(preferenceManager: PreferenceManager) { super.onAttachedToHierarchy(preferenceManager) if (showDialog) { val activity = getPrefActivity(this) val fragment = activity?.fragmentManager?.findFragmentByTag(fragmentTag) as ColorPickerDialog? fragment?.setColorPickerDialogListener(this) } } override fun onBindViewHolder(holder: PreferenceViewHolder) { super.onBindViewHolder(holder) val preview = holder.findViewById(R.id.cpv_preference_preview_color_panel) as ColorPanelView if (preview != null) { preview.color = color } } override fun onSetInitialValue(restorePersistedValue: Boolean, defaultValue: Any?) { if (restorePersistedValue) { color = getPersistedInt(-0x1000000) } else { color = (defaultValue as Int?)!! persistInt(color) } } override fun onGetDefaultValue(a: TypedArray?, index: Int): Any { return a!!.getInteger(index, Color.BLACK) } override fun onColorSelected(dialogId: Int, @ColorInt color: Int) { saveValue(color) } override fun onDialogDismissed(dialogId: Int) { // no-op } /** * Set the new color * * @param color The newly selected color */ fun saveValue(@ColorInt color: Int) { this.color = color persistInt(this.color) notifyChanged() callChangeListener(color) } /** * The listener used for showing the [ColorPickerDialog]. * Call [.saveValue] after the user chooses a color. * If this is set then it is up to you to show the dialog. * * @param listener The listener to show the dialog */ fun setOnShowDialogListener(listener: OnShowDialogListener) { onShowDialogListener = listener } interface OnShowDialogListener { fun onShowColorPickerDialog(title: String, currentColor: Int) } companion object { private val SIZE_NORMAL = 0 private val SIZE_LARGE = 1 fun getPrefActivity(pref: Preference): Activity? { val c = pref.context if (c is ContextThemeWrapper) { if (c.baseContext is Activity) return c.baseContext as Activity } else if (c is Activity) return c return null } } }
0
Java
1
0
f6edb6fd668f7769c6d34731a0e77f49d078b460
7,704
openlauncher
Apache License 2.0
assertk-js/src/main/kotlin/assertk/failure.kt
sowmyav24
154,699,057
false
null
package assertk @Suppress("NOTHING_TO_INLINE") internal actual inline fun failWithNotInStacktrace(error: Throwable): Nothing { throw error }
1
null
1
1
f1175aefbe46a180dc586bcc5a8093baf500fad9
146
assertk
MIT License
WorkManagerNotifications/app/src/main/java/com/lazypotato/workmanager_notifications/receiver/MediaBroadcastReceiver.kt
eishon
346,190,149
false
null
package com.lazypotato.workmanager_notifications.receiver import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.widget.Toast class MediaBroadcastReceiver : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { val extras = intent!!.extras extras?.let { val id = extras?.getInt("ACTION") Toast.makeText( context, when (id) { 0 -> "pause" -1 -> "prev" 1 -> "next" else -> "Not Recognised" }, Toast.LENGTH_SHORT ).show() } } }
1
Kotlin
1
1
5bb1c98644ee46c9ce108c9e8af7f3b4ba55fdcf
732
Android-Samples
MIT License
JediTerm/src/main/kotlin/com/jediterm/app/JediTermMain.kt
BeichenDream
382,110,263
false
null
package com.jediterm.app import com.google.common.base.Predicate import com.google.common.collect.ForwardingMap import com.google.common.collect.Lists import com.google.common.collect.Maps import com.intellij.execution.filters.UrlFilter import com.intellij.openapi.Disposable import com.intellij.openapi.util.Pair import com.intellij.util.EncodingEnvironmentUtil import com.jediterm.pty.PtyProcessTtyConnector import com.jediterm.terminal.LoggingTtyConnector import com.jediterm.terminal.TtyConnector import com.jediterm.terminal.ui.AbstractTerminalFrame import com.jediterm.terminal.ui.TerminalWidget import com.jediterm.terminal.ui.UIUtil import com.jediterm.terminal.ui.settings.DefaultTabbedSettingsProvider import com.jediterm.terminal.ui.settings.TabbedSettingsProvider import com.pty4j.PtyProcess import org.apache.log4j.BasicConfigurator import org.apache.log4j.Level import org.apache.log4j.Logger import java.awt.KeyboardFocusManager import java.io.IOException import java.nio.charset.Charset import java.util.* import java.util.function.Function /** * Created by traff on 22/08/16. */ object JediTermMain { @JvmStatic fun main(arg: Array<String>) { BasicConfigurator.configure() Logger.getRootLogger().level = Level.INFO // initLoggingTracing() JediTerm() } } fun initLoggingTracing() { val mrfoField = KeyboardFocusManager::class.java!!.getDeclaredField("mostRecentFocusOwners") mrfoField.setAccessible(true) val delegate = mrfoField.get(null) as Map<Any, Any> val mrfo = object : ForwardingMap<Any, Any>() { override fun put(key: Any?, value: Any?): Any? { Throwable().printStackTrace() return super.put(key, value) } override fun delegate(): Map<Any, Any> { return delegate } } mrfoField.set(null, mrfo) } class JediTerm : AbstractTerminalFrame(), Disposable { override fun dispose() { // TODO } override fun createTabbedTerminalWidget(): JediTabbedTerminalWidget { return object : JediTabbedTerminalWidget(DefaultTabbedSettingsProvider(), Function<Pair<TerminalWidget, String>, JediTerminalWidget> { pair -> openSession(pair?.first) as JediTerminalWidget }, this) { override fun createInnerTerminalWidget(): JediTerminalWidget { return createTerminalWidget(settingsProvider) } } } override fun createTtyConnector(): TtyConnector { try { val charset = Charset.forName("UTF-8") val envs = Maps.newHashMap(System.getenv()) EncodingEnvironmentUtil.setLocaleEnvironmentIfMac(envs, charset) val command: Array<String> if (UIUtil.isWindows) { command = arrayOf("cmd.exe") } else { command = arrayOf("/bin/bash", "--login") envs.put("TERM", "xterm") } val process = PtyProcess.exec(command, envs, null) return LoggingPtyProcessTtyConnector(process, charset) } catch (e: Exception) { throw IllegalStateException(e) } } override fun createTerminalWidget(settingsProvider: TabbedSettingsProvider): JediTerminalWidget { val widget = JediTerminalWidget(settingsProvider, this) widget.addHyperlinkFilter(UrlFilter()) return widget } class LoggingPtyProcessTtyConnector(process: PtyProcess, charset: Charset) : PtyProcessTtyConnector(process, charset), LoggingTtyConnector { private val myDataChunks = Lists.newArrayList<CharArray>() @Throws(IOException::class) override fun read(buf: CharArray, offset: Int, length: Int): Int { val len = super.read(buf, offset, length) if (len > 0) { val arr = Arrays.copyOfRange(buf, offset, len) myDataChunks.add(arr) } return len } override fun getChunks(): List<CharArray> { return Lists.newArrayList(myDataChunks) } @Throws(IOException::class) override fun write(string: String) { AbstractTerminalFrame.LOG.debug("Writing in OutputStream : " + string) super.write(string) } @Throws(IOException::class) override fun write(bytes: ByteArray) { AbstractTerminalFrame.LOG.debug("Writing in OutputStream : " + Arrays.toString(bytes) + " " + String(bytes)) super.write(bytes) } } }
0
null
0
1
dd6eb93967891556746e5a60714c425e3853002d
4,536
jediterm
Apache License 2.0
app-inspection/inspectors/database/testSrc/com/android/tools/idea/sqlite/mocks/FakeTableView.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.sqlite.mocks import com.android.tools.idea.sqlite.ui.tableView.OrderBy import com.android.tools.idea.sqlite.ui.tableView.RowDiffOperation import com.android.tools.idea.sqlite.ui.tableView.TableView import com.android.tools.idea.sqlite.ui.tableView.ViewColumn import org.mockito.Mockito.mock import javax.swing.JComponent open class FakeTableView : TableView { val errorReported = mutableListOf<Pair<String, Throwable?>>() val listeners = mutableListOf<TableView.Listener>() override val component = mock(JComponent::class.java) override fun resetView() {} override fun startTableLoading() {} override fun showTableColumns(columns: List<ViewColumn>) {} override fun stopTableLoading() {} override fun reportError(message: String, t: Throwable?) { errorReported.add(Pair(message, t)) } override fun setFetchPreviousRowsButtonState(enable: Boolean) {} override fun setFetchNextRowsButtonState(enable: Boolean) {} override fun setEditable(isEditable: Boolean) {} override fun addListener(listener: TableView.Listener) { listeners.add(listener) } override fun removeListener(listener: TableView.Listener) { listeners.remove(listener) } override fun updateRows(rowDiffOperations: List<RowDiffOperation>) {} override fun setEmptyText(text: String) {} override fun setRowOffset(rowOffset: Int) {} override fun revertLastTableCellEdit() {} override fun setColumnSortIndicator(orderBy: OrderBy) {} override fun setLiveUpdatesButtonState(state: Boolean) {} override fun setRefreshButtonState(state: Boolean) {} override fun showPageSizeValue(maxRowCount: Int) {} }
5
null
227
948
10110983c7e784122d94c7467e9d243aba943bf4
2,288
android
Apache License 2.0
Tester/src/main/java/indi/arrowyi/autoconfigtest/KotlinTest.kt
Arrowyi
571,398,529
false
{"Java": 91960, "Kotlin": 1188}
package indi.arrowyi.autoconfigtest import indi.arrowyi.autoconfig.AutoRegisterInt import indi.arrowyi.autoconfig.AutoRegisterString import indi.arrowyi.autoconfig.configmanager.AutoConfig @AutoRegisterString(defaultValue = "kotlin") const val KOLINT_TEST : String = "KOLINT_TEST" class KotlinTest { companion object{ @AutoRegisterInt(defaultValue = 6) const val KOTLIN_COMPANION = "KOLINT_COM_TEST" } fun main(){ println("test String is ${AutoConfig.get(KOLINT_TEST)}") } }
1
null
1
1
02378435246a1f0f7ef8aa40fc1a2e91b697cb31
520
AutoConfig
Apache License 2.0
app/src/main/java/rgu5android/jetpack/data/ApiService.kt
RGU5Android
159,908,258
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Markdown": 1, "Proguard": 1, "XML": 22, "Kotlin": 44, "Java": 2}
package rgu5android.jetpack.data import androidx.lifecycle.LiveData import com.google.gson.JsonObject import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Path import retrofit2.http.Query import rgu5android.jetpack.data.model.RepositorySearchResponse import rgu5android.jetpack.helper.ApiResponse import rgu5android.jetpack.vo.Follow import rgu5android.jetpack.vo.GithubUser interface ApiService { companion object { const val baseUrl: String = "https://api.github.com/" const val clientId: String = "YOUR_CLIENT_ID" const val clientSecret: String = "YOUR_CLIENT_SECRET" } @GET("users/{userName}") fun findUser( @Path("userName") userName: String, @Query("client_id") clientId: String = Companion.clientId, @Query("client_secret") clientSecret: String = Companion.clientSecret ): LiveData<ApiResponse<GithubUser>> @GET("users/{userName}/followers") fun userFollowers( @Path("userName") userName: String, @Query("client_id") clientId: String = Companion.clientId, @Query("client_secret") clientSecret: String = Companion.clientSecret ): LiveData<ApiResponse<List<Follow>>> @GET("users/{userName}/following") fun userFollowings( @Path("userName") userName: String, @Query("client_id") clientId: String = Companion.clientId, @Query("client_secret") clientSecret: String = Companion.clientSecret ): LiveData<ApiResponse<List<Follow>>> @GET("search/repositories") fun searchRepository( @Query("client_id") clientId: String = Companion.clientId, @Query("client_secret") clientSecret: String = Companion.clientSecret, @Query("sort") sortBy: String = "stars", @Query("order") order: String = "desc", @Query("q") query: String, @Query("page") page: Int, @Query("per_page") perPage: Int ): Call<RepositorySearchResponse> @GET("users/rgu5android") fun authenticate( @Query("client_id") clientId: String = Companion.clientId, @Query("client_secret") clientSecret: String = Companion.clientSecret ): Call<JsonObject> }
0
Kotlin
0
0
8795f51b712489552492ab268b62f6584f0637c2
1,988
Android-Jetpack-Sample
Apache License 2.0
app/src/main/java/com/mapswithme/maps/auth/PhoneTokenHandler.kt
dnemov
245,413,600
false
null
package com.mapswithme.maps.auth import android.content.Intent import android.text.TextUtils import com.mapswithme.maps.Framework class PhoneTokenHandler : TokenHandler { override var token: String? = null override fun checkToken(requestCode: Int, data: Intent): Boolean { if (requestCode != Constants.REQ_CODE_PHONE_AUTH_RESULT) return false token = data.getStringExtra(Constants.EXTRA_PHONE_AUTH_TOKEN) return !TextUtils.isEmpty(token) } override val type: Int get() = Framework.SOCIAL_TOKEN_PHONE }
0
Kotlin
0
1
8b75114193e141aee14fcbc207a208c4a39de1db
553
omim.kt
Apache License 2.0
proto-router/src/test/kotlin/actor/proto/router/fixture/TestDispatcher.kt
asynkron
96,669,281
false
null
package actor.proto.router.fixture import actor.proto.mailbox.Dispatcher import actor.proto.mailbox.Mailbox class TestDispatcher : Dispatcher { override var throughput: Int = 10 override fun schedule(mailbox:Mailbox) { } }
8
null
21
211
5d42177ff79969000b64a150ac4433dee3209b45
238
protoactor-kotlin
Apache License 2.0
domain/src/main/java/com/luismunyoz/domain/browser/GetUserUseCase.kt
luismunyoz
589,924,211
false
null
package com.luismunyoz.domain.browser import javax.inject.Inject class GetUserUseCase @Inject constructor( private val browserRepositoryContract: BrowserRepositoryContract ) { suspend operator fun invoke() = browserRepositoryContract.getUser() }
0
Kotlin
0
0
8ca2a9579481eda06517ffb3c234fd6f095de2ce
256
DirBrowser
Apache License 2.0
src/test/kotlin/de/flapdoodle/kfx/layout/absolute/AbsolutePaneSampler.kt
flapdoodle-oss
451,526,335
false
{"Kotlin": 833180, "Java": 154205, "CSS": 40962, "Shell": 297}
/* * Copyright (C) 2022 * <NAME> <<EMAIL>> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.flapdoodle.kfx.layout.absolute import de.flapdoodle.kfx.extensions.withAnchors import de.flapdoodle.kfx.layout.grid.WeightGridPane import de.flapdoodle.kfx.layout.splitpane.BetterSplitPane import de.flapdoodle.kfx.layout.splitpane.SplitPane import javafx.application.Application import javafx.beans.property.SimpleObjectProperty import javafx.event.EventHandler import javafx.geometry.HPos import javafx.geometry.Insets import javafx.geometry.VPos import javafx.scene.Group import javafx.scene.Node import javafx.scene.Scene import javafx.scene.control.Button import javafx.scene.control.Label import javafx.scene.control.ScrollPane import javafx.scene.layout.AnchorPane import javafx.scene.layout.Background import javafx.scene.layout.HBox import javafx.scene.layout.Pane import javafx.scene.layout.Region import javafx.scene.paint.Color import javafx.scene.shape.LineTo import javafx.scene.shape.MoveTo import javafx.scene.shape.Path import javafx.stage.Stage import org.junit.jupiter.api.Assertions.* class AbsolutePaneSampler { class Sample : Application() { override fun start(stage: Stage) { // val oldSplitPane = BetterSplitPane().apply { //// background = Background.fill(Color.rgb(240,240,204)) //// border = Border.stroke(Color.BLUE) // // nodes().addAll(LabelContent("A"), ButtonContent("1"), LabelContent("B")) // } // // val nodes = SimpleObjectProperty( // listOf(LabelContent("A"), ButtonContent("1"), LabelContent("B")) // ) // // val onDoubleClick = { node: Content -> // println("clicked on $node") // } // val splitPane = SplitPane(nodes, onDoubleClick).apply { //// background = Background.fill(Color.RED) //// border = Border.stroke(Color.RED) // } // // val buttons = SimpleObjectProperty( // listOf(Label("A"), Button("1"), Label("B")) // ) // //// val splitPane2 = SplitPane(buttons).apply { ////// background = Background.fill(Color.RED) //// border = Border.stroke(Color.GREEN) //// WeightGridPane.setPosition(this,1,2, HPos.LEFT, VPos.CENTER) //// } // // val grid = WeightGridPane().apply { // setColumnWeight(0, 0.01) // setColumnWeight(2, 0.01) // } // grid.children.add(wrap(oldSplitPane).apply { // WeightGridPane.setPosition(this,1,0, HPos.LEFT, VPos.CENTER) // }) // grid.children.add(wrap(splitPane).apply { // WeightGridPane.setPosition(this,1,1, HPos.LEFT, VPos.CENTER) // }) //// content.children.add(splitPane2) //// stuff.children.add(VBox().apply { //// WeightGridPane.setPosition(this,2,0, HPos.LEFT, VPos.CENTER) //// children.add(Button("noop").apply { //// }) //// }) //// stuff.children.add(VBox().apply { //// WeightGridPane.setPosition(this,0,1, HPos.LEFT, VPos.CENTER) //// children.add(Button("noop").apply { //// }) //// }) // // val all= AnchorPane() // all.children.add(grid.withAnchors(all = 10.0, bottom = 50.0)) // all.children.add(HBox().withAnchors(left = 10.0, bottom = 2.0, right = 10.0).apply { // children.add(Button("+").apply { // onAction = EventHandler { // nodes.value = nodes.value + LabelContent("X") // } // }) // }) val pane = Pane().apply { WeightGridPane.setPosition(this, 0, 0, HPos.LEFT, VPos.TOP) background = Background.fill(Color.AQUAMARINE) children.addAll(samplePath(), sampleLabel()) } val anchorPane = AnchorPane().apply { WeightGridPane.setPosition(this, 1, 0, HPos.LEFT, VPos.TOP) background = Background.fill(Color.LIME) children.addAll(samplePath(), sampleLabel()) } val region = object: Region() { init { WeightGridPane.setPosition(this, 0, 1, HPos.LEFT, VPos.TOP) background = Background.fill(Color.BLANCHEDALMOND) children.addAll(samplePath(), sampleLabel()) } } val testee = Group().apply { WeightGridPane.setPosition(this, 1, 1, HPos.LEFT, VPos.TOP) // background = Background.fill(Color.DARKGOLDENROD) children.addAll(samplePath(), sampleLabel()) } val all = WeightGridPane().apply { padding = Insets(20.0, 20.0, 20.0, 20.0) // setColumnWeight(0, 1.0) // setColumnWeight(1, 1.0) } all.children.addAll(pane, anchorPane, region, testee) stage.scene = Scene(all, 800.0, 600.0) stage.show() } private fun sampleLabel(): Label { return Label("sample").apply { layoutX = 30.0 layoutY = 30.0 } } private fun samplePath(): Path { return Path().apply { stroke = Color.RED elements.addAll( MoveTo(10.0, 10.0), LineTo(50.0, 50.0), LineTo(-10.0, 50.0), LineTo(-10.0, -10.0), LineTo(50.0, -10.0) ) } } // fun wrap(node: Node): ScrollPane { // return ScrollPane(node).apply { // isFitToHeight = true // } // } } abstract class Content : AnchorPane() { } class LabelContent(text: String) : Content() { init { children.add(Label(text).withAnchors(all = 0.0)) } } class ButtonContent(text: String) : Content() { init { children.add(Button(text).withAnchors(all = 0.0)) } } companion object { @JvmStatic fun main(args: Array<String>) { Application.launch(Sample::class.java, *args) } } }
0
Kotlin
1
0
b879584f16bcd451b20596fd8c9f7d028105988f
6,173
de.flapdoodle.kfx
Apache License 2.0
lib/Domain/src/main/kotlin/com/blok/post/ListPostsQuery.kt
jvalduvieco
61,638,034
false
null
package com.blok.post import com.blok.common.Query import com.blok.common.Response import com.blok.model.Post class ListPostsQuery: Query() class ListPostsQueryResponse (val posts: List<Post>): Response()
0
Kotlin
0
0
fc9f9d50b77cfa80e8349c55d349fc8d0289759c
207
blok
MIT License
src/main/kotlin/com/gmail/blueboxware/libgdxplugin/filetypes/atlas/psi/impl/mixins/AtlasRegionMixin.kt
eashevchenko
83,151,121
true
{"Kotlin": 493156, "Java": 38976, "Lex": 3884, "HTML": 754}
package com.gmail.blueboxware.libgdxplugin.filetypes.atlas.psi.impl.mixins import com.gmail.blueboxware.libgdxplugin.filetypes.atlas.getValue import com.gmail.blueboxware.libgdxplugin.filetypes.atlas.psi.AtlasRegion import com.gmail.blueboxware.libgdxplugin.filetypes.atlas.psi.impl.AtlasElementImpl import com.intellij.lang.ASTNode import com.intellij.navigation.ItemPresentation import icons.ImagesIcons /* * Copyright 2017 Blue Box Ware * * 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. */ abstract class AtlasRegionMixin(node: ASTNode) : AtlasRegion, AtlasElementImpl(node) { override fun getPresentation() = object : ItemPresentation { override fun getLocationString() = null override fun getIcon(unused: Boolean) = ImagesIcons.ImagesFileType override fun getPresentableText() = regionName.getValue() } }
0
Kotlin
0
0
b546e7c169130e518022e28fa9f2580dd2204607
1,339
LibGDXPlugin
Apache License 2.0
app/src/main/java/com/platform/jsbridge/KVStoreJs.kt
breadwallet
37,503,422
false
null
package com.platform.jsbridge import android.content.Context import android.webkit.JavascriptInterface import com.platform.APIClient import com.platform.kvstore.RemoteKVStore import com.platform.kvstore.ReplicatedKVStore import com.platform.sqlite.KVItem import org.json.JSONObject import java.text.SimpleDateFormat import java.util.Locale class KVStoreJs( private val nativePromiseFactory: NativePromiseFactory, private val context: Context ) : JsApi { private val store: ReplicatedKVStore get() { val remote = RemoteKVStore.getInstance(APIClient.getInstance(context)) return ReplicatedKVStore.getInstance(context, remote) } companion object { const val KEY_VERSION = "version" const val KEY_LAST_MODIFIED = "lastModified" } @JavascriptInterface fun get( key: String ) = nativePromiseFactory.create { val completionObj = store.get(getKey(key), 0) val kv = completionObj.kv check(kv != null && kv.deleted == 0) { "KVStore does not contain an entry for $key" } try { val jsonVal = kv.value.toString(Charsets.UTF_8) JSONObject(jsonVal).decorate(kv.version, kv.time) } catch (e: Exception) { store.delete(getKey(key), kv.version) throw e } } @JavascriptInterface fun put( key: String, valueStr: String, version: Long ) = nativePromiseFactory.create { val completionObj = store.set( KVItem( version, 0, getKey(key), valueStr.toByteArray(Charsets.UTF_8), System.currentTimeMillis(), 0 ) ) check(completionObj.err == null) { "KVStore error on setting the key: $key, err: ${completionObj.err}" } JSONObject(valueStr).decorate(completionObj.version, completionObj.time) } @JavascriptInterface fun delete( key: String, version: Long ) = nativePromiseFactory.create { val completionObj = store.delete(getKey(key), version) check(completionObj != null && completionObj.err == null) { "KVStore error deleting the key: $key, err: ${completionObj.err}" } JSONObject().decorate(completionObj.version, completionObj.time) } private fun JSONObject.decorate(version: Long, time: Long): JSONObject { put(KEY_VERSION, version) val dateTime = SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US).format(time) return put(KEY_LAST_MODIFIED, dateTime) } private fun getKey(key: String) = "plat-$key" }
5
Kotlin
450
385
dfbbfbfc92dae054e47f245e1ce2ac8a39e65e57
2,735
breadwallet-android
MIT License
an/Wechat/app/src/main/java/com/example/wechat/Message_Fragment.kt
danyfang
120,310,634
false
{"Java": 4437735, "Jupyter Notebook": 3510225, "Python": 2038115, "C++": 1751271, "HTML": 470330, "Scala": 345699, "TeX": 92352, "C": 58145, "Haskell": 35292, "Kotlin": 32248, "Shell": 8393, "R": 1616, "CSS": 1278, "ActionScript": 543, "JavaScript": 402, "Ruby": 303, "CMake": 239, "Go": 182}
package com.example.wechat import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment class Message_Fragment : Fragment() { override fun onCreateView(inflator : LayoutInflater, container : ViewGroup?, savedInstanceState : Bundle?) : View?{ val view = inflator.inflate(R.layout.message_fragment, null) return view } }
1
Java
1
1
8168f6058648f2a330a7354daf3a73a4d8a4e730
439
SourceCode
MIT License
an/Wechat/app/src/main/java/com/example/wechat/Message_Fragment.kt
danyfang
120,310,634
false
{"Java": 4437735, "Jupyter Notebook": 3510225, "Python": 2038115, "C++": 1751271, "HTML": 470330, "Scala": 345699, "TeX": 92352, "C": 58145, "Haskell": 35292, "Kotlin": 32248, "Shell": 8393, "R": 1616, "CSS": 1278, "ActionScript": 543, "JavaScript": 402, "Ruby": 303, "CMake": 239, "Go": 182}
package com.example.wechat import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment class Message_Fragment : Fragment() { override fun onCreateView(inflator : LayoutInflater, container : ViewGroup?, savedInstanceState : Bundle?) : View?{ val view = inflator.inflate(R.layout.message_fragment, null) return view } }
1
Java
1
1
8168f6058648f2a330a7354daf3a73a4d8a4e730
439
SourceCode
MIT License
cinescout/search/presentation/src/main/kotlin/cinescout/search/presentation/action/SearchAction.kt
fardavide
280,630,732
false
null
package cinescout.search.presentation.action internal sealed interface SearchAction { @JvmInline value class Search(val query: String) : SearchAction }
10
Kotlin
2
6
4c1b7baa4270e2b786982b2fd435a7128be9a70e
162
CineScout
Apache License 2.0
app/src/main/java/com/hope/guanjiapo/model/PrintDeviceModel.kt
kazeik
172,053,633
false
null
package com.hope.guanjiapo.model /** * @author <NAME> * QQ:77132995 email:<EMAIL> * 2019 03 05 19:20 * 类说明: */ class PrintDeviceModel { var address: String? = "" var name: String? = "" var status: Int? = 0 }
0
Kotlin
2
1
9c435adb7dfa134fdd016f26ee7817f971e2a11c
242
GuanJiaPo
Apache License 2.0
meijue-ui/src/main/java/com/obsez/mobile/meijue/ui/base/BaseActivity.kt
hedzr
146,757,111
false
null
package com.obsez.mobile.meijue.ui.base import android.annotation.SuppressLint import android.os.Build import android.os.Bundle import android.os.Handler import android.os.PersistableBundle import android.view.MenuItem import androidx.appcompat.app.ActionBarDrawerToggle import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatDelegate import androidx.appcompat.widget.Toolbar import androidx.drawerlayout.widget.DrawerLayout import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentTransaction import androidx.viewpager.widget.ViewPager import com.google.android.material.appbar.CollapsingToolbarLayout import com.google.android.material.bottomnavigation.BottomNavigationView import com.google.android.material.floatingactionbutton.FloatingActionButton import com.google.android.material.navigation.NavigationView import com.google.android.material.tabs.TabLayout import com.obsez.mobile.meijue.ui.R import com.obsez.mobile.meijue.ui.base.fr.Entering import com.obsez.mobile.meijue.ui.base.fr.FrameElements import com.obsez.mobile.meijue.ui.ext.snackBar import com.obsez.mobile.meijue.ui.pref.PreferenceUtil import timber.log.Timber import java.lang.ref.WeakReference @Suppress("MemberVisibilityCanBePrivate") open class BaseActivity : AppCompatActivity(), FrameElements { /** * 当回退栈仅剩一个fragment时,是否立即退出app */ open var allowExitAtLastFragment: Boolean = false /** * 双击返回按钮才会退出app */ open var allowDoubleTapToExit: Boolean = false override val drawerLayoutUi: DrawerLayout? get() = null override val navDrawerUi: NavigationView? get() = null override val actionBarDrawerToggleUi: ActionBarDrawerToggle? get() = null override val toolbarUi: Toolbar? get() = null override val collapsingToolbarLayoutUi: CollapsingToolbarLayout? get() = null override val tabLayoutUi: TabLayout? get() = null override val viewPagerUi: ViewPager? get() = null override val bottomNavigationViewUi: BottomNavigationView? get() = null override val fabUi: FloatingActionButton? get() = null //fun getSupportFragmentManager(): FragmentManager { // return mFragments.supportFragmentManager //} protected var lastAttachedFragment: WeakReference<Fragment>? = null override fun onAttachFragment(fragment: Fragment) { super.onAttachFragment(fragment) Timber.d("onAttachFragment: $fragment") if (fragment != null) { lastAttachedFragment = WeakReference(fragment) if (fragment is Entering) { fragment.onAttachToActivity(this) } } } override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) { preOnCreate(savedInstanceState) super.onCreate(savedInstanceState, persistentState) myCreate(savedInstanceState) } override fun onCreate(savedInstanceState: Bundle?) { preOnCreate(savedInstanceState) super.onCreate(savedInstanceState) myCreate(savedInstanceState) } protected open fun preOnCreate(savedInstanceState: Bundle?) { loadNightMode() } protected open fun myCreate(savedInstanceState: Bundle?) { } override fun setContentView(layoutResID: Int) { super.setContentView(layoutResID) postSetContentView(layoutResID) } fun superSetContentView(layoutResID: Int) { super.setContentView(layoutResID) } protected open fun postSetContentView(layoutResID: Int) { } protected open fun loadNightMode() { val nm = nightMode if (nm != AppCompatDelegate.getDefaultNightMode()) { setNightMode(nm) } } @AppCompatDelegate.NightMode open var nightMode: Int get() { //return pref("nightMode", AppCompatDelegate.getDefaultNightMode()).getValue() val pref = PreferenceUtil.get(this) @Suppress("UnnecessaryVariable") @AppCompatDelegate.NightMode val nightModeLocal = pref.getInt("nightMode", AppCompatDelegate.getDefaultNightMode()) //Timber.d("load nightMode : $nightMode_") return nightModeLocal } @SuppressLint("ObsoleteSdkInt") set(value) { setNightMode(value, true) } @SuppressLint("ObsoleteSdkInt") open fun setNightMode(@AppCompatDelegate.NightMode nightMode_: Int, needRecreate: Boolean = false) { val pref = PreferenceUtil.get(this) //pref.getInt("nightMode") pref.edit().putInt("nightMode", nightMode_).apply() //Timber.d("setNightMode : $value") AppCompatDelegate.setDefaultNightMode(nightMode_) if (Build.VERSION.SDK_INT >= 11 && needRecreate) { recreate() } } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. return when (item.itemId) { //R.id.menu_night_mode_system -> { nightMode = (AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM); true } //R.id.menu_night_mode_day -> { nightMode = (AppCompatDelegate.MODE_NIGHT_NO); true } //R.id.menu_night_mode_night -> { nightMode = (AppCompatDelegate.MODE_NIGHT_YES); true } //R.id.menu_night_mode_auto -> { nightMode = (AppCompatDelegate.MODE_NIGHT_AUTO); true } android.R.id.home -> { //mDrawerLayout.openDrawer(GravityCompat.START); return true onBackPressed() true } //R.id.action_settings -> true //R.id.action_favorites -> { startActivity<ScrollingActivity>(); true } else -> super.onOptionsItemSelected(item) } } // fun fixBackStack(): Fragment? { val af = supportFragmentManager.activeFragment if (af != null) { val ft = supportFragmentManager.beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN) ft.show(af) ft.commitAllowingStateLoss() } return af } /** * * Activity + 多Frament 使用时的一些坑.md * https://github.com/gpfduoduo/android-article/blob/master/Activity%20%2B%20%E5%A4%9AFrament%20%E4%BD%BF%E7%94%A8%E6%97%B6%E7%9A%84%E4%B8%80%E4%BA%9B%E5%9D%91.md * */ inline val FragmentManager.activeFragment: Fragment? get() { if (this.backStackEntryCount > 0) { val entry = this.getBackStackEntryAt(this.backStackEntryCount - 1) return this.findFragmentByTag(entry.name) } return null } /** * baSuperOnBackPressed */ fun baSuperOnBackPressed() { super.onBackPressed() } override fun onBackPressed() { //super.onBackPressed() Timber.d("onBackPressed()") val fragmentManager = this.supportFragmentManager val isStateSaved = fragmentManager.isStateSaved // if (isStateSaved && Build.VERSION.SDK_INT <= Build.VERSION_CODES.N_MR1) { // // Older versions will throw an exception from the framework // // FragmentManager.popBackStackImmediate(), so we'll just // // return here. The Activity is likely already on its way out // // since the fragmentManager has already been saved. // return // } if (!isStateSaved || Build.VERSION.SDK_INT > Build.VERSION_CODES.N_MR1) { if (allowExitAtLastFragment) { // 当只有初始fragment时,不允许弹出backStack,而是应该退出app了 if (fragmentManager.backStackEntryCount > 1) { this.doubleBackToExitPressedOnce = false baSuperOnBackPressed() fixBackStack() return } } } if (allowDoubleTapToExit) { if (doubleBackToExitPressedOnce) { if (fragmentManager.backStackEntryCount == 1) { fragmentManager.popBackStack() // 弹出初始fragment } baSuperOnBackPressed() this.doubleBackToExitPressedOnce = false return } this.doubleBackToExitPressedOnce = true snackBar(getString(R.string.twice_back_pressed_to_exit)) Handler().postDelayed({ doubleBackToExitPressedOnce = false }, 2000) } else baSuperOnBackPressed() } private var doubleBackToExitPressedOnce = false }
0
null
0
4
aa0782c8d42d412011faac9b7787eeb53efe7528
9,023
meijue-ui
MIT License
app/src/main/java/kr/feliz/tutorial_collection/common/CurrencyListFragmentExample.kt
daryeou
472,661,370
false
null
package kr.feliz.tutorial_collection.common // //import android.annotation.SuppressLint //import android.os.Bundle //import android.util.Log //import android.view.View //import androidx.core.content.ContextCompat //import androidx.fragment.app.activityViewModels //import androidx.lifecycle.Observer //import androidx.recyclerview.widget.DividerItemDecoration //import com.google.android.material.snackbar.Snackbar //import com.lemonfox.exchange.R //import com.lemonfox.exchange.common.BaseFragment //import com.lemonfox.exchange.databinding.FragmentHomeCurrencySimpleListBinding //import com.lemonfox.exchange.scene.market.adapter.CurrencyListAdapter //import com.lemonfox.exchange.scene.market.item.CurrencyListItem //import com.lemonfox.exchange.scene.market.viewmodel.CurrencyListViewModel // // //class CurrencyListFragmentExample: BaseFragment<FragmentHomeCurrencySimpleListBinding>() { // // override val resId = R.layout.fragment_home_currency_simple_list // private lateinit var binding: FragmentHomeCurrencySimpleListBinding // // private val viewModel: CurrencyListViewModel by activityViewModels() // private lateinit var currencyListAdapter: CurrencyListAdapter // // override fun onViewCreated(view: View, savedInstanceState: Bundle?) { // /** 전달받은 인스턴스를 호출하는 방법 */ // // val someInt = requireArguments().getInt("some_int") // super.onViewCreated(view, savedInstanceState) // // binding = getViewBinding() // // val itemDecorator: DividerItemDecoration = // DividerItemDecoration(requireContext(), DividerItemDecoration.VERTICAL) // itemDecorator.setDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.item_grayline)!!) // // currencyListAdapter = CurrencyListAdapter(requireContext()) // binding.currencySimpleListview.addItemDecoration(itemDecorator) // binding.currencySimpleListview.adapter = currencyListAdapter // // viewModel.currencyListDatas.observe(viewLifecycleOwner, currencyObserver) // viewModel.request() // } // // @SuppressLint("NotifyDataSetChanged") // val currencyObserver = // Observer<List<CurrencyListItem>> { data -> // // Log.d("orion","update log $data") // Snackbar.make(binding.root,"데이터 갱신", Snackbar.LENGTH_SHORT).show() // currencyListAdapter.datas = data // currencyListAdapter.notifyDataSetChanged() // } // // override fun onResume() { // super.onResume() // Log.d("orion","fragment onResume") // } // // override fun onDestroyView() { // super.onDestroyView() // Log.d("orion","fragment Destroyed") // } // // // //}
0
Kotlin
0
0
303f2a572ce06df3c57032c72bb19350a68d78d8
2,687
android_tutorial_collection
MIT License
plugin-build/plugin/src/main/java/io/github/rudikone/plugin/RegisterTask.kt
rudikone
737,096,619
false
null
package io.github.rudikov.plugin import io.confluent.kafka.schemaregistry.avro.AvroSchema import io.confluent.kafka.schemaregistry.client.CachedSchemaRegistryClient import org.apache.avro.Schema import org.gradle.api.DefaultTask import org.gradle.api.provider.MapProperty import org.gradle.api.provider.Property import org.gradle.api.provider.SetProperty import org.gradle.api.tasks.Input import org.gradle.api.tasks.Optional import org.gradle.api.tasks.TaskAction abstract class RegisterTask : DefaultTask() { init { description = "Register all schemas" group = "other" } @get:Input @get:Optional abstract val schemaRegistryUrl: Property<String> @get:Input @get:Optional abstract val searchAvroFilesPaths: SetProperty<String> @get:Input abstract val subjectToSchema: MapProperty<String, String> @TaskAction fun registerAllSchemas() { if (subjectToSchema.orNull.isNullOrEmpty()) { error("No schema has been announced!") } val client = CachedSchemaRegistryClient(schemaRegistryUrl.get(), subjectToSchema.get().entries.size) subjectToSchema.get().forEach { (subject, schemaName) -> searchAvroFilesPaths.get().forEach { searchPath -> runCatching { val avroFile = findAvroFileByName(searchPath = searchPath, schemaName = schemaName) val schema = AvroSchema(Schema.Parser().parse(avroFile)) client.register(subject, schema) }.onSuccess { logger.lifecycle(it.toString()) }.onFailure { logger.warn("Failed register $schemaName for $subject!", it) } } } } }
0
null
0
1
c58c54a10eac132ce33fa0ad1f85b1db9596a86b
1,767
avroschema-wizard-plugin
MIT License
app/src/main/java/com/example/covidapp/ui/adapter/PrecautionsAdapter.kt
swapnilsparsh
341,976,513
false
null
package com.example.covidapp.ui.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.example.covidapp.data.model.Model import com.example.covidapp.databinding.ItemSymptomsBinding class PrecautionsAdapter() : ListAdapter<Model, PrecautionsAdapter.ViewHolder>(COMPARATOR) { companion object { private val COMPARATOR = object : DiffUtil.ItemCallback<Model>() { override fun areContentsTheSame(oldItem: Model, newItem: Model): Boolean { return oldItem.equals(newItem) } override fun areItemsTheSame(oldItem: Model, newItem: Model): Boolean { return oldItem == newItem } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder( ItemSymptomsBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind(getItem(position)) } inner class ViewHolder(private val binding: ItemSymptomsBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(precautionsModel: Model) = binding.run { imageView.setImageResource(precautionsModel.imageview) txtSymptoms.text = precautionsModel.symptomsText txtSymptomsDetail.text = precautionsModel.symptomsDetail } } }
1
Kotlin
7
9
37770bc00d7f5a461b34a78129e840bba3abb2ac
1,646
Covid-App
MIT License
src/main/kotlin/com/github/stormbit/vksdk/events/chat/ChatLeaveEvent.kt
Storm-bit
292,098,640
false
null
package com.github.stormbit.vksdk.events.chat import com.github.stormbit.vksdk.events.ServiceActionEvent import com.github.stormbit.vksdk.events.message.ChatMessageEvent import com.github.stormbit.vksdk.objects.AbstractMessage data class ChatLeaveEvent( val fromId: Int, val userId: Int, val chatId: Int ) : ChatMessageEvent(fromId), ServiceActionEvent
0
Kotlin
0
1
fe89aef3d11761475b1a246b92c49c2286c38130
366
vk-bot-sdk-kotlin
MIT License
src/commonMain/kotlin/com/soywiz/ktcc/util/CharExt.kt
korlibs
165,555,533
false
null
package com.soywiz.ktcc.util fun Char.isHexDigit() = this in '0'..'9' || this in 'a'..'f' || this in 'A'..'F' fun Char.isDigit() = this in '0'..'9' fun Char.isAlphaLC() = (this in 'a'..'z') fun Char.isAlphaUC() = (this in 'A'..'Z') fun Char.isAlpha() = isAlphaLC() || isAlphaUC() fun Char.isAlnum() = isAlpha() || isDigit() fun Char.isAlphaOrUnderscore() = this.isAlpha() || this == '_' fun Char.isAlnumOrUnderscore() = this.isAlphaOrUnderscore() || isDigit() fun Char.isWhitespaceFast(): Boolean = this == ' ' || this == '\t' || this == '\r' || this == '\n' || this == '\u00A0'
1
Kotlin
5
63
f3d1cace49f6a74e3aad71a2cdcc22b877d3c783
580
ktcc
MIT License
compose/animation/animation-core/src/commonMain/kotlin/androidx/compose/animation/core/AnimationEndReason.kt
androidx
256,589,781
false
{"Kotlin": 112114129, "Java": 66594571, "C++": 9132142, "AIDL": 635065, "Python": 325169, "Shell": 194520, "TypeScript": 40647, "HTML": 35176, "Groovy": 27178, "ANTLR": 26700, "Svelte": 20397, "CMake": 15512, "C": 15043, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019}
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.animation.core /** Possible reasons for [Animatable]s to end. */ enum class AnimationEndReason { /** * Animation will be forced to end when its value reaches upper/lower bound (if they have been * defined, e.g. via [Animatable.updateBounds]) * * Unlike [Finished], when an animation ends due to [BoundReached], it often falls short from * its initial target, and the remaining velocity is often non-zero. Both the end value and the * remaining velocity can be obtained via [AnimationResult]. */ BoundReached, /** Animation has finished successfully without any interruption. */ Finished }
30
Kotlin
950
5,321
98b929d303f34d569e9fd8a529f022d398d1024b
1,283
androidx
Apache License 2.0
app/src/main/java/com/mxt/anitrend/view/fragment/detail/NotificationFragment.kt
AniTrend
91,993,436
false
null
package com.mxt.anitrend.view.fragment.detail import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.widget.Toast import com.annimon.stream.IntPair import com.annimon.stream.Stream import com.mxt.anitrend.R import com.mxt.anitrend.adapter.recycler.detail.NotificationAdapter import com.mxt.anitrend.base.custom.async.ThreadPool import com.mxt.anitrend.base.custom.fragment.FragmentBaseList import com.mxt.anitrend.model.entity.anilist.Notification import com.mxt.anitrend.model.entity.anilist.User import com.mxt.anitrend.model.entity.base.NotificationHistory import com.mxt.anitrend.model.entity.base.NotificationHistory_ import com.mxt.anitrend.model.entity.container.body.PageContainer import com.mxt.anitrend.model.entity.container.request.QueryContainerBuilder import com.mxt.anitrend.presenter.base.BasePresenter import com.mxt.anitrend.util.CompatUtil import com.mxt.anitrend.util.DialogUtil import com.mxt.anitrend.util.GraphUtil import com.mxt.anitrend.util.KeyUtil import com.mxt.anitrend.util.MediaActionUtil import com.mxt.anitrend.util.NotifyUtil import com.mxt.anitrend.view.activity.detail.CommentActivity import com.mxt.anitrend.view.activity.detail.MediaActivity import com.mxt.anitrend.view.activity.detail.ProfileActivity import java.util.Collections /** * Created by max on 2017/12/06. * NotificationFragment */ class NotificationFragment : FragmentBaseList<Notification, PageContainer<Notification>, BasePresenter>() { /** * Override and set presenter, mColumnSize, and fetch argument/s * * @param savedInstanceState */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mColumnSize = R.integer.single_list_x1 isPager = true setInflateMenu(R.menu.notification_menu) mAdapter = NotificationAdapter(context!!) setPresenter(BasePresenter(context)) setViewModel(true) } /** * Is automatically called in the @onStart Method if overridden in list implementation */ override fun updateUI() { val historyItems = presenter.database.getBoxStore(NotificationHistory::class.java).count() if (historyItems < 1) markAllNotificationsAsRead() injectAdapter() val currentUser = presenter.database.currentUser currentUser.unreadNotificationCount = 0 presenter.database.saveCurrentUser(currentUser) //Testing notifications by forcing the notification dispatcher /*for (int i = 0; i < 3; i++) NotificationUtil.createNotification(getContext(), new ArrayList<>(model.subList(i, i + 1)));*/ // NotificationUtil.createNotification(getContext(), new ArrayList<>(model.subList(5, 6))); } override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) { super.onCreateOptionsMenu(menu, inflater) menu!!.findItem(R.id.action_mark_all).isVisible = true } override fun onOptionsItemSelected(item: MenuItem?): Boolean { when (item!!.itemId) { R.id.action_mark_all -> { if (mAdapter.itemCount > 0) { ThreadPool.Builder() .build().execute { this.markAllNotificationsAsRead() } } else NotifyUtil.makeText(context, R.string.text_activity_loading, Toast.LENGTH_SHORT) return true } } return super.onOptionsItemSelected(item) } override fun onResume() { super.onResume() if (mAdapter != null) mAdapter.notifyDataSetChanged() } override fun onChanged(content: PageContainer<Notification>?) { if (content != null) { if (content.hasPageInfo()) presenter.pageInfo = content.pageInfo if (!content.isEmpty) { val notifications = GraphUtil.filterNotificationList( presenter, content.pageData ) onPostProcessed(notifications) } else onPostProcessed(emptyList()) } else onPostProcessed(emptyList()) if (mAdapter.itemCount < 1) onPostProcessed(null) } /** * All new or updated network requests should be handled in this method */ override fun makeRequest() { val queryContainer = GraphUtil.getDefaultQuery(isPager) .putVariable(KeyUtil.arg_page, presenter.currentPage) .putVariable(KeyUtil.arg_resetNotificationCount, true) getViewModel().params.putParcelable(KeyUtil.arg_graph_params, queryContainer) getViewModel().requestData(KeyUtil.USER_NOTIFICATION_REQ, context!!) } /** * Ran on a background thread to assure we don't skip frames * @see ThreadPool */ private fun setItemAsRead(data: Notification) { ThreadPool.Builder().build() .execute { val isNotificationRead = presenter.database.getBoxStore(NotificationHistory::class.java) .query().equal(NotificationHistory_.id, data.id).build().count() != 0L if (!isNotificationRead) { val dismissibleNotifications = Stream.of(mAdapter.data) .filter { item -> item.activityId != 0L && item.activityId == data.activityId } .map { item -> NotificationHistory(item.id) } .toList() if (!CompatUtil.isEmpty(dismissibleNotifications)) presenter.database.getBoxStore(NotificationHistory::class.java) .put(dismissibleNotifications) else presenter.database.getBoxStore(NotificationHistory::class.java) .put(NotificationHistory(data.id)) } } } /** * Ran on a background thread to assure we don't skip frames * @see ThreadPool */ private fun markAllNotificationsAsRead() { val notificationHistories = Stream.of(mAdapter.data) .map { notification -> NotificationHistory(notification.id) } .toList() presenter.database.getBoxStore(NotificationHistory::class.java) .put(notificationHistories) activity?.runOnUiThread { if (mAdapter != null) mAdapter.notifyDataSetChanged() } } /** * When the target view from [View.OnClickListener] * is clicked from a view holder this method will be called * * @param target view that has been clicked * @param data the model that at the click index */ override fun onItemClick(target: View, data: IntPair<Notification>) { val intent: Intent setItemAsRead(data.second) if (target.id == R.id.notification_img && !CompatUtil.equals(data.second.type, KeyUtil.AIRING) && !CompatUtil.equals(data.second.type, KeyUtil.RELATED_MEDIA_ADDITION) ) { intent = Intent(activity, ProfileActivity::class.java) intent.putExtra(KeyUtil.arg_id, data.second.user.id) CompatUtil.startRevealAnim(activity, target, intent) } else when (data.second.type) { KeyUtil.ACTIVITY_MESSAGE -> { intent = Intent(activity, CommentActivity::class.java) intent.putExtra(KeyUtil.arg_id, data.second.activityId) CompatUtil.startRevealAnim(activity, target, intent) } KeyUtil.FOLLOWING -> { intent = Intent(activity, ProfileActivity::class.java) intent.putExtra(KeyUtil.arg_id, data.second.user.id) CompatUtil.startRevealAnim(activity, target, intent) } KeyUtil.ACTIVITY_MENTION -> { intent = Intent(activity, CommentActivity::class.java) intent.putExtra(KeyUtil.arg_id, data.second.activityId) CompatUtil.startRevealAnim(activity, target, intent) } KeyUtil.THREAD_COMMENT_MENTION -> DialogUtil.createMessage(context, data.second.user.name, data.second.context) KeyUtil.THREAD_SUBSCRIBED -> DialogUtil.createMessage(context, data.second.user.name, data.second.context) KeyUtil.THREAD_COMMENT_REPLY -> DialogUtil.createMessage(context, data.second.user.name, data.second.context) KeyUtil.AIRING, KeyUtil.RELATED_MEDIA_ADDITION -> { intent = Intent(activity, MediaActivity::class.java) intent.putExtra(KeyUtil.arg_id, data.second.media.id) intent.putExtra(KeyUtil.arg_mediaType, data.second.media.type) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) CompatUtil.startRevealAnim(activity, target, intent) } KeyUtil.ACTIVITY_LIKE -> { intent = Intent(activity, CommentActivity::class.java) intent.putExtra(KeyUtil.arg_id, data.second.activityId) CompatUtil.startRevealAnim(activity, target, intent) } KeyUtil.ACTIVITY_REPLY, KeyUtil.ACTIVITY_REPLY_SUBSCRIBED -> { intent = Intent(activity, CommentActivity::class.java) intent.putExtra(KeyUtil.arg_id, data.second.activityId) CompatUtil.startRevealAnim(activity, target, intent) } KeyUtil.ACTIVITY_REPLY_LIKE -> { intent = Intent(activity, CommentActivity::class.java) intent.putExtra(KeyUtil.arg_id, data.second.activityId) CompatUtil.startRevealAnim(activity, target, intent) } KeyUtil.THREAD_LIKE -> DialogUtil.createMessage(context, data.second.user.name, data.second.context) KeyUtil.THREAD_COMMENT_LIKE -> DialogUtil.createMessage(context, data.second.user.name, data.second.context) } } /** * When the target view from [View.OnLongClickListener] * is clicked from a view holder this method will be called * * @param target view that has been long clicked * @param data the model that at the long click index */ override fun onItemLongClick(target: View, data: IntPair<Notification>) { if (CompatUtil.equals(data.second.type, KeyUtil.AIRING)) { setItemAsRead(data.second) if (presenter.applicationPref.isAuthenticated) { mediaActionUtil = MediaActionUtil.Builder() .setId(data.second.media.id).build(activity) mediaActionUtil.startSeriesAction() } else NotifyUtil.makeText(context, R.string.info_login_req, R.drawable.ic_group_add_grey_600_18dp, Toast.LENGTH_SHORT).show() } } companion object { fun newInstance(): NotificationFragment { return NotificationFragment() } } }
32
null
26
194
57aab12703f9e7cceac34e75557fca89247bae7c
11,433
anitrend-app
MIT License
Application/app/src/main/java/com/thephoenix/rockpaperscissors/data/viewModel/NavigationViewModel.kt
Samuelk0nrad
729,453,053
false
{"Kotlin": 261149}
package com.game.rockpaperscissors.data.viewModel import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.game.rockpaperscissors.data.PlayerDataState import com.game.rockpaperscissors.data.local.database.PlayerDataDao import com.google.firebase.ktx.Firebase import com.google.firebase.messaging.ktx.messaging import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import kotlinx.coroutines.tasks.await import javax.inject.Inject import javax.inject.Named @HiltViewModel class NavigationViewModel @Inject constructor( @Named("playerDao") val dao: PlayerDataDao ): ViewModel() { private val _allPlayer = dao.allPlayerData().stateIn(viewModelScope, SharingStarted.WhileSubscribed(), emptyList()) private val _state = MutableStateFlow(PlayerDataState()) val state = combine(_state, _allPlayer) { state, allPlayer -> state.copy( allPlayer = allPlayer, ) }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), PlayerDataState()) private val _isLoggedIn = MutableStateFlow(state.value.allPlayer.isNotEmpty()) val isLoggedIn = _isLoggedIn.asStateFlow() private val _isDatabaseLoaded = MutableStateFlow(false) val isDatabaseLoaded = _isDatabaseLoaded.asStateFlow() private val _isReady = MutableStateFlow(false) val isReady = _isReady.asStateFlow() init { viewModelScope.launch { delay(1000) _isReady.value = true _isLoggedIn.value = state.value.allPlayer.isNotEmpty() Firebase.messaging.subscribeToTopic("weather").await() } } }
0
Kotlin
0
0
9d3d557e91142b82f90f460397b1929460a024a4
1,907
Rock-Paper-Scissors
Boost Software License 1.0
android/apolloui/src/main/java/io/muun/apollo/presentation/ui/fragments/error/ErrorView.kt
muun
150,655,434
false
null
package io.muun.apollo.presentation.ui.fragments.error import io.muun.apollo.presentation.ui.base.BaseView interface ErrorView: BaseView { fun setViewModel(viewModel: ErrorViewModel) }
39
null
46
256
86048fe9f8059c9617f2e6d32e7d41c460dfb785
192
apollo
MIT License
hilt/hilt-network/src/main/java/org/fnives/test/showcase/hilt/network/auth/model/CredentialsRequest.kt
fknives
356,982,481
false
null
package org.fnives.test.showcase.hilt.network.auth.model import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) internal class CredentialsRequest( @Json(name = "username") val user: String, @Json(name = "password") val password: String )
9
Kotlin
2
5
5bf503d90e8a13daf5626afc0cdf8bff523d2b94
303
AndroidTest-ShowCase
Apache License 2.0
app/src/main/java/chat/rocket/android/chatroom/ui/bottomsheet/BottomSheetMenu.kt
lucasmontano
128,559,523
false
null
package chat.rocket.android.chatroom.ui.bottomsheet import android.support.design.widget.BottomSheetDialog import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.MenuItem import ru.whalemare.sheetmenu.SheetMenu import ru.whalemare.sheetmenu.adapter.MenuAdapter class BottomSheetMenu(adapter: MenuAdapter) : SheetMenu(adapter = adapter) { override fun processRecycler(recycler: RecyclerView, dialog: BottomSheetDialog) { if (layoutManager == null) { layoutManager = LinearLayoutManager(recycler.context, LinearLayoutManager.VERTICAL, false) } // Superclass SheetMenu adapter property is nullable MenuAdapter? but this class enforces // passing one at the constructor, so we assume it's always non-null. val adapter = adapter!! val callback = adapter.callback adapter.callback = MenuItem.OnMenuItemClickListener { callback?.onMenuItemClick(it) dialog.cancel() true } recycler.adapter = adapter recycler.layoutManager = layoutManager } }
0
null
0
3
83b14b60deade340b1b2b05e20f10fb7d3772280
1,139
Rocket.Chat.Android
MIT License
common/kotlinx-coroutines-core-common/src/test/kotlin/kotlinx/coroutines/experimental/WithContextTest.kt
sahlone
141,607,927
false
null
/* * Copyright 2016-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("NAMED_ARGUMENTS_NOT_ALLOWED") // KT-21913 package kotlinx.coroutines.experimental import kotlin.test.* import kotlin.coroutines.experimental.ContinuationInterceptor import kotlin.coroutines.experimental.CoroutineContext class CommonWithContextTest : TestBase() { @Test fun testSameContextNoSuspend() = runTest { expect(1) launch(coroutineContext) { // make sure there is not early dispatch here finish(5) // after main exits } expect(2) val result = withContext(coroutineContext) { // same context! expect(3) // still here "OK" } assertEquals("OK", result) expect(4) // will wait for the first coroutine } @Test fun testSameContextWithSuspend() = runTest { expect(1) launch(coroutineContext) { // make sure there is not early dispatch here expect(4) } expect(2) val result = withContext(coroutineContext) { // same context! expect(3) // still here yield() // now yields to launch! expect(5) "OK" } assertEquals("OK", result) finish(6) } @Test fun testCancelWithJobNoSuspend() = runTest { expect(1) launch(coroutineContext) { // make sure there is not early dispatch to here finish(6) // after main exits } expect(2) val job = Job() val result = withContext(coroutineContext + job) { // same context + new job expect(3) // still here job.cancel() // cancel out job! try { yield() // shall throw CancellationException expectUnreached() } catch (e: CancellationException) { expect(4) } "OK" } assertEquals("OK", result) expect(5) // will wait for the first coroutine } @Test fun testCancelWithJobWithSuspend() = runTest { expect(1) launch(coroutineContext) { // make sure there is not early dispatch to here expect(4) } expect(2) val job = Job() val result = withContext(coroutineContext + job) { // same context + new job expect(3) // still here yield() // now yields to launch! expect(5) job.cancel() // cancel out job! try { yield() // shall throw CancellationException expectUnreached() } catch (e: CancellationException) { expect(6) } "OK" } assertEquals("OK", result) finish(7) } @Test fun testRunCancellableDefault() = runTest( expected = { it is JobCancellationException } ) { val job = Job() job.cancel() // cancel before it has a chance to run withContext(job + wrapperDispatcher(coroutineContext)) { expectUnreached() // will get cancelled } } @Test fun testRunAtomicTryCancel() = runTest( expected = { it is JobCancellationException } ) { expect(1) val job = Job() job.cancel() // try to cancel before it has a chance to run withContext(job + wrapperDispatcher(coroutineContext), CoroutineStart.ATOMIC) { // but start atomically finish(2) yield() // but will cancel here expectUnreached() } } @Test fun testRunUndispatchedTryCancel() = runTest( expected = { it is JobCancellationException } ) { expect(1) val job = Job() job.cancel() // try to cancel before it has a chance to run withContext(job + wrapperDispatcher(coroutineContext), CoroutineStart.UNDISPATCHED) { // but start atomically finish(2) yield() // but will cancel here expectUnreached() } } @Test fun testRunWithException() = runTest { expect(1) var job: Job? = null job = launch(coroutineContext) { try { expect(3) withContext(wrapperDispatcher(coroutineContext)) { expect(5) job!!.cancel() // cancel itself throw TestException() // but throw a different exception } } catch (e: Throwable) { expect(7) // make sure IOException, not CancellationException is thrown! assertTrue(e is TestException) } } expect(2) yield() // to the launched job expect(4) yield() // again to the job expect(6) yield() // again to exception handler finish(8) } private fun wrapperDispatcher(context: CoroutineContext): CoroutineContext { val dispatcher = context[ContinuationInterceptor] as CoroutineDispatcher return object : CoroutineDispatcher() { override fun dispatch(context: CoroutineContext, block: Runnable) { dispatcher.dispatch(context, block) } } } private class TestException : Exception() }
0
null
0
1
dae510bba39181b93978f7878c033a50dccad62b
5,843
kotlinx.coroutines
Apache License 2.0
app/src/main/java/com/farmerbb/notepad/model/Note.kt
Ajit-saini
706,726,758
false
{"Kotlin": 109678}
package com.farmerbb.notepad.model import java.util.Date data class Note( val metadata: NoteMetadata = Defaults.metadata, private val contents: NoteContents = Defaults.contents ) { val id: Long get() = metadata.metadataId val text: String get() = contents.text ?: "" val draftText: String get() = contents.draftText ?: "" val title: String get() = metadata.title val date: Date get() = metadata.date }
0
Kotlin
0
0
516d34d6864b70d52ea2ddee7b190bc27d4147ac
431
Notepadd_App
Apache License 2.0
content/core/src/main/kotlin/br/com/mrocigno/bigbrother/core/BigBrother.kt
mrocigno
574,215,368
false
{"Kotlin": 343969, "HTML": 7133}
package br.com.mrocigno.bigbrother.core import android.app.Activity import android.app.Application import androidx.fragment.app.Fragment import com.jakewharton.threetenabp.AndroidThreeTen import kotlin.reflect.KClass object BigBrother { internal val tasks = mutableListOf<BigBrotherTask>() internal val config = BigBrotherConfig() private val activityPages: HashMap<KClass<out Activity>, List<PageData>> = hashMapOf() private val pages: MutableList<PageData> = mutableListOf() fun addPage(location: KClass<out Activity>, wrapper: ActivityPageWrapper.() -> Unit) { activityPages[location] = ActivityPageWrapper().apply(wrapper).pages } fun addPage(name: String, creator: (BigBrotherView) -> Fragment) { pages.add(PageData(name, creator)) } internal fun getPages(location: KClass<*>) = activityPages[location] internal fun getPages() = pages fun config(configuration: BigBrotherConfig.() -> Unit) = apply { config.apply(configuration) } fun watch(context: Application, isBubbleEnabled: Boolean = true) { if (!isBubbleEnabled) tasks.removeAll { it is BigBrotherWatchTask } AndroidThreeTen.init(context) context.registerActivityLifecycleCallbacks(BigBrotherObserver()) } }
0
Kotlin
0
4
8deac7d4cf1b1395e5c23dc3b788266beb1fa19b
1,282
big-brother
Apache License 2.0
components/generator/imagevector/src/test/resources/kt/backing/WithoutPath.preview.kt
ComposeGears
778,162,113
false
{"Kotlin": 777429}
package io.github.composegears.valkyrie.icons import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import kotlin.Suppress val WithoutPath: ImageVector get() { if (_WithoutPath != null) { return _WithoutPath!! } _WithoutPath = ImageVector.Builder( name = "WithoutPath", defaultWidth = 24.dp, defaultHeight = 24.dp, viewportWidth = 18f, viewportHeight = 18f ).build() return _WithoutPath!! } @Suppress("ObjectPropertyName") private var _WithoutPath: ImageVector? = null @Preview(showBackground = true) @Composable private fun WithoutPathPreview() { Box(modifier = Modifier.padding(12.dp)) { Image(imageVector = WithoutPath, contentDescription = null) } }
27
Kotlin
6
321
f0647081b15b907ad92b38c33eb62179ffd0f969
1,098
Valkyrie
Apache License 2.0
src/main/kotlin/no/nav/syfo/repository/dao/FeiletSendingDAO.kt
navikt
164,875,446
false
{"Kotlin": 389813, "Java": 333680, "XSLT": 25351, "PLSQL": 1668, "Dockerfile": 588, "Shell": 257}
package no.nav.syfo.repository.dao import no.nav.syfo.domain.FeiletSending import no.nav.syfo.repository.DbUtil import no.nav.syfo.repository.domain.PFeiletSending import org.springframework.jdbc.core.JdbcTemplate import org.springframework.jdbc.core.RowMapper import org.springframework.jdbc.core.namedparam.MapSqlParameterSource import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate import org.springframework.stereotype.Repository import java.sql.ResultSet import java.sql.SQLException import java.time.LocalDateTime import java.util.* import java.util.stream.Collectors import javax.inject.Inject const val MAX_RETRIES = 6; @Repository class FeiletSendingDAO @Inject constructor( private val jdbcTemplate: JdbcTemplate, private val namedParameterJdbcTemplate: NamedParameterJdbcTemplate ) { fun findByOppfolgingsplanId(oppfolgingsplanId: Long): FeiletSending { val pFeiletSending = jdbcTemplate.queryForObject("select * from feilet_sending where oppfolgingsplanlps_id = ?", FeiletSendingRowMapper(), oppfolgingsplanId) if(pFeiletSending != null) { return mapPFeiletSendingToFeiletSending(pFeiletSending) } else { throw RuntimeException("No FeiletSending was found in database with given ID") } } fun hentFeiledeSendinger(): List<FeiletSending> { val query = """ SELECT * FROM feilet_sending WHERE number_of_tries <= $MAX_RETRIES """.trimIndent() val feiletSendingList = Optional.ofNullable(jdbcTemplate.query(query, FeiletSendingRowMapper())).orElse(emptyList()) return feiletSendingList.stream() .map { pFeiletSending: PFeiletSending -> mapPFeiletSendingToFeiletSending(pFeiletSending) } .collect(Collectors.toList()) } fun create(oppfolgingsplanId: Long) { val feiletSendingId = DbUtil.nesteSekvensverdi("FEILET_SENDING_ID_SEQ", jdbcTemplate) val query = """ INSERT INTO feilet_sending (id, oppfolgingsplanlps_id, number_of_tries, opprettet, sist_endret) values (:id, :oppfolgingsplanlps_id, :number_of_tries, :opprettet, :sist_endret) """.trimIndent() val namedParameters = MapSqlParameterSource() .addValue("id", feiletSendingId) .addValue("oppfolgingsplanlps_id", oppfolgingsplanId) .addValue("number_of_tries", 1) .addValue("opprettet", DbUtil.convert(LocalDateTime.now())) .addValue("sist_endret", DbUtil.convert(LocalDateTime.now())) namedParameterJdbcTemplate.update(query, namedParameters) } fun updateAfterRetry(feiletSending: FeiletSending) { val query = """ UPDATE feilet_sending SET number_of_tries=:number_of_tries, sist_endret=:sist_endret where id=:id """.trimIndent() val namedParameters = MapSqlParameterSource() .addValue("id", feiletSending.id) .addValue("number_of_tries", feiletSending.number_of_tries) .addValue("sist_endret", DbUtil.convert(LocalDateTime.now())) namedParameterJdbcTemplate.update(query, namedParameters) } fun remove(oppfolgingsplanId: Long?) { val query = """ DELETE FROM feilet_sending WHERE oppfolgingsplanlps_id=:oppfolgingsplanlps_id """.trimIndent() val namedParameters = MapSqlParameterSource() .addValue("oppfolgingsplanlps_id", oppfolgingsplanId) namedParameterJdbcTemplate.update(query, namedParameters) } private inner class FeiletSendingRowMapper : RowMapper<PFeiletSending> { @Throws(SQLException::class) override fun mapRow(rs: ResultSet, rowNum: Int): PFeiletSending { return PFeiletSending( id = rs.getLong("id"), oppfolgingsplanId = rs.getLong("oppfolgingsplanlps_id"), number_of_tries = rs.getInt("number_of_tries"), opprettet = DbUtil.convert(rs.getTimestamp("opprettet")), sist_endret = DbUtil.convert(rs.getTimestamp("sist_endret"))) } } } private fun mapPFeiletSendingToFeiletSending(pFeiletSending: PFeiletSending): FeiletSending { return FeiletSending( id = pFeiletSending.id, oppfolgingsplanId = pFeiletSending.oppfolgingsplanId, number_of_tries = pFeiletSending.number_of_tries, sist_endret = pFeiletSending.sist_endret, opprettet = pFeiletSending.opprettet ) }
1
Kotlin
0
0
b639ea519f4144e8f9c5d8d757240b68eddb25df
4,637
syfooppfolgingsplanservice
MIT License
sphinx/application/common/wrappers/wrapper-common/src/main/java/chat/sphinx/wrapper_common/HideBalance.kt
stakwork
340,103,148
false
{"Kotlin": 4008358, "Java": 403469, "JavaScript": 4745, "HTML": 4706, "Shell": 2453}
package chat.sphinx.wrapper_common object HideBalance { const val ENABLED = 1 const val DISABLED = 0 const val HIDE_BALANCE_SHARED_PREFERENCES = "general_settings" const val HIDE_BALANCE_ENABLED_KEY = "hide-balance-enabled" }
90
Kotlin
11
18
7811b4f4e5a0cf8a26f343704cfced011b1f9bad
245
sphinx-kotlin
MIT License
api/src/main/kotlin/no/nav/helsearbeidsgiver/inntektsmelding/api/inntekt/InntektResponse.kt
navikt
495,713,363
false
null
package no.nav.helsearbeidsgiver.inntektsmelding.api.inntekt import kotlinx.serialization.Serializable import no.nav.helsearbeidsgiver.felles.MottattHistoriskInntekt @Serializable data class InntektResponse( val bruttoinntekt: Double, val tidligereInntekter: List<MottattHistoriskInntekt> )
7
Kotlin
0
2
675e15bbbe24a959dd9425830a1724ca6f920588
301
helsearbeidsgiver-inntektsmelding
MIT License
src/main/kotlin/de/thm/mni/microservices/gruppe6/user/controller/LoginController.kt
microservices-thm-ss21
517,717,526
false
{"Kotlin": 47123, "Dockerfile": 150}
package de.thm.mni.microservices.gruppe6.user.controller import de.thm.mni.microservices.gruppe6.lib.classes.userService.User import org.slf4j.LoggerFactory import org.springframework.security.core.Authentication import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RestController import reactor.core.publisher.Mono @RestController class LoginController { private val logger = LoggerFactory.getLogger(this::class.java) @GetMapping("/login") fun login(auth: Authentication): Mono<Void> { logger.debug("${(auth.principal as User).name} logged in with password ${auth.credentials as String}!") return Mono.empty() } }
0
Kotlin
0
0
e363e88c8b2a8ee667e87a6fdc523639f662eff1
703
user-service
Apache License 2.0
src/main/kotlin/com/gegenbauer/typora/imagehelper/MigrationFileInfo.kt
Gegenbauer
603,798,747
false
null
package com.gegenbauer.typora.imagehelper import java.io.File /** * used for image file migration * key: source filename */ data class MigrationFileInfo( val imageFilename: String, val imageFile: File, var referredMdFile: File? = null, var targetPath: String = "", var targetMdReference: String = "" ) { override fun hashCode(): Int { return imageFilename.hashCode() } override fun equals(other: Any?): Boolean { return other is MigrationFileInfo && other.imageFilename == imageFilename } }
0
Kotlin
0
1
c27b01973483b5af9529d9008d167baab5ab5bcb
548
TyporaImageHelper
Apache License 2.0
src/test/kotlin/usecases/user/UpdatePasswordTests.kt
ktlib-org
718,419,916
false
{"Kotlin": 82894, "PLpgSQL": 4310}
package usecases.user import entities.user.Users import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.shouldBe import org.ktlib.Encryption import org.ktlib.entities.ValidationException import usecases.UseCaseSpec class UpdatePasswordTests : UseCaseSpec() { init { "updatePassword" { execute("<PASSWORD>") Encryption.passwordMatches("<PASSWORD>", Users.findById(currentUserId)!!.password) shouldBe true } "updatePassword with too short of password throws exception" { val exception = shouldThrow<ValidationException> { execute("short") } exception.validationErrors.size shouldBe 1 exception.validationErrors.errors.first().field shouldBe "password" } } private fun execute(password: String) = useCase(UpdatePassword::class, UpdatePassword.Input(password)).execute() }
0
Kotlin
0
0
89b34a887ba192c4e4e3e7ff9103127dc3c7b9ff
938
example-api
The Unlicense
line-awesome/src/commonMain/kotlin/compose/icons/lineawesomeicons/FishSolid.kt
DevSrSouza
311,134,756
false
{"Kotlin": 36756847}
package compose.icons.lineawesomeicons 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.LineAwesomeIcons public val LineAwesomeIcons.FishSolid: ImageVector get() { if (_fishSolid != null) { return _fishSolid!! } _fishSolid = Builder(name = "FishSolid", defaultWidth = 32.0.dp, defaultHeight = 32.0.dp, viewportWidth = 32.0f, viewportHeight = 32.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(10.5f, 6.0f) lineTo(11.0625f, 7.375f) curveTo(11.4141f, 8.2305f, 11.8906f, 10.3672f, 11.7813f, 11.375f) curveTo(10.418f, 12.2148f, 9.582f, 13.0352f, 8.9375f, 13.7188f) curveTo(8.1484f, 13.082f, 6.5898f, 12.0f, 4.0f, 12.0f) lineTo(3.0f, 12.0f) lineTo(3.0f, 13.0f) curveTo(3.0f, 14.9141f, 3.6914f, 16.4688f, 3.9375f, 17.0f) curveTo(3.6875f, 17.5273f, 3.0f, 19.0273f, 3.0f, 21.0f) lineTo(3.0f, 22.0f) lineTo(4.0f, 22.0f) curveTo(6.5703f, 22.0f, 8.1484f, 20.9141f, 8.9375f, 20.2813f) curveTo(10.1211f, 21.5f, 11.8086f, 22.7852f, 13.9375f, 23.75f) curveTo(13.8438f, 24.3711f, 13.7695f, 25.2383f, 14.0313f, 26.25f) lineTo(14.2188f, 27.0f) lineTo(15.0f, 27.0f) curveTo(16.2344f, 27.0f, 17.2969f, 26.3867f, 18.1563f, 25.8438f) curveTo(18.8594f, 25.3984f, 19.1992f, 25.0859f, 19.375f, 24.9375f) curveTo(23.3516f, 24.7969f, 25.8906f, 22.6523f, 27.25f, 20.5313f) curveTo(28.6563f, 18.3398f, 29.0f, 16.1563f, 29.0f, 16.1563f) lineTo(29.0313f, 15.9063f) lineTo(28.9375f, 15.6563f) curveTo(28.9375f, 15.6563f, 26.6484f, 9.3672f, 20.4375f, 9.0625f) curveTo(19.7773f, 8.2617f, 18.8555f, 7.5977f, 17.5625f, 7.0625f) curveTo(16.0352f, 6.4297f, 14.1133f, 6.0f, 12.0f, 6.0f) close() moveTo(13.4063f, 8.125f) curveTo(14.668f, 8.2656f, 15.8477f, 8.5195f, 16.7813f, 8.9063f) curveTo(18.0586f, 9.4336f, 18.9492f, 10.1914f, 19.1563f, 10.5313f) lineTo(19.4375f, 11.0f) lineTo(20.0f, 11.0f) curveTo(24.9961f, 11.0f, 26.793f, 15.7305f, 26.9375f, 16.125f) curveTo(26.8672f, 16.4922f, 26.5781f, 17.8867f, 25.5625f, 19.4688f) curveTo(24.4023f, 21.2773f, 22.5234f, 23.0f, 19.0f, 23.0f) lineTo(18.625f, 23.0f) lineTo(18.3438f, 23.25f) curveTo(18.3438f, 23.25f, 17.8164f, 23.6992f, 17.0938f, 24.1563f) curveTo(16.7148f, 24.3945f, 16.3906f, 24.4375f, 16.0f, 24.5938f) curveTo(16.0391f, 24.1367f, 16.0f, 23.4688f, 16.0f, 23.4688f) lineTo(16.2188f, 22.5938f) lineTo(15.4063f, 22.3125f) curveTo(12.9297f, 21.3672f, 10.8242f, 19.5859f, 9.75f, 18.3438f) lineTo(9.0625f, 17.5313f) lineTo(8.3125f, 18.2813f) curveTo(8.3125f, 18.2813f, 6.9805f, 19.2148f, 5.25f, 19.6563f) curveTo(5.5078f, 18.4844f, 5.9063f, 17.4375f, 5.9063f, 17.4375f) lineTo(6.125f, 17.0f) lineTo(5.9063f, 16.5625f) curveTo(5.9063f, 16.5625f, 5.4727f, 15.4141f, 5.2188f, 14.1875f) curveTo(7.0625f, 14.5938f, 8.3125f, 15.7188f, 8.3125f, 15.7188f) lineTo(9.0625f, 16.4688f) lineTo(9.75f, 15.6563f) curveTo(10.6445f, 14.6445f, 13.0547f, 12.125f, 16.5938f, 11.6563f) lineTo(16.3125f, 9.6875f) curveTo(15.3555f, 9.8125f, 14.5195f, 10.0898f, 13.7188f, 10.4063f) curveTo(13.668f, 9.5664f, 13.625f, 8.8438f, 13.4063f, 8.125f) close() moveTo(22.5f, 15.0f) curveTo(21.6719f, 15.0f, 21.0f, 15.6719f, 21.0f, 16.5f) curveTo(21.0f, 17.3281f, 21.6719f, 18.0f, 22.5f, 18.0f) curveTo(23.3281f, 18.0f, 24.0f, 17.3281f, 24.0f, 16.5f) curveTo(24.0f, 15.6719f, 23.3281f, 15.0f, 22.5f, 15.0f) close() } } .build() return _fishSolid!! } private var _fishSolid: ImageVector? = null
15
Kotlin
20
460
651badc4ace0137c5541f859f61ffa91e5242b83
5,008
compose-icons
MIT License
app/src/test/java/com/microsoft/device/samples/dualscreenexperience/domain/store/testutil/MockStoreDataSource.kt
microsoft
333,507,793
false
{"Kotlin": 626561, "HTML": 33449}
/* * * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. * */ package com.microsoft.device.samples.dualscreenexperience.domain.store.testutil import com.microsoft.device.samples.dualscreenexperience.data.store.StoreDataSource import com.microsoft.device.samples.dualscreenexperience.data.store.model.CityEntity import com.microsoft.device.samples.dualscreenexperience.data.store.model.CityWithStoresEntity import com.microsoft.device.samples.dualscreenexperience.data.store.model.StoreEntity class MockStoreDataSource : StoreDataSource { private var storeEntityMap = mutableMapOf<Long, StoreEntity>() private var cityEntityMap = mutableMapOf<Long, CityEntity>() private var cityWithStoreEntityMap = mutableMapOf<Long, CityWithStoresEntity>() override suspend fun getAll(): List<StoreEntity> = storeEntityMap.values.toList() override suspend fun getById(storeId: Long): StoreEntity? = storeEntityMap[storeId] override suspend fun getCitiesWithStores(): List<CityWithStoresEntity> = cityWithStoreEntityMap.values.toList() fun insert(vararg stores: StoreEntity) { stores.forEach { store -> storeEntityMap[store.storeId] = store store.cityLocatorId?.let { cityId -> cityWithStoreEntityMap[cityId]?.stores?.add(store) } } } fun insertCities(vararg cities: CityEntity) { cities.forEach { city -> cityEntityMap[city.cityId] = city cityWithStoreEntityMap[city.cityId] = CityWithStoresEntity( city, storeEntityMap.values.filter { it.cityLocatorId == city.cityId }.toMutableList() ) } } }
1
Kotlin
6
29
76577bf9cb72fc5cadd0170652936cd7fc30e3f5
1,762
surface-duo-dual-screen-experience-example
MIT License
feature/home/src/main/kotlin/com/finwise/feature/home/LoginScreen.kt
nimaiwalsh
757,345,803
false
{"Kotlin": 31597, "Shell": 2385}
package com.finwise.feature.home import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.material3.Button import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import com.finwise.core.ui.theme.FinWiseAppTheme @Composable fun LoginScreen( navigateToHome: () -> Unit, viewModel: LoginViewModel = hiltViewModel(), ) { LoginScreen(navigateToHome = navigateToHome) } @Composable fun LoginScreen(navigateToHome: () -> Unit) { FinWiseAppTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { Column( modifier = Modifier .padding(24.dp) .fillMaxSize() .wrapContentSize(), horizontalAlignment = Alignment.CenterHorizontally ) { Spacer(Modifier.size(24.dp)) Button( modifier = Modifier.fillMaxWidth(), onClick = navigateToHome, ) { Text("Login") } } } } } @Preview(showBackground = true) @Composable fun LoginScreenPreview() { FinWiseAppTheme { LoginScreen(navigateToHome = {}) } }
0
Kotlin
0
0
6f003a50f5fe59133c12069e631474a6e4f580df
1,919
finwise
Apache License 2.0
capjoy/src/nativeMain/kotlin/capjoy/command/list/ListDevicesCommand.kt
tokuhirom
811,163,805
false
{"Kotlin": 69973}
package capjoy.command.list import capjoy.command.list.utils.showTable import capjoy.model.command.ListDevicesOutput import capjoy.model.entity.CaptureDevice import capjoy.model.entity.CaptureDeviceFormat import com.github.ajalt.clikt.core.CliktCommand import com.github.ajalt.clikt.parameters.options.default import com.github.ajalt.clikt.parameters.options.option import com.github.ajalt.clikt.parameters.types.choice import kotlinx.cinterop.BetaInteropApi import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import platform.AVFoundation.AVCaptureDevice import platform.AVFoundation.AVCaptureDeviceFormat import platform.AVFoundation.AVMediaTypeAudio import platform.AVFoundation.AVMediaTypeVideo class ListDevicesCommand : CliktCommand( "List all capture devices", ) { private val format by option().choice("json", "table").default("table") private val json = Json { prettyPrint = true } @BetaInteropApi override fun run() { val defaultAudioDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeAudio) val defaultVideoDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) val devices = AVCaptureDevice.devices() val got = devices.map { it as AVCaptureDevice }.map { CaptureDevice( formats = it.formats .map { format -> format as AVCaptureDeviceFormat } .map { captureDeviceFormat -> CaptureDeviceFormat(captureDeviceFormat.description, captureDeviceFormat.mediaType) }, localizedName = it.localizedName, manufacturer = it.manufacturer, uniqueID = it.uniqueID, suspended = it.suspended, transportType = it.transportType, modelID = it.modelID, default = it == defaultAudioDevice || it == defaultVideoDevice, ) } when (format) { "json" -> println(json.encodeToString(ListDevicesOutput(got))) "table" -> { val headers = listOf( "LocalizedName", "Manufacturer", "UniqueID", "Suspended", "TransportType", "ModelID", "Default", ) val data = got.map { listOf( it.localizedName, it.manufacturer, it.uniqueID, it.suspended.toString(), it.transportType.toString(), it.modelID, if (it.default) "Default" else "", ) } showTable(headers, data) } } } }
2
Kotlin
0
0
45072351cb901fd3b721f42037b881f943deb9d6
2,929
capjoy
The Unlicense
app/src/main/kotlin/github/buriedincode/bookshelf/models/ReadBook.kt
Buried-In-Code
216,420,518
false
{"Kotlin": 151756, "JavaScript": 5009, "CSS": 758, "Dockerfile": 462}
package github.buriedincode.bookshelf.models import github.buriedincode.bookshelf.tables.ReadBookTable import kotlinx.datetime.LocalDate import org.jetbrains.exposed.dao.LongEntity import org.jetbrains.exposed.dao.LongEntityClass import org.jetbrains.exposed.dao.id.EntityID import org.jetbrains.exposed.sql.and class ReadBook(id: EntityID<Long>) : LongEntity(id) { companion object : LongEntityClass<ReadBook>(ReadBookTable) { fun find(book: Book, user: User): ReadBook? { return ReadBook.find { (ReadBookTable.bookCol eq book.id) and (ReadBookTable.userCol eq user.id) }.firstOrNull() } fun findOrCreate(book: Book, user: User): ReadBook { return find(book, user) ?: ReadBook.new { this.book = book this.user = user } } } var book: Book by Book referencedOn ReadBookTable.bookCol var user: User by User referencedOn ReadBookTable.userCol var readDate: LocalDate? by ReadBookTable.readDateCol }
2
Kotlin
0
0
c6e11f96e8ddf35a8b1ac4a32224fb0b79770188
1,020
Bookshelf
MIT License
app/src/main/kotlin/github/buriedincode/bookshelf/models/ReadBook.kt
Buried-In-Code
216,420,518
false
{"Kotlin": 151756, "JavaScript": 5009, "CSS": 758, "Dockerfile": 462}
package github.buriedincode.bookshelf.models import github.buriedincode.bookshelf.tables.ReadBookTable import kotlinx.datetime.LocalDate import org.jetbrains.exposed.dao.LongEntity import org.jetbrains.exposed.dao.LongEntityClass import org.jetbrains.exposed.dao.id.EntityID import org.jetbrains.exposed.sql.and class ReadBook(id: EntityID<Long>) : LongEntity(id) { companion object : LongEntityClass<ReadBook>(ReadBookTable) { fun find(book: Book, user: User): ReadBook? { return ReadBook.find { (ReadBookTable.bookCol eq book.id) and (ReadBookTable.userCol eq user.id) }.firstOrNull() } fun findOrCreate(book: Book, user: User): ReadBook { return find(book, user) ?: ReadBook.new { this.book = book this.user = user } } } var book: Book by Book referencedOn ReadBookTable.bookCol var user: User by User referencedOn ReadBookTable.userCol var readDate: LocalDate? by ReadBookTable.readDateCol }
2
Kotlin
0
0
c6e11f96e8ddf35a8b1ac4a32224fb0b79770188
1,020
Bookshelf
MIT License
app/src/main/kotlin/io/github/plastix/kotlinboilerplate/ui/base/AbstractViewModel.kt
Plastix
65,548,118
false
null
package com.trunglen.sexygirl.ui.base import android.databinding.BaseObservable abstract class AbstractViewModel : BaseObservable(), ViewModel { override fun bind() { } override fun unbind() { } override fun onDestroy() { // Hook for subclasses to clean up used resources } }
3
Kotlin
50
282
443762ca4f331cd2d37a042298e57416d3c63ab1
313
Kotlin-Android-Boilerplate
MIT License
subprojects/xsts/xsts-analysis/src/main/kotlin/hu/bme/mit/theta/xsts/analysis/util/XstsCombineExtractUtils.kt
ftsrg
39,392,321
false
null
/* * Copyright 2024 Budapest University of Technology and Economics * * 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 hu.bme.mit.theta.xsts.analysis import hu.bme.mit.theta.analysis.Prec import hu.bme.mit.theta.analysis.expr.ExprState import hu.bme.mit.theta.analysis.unit.UnitPrec import hu.bme.mit.theta.analysis.unit.UnitState fun <S : ExprState> xstsCombineStates(xstsState: XstsState<UnitState>, dataState: S): XstsState<S> { return XstsState.of(dataState, xstsState.lastActionWasEnv(), xstsState.isInitialized) } fun xstsExtractControlState(xstsState: XstsState<*>): XstsState<UnitState> { return XstsState.of(UnitState.getInstance(), xstsState.lastActionWasEnv(), xstsState.isInitialized) } fun <S : ExprState> xstsExtractDataState(xstsState: XstsState<S>): S { return xstsState.state } fun <P : Prec> xstsExtractControlPrec(p: P): UnitPrec = UnitPrec.getInstance()
50
null
42
49
cb77d7e6bb0e51ea00d2a1dc483fdf510dd8e8b4
1,421
theta
Apache License 2.0
src/main/java/net/azzy/forgotten/util/shenanigans/RarityNursery.kt
Dragonoidzero
300,290,159
false
null
package net.azzy.forgotten.util.shenanigans import net.azzy.forgotten.Forgotten.Companion.WTSLog import net.minecraft.enchantment.Enchantment import net.minecraft.util.Formatting import net.minecraft.util.Rarity import sun.misc.Unsafe import java.lang.reflect.Field object RarityNursery { private val rarityField = Rarity::class.java.getDeclaredField("formatting") private val ordinalField = Enum::class.java.getDeclaredField("ordinal") init { rarityField.isAccessible = true ordinalField.isAccessible = true } fun createRarity(formatting: Formatting, tier: Int): Rarity { val rarity = Artillery.theArtillery.allocateInstance(Rarity::class.java) as Rarity rarityField.set(rarity, formatting) ordinalField.setInt(rarity, tier) return rarity } }
0
Kotlin
0
0
fce2fe1592e7760e66a45f503dd48db3db8f8308
823
Where-They-Stood
Creative Commons Zero v1.0 Universal
app/src/main/kotlin/me/zhiyao/waterever/data/repo/ImageRepository.kt
WangZhiYao
243,558,800
false
null
package me.zhiyao.waterever.data.repo import me.zhiyao.waterever.data.db.dao.ImageDao import me.zhiyao.waterever.data.db.model.Image /** * * @author WangZhiYao * @date 2020/9/12 */ class ImageRepository( private val imageDao: ImageDao ) : Repository { suspend fun addImages(images: List<Image>) { imageDao.insertBatch(images) } }
0
Kotlin
0
0
232f20d623209eb2b9fb889aeb05af6ec3fee535
356
WaterEver
Apache License 2.0
src/main/kotlin/net/bratur/trip/plugins/CallLogging.kt
stavangler
298,249,881
false
null
package net.bratur.trip.net.bratur.trip.plugins import io.ktor.application.Application import io.ktor.application.install import io.ktor.features.CallLogging import io.ktor.request.path import java.util.UUID import org.slf4j.event.Level fun Application.configureCallLogging() { install(CallLogging) { level = Level.INFO mdc("executionID") { UUID.randomUUID().toString() } filter { call -> call.request.path().startsWith("/") } } }
0
Kotlin
0
0
a297fb7b087c9966bf3b3a885122472338a5231a
459
trip
Apache License 2.0
lib/src/main/java/graphql/nadel/engine/transform/hydration/batch/NadelBatchHydrator.kt
atlassian-labs
121,346,908
false
null
package graphql.nadel.engine.transform.hydration.batch import graphql.nadel.NextgenEngine import graphql.nadel.ServiceExecutionHydrationDetails import graphql.nadel.ServiceExecutionResult import graphql.nadel.engine.NadelEngineExecutionHooks import graphql.nadel.engine.blueprint.NadelBatchHydrationFieldInstruction import graphql.nadel.engine.blueprint.NadelOverallExecutionBlueprint import graphql.nadel.engine.blueprint.hydration.NadelBatchHydrationMatchStrategy import graphql.nadel.engine.transform.getInstructionsForNode import graphql.nadel.engine.transform.hydration.NadelHydrationFieldsBuilder import graphql.nadel.engine.transform.hydration.NadelHydrationUtil.getInstructionsToAddErrors import graphql.nadel.engine.transform.hydration.batch.NadelBatchHydrationByIndex.Companion.getHydrateInstructionsMatchingIndex import graphql.nadel.engine.transform.hydration.batch.NadelBatchHydrationByObjectId.getHydrateInstructionsMatchingObjectId import graphql.nadel.engine.transform.hydration.batch.NadelBatchHydrationByObjectId.getHydrateInstructionsMatchingObjectIds import graphql.nadel.engine.transform.hydration.batch.NadelBatchHydrationTransform.State import graphql.nadel.engine.transform.result.NadelResultInstruction import graphql.nadel.engine.transform.result.NadelResultKey import graphql.nadel.engine.transform.result.json.JsonNode import graphql.schema.FieldCoordinates import kotlinx.coroutines.Deferred import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope internal class NadelBatchHydrator( private val engine: NextgenEngine, ) { suspend fun hydrate( state: State, executionBlueprint: NadelOverallExecutionBlueprint, parentNodes: List<JsonNode>, ): List<NadelResultInstruction> { val parentNodesByInstruction: Map<NadelBatchHydrationFieldInstruction?, List<JsonNode>> = parentNodes .mapNotNull { parentNode -> val instructions = state.instructionsByObjectTypeNames.getInstructionsForNode( executionBlueprint = executionBlueprint, service = state.hydratedFieldService, aliasHelper = state.aliasHelper, parentNode = parentNode, ) // Becomes Pair<JsonNode, Instruction?> when { instructions.isEmpty() -> null instructions.size == 1 -> parentNode to instructions.single() else -> parentNode to getHydrationInstruction(state, instructions, parentNode) } } // Becomes Map<Instruction?, List<Pair<JsonNode, Instruction?>>> .groupBy { pair -> pair.second } // Changes List<Pair<JsonNode, Instruction?>> to List<JsonNode> .mapValues { pairs -> pairs.value.map { pair -> pair.first } } val jobs: List<Deferred<List<NadelResultInstruction>>> = coroutineScope { parentNodesByInstruction.map { (instruction, parentNodes) -> async { when (instruction) { null -> parentNodes.map { NadelResultInstruction.Set( subject = it, key = NadelResultKey(state.hydratedField.resultKey), newValue = null, ) } else -> hydrate(executionBlueprint, state, instruction, parentNodes) } } } } return jobs.awaitAll().flatten() } private suspend fun hydrate( executionBlueprint: NadelOverallExecutionBlueprint, state: State, instruction: NadelBatchHydrationFieldInstruction, parentNodes: List<JsonNode>, ): List<NadelResultInstruction> { val batches: List<ServiceExecutionResult> = executeBatches( state = state, instruction = instruction, parentNodes = parentNodes ) return when (val matchStrategy = instruction.batchHydrationMatchStrategy) { is NadelBatchHydrationMatchStrategy.MatchIndex -> getHydrateInstructionsMatchingIndex( state = state, instruction = instruction, parentNodes = parentNodes, batches = batches, ) is NadelBatchHydrationMatchStrategy.MatchObjectIdentifier -> getHydrateInstructionsMatchingObjectId( executionBlueprint = executionBlueprint, state = state, instruction = instruction, parentNodes = parentNodes, batches = batches, matchStrategy = matchStrategy, ) is NadelBatchHydrationMatchStrategy.MatchObjectIdentifiers -> getHydrateInstructionsMatchingObjectIds( executionBlueprint = executionBlueprint, state = state, instruction = instruction, parentNodes = parentNodes, batches = batches, matchStrategy = matchStrategy, ) } + getInstructionsToAddErrors(batches) } private suspend fun executeBatches( state: State, instruction: NadelBatchHydrationFieldInstruction, parentNodes: List<JsonNode>, ): List<ServiceExecutionResult> { val executionBlueprint = state.executionBlueprint val actorQueries = NadelHydrationFieldsBuilder.makeBatchActorQueries( executionBlueprint = executionBlueprint, instruction = instruction, aliasHelper = state.aliasHelper, hydratedField = state.hydratedField, parentNodes = parentNodes, hooks = state.executionContext.hooks ) return coroutineScope { actorQueries .map { actorQuery -> async { // This async executes the batches in parallel i.e. executes hydration as Deferred/Future val hydrationSourceService = executionBlueprint.getServiceOwning(instruction.location)!! val hydrationActorField = FieldCoordinates.coordinates(instruction.actorFieldContainer, instruction.actorFieldDef) val serviceHydrationDetails = ServiceExecutionHydrationDetails( timeout = instruction.timeout, batchSize = instruction.batchSize, hydrationSourceService = hydrationSourceService, hydrationSourceField = instruction.location, hydrationActorField = hydrationActorField ) engine.executeTopLevelField( service = instruction.actorService, topLevelField = actorQuery, executionContext = state.executionContext, serviceHydrationDetails = serviceHydrationDetails, ) } } .awaitAll() } } private fun getHydrationInstruction( state: State, instructions: List<NadelBatchHydrationFieldInstruction>, parentNode: JsonNode, ): NadelBatchHydrationFieldInstruction? { if (state.executionContext.hooks !is NadelEngineExecutionHooks) { error( "Cannot decide which hydration instruction should be used. " + "Provided ServiceExecutionHooks has to be of type NadelEngineExecutionHooks" ) } return state.executionContext.hooks.getHydrationInstruction( instructions, parentNode, state.aliasHelper, state.executionContext.userContext ) } }
24
null
23
157
d9bb3cf1f301c685ca6d578279c4b2c6d6a74158
8,030
nadel
Apache License 2.0
generate/src/main/kotlin/link/kotlin/scripts/ApplicationModule.kt
mmorihiro
83,640,176
true
{"TypeScript": 73763, "Kotlin": 61968, "CSS": 8914, "JavaScript": 4622, "HTML": 2000, "Shell": 517}
package link.kotlin.scripts import com.google.inject.Binder import com.google.inject.Module import com.google.inject.Provides import io.bootique.BQCoreModule import io.bootique.config.ConfigurationFactory import link.kotlin.scripts.commands.BuildCommand import link.kotlin.scripts.commands.ReadmeCommand class ApplicationModule : Module { override fun configure(binder: Binder) { arrayOf( BuildCommand::class, ReadmeCommand::class ).forEach { BQCoreModule .contributeCommands(binder) .addBinding() .to(it.java) } } @Provides fun createBotConfiguration(configurationFactory: ConfigurationFactory): LinkCheckerFactory { return configurationFactory.config(LinkCheckerFactory::class.java, "links") } }
0
TypeScript
0
0
72fd5a25f256474888811b88e419782783fa7ae5
837
awesome-kotlin
Creative Commons Zero v1.0 Universal
varp-core/src/main/kotlin/net/voxelpi/varp/exception/path/InvalidWarpPathException.kt
VoxelPi
869,165,536
false
{"Kotlin": 178363, "Java": 2122}
package net.voxelpi.varp.exception.path public class InvalidWarpPathException( public val path: String, ) : Exception("Invalid warp path: \"$path\"")
0
Kotlin
0
0
f9c616f84996d87363d37ba64eac4f89b9a32bd6
155
Varp
MIT License
shared/src/commonMain/kotlin/uk/co/sentinelweb/cuer/app/service/cast/CastServiceController.kt
sentinelweb
220,796,368
false
{"Kotlin": 2627509, "CSS": 205156, "Java": 98919, "Swift": 85812, "HTML": 19322, "JavaScript": 12105, "Ruby": 2170}
package uk.co.sentinelweb.cuer.app.service.cast import kotlinx.coroutines.launch import uk.co.sentinelweb.cuer.app.service.EXTRA_ITEM_ID import uk.co.sentinelweb.cuer.app.service.cast.CastServiceContract.Companion.ACTION_DISCONNECT import uk.co.sentinelweb.cuer.app.service.cast.CastServiceContract.Companion.ACTION_STAR import uk.co.sentinelweb.cuer.app.service.cast.CastServiceContract.Companion.ACTION_STOP import uk.co.sentinelweb.cuer.app.service.cast.CastServiceContract.Companion.ACTION_VOL_DOWN import uk.co.sentinelweb.cuer.app.service.cast.CastServiceContract.Companion.ACTION_VOL_MUTE import uk.co.sentinelweb.cuer.app.service.cast.CastServiceContract.Companion.ACTION_VOL_UP import uk.co.sentinelweb.cuer.app.service.cast.notification.player.PlayerControlsNotificationContract import uk.co.sentinelweb.cuer.app.ui.cast.CastController import uk.co.sentinelweb.cuer.app.usecase.StarMediaUseCase import uk.co.sentinelweb.cuer.core.providers.CoroutineContextProvider import uk.co.sentinelweb.cuer.core.wrapper.LogWrapper import uk.co.sentinelweb.cuer.domain.ext.deserialiseGuidIdentifier class CastServiceController( private val service: CastServiceContract.Service, private val notification: PlayerControlsNotificationContract.External, private val castController: CastController, private val coroutines: CoroutineContextProvider, private val log: LogWrapper, private val starMediaUseCase: StarMediaUseCase, ) : CastServiceContract.Controller { init { log.tag(this) } override fun initialise() { castController.initialiseForService() } override fun handleAction(action: String?, extras: Map<String, Any>?) { when (action) { ACTION_DISCONNECT -> { castController.killCurrentSession() service.stopSelf() } ACTION_STOP -> coroutines.mainScope.launch { castController.stopCuerCast() service.stopSelf() } ACTION_STAR -> { (extras ?.get(EXTRA_ITEM_ID) as String?) ?.let { deserialiseGuidIdentifier(it) } ?.also { itemId -> coroutines.mainScope.launch { starMediaUseCase.starMedia(itemId = itemId) } } } ACTION_VOL_DOWN -> castController.decrementVolume() ACTION_VOL_UP -> castController.incrementVolume() ACTION_VOL_MUTE -> castController.setVolume(0f) else -> notification.handleAction(action) } } override fun destroy() { notification.destroy() castController.onServiceDestroy() } }
95
Kotlin
0
2
1e3522bffa43f75f0e030f7ead3ce1b6873f5bd6
2,853
cuer
Apache License 2.0
mtproto/src/main/kotlin/com/github/badoualy/telegram/mtproto/secure/MTProtoMessageEncryption.kt
Miha-x64
436,587,061
true
{"Kotlin": 3919807, "Java": 75352}
package com.github.badoualy.telegram.mtproto.secure import com.github.badoualy.telegram.mtproto.auth.AuthKey import com.github.badoualy.telegram.mtproto.exception.AuthKeyIdDontMatchException import com.github.badoualy.telegram.mtproto.exception.MessageDecryptionException import com.github.badoualy.telegram.mtproto.secure.CryptoUtils.* import com.github.badoualy.telegram.mtproto.tl.MTProtoMessage import com.github.badoualy.telegram.mtproto.util.AesKeyIvPair import com.github.badoualy.telegram.tl.serialization.TLSerializerFactory import com.github.badoualy.telegram.tl.serialization.TLStreamSerializerFactory import com.github.badoualy.telegram.tl.stream.* import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.io.IOException import java.math.BigInteger import java.security.MessageDigest import java.security.NoSuchAlgorithmException import java.util.* /** * Helper class to handle the encryption/decryption of message following the MTProto protocol description */ object MTProtoMessageEncryption { private val tlSerializerFactory: TLSerializerFactory = TLStreamSerializerFactory /** * Generate message key * The lower-order 128 bits of the SHA1 hash of the part of the message to be encrypted (including the internal header and excluding the alignment bytes). * @param unencryptedData concatenation of the data to be encrypted (without padding) * @return message key * @see [Message Key](https://core.telegram.org/mtproto/description.message-key) */ @JvmStatic private fun generateMsgKey(unencryptedData: ByteArray) = substring(SHA1(unencryptedData), 4, 16)!! /** * Generate message key for the given message * @param serverSalt server salt used * @param sessionId session id used * @param message concerned message * @return The lower-order 128 bits of the SHA1 hash of the part of the message to be encrypted * @see [Message Key](https://core.telegram.org/mtproto/description.message-key) */ @JvmStatic private fun generateMsgKey(serverSalt: ByteArray, sessionId: ByteArray, message: MTProtoMessage): ByteArray? { try { val crypt = MessageDigest.getInstance("SHA-1") crypt.reset() crypt.update(serverSalt) crypt.update(sessionId) crypt.update(message.messageId.toBytes()) crypt.update(message.seqNo.toBytes()) crypt.update(message.payloadLength.toBytes()) crypt.update(message.payload, 0, message.payloadLength) // Use len as payload may have padding return substring(crypt.digest(), 4, 16) } catch (e: NoSuchAlgorithmException) { e.printStackTrace() } return null } /** * Encrypt a message following the MTProto description * @see [MTProto description](https://core.telegram.org/mtproto/description) * @param authKey authKey to use to encrypt * @param sessionId session id used * @param serverSalt server salt used * @param message message to be encrypted * @return encrypted message containing the encryption and the origin message * @throws IOException */ @Throws(IOException::class) @JvmStatic fun generateEncryptedMessage(authKey: AuthKey, sessionId: ByteArray, serverSalt: Long, message: MTProtoMessage): EncryptedMessage { // Build message body val unencryptedStream = ByteArrayOutputStream().apply { writeLong(serverSalt) writeByteArray(sessionId) writeLong(message.messageId) writeInt(message.seqNo) writeInt(message.payload.size) writeByteArray(message.payload) } val unencryptedData = unencryptedStream.toByteArray() val msgKey = generateMsgKey(unencryptedData) // Encrypt data val aesKeyIvPair = computeAESKeyAndInitVector(authKey, msgKey, 0) val encryptedData = AES256IGEEncrypt(align(unencryptedData, 16), aesKeyIvPair.iv, aesKeyIvPair.key) // Auth key is 8 bytes, Message key is 16 val out = ByteArrayOutputStream(24 + encryptedData.size).apply { writeByteArray(authKey.keyId) writeByteArray(msgKey) writeByteArray(encryptedData) } return EncryptedMessage(message, out.toByteArray()) } @Throws(IOException::class) @JvmStatic fun generateUnencryptedMessage(messageId: Long, data: ByteArray): ByteArray { // @see https://core.telegram.org/mtproto/description#unencrypted-message val out = ByteArrayOutputStream() tlSerializerFactory.createSerializer(out).apply { writeLong(0L) // auth_key_id writeLong(messageId) // message_id writeInt(data.size) // message_data_length writeByteArray(data) // message_data } return out.toByteArray() } /** * Decrypt a message following the MTProto description * @see [MTProto description](https://core.telegram.org/mtproto/description) * @param authKey authKey to use to encrypt * @param sessionId session id used * @param data message to be decrypted * @return decrypted message * @throws IOException */ @Throws(IOException::class) @JvmStatic fun extractMessage(authKey: AuthKey, sessionId: ByteArray, data: ByteArray): MTProtoMessage { val stream = ByteArrayInputStream(data) // Retrieve and check authKey val msgAuthKeyId = stream.readBytes(8) if (!Arrays.equals(authKey.keyId, msgAuthKeyId)) throw AuthKeyIdDontMatchException(msgAuthKeyId, authKey.key) // Message key val msgKey = stream.readBytes(16) val aesKeyIvPair = computeAESKeyAndInitVector(authKey, msgKey, 8) // Read encrypted data val encryptedDataLength = data.size - 24 // Subtract authKey(8) + msgKey(16) length val encryptedData = ByteArray(encryptedDataLength) stream.readBytes(encryptedData, 0, encryptedDataLength) // Decrypt val unencryptedData = ByteArray(encryptedDataLength) // AES input/output have the same size AES256IGEDecryptBig(encryptedData, unencryptedData, encryptedDataLength, aesKeyIvPair.iv, aesKeyIvPair.key) // Decompose val unencryptedStream = ByteArrayInputStream(unencryptedData) val serverSalt = unencryptedStream.readBytes(8) val session = unencryptedStream.readBytes(8) // Payload starts here val msgId = unencryptedStream.readLong() val seqNo = unencryptedStream.readInt() val msgLength = unencryptedStream.readInt() val paddingSize = encryptedDataLength - 32 - msgLength // serverSalt(8) + sessionId(8) + messageId(8) + seqNo(4) + msgLen(4) // Security checks if (msgId % 2 == 0L) throw MessageDecryptionException( "Message id of messages sent be the server must be odd, found $msgId") if (msgLength % 4 != 0) throw MessageDecryptionException( "Message length must be a multiple of 4, found $msgLength") if (paddingSize > 15 || paddingSize < 0) throw MessageDecryptionException( "Padding must be between 0 and 15 included, found $paddingSize") if (!Arrays.equals(session, sessionId)) throw MessageDecryptionException( "The message was not intended for this session, expected ${BigInteger( sessionId).toLong()}, found ${BigInteger(session).toLong()}") // Read message val message = ByteArray(msgLength) unencryptedStream.readBytes(message, 0, msgLength) val mtMessage = MTProtoMessage(msgId, seqNo, message, message.size) // Check that msgKey is equal to the 128 lower-order bits of the SHA1 hash of the previously encrypted portion val checkMsgKey = generateMsgKey(serverSalt, session, mtMessage) if (!Arrays.equals(checkMsgKey, msgKey)) throw MessageDecryptionException("The message msgKey is inconsistent with it's data") return mtMessage } fun extractUnencryptedMessage(data: ByteArray): ByteArray { return with(ByteArrayInputStream(data)) { readLong().takeIf { it == 0L }?.let { @Suppress("UNUSED_VARIABLE") val messageId = readLong() val length = readInt() readBytes(length) } ?: throw MessageDecryptionException("Auth id must be equal to zero") } } /** * Compute the AES Key and the Initialization Vector * @param x x = 0 for messages from client to server and x = 8 for those from server to client. * @see [Defining AES Key and Initialization Vector](https://core.telegram.org/mtproto/description.defining-aes-key-and-initialization-vector) */ @JvmStatic private fun computeAESKeyAndInitVector(authKey: AuthKey, msgKey: ByteArray, x: Int): AesKeyIvPair { val sha1_a = CryptoUtils.SHA1(msgKey, substring(authKey.key, x, 32)) val sha1_b = CryptoUtils.SHA1(substring(authKey.key, 32 + x, 16), msgKey, substring(authKey.key, 48 + x, 16)) val sha1_c = CryptoUtils.SHA1(substring(authKey.key, 64 + x, 32), msgKey) val sha1_d = CryptoUtils.SHA1(msgKey, substring(authKey.key, 96 + x, 32)) val aesKey = concat(substring(sha1_a, 0, 8), substring(sha1_b, 8, 12), substring(sha1_c, 4, 12)) val aesIv = concat(substring(sha1_a, 8, 12), substring(sha1_b, 0, 8), substring(sha1_c, 16, 4), substring(sha1_d, 0, 8)) return AesKeyIvPair(aesKey, aesIv) } }
1
Kotlin
2
3
1a8963dce921c1e9ef05b9d1e56d8fbcb1ea1c4b
10,210
kotlogram-resurrected
MIT License
shared/presentation/src/commonMain/kotlin/org/dukecon/presentation/model/FeedbackView.kt
dukecon
211,271,600
false
{"Gradle Kotlin DSL": 12, "Gradle": 5, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Groovy": 1, "AsciiDoc": 1, "Markdown": 1, "Proguard": 4, "XML": 107, "Kotlin": 259, "Java": 1, "JSON": 7, "Ruby": 2, "OpenStep Property List": 4, "Swift": 15, "YAML": 1, "Dockerfile": 1, "OASv3-json": 3}
package org.dukecon.presentation.model class FeedbackView(val value: Int)
16
Kotlin
0
5
aa12bd09830c3407635d0bc3e5691ba1ffaeeb2f
74
dukecon_mobile
Apache License 2.0
technocracy.foundation/src/main/kotlin/net/cydhra/technocracy/foundation/model/tileentities/impl/AggregatableTileEntity.kt
tth05
198,904,996
false
null
package net.cydhra.technocracy.foundation.tileentity import net.cydhra.technocracy.foundation.tileentity.api.TCAggregatable import net.cydhra.technocracy.foundation.tileentity.api.TCAggregatableTileEntity import net.minecraft.nbt.NBTTagCompound import net.minecraft.util.EnumFacing import net.minecraftforge.common.capabilities.Capability @Suppress("DELEGATED_MEMBER_HIDES_SUPERTYPE_OVERRIDE") open class AggregatableTileEntity : AbstractTileEntity(), TCAggregatableTileEntity, TCAggregatable by AggregatableDelegate() { init { this.tile = this } override fun writeToNBT(compound: NBTTagCompound): NBTTagCompound { super.writeToNBT(compound) this.serializeNBT(compound) return compound } override fun readFromNBT(compound: NBTTagCompound) { super.readFromNBT(compound) this.deserializeNBT(compound) } override fun hasCapability(capability: Capability<*>, facing: EnumFacing?): Boolean { return this.supportsCapability(capability, facing) || super.hasCapability(capability, facing) } override fun <T : Any?> getCapability(capability: Capability<T>, facing: EnumFacing?): T? { return this.castCapability(capability, facing) ?: super.getCapability(capability, facing) } }
0
null
0
1
057d12813fbcb73a11b202caae0631020b2fa303
1,279
Technocracy
MIT License
clouddriver-event/src/main/kotlin/com/netflix/spinnaker/clouddriver/event/persistence/InMemoryEventRepository.kt
spinnaker
37,556,951
false
null
/* * Copyright 2019 Netflix, Inc. * * 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.netflix.spinnaker.clouddriver.event.persistence import com.netflix.spectator.api.Registry import com.netflix.spinnaker.clouddriver.event.Aggregate import com.netflix.spinnaker.clouddriver.event.EventMetadata import com.netflix.spinnaker.clouddriver.event.SpinnakerEvent import com.netflix.spinnaker.clouddriver.event.config.MemoryEventRepositoryConfigProperties import com.netflix.spinnaker.clouddriver.event.exceptions.AggregateChangeRejectedException import com.netflix.spinnaker.kork.exceptions.SystemException import org.slf4j.LoggerFactory import org.springframework.context.ApplicationEventPublisher import org.springframework.scheduling.annotation.Scheduled import java.time.Duration import java.time.Instant import java.util.concurrent.ConcurrentHashMap import kotlin.math.max /** * An in-memory only [EventRepository]. This implementation should only be used for testing. */ class InMemoryEventRepository( private val config: MemoryEventRepositoryConfigProperties, private val applicationEventPublisher: ApplicationEventPublisher, private val registry: Registry ) : EventRepository { private val log by lazy { LoggerFactory.getLogger(javaClass) } private val aggregateCountId = registry.createId("eventing.aggregates") private val aggregateWriteCountId = registry.createId("eventing.aggregates.writes") private val aggregateReadCountId = registry.createId("eventing.aggregates.reads") private val eventCountId = registry.createId("eventing.events") private val eventWriteCountId = registry.createId("eventing.events.writes") private val eventReadCountId = registry.createId("eventing.events.reads") private val events: MutableMap<Aggregate, MutableList<SpinnakerEvent>> = ConcurrentHashMap() override fun save( aggregateType: String, aggregateId: String, originatingVersion: Long, newEvents: List<SpinnakerEvent> ) { registry.counter(aggregateWriteCountId).increment() val aggregate = getAggregate(aggregateType, aggregateId) if (aggregate.version != originatingVersion) { // If this is being thrown, ensure that the originating process is retried on the latest aggregate version // by re-reading the newEvents list. throw AggregateChangeRejectedException( "Attempting to save newEvents against an old aggregate version " + "(version: ${aggregate.version}, originatingVersion: $originatingVersion)") } events.getOrPut(aggregate) { mutableListOf() }.let { aggregateEvents -> val currentSequence = aggregateEvents.map { it.metadata.sequence }.max() ?: 0 newEvents.forEachIndexed { index, newEvent -> newEvent.aggregateType = aggregateType newEvent.aggregateId = aggregateId // TODO(rz): Plugin more metadata (provenance, serviceVersion, etc) newEvent.metadata = EventMetadata( sequence = currentSequence + (index + 1), originatingVersion = originatingVersion ) } registry.counter(eventWriteCountId).increment(newEvents.size.toLong()) aggregateEvents.addAll(newEvents) aggregate.version = aggregate.version + 1 } log.debug("Saved $aggregateType/$aggregateId@${aggregate.version}: " + "[${newEvents.joinToString(",") { it.javaClass.simpleName }}]") newEvents.forEach { applicationEventPublisher.publishEvent(it) } } override fun list(aggregateType: String, aggregateId: String): List<SpinnakerEvent> { registry.counter(eventReadCountId).increment() return getAggregate(aggregateType, aggregateId) .let { events[it]?.toList() } ?: throw MissingAggregateEventsException(aggregateType, aggregateId) } override fun listAggregates(aggregateType: String?): List<Aggregate> { val aggregates = events.keys return if (aggregateType != null) { aggregates.filter { it.type == aggregateType } } else { aggregates.toList() } } private fun getAggregate(aggregateType: String, aggregateId: String): Aggregate { registry.counter(aggregateReadCountId).increment() val aggregate = Aggregate( aggregateType, aggregateId, 0L ) events.putIfAbsent(aggregate, mutableListOf()) return events.keys.first { it == aggregate } } @Scheduled(fixedDelayString = "\${spinnaker.clouddriver.eventing.memory-repository.cleanup-job-delay-ms:60000}") private fun cleanup() { registry.counter(eventReadCountId).increment() config.maxAggregateAgeMs ?.let { Duration.ofMillis(it) } ?.let { maxAge -> val horizon = Instant.now().minus(maxAge) log.info("Cleaning up aggregates last updated earlier than $maxAge ($horizon)") events.entries .filter { it.value.any { event -> event.metadata.timestamp.isBefore(horizon) } } .map { it.key } .forEach { log.trace("Cleaning up $it") events.remove(it) } } config.maxAggregatesCount ?.let { maxCount -> log.info("Cleaning up aggregates to max $maxCount items, pruning by earliest updated") events.entries // Flatten into pairs of List<Aggregate, SpinnakerEvent> .flatMap { entry -> entry.value.map { Pair(entry.key, it) } } .sortedBy { it.second.metadata.timestamp } .subList(0, max(events.size - maxCount, 0)) .forEach { log.trace("Cleaning up ${it.first}") events.remove(it.first) } } } @Scheduled(fixedRate = 1_000) private fun recordMetrics() { registry.gauge(aggregateCountId).set(events.size.toDouble()) registry.gauge(eventCountId).set(events.flatMap { it.value }.size.toDouble()) } inner class MissingAggregateEventsException(aggregateType: String, aggregateId: String) : SystemException( "Aggregate $aggregateType/$aggregateId is missing its internal events list store" ) }
3
null
1029
434
88d1fd00b84e10cfefeed7628e749f9a24c13cc3
6,525
clouddriver
Apache License 2.0
js/js.translator/testData/box/package/initializersOfNestedPackagesExecute.kt
JakeWharton
99,388,807
true
null
// EXPECTED_REACHABLE_NODES: 1109 package foo1.foo2.foo3.foo5.foo6.foo7.foo8 val f = "OK" fun box() = f
0
Kotlin
28
83
4383335168338df9bbbe2a63cb213a68d0858104
105
kotlin
Apache License 2.0
src/main/java/org/samoxive/safetyjim/discord/commands/Ban.kt
Samoxive
90,876,603
false
null
package org.samoxive.safetyjim.discord.commands import net.dv8tion.jda.api.EmbedBuilder import net.dv8tion.jda.api.Permission import net.dv8tion.jda.api.entities.Guild import net.dv8tion.jda.api.entities.TextChannel import net.dv8tion.jda.api.entities.User import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent import org.samoxive.safetyjim.database.BanEntity import org.samoxive.safetyjim.database.BansTable import org.samoxive.safetyjim.database.SettingsEntity import org.samoxive.safetyjim.discord.* import org.samoxive.safetyjim.tryhardAsync import java.awt.Color import java.util.* suspend fun banAction(guild: Guild, channel: TextChannel?, settings: SettingsEntity, modUser: User, banUser: User, reason: String, expirationDate: Date?) { val now = Date() val embed = EmbedBuilder() embed.setTitle("Banned from ${guild.name}") embed.setColor(Color(0x4286F4)) embed.setDescription("You were banned from ${guild.name}") embed.addField("Reason:", truncateForEmbed(reason), false) embed.addField("Banned until", expirationDate?.toString() ?: "Indefinitely", false) embed.setFooter("Banned by ${modUser.getUserTagAndId()}", null) embed.setTimestamp(now.toInstant()) banUser.trySendMessage(embed.build()) val auditLogReason = "Banned by ${modUser.getUserTagAndId()} - $reason" guild.ban(banUser, 0, auditLogReason).await() val expires = expirationDate != null BansTable.invalidatePreviousUserBans(guild, banUser) val record = BansTable.insertBan( BanEntity( userId = banUser.idLong, moderatorUserId = modUser.idLong, guildId = guild.idLong, banTime = now.time / 1000, expireTime = if (expirationDate != null) expirationDate.time / 1000 else 0, reason = reason, expires = expires, unbanned = false ) ) val banId = record.id createModLogEntry(guild, channel, settings, modUser, banUser, reason, ModLogAction.Ban, banId, expirationDate) } class Ban : Command() { override val usages = arrayOf("ban @user [reason] | [time] - bans the user with specific arguments. Both arguments can be omitted") override suspend fun run(bot: DiscordBot, event: GuildMessageReceivedEvent, settings: SettingsEntity, args: String): Boolean { val messageIterator = Scanner(args) val member = event.member!! val user = event.author val message = event.message val channel = event.channel val guild = event.guild val selfMember = guild.selfMember if (!member.hasPermission(Permission.BAN_MEMBERS)) { message.failMessage("You don't have enough permissions to execute this command! Required permission: Ban Members") return false } if (args.isEmpty()) { return true } val (searchResult, banUser) = messageIterator.findUser(message, true) if (searchResult == SearchUserResult.NOT_FOUND || (banUser == null)) { message.failMessage("Could not find the user to ban!") return false } if (searchResult == SearchUserResult.GUESSED) { message.askConfirmation(bot, banUser) ?: return false } val banMember = tryhardAsync { guild.retrieveMember(banUser, true).await() } if (!selfMember.hasPermission(Permission.BAN_MEMBERS)) { message.failMessage("I don't have enough permissions to do that!") return false } if (user == banUser) { message.failMessage("You can't ban yourself, dummy!") return false } if (banMember != null && !banMember.isBannableBy(selfMember)) { message.failMessage("I don't have enough permissions to do that!") return false } val parsedReasonAndTime = try { messageIterator.getTextAndTime() } catch (e: InvalidTimeInputException) { message.failMessage("Invalid time argument. Please try again.") return false } catch (e: TimeInputInPastException) { message.failMessage("Your time argument was set for the past. Try again.\nIf you're specifying a date, e.g. `30 December`, make sure you also write the year.") return false } val (text, expirationDate) = parsedReasonAndTime val reason = if (text == "") "No reason specified" else text try { banAction(guild, channel, settings, user, banUser, reason, expirationDate) message.successReact() channel.sendModActionConfirmationMessage(settings, "Banned ${banUser.getUserTagAndId()} ${getExpirationTextInChannel(expirationDate)}") } catch (e: Exception) { message.failMessage("Could not ban the specified user. Do I have enough permissions?") } return false } }
6
null
14
29
159333ad78809a9de6e1491c62bfc2875970bac0
4,940
SafetyJim
MIT License
src/main/kotlin/no/nav/syfo/behandling/BehandlingException.kt
navikt
121,716,621
false
{"Kotlin": 376271, "Dockerfile": 440}
package no.nav.syfo.behandling open class BehandlingException(val feiltype: Feiltype, message: String, cause: Exception?) : RuntimeException(message, cause) // AktorClient open class AktørException(feiltype: Feiltype, message: String, causedBy: Exception?) : BehandlingException(feiltype, message, causedBy) open class FantIkkeAktørException(causedBy: java.lang.Exception?) : AktørException(Feiltype.AKTØR_IKKE_FUNNET, "Fant ikke aktørId", causedBy) // OppgaveClient open class OppgaveException(feiltype: Feiltype, message: String, causedBy: Exception?) : BehandlingException(feiltype, message, causedBy) open class HentOppgaveException(journalpostId: String, oppgaveType: String, cause: Exception?) : OppgaveException(Feiltype.OPPGAVE_HENT, "Feil ved oppslag til oppgave for journalpostId $journalpostId med oppgavetype $oppgaveType!", cause) open class OpprettOppgaveException(journalpostId: String, cause: Exception?) : OppgaveException(Feiltype.OPPGAVE_OPPRETT_VANLIG, "Klarte ikke opprette oppgave for journalpostId $journalpostId!", cause) open class OpprettFordelingsOppgaveException(journalpostId: String, cause: Exception?) : OppgaveException(Feiltype.OPPGAVE_OPPRETT_FORDELING, "Klarte ikke opprette fordelingsoppgave for journalpostId $journalpostId!", cause) // BehandlendeEnhetConsumer open class BehandlendeEnhetException(feiltype: Feiltype, message: String, cause: Exception?) : BehandlingException(feiltype, message, cause) open class IngenAktivEnhetException(geografiskTilknytning: String?, cause: java.lang.Exception?) : BehandlendeEnhetException(Feiltype.BEHANDLENDE_INGEN_AKTIV_ENHET, "Fant ingen aktiv enhet for $geografiskTilknytning", cause) open class BehandlendeEnhetFeiletException(cause: java.lang.Exception?) : BehandlendeEnhetException(Feiltype.BEHANDLENDE_FEILET, "Feil ved henting av geografisk tilknytning", cause) // JournalConsumer open class JournalException(feiltype: Feiltype, message: String, cause: Exception?) : BehandlingException(feiltype, message, cause) open class HentDokumentFeiletException(journalpostId: String, cause: java.lang.Exception?) : JournalException(Feiltype.DOKUMENT_FEILET, "Kall til journal feilet for journalpostId $journalpostId!", cause)
9
Kotlin
3
4
b8890f9b7464d3c300cb8bbedd07f572516883ed
2,207
syfoinntektsmelding
MIT License
ksol-core/src/test/kotlin/com/dgsd/ksol/core/utils/IntExtensionsTests.kt
dlgrech
524,875,633
false
null
package com.dgsd.ksol.core.utils import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.DynamicTest import org.junit.jupiter.api.TestFactory class IntExtensionsTests { private val intToBytes = listOf( 1 to byteArrayOf(1, 0, 0, 0), 20 to byteArrayOf(20, 0, 0, 0), 44 to byteArrayOf(44, 0, 0, 0), 128 to byteArrayOf(-128, 0, 0, 0), 129 to byteArrayOf(-127, 0, 0, 0), 500 to byteArrayOf(-12, 1, 0, 0), ) @TestFactory fun testFactory_toByteArray() = intToBytes.map { (input, expected) -> DynamicTest.dynamicTest("${input}toByteArray() == ${expected.toList()}") { Assertions.assertArrayEquals( expected, input.toByteArray() ) } } @TestFactory fun testFactory_reverseBytes() = intToBytes.map { (input, expected) -> val reversed = expected.reversedArray() DynamicTest.dynamicTest("${input}.reverseBytes() == ${reversed.toList()}") { Assertions.assertArrayEquals( reversed, input.reverseBytes().toByteArray() ) } } }
0
Kotlin
2
9
153e922fa405d6ba6c33041002bcf53d6293c7cf
1,043
ksol
Apache License 2.0
zoomx/src/main/java/com/zoomx/zoomx/util/FileUtils.kt
district0
111,302,914
false
null
package com.zoomx.zoomx.util import java.io.File import java.io.FileInputStream import java.io.FileOutputStream import java.io.IOException import java.nio.channels.FileChannel @Throws(IOException::class) fun copyFile(sourceFile: File, destFile: File) { if (!destFile.parentFile.exists()) destFile.parentFile.mkdirs() if (!destFile.exists()) { destFile.createNewFile() } var source: FileChannel? = null var destination: FileChannel? = null try { source = FileInputStream(sourceFile).channel destination = FileOutputStream(destFile).channel destination!!.transferFrom(source, 0, source!!.size()) } finally { if (source != null) { source!!.close() } if (destination != null) { destination!!.close() } } }
3
null
6
14
4274335315f92520e86c09abf7e8fb9e359d2a72
834
ZoomX
MIT License
app/src/main/java/com/evourse/instaclone/MainActivity.kt
dayashanknar
736,360,187
false
{"Kotlin": 38103}
package com.evourse.instaclone import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.evourse.instaclone.databinding.ActivityMainBinding import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : AppCompatActivity() { private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) supportFragmentManager.beginTransaction().apply { replace(R.id.mainFragmentC, FrHome()) commit() } } }
0
Kotlin
0
0
72d4d9f1e711327c3cdf139ec935b9b82827f2ad
661
anonym
MIT License
common/src/commonMain/kotlin/com/artemchep/keyguard/provider/bitwarden/entity/request/CipherShareRequest.kt
AChep
669,697,660
false
{"Kotlin": 5516822, "HTML": 45876}
package com.artemchep.keyguard.provider.bitwarden.entity.request import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class CipherShareRequest( @SerialName("cipher") val cipher: CipherRequest, @SerialName("collectionIds") val collectionIds: List<String>, )
66
Kotlin
31
995
557bf42372ebb19007e3a8871e3f7cb8a7e50739
323
keyguard-app
Linux Kernel Variant of OpenIB.org license