path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
app/src/main/java/hu/agostonberger/todoforwatch/data/TodoService.kt
bergeragoston
245,888,350
false
null
package hu.agostonberger.todoforwatch.data internal interface TodoService { val incompleteTodoItems: List<TodoItem> fun markItemAsDone(todoItem: TodoItem) }
0
Kotlin
0
0
eae17956490e5bc33673ef6f71b6eff05bed077b
167
todo-for-watch-companion
MIT License
app/src/main/java/com/ignagr/quecomemos/entities/Enums.kt
IgnaGarcia
433,287,220
false
null
package com.ignagr.quecomemos.entities import com.google.gson.annotations.SerializedName class Enums( @SerializedName("types") val types: List<String>, @SerializedName("diets") val diets: List<String>, @SerializedName("cultures") val cultures: List<String> )
0
Kotlin
0
0
3f19b330dcf5defd9d2d6fdf2058fbced6aad43d
272
APP-QueComemos
Apache License 2.0
pulsar-plugins/pulsar-protocol/src/main/kotlin/ai/platon/pulsar/protocol/browser/emulator/BrowserEmulateEventHandler.kt
owinfo
271,195,380
true
{"Java": 9365198, "HTML": 2558036, "Kotlin": 1862834, "JavaScript": 51731, "Shell": 18915, "PLSQL": 10825, "TSQL": 7164, "CSS": 4671, "Rich Text Format": 2235}
package ai.platon.pulsar.protocol.browser.emulator import ai.platon.pulsar.browser.driver.BrowserControl import ai.platon.pulsar.common.* import ai.platon.pulsar.common.config.CapabilityTypes import ai.platon.pulsar.common.config.ImmutableConfig import ai.platon.pulsar.common.files.ext.export import ai.platon.pulsar.common.message.MiscMessageWriter import ai.platon.pulsar.crawl.fetch.FetchTask import ai.platon.pulsar.crawl.protocol.ForwardingResponse import ai.platon.pulsar.crawl.protocol.Response import ai.platon.pulsar.persist.ProtocolStatus import ai.platon.pulsar.persist.RetryScope import ai.platon.pulsar.persist.WebPage import ai.platon.pulsar.persist.metadata.MultiMetadata import ai.platon.pulsar.persist.metadata.ProtocolStatusCodes import ai.platon.pulsar.persist.model.ActiveDomMessage import ai.platon.pulsar.protocol.browser.driver.ManagedWebDriver import ai.platon.pulsar.protocol.browser.driver.WebDriverManager import com.codahale.metrics.SharedMetricRegistries import org.openqa.selenium.OutputType import org.openqa.selenium.remote.RemoteWebDriver import org.slf4j.LoggerFactory import java.io.IOException import java.nio.charset.StandardCharsets import java.nio.file.Files import java.time.Duration import java.time.Instant import java.util.concurrent.atomic.AtomicInteger open class BrowserEmulateEventHandler( private val driverManager: WebDriverManager, private val messageWriter: MiscMessageWriter, private val immutableConfig: ImmutableConfig ) { private val log = LoggerFactory.getLogger(BrowserEmulateEventHandler::class.java)!! private val supportAllCharsets get() = immutableConfig.getBoolean(CapabilityTypes.PARSE_SUPPORT_ALL_CHARSETS, true) private val fetchMaxRetry = immutableConfig.getInt(CapabilityTypes.HTTP_FETCH_MAX_RETRY, 3) val charsetPattern = if (supportAllCharsets) SYSTEM_AVAILABLE_CHARSET_PATTERN else DEFAULT_CHARSET_PATTERN private val metrics = SharedMetricRegistries.getDefault() private val pageSourceBytes = metrics.histogram(prependReadableClassName(this, "pageSourceBytes")) private val totalPageSourceBytes = metrics.meter(prependReadableClassName(this, "totalPageSourceBytes")) private val bannedPages = metrics.meter(prependReadableClassName(this, "bannedPages")) private val smallPages = metrics.meter(prependReadableClassName(this, "smallPages")) private val smallPageRate = metrics.histogram(prependReadableClassName(this, "smallPageRate")) private val emptyPages = metrics.meter(prependReadableClassName(this, "emptyPages")) private val numNavigates = AtomicInteger() private val driverPool = driverManager.driverPool fun logBeforeNavigate(task: FetchTask, driverConfig: BrowserControl) { if (log.isTraceEnabled) { log.trace("Navigate {}/{}/{} in [t{}]{}, drivers: {}/{}/{}(w/f/o) | {} | timeouts: {}/{}/{}", task.batchTaskId, task.batchSize, task.id, Thread.currentThread().id, if (task.nRetries <= 1) "" else "(${task.nRetries})", driverPool.numWorking, driverPool.numFree, driverPool.numOnline, task.page.configuredUrl, driverConfig.pageLoadTimeout, driverConfig.scriptTimeout, driverConfig.scrollInterval ) } } fun onAfterNavigate(task: NavigateTask): Response { numNavigates.incrementAndGet() val length = task.pageSource.length pageSourceBytes.update(length) totalPageSourceBytes.mark(length.toLong()) val browserStatus = checkErrorPage(task.page, task.status) task.status = browserStatus.status if (browserStatus.code != ProtocolStatusCodes.SUCCESS_OK) { // The browser shows it's own error page, which is no value to store task.pageSource = "" return ForwardingResponse(task.pageSource, task.status, task.headers, task.page) } // Check if the page source is integral val integrity = checkHtmlIntegrity(task.pageSource, task.page, task.status, task.task) // Check browse timeout event, transform status to be success if the page source is good if (task.status.isTimeout) { if (integrity.isOK) { // fetch timeout but content is OK task.status = ProtocolStatus.STATUS_SUCCESS } handleBrowseTimeout(task) } task.headers.put(HttpHeaders.CONTENT_LENGTH, task.pageSource.length.toString()) if (integrity.isOK) { // Update page source, modify charset directive, do the caching stuff task.pageSource = handlePageSource(task.pageSource).toString() } else { // The page seems to be broken, retry it task.status = handleBrokenPageSource(task.task, integrity) logBrokenPage(task.task, task.pageSource, integrity) } // Update headers, metadata, do the logging stuff task.page.lastBrowser = task.driver.browserType task.page.htmlIntegrity = integrity // TODO: collect response headers of main resource return createResponse(task) } open fun checkErrorPage(page: WebPage, status: ProtocolStatus): BrowserStatus { val browserStatus = BrowserStatus(status, ProtocolStatusCodes.SUCCESS_OK) if (status.minorCode == ProtocolStatusCodes.BROWSER_ERR_CONNECTION_TIMED_OUT) { // The browser can not connect to remote peer, it must be caused by the bad proxy ip // It might be fixed by resetting the privacy context // log.warn("Connection timed out in browser, resetting the browser context") browserStatus.status = ProtocolStatus.retry(RetryScope.PRIVACY, status) browserStatus.code = status.minorCode // throw PrivacyLeakException() } else if (status.minorCode == ProtocolStatusCodes.BROWSER_ERROR) { browserStatus.status = ProtocolStatus.retry(RetryScope.CRAWL, status) browserStatus.code = status.minorCode } return browserStatus } /** * Check if the html is integral without field extraction, a further html integrity checking can be * applied after field extraction. * */ open fun checkHtmlIntegrity(pageSource: String, page: WebPage, status: ProtocolStatus, task: FetchTask): HtmlIntegrity { val length = pageSource.length.toLong() var integrity = HtmlIntegrity.OK if (length == 0L) { integrity = HtmlIntegrity.EMPTY_0B } else if (length == 39L) { integrity = HtmlIntegrity.EMPTY_39B } // might be caused by web driver exception if (integrity.isOK && isBlankBody(pageSource)) { integrity = HtmlIntegrity.EMPTY_BODY } if (integrity.isOK) { integrity = checkHtmlIntegrity(pageSource) } return integrity } protected fun checkHtmlIntegrity(pageSource: String): HtmlIntegrity { val p1 = pageSource.indexOf("<body") if (p1 <= 0) return HtmlIntegrity.OTHER val p2 = pageSource.indexOf(">", p1) if (p2 < p1) return HtmlIntegrity.OTHER // no any link, it's broken val p3 = pageSource.indexOf("<a", p2) if (p3 < p2) return HtmlIntegrity.NO_ANCHOR // TODO: optimize using region match val bodyTag = pageSource.substring(p1, p2) // The javascript set data-error flag to indicate if the vision information of all DOM nodes is calculated val r = bodyTag.contains("data-error=\"0\"") if (!r) { return HtmlIntegrity.NO_JS_OK_FLAG } return HtmlIntegrity.OK } open fun handleBrowseTimeout(task: NavigateTask) { if (log.isInfoEnabled) { val elapsed = Duration.between(task.startTime, Instant.now()) val length = task.pageSource.length val link = AppPaths.uniqueSymbolicLinkForUri(task.page.url) val driverConfig = task.driverConfig log.info("Timeout ({}) after {} with {} drivers: {}/{}/{} timeouts: {}/{}/{} | file://{}", task.status.minorName, elapsed, Strings.readableBytes(length.toLong()), driverPool.numWorking, driverPool.numFree, driverPool.numOnline, driverConfig.pageLoadTimeout, driverConfig.scriptTimeout, driverConfig.scrollInterval, link) } } open fun createResponse(task: NavigateTask): ForwardingResponse { val response = ForwardingResponse(task.pageSource, task.status, task.headers, task.page) val headers = task.headers val page = task.page // The page content's encoding is already converted to UTF-8 by Web driver val utf8 = StandardCharsets.UTF_8.name() require(utf8 == "UTF-8") headers.put(HttpHeaders.CONTENT_ENCODING, utf8) headers.put(HttpHeaders.Q_TRUSTED_CONTENT_ENCODING, utf8) headers.put(HttpHeaders.Q_RESPONSE_TIME, System.currentTimeMillis().toString()) // TODO: Update all page data in the same place val urls = page.activeDomUrls if (urls != null) { response.location = urls.location if (page.url != response.location) { // in-browser redirection messageWriter.debugRedirects(page.url, urls) } } exportIfNecessary(task) return response } fun handlePageSource(pageSource: String): StringBuilder { // The browser has already convert source code to UTF-8 return replaceHTMLCharset(pageSource, charsetPattern, "UTF-8") } /** * Chrome redirected to the error page chrome-error:// * This page should be text analyzed to determine the actual error * */ fun handleChromeError(message: String): BrowserError { val activeDomMessage = ActiveDomMessage.fromJson(message) val status = if (activeDomMessage.multiStatus?.status?.ec == BrowserError.CONNECTION_TIMED_OUT) { // chrome can not connect to the peer, it probably be caused by a bad proxy // convert to retry in PRIVACY_CONTEXT later ProtocolStatus.failed(ProtocolStatusCodes.BROWSER_ERR_CONNECTION_TIMED_OUT) } else { // unhandled exception ProtocolStatus.failed(ProtocolStatusCodes.BROWSER_ERROR) } return BrowserError(status, activeDomMessage) } fun handleBrokenPageSource(task: FetchTask, htmlIntegrity: HtmlIntegrity): ProtocolStatus { return when { // should cancel all running tasks and reset the privacy context and then re-fetch them htmlIntegrity.isBanned -> ProtocolStatus.retry(RetryScope.PRIVACY, htmlIntegrity).also { bannedPages.mark() } // must come after privacy context reset, PRIVACY_CONTEXT reset have the higher priority task.nRetries > fetchMaxRetry -> ProtocolStatus.retry(RetryScope.CRAWL) .also { log.info("Retry task ${task.id} in the next crawl round") } htmlIntegrity.isEmpty -> ProtocolStatus.retry(RetryScope.PRIVACY, htmlIntegrity).also { emptyPages.mark() } htmlIntegrity.isSmall -> ProtocolStatus.retry(RetryScope.CRAWL, htmlIntegrity).also { smallPages.mark() smallPageRate.update(100 * smallPages.count / numNavigates.get()) } else -> ProtocolStatus.retry(RetryScope.CRAWL, htmlIntegrity) } } private fun exportIfNecessary(task: NavigateTask) { exportIfNecessary(task.pageSource, task.status, task.page) } private fun exportIfNecessary(pageSource: String, status: ProtocolStatus, page: WebPage) { if (pageSource.isEmpty()) { return } val shouldExport = (log.isInfoEnabled && !status.isSuccess) || log.isDebugEnabled if (shouldExport) { val path = AppFiles.export(status, pageSource, page) // Create symbolic link with an url based, unique, shorter but not readable file name, // we can generate and refer to this path at any place val link = AppPaths.uniqueSymbolicLinkForUri(page.url) try { Files.deleteIfExists(link) Files.createSymbolicLink(link, path) } catch (e: IOException) { log.warn(e.toString()) } if (log.isTraceEnabled) { // takeScreenshot(pageSource.length.toLong(), page, driver.driver as RemoteWebDriver) } } } fun takeScreenshot(contentLength: Long, page: WebPage, driver: RemoteWebDriver) { try { if (contentLength > 100) { val bytes = driver.getScreenshotAs(OutputType.BYTES) AppFiles.export(page, bytes, ".png") } } catch (e: Exception) { log.warn("Screenshot failed {} | {}", Strings.readableBytes(contentLength), page.url) log.warn(Strings.stringifyException(e)) } } fun logBrokenPage(task: FetchTask, pageSource: String, integrity: HtmlIntegrity) { val proxyEntry = task.proxyEntry val domain = task.domain val link = AppPaths.uniqueSymbolicLinkForUri(task.url) val readableLength = Strings.readableBytes(pageSource.length.toLong()) if (proxyEntry != null) { val count = proxyEntry.servedDomains.count(domain) log.warn("Page is {}({}) with {} in {}({}) | file://{} | {}", integrity.name, readableLength, proxyEntry.display, domain, count, link, task.url) } else { log.warn("Page is {}({}) | file://{} | {}", integrity.name, readableLength, link, task.url) } } }
0
null
0
0
9b284ddde911307ec6011e490a3b843ed724ed61
13,928
pulsar
Apache License 2.0
src/main/kotlin/no/nav/hm/grunndata/register/product/ProductRegistrationAdminApiController.kt
navikt
572,421,718
false
{"Kotlin": 718915, "Dockerfile": 113, "Shell": 111}
package no.nav.hm.grunndata.register.product import io.micronaut.data.exceptions.DataAccessException import io.micronaut.data.model.Page import io.micronaut.data.model.Pageable import io.micronaut.data.model.Slice import io.micronaut.data.model.jpa.criteria.impl.LiteralExpression import io.micronaut.data.repository.jpa.criteria.PredicateSpecification import io.micronaut.data.runtime.criteria.get import io.micronaut.data.runtime.criteria.where import io.micronaut.http.HttpResponse import io.micronaut.http.MediaType import io.micronaut.http.annotation.Body import io.micronaut.http.annotation.Controller import io.micronaut.http.annotation.Delete import io.micronaut.http.annotation.Get import io.micronaut.http.annotation.PathVariable import io.micronaut.http.annotation.Post import io.micronaut.http.annotation.Put import io.micronaut.http.annotation.QueryValue import io.micronaut.http.multipart.CompletedFileUpload import io.micronaut.http.server.types.files.StreamedFile import io.micronaut.security.annotation.Secured import io.micronaut.security.authentication.Authentication import io.swagger.v3.oas.annotations.tags.Tag import no.nav.hm.grunndata.rapid.dto.AdminStatus import no.nav.hm.grunndata.rapid.dto.DraftStatus import no.nav.hm.grunndata.rapid.dto.RegistrationStatus import no.nav.hm.grunndata.register.error.BadRequestException import no.nav.hm.grunndata.register.product.batch.ProductExcelExport import no.nav.hm.grunndata.register.product.batch.ProductExcelImport import no.nav.hm.grunndata.register.security.Roles import no.nav.hm.grunndata.register.series.SeriesGroupDTO import org.apache.commons.io.output.ByteArrayOutputStream import org.slf4j.LoggerFactory import java.util.UUID @Secured(Roles.ROLE_ADMIN) @Controller(ProductRegistrationAdminApiController.API_V1_ADMIN_PRODUCT_REGISTRATIONS) @Tag(name = "Admin Product") class ProductRegistrationAdminApiController( private val productRegistrationService: ProductRegistrationService, private val xlImport: ProductExcelImport, private val xlExport: ProductExcelExport, private val productDTOMapper: ProductDTOMapper, ) { companion object { const val API_V1_ADMIN_PRODUCT_REGISTRATIONS = "/admin/api/v1/product/registrations" private val LOG = LoggerFactory.getLogger(ProductRegistrationAdminApiController::class.java) } @Get("/series/group{?params*}") suspend fun findSeriesGroup( @QueryValue params: HashMap<String, String>?, pageable: Pageable, ): Slice<SeriesGroupDTO> = productRegistrationService.findSeriesGroup(pageable) @Get("/series/{seriesUUID}") suspend fun findBySeriesUUIDAndSupplierId(seriesUUID: UUID) = productRegistrationService.findAllBySeriesUuid(seriesUUID).sortedBy { it.created } @Get("/{?params*}") suspend fun findProducts( @QueryValue params: HashMap<String, String>?, pageable: Pageable, ): Page<ProductRegistrationDTO> = productRegistrationService .findAll(buildCriteriaSpec(params), pageable) .mapSuspend { productDTOMapper.toDTO(it) } @Get("/til-godkjenning") suspend fun findProductsPendingApprove( @QueryValue params: HashMap<String, String>?, pageable: Pageable, ): Page<ProductToApproveDto> = productRegistrationService.findProductsToApprove(pageable) private fun buildCriteriaSpec(params: HashMap<String, String>?): PredicateSpecification<ProductRegistration>? = params?.let { where { if (params.contains("supplierRef")) root[ProductRegistration::supplierRef] eq params["supplierRef"] if (params.contains("hmsArtNr")) root[ProductRegistration::hmsArtNr] eq params["hmsArtNr"] if (params.contains("adminStatus")) root[ProductRegistration::adminStatus] eq AdminStatus.valueOf(params["adminStatus"]!!) if (params.contains("registrationStatus")) { root[ProductRegistration::registrationStatus] eq RegistrationStatus.valueOf( params["registrationStatus"]!!, ) } if (params.contains("supplierId")) root[ProductRegistration::supplierId] eq UUID.fromString(params["supplierId"]!!) if (params.contains("draft")) root[ProductRegistration::draftStatus] eq DraftStatus.valueOf(params["draft"]!!) if (params.contains("createdByUser")) root[ProductRegistration::createdByUser] eq params["createdByUser"] if (params.contains("updatedByUser")) root[ProductRegistration::updatedByUser] eq params["updatedByUser"] }.and { root, criteriaBuilder -> if (params.contains("title")) { criteriaBuilder.like(root[ProductRegistration::title], LiteralExpression("%${params["title"]}%")) } else { null } } } @Get("/v2/{id}") suspend fun getProductByIdV2(id: UUID): HttpResponse<ProductRegistrationDTOV2> = productRegistrationService.findById(id) ?.let { HttpResponse.ok(productDTOMapper.toDTOV2(it)) } ?: HttpResponse.notFound() @Get("/hmsArtNr/{hmsArtNr}") suspend fun getProductByHmsArtNr(hmsArtNr: String): HttpResponse<ProductRegistrationDTO> = productRegistrationService.findByHmsArtNr(hmsArtNr) ?.let { HttpResponse.ok(productDTOMapper.toDTO(it)) } ?: HttpResponse.notFound() @Post("/draftWithV3/{seriesUUID}") suspend fun createDraft( @PathVariable seriesUUID: UUID, @Body draftVariant: DraftVariantDTO, authentication: Authentication, ): HttpResponse<ProductRegistrationDTO> = try { val variant = productRegistrationService.createDraft(seriesUUID, draftVariant, authentication) HttpResponse.ok(productDTOMapper.toDTO(variant)) } catch (e: DataAccessException) { throw BadRequestException(e.message ?: "Error creating draft") } catch (e: Exception) { throw BadRequestException("Error creating draft") } @Put("/v2/{id}") suspend fun updateProductV2( @Body registrationDTO: UpdateProductRegistrationDTO, @PathVariable id: UUID, authentication: Authentication, ): HttpResponse<ProductRegistrationDTO> = try { val dto = productDTOMapper.toDTO( productRegistrationService.updateProduct( registrationDTO, id, authentication ) ) HttpResponse.ok(dto) } catch (dataAccessException: DataAccessException) { LOG.error("Got exception while updating product", dataAccessException) throw BadRequestException(dataAccessException.message ?: "Got exception while updating product $id") } catch (e: Exception) { LOG.error("Got exception while updating product", e) throw BadRequestException("Got exception while updating product $id") } @Put("/to-expired/{id}") suspend fun setPublishedProductToInactive( @PathVariable id: UUID, authentication: Authentication, ): HttpResponse<ProductRegistrationDTO> { val updated = productRegistrationService.updateRegistrationStatus(id, authentication, RegistrationStatus.INACTIVE) return HttpResponse.ok(productDTOMapper.toDTO(updated)) } @Put("/to-active/{id}") suspend fun setPublishedProductToActive( @PathVariable id: UUID, authentication: Authentication, ): HttpResponse<ProductRegistrationDTO> { val updated = productRegistrationService.updateRegistrationStatus(id, authentication, RegistrationStatus.ACTIVE) return HttpResponse.ok(productDTOMapper.toDTO(updated)) } @Delete("/delete") suspend fun deleteProducts( @Body ids: List<UUID>, authentication: Authentication, ): HttpResponse<List<ProductRegistrationDTO>> { val updated = productRegistrationService.setDeletedStatus(ids, authentication) return HttpResponse.ok(updated.map { productDTOMapper.toDTO(it) }) } @Delete("/draft/delete") suspend fun deleteDraftVariants( @Body ids: List<UUID>, authentication: Authentication, ): HttpResponse<List<ProductRegistrationDTO>> { productRegistrationService.deleteDraftVariants(ids, authentication) return HttpResponse.ok(emptyList()) } @Post("/draft/variant/{id}") suspend fun createProductVariant( @PathVariable id: UUID, @Body draftVariant: DraftVariantDTO, authentication: Authentication, ): HttpResponse<ProductRegistrationDTO> { return try { productRegistrationService.createProductVariant(id, draftVariant, authentication)?.let { HttpResponse.ok(productDTOMapper.toDTO(it)) } ?: HttpResponse.notFound() } catch (e: DataAccessException) { LOG.error("Got exception while creating variant ${draftVariant.supplierRef}", e) throw BadRequestException(e.message ?: "Error creating variant") } catch (e: Exception) { LOG.error("Got exception while creating variant ${draftVariant.supplierRef}", e) throw e } } @Post( "/excel/export", consumes = ["application/json"], produces = ["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"], ) suspend fun createExport( @Body uuids: List<UUID>, authentication: Authentication, ): HttpResponse<StreamedFile> { val products = uuids.map { productRegistrationService.findById(it) }.filterNotNull() if (products.isEmpty()) throw BadRequestException("No products found") val id = UUID.randomUUID() LOG.info("Generating Excel file: $id.xlsx") return ByteArrayOutputStream().use { byteStream -> xlExport.createWorkbookToOutputStream(products.map { productDTOMapper.toDTO(it) }, byteStream) HttpResponse.ok(StreamedFile(byteStream.toInputStream(), MediaType.MICROSOFT_EXCEL_OPEN_XML_TYPE)) .header("Content-Disposition", "attachment; filename=$id.xlsx") } } @Post( "/excel/import", consumes = [MediaType.MULTIPART_FORM_DATA], produces = [MediaType.APPLICATION_JSON], ) suspend fun importExcel( file: CompletedFileUpload, authentication: Authentication, ): HttpResponse<List<ProductRegistrationDTO>> { LOG.info("Importing Excel file ${file.filename} by admin") return file.inputStream.use { inputStream -> val excelDTOList = xlImport.importExcelFileForRegistration(inputStream) LOG.info("found ${excelDTOList.size} products in Excel file") val products = productRegistrationService.importExcelRegistrations(excelDTOList, authentication) HttpResponse.ok(products.map { productDTOMapper.toDTO(it) }) } } @Post( "/excel/import-dryrun", consumes = [MediaType.MULTIPART_FORM_DATA], produces = [MediaType.APPLICATION_JSON], ) suspend fun importExcelDryrun( file: CompletedFileUpload, authentication: Authentication, ): HttpResponse<List<ProductRegistrationDryRunDTO>> { LOG.info("Dryrun - Importing Excel file ${file.filename} by admin") return file.inputStream.use { inputStream -> val excelDTOList = xlImport.importExcelFileForRegistration(inputStream) LOG.info("found ${excelDTOList.size} products in Excel file") val products = productRegistrationService.importDryRunExcelRegistrations(excelDTOList, authentication) HttpResponse.ok(products) } } } fun Authentication.isAdmin(): Boolean = roles.contains(Roles.ROLE_ADMIN)
0
Kotlin
0
2
19826d375e95cdd5423bd09d83620994c17482f9
11,936
hm-grunndata-register
MIT License
sax-adapter/src/main/kotlin/fr/speekha/httpmocker/sax/builders/NodeBuilder.kt
speekha
190,229,886
false
{"Gradle": 20, "YAML": 2, "Shell": 5, "Batchfile": 4, "Java Properties": 13, "Ignore List": 1, "EditorConfig": 1, "Text": 6, "Markdown": 3, "Kotlin": 176, "Proguard": 1, "JSON": 30, "XML": 36, "Java": 1}
/* * Copyright 2019 David Blanc * * 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 fr.speekha.httpmocker.sax.builders import fr.speekha.httpmocker.model.Header abstract class NodeBuilder { protected var textContent: String? = null abstract fun build(): Any fun addTextContent(text: String) { textContent = text } } interface NodeWithHeaders { val headers: MutableList<Header> fun addHeader(header: Header) { headers += header } } interface NodeWithBody { var body: String? var bodyFile: String? }
1
null
1
1
bb4f8ea57f40fd149171632e86b63e2304d60402
1,079
httpmocker
Apache License 2.0
packages/core/android/src/main/java/com/airbnb/android/react/lottie/LottieAnimationViewManagerImpl.kt
matinzd
217,756,691
false
{"YAML": 4, "JSON": 25, "CODEOWNERS": 1, "Markdown": 8, "Text": 1, "Ignore List": 8, "Git Attributes": 1, "JSON with Comments": 2, "JavaScript": 17, "Ruby": 5, "TSX": 3, "Java Properties": 3, "Gradle": 7, "Shell": 3, "Batchfile": 3, "INI": 5, "Kotlin": 5, "XML": 34, "C#": 8, "C++": 24, "Microsoft Visual Studio Solution": 3, "C": 2, "Objective-C": 10, "Swift": 3, "OpenStep Property List": 6, "Starlark": 2, "Java": 12, "CMake": 2, "Dotenv": 2, "Objective-C++": 2, "Gemfile.lock": 1}
package com.airbnb.android.react.lottie import android.os.Handler import android.os.Looper import android.view.View import android.view.View.OnAttachStateChangeListener import android.widget.ImageView import androidx.core.view.ViewCompat import com.airbnb.lottie.LottieAnimationView import com.airbnb.lottie.RenderMode import com.facebook.react.bridge.ReadableArray import com.facebook.react.common.MapBuilder import com.facebook.react.uimanager.ThemedReactContext import java.io.BufferedReader import java.io.InputStreamReader import java.net.URL import kotlin.concurrent.thread internal object LottieAnimationViewManagerImpl { const val REACT_CLASS = "LottieAnimationView" @JvmStatic val exportedViewConstants: Map<String, Any> get() = MapBuilder.builder<String, Any>() .put("VERSION", 1) .build() @JvmStatic fun createViewInstance(context: ThemedReactContext): LottieAnimationView { return LottieAnimationView(context).apply { scaleType = ImageView.ScaleType.CENTER_INSIDE } } @JvmStatic fun getExportedCustomBubblingEventTypeConstants(): MutableMap<String, Any> { return MapBuilder.of( "animationFinish", MapBuilder.of("phasedRegistrationNames", MapBuilder.of("bubbled", "onAnimationFinish")) ) } @JvmStatic fun play(view: LottieAnimationView, startFrame: Int, endFrame: Int) { Handler(Looper.getMainLooper()).post { if (startFrame != -1 && endFrame != -1) { if (startFrame > endFrame) { view.setMinAndMaxFrame(endFrame, startFrame) if (view.speed > 0) { view.reverseAnimationSpeed() } } else { view.setMinAndMaxFrame(startFrame, endFrame) if (view.speed < 0) { view.reverseAnimationSpeed() } } } if (ViewCompat.isAttachedToWindow(view)) { view.progress = 0f view.playAnimation() } else { view.addOnAttachStateChangeListener(object : OnAttachStateChangeListener { override fun onViewAttachedToWindow(v: View) { val listenerView = v as LottieAnimationView listenerView.progress = 0f listenerView.playAnimation() listenerView.removeOnAttachStateChangeListener(this) } override fun onViewDetachedFromWindow(v: View) { val listenerView = v as LottieAnimationView listenerView.removeOnAttachStateChangeListener(this) } }) } } } @JvmStatic fun reset(view: LottieAnimationView) { Handler(Looper.getMainLooper()).post { if (ViewCompat.isAttachedToWindow(view)) { view.cancelAnimation() view.progress = 0f } } } @JvmStatic fun pause(view: LottieAnimationView) { Handler(Looper.getMainLooper()).post { if (ViewCompat.isAttachedToWindow(view)) { view.pauseAnimation() } } } @JvmStatic fun resume(view: LottieAnimationView) { Handler(Looper.getMainLooper()).post { if (ViewCompat.isAttachedToWindow(view)) { view.resumeAnimation() } } } @JvmStatic fun setSourceName( name: String?, viewManager: LottieAnimationViewPropertyManager ) { // To match the behaviour on iOS we expect the source name to be // extensionless. This means "myAnimation" corresponds to a file // named `myAnimation.json` in `main/assets`. To maintain backwards // compatibility we only add the .json extension if no extension is // passed. var resultSourceName = name if (resultSourceName?.contains(".") == false) { resultSourceName = "$resultSourceName.json" } viewManager.animationName = resultSourceName } @JvmStatic fun setSourceJson( json: String?, propManagersMap: LottieAnimationViewPropertyManager ) { propManagersMap.animationJson = json } @JvmStatic fun setSourceURL( urlString: String?, propManagersMap: LottieAnimationViewPropertyManager ) { thread { BufferedReader(InputStreamReader(URL(urlString).openStream())).useLines { Handler(Looper.getMainLooper()).post { propManagersMap.animationJson = it.toString() propManagersMap.commitChanges() } } } } @JvmStatic fun setCacheComposition(view: LottieAnimationView, cacheComposition: Boolean) { view.setCacheComposition(cacheComposition) } @JvmStatic fun setResizeMode( resizeMode: String?, viewManager: LottieAnimationViewPropertyManager ) { var mode: ImageView.ScaleType? = null when (resizeMode) { "cover" -> { mode = ImageView.ScaleType.CENTER_CROP } "contain" -> { mode = ImageView.ScaleType.CENTER_INSIDE } "center" -> { mode = ImageView.ScaleType.CENTER } } viewManager.scaleType = mode } @JvmStatic fun setRenderMode( renderMode: String?, viewManager: LottieAnimationViewPropertyManager ) { var mode: RenderMode? = null when (renderMode) { "AUTOMATIC" -> { mode = RenderMode.AUTOMATIC } "HARDWARE" -> { mode = RenderMode.HARDWARE } "SOFTWARE" -> { mode = RenderMode.SOFTWARE } } viewManager.renderMode = mode } @JvmStatic fun setHardwareAcceleration( hardwareAccelerationAndroid: Boolean, viewManager: LottieAnimationViewPropertyManager ) { var layerType: Int? = View.LAYER_TYPE_SOFTWARE if (hardwareAccelerationAndroid) { layerType = View.LAYER_TYPE_HARDWARE } viewManager.layerType = layerType } @JvmStatic fun setProgress( progress: Float, viewManager: LottieAnimationViewPropertyManager ) { viewManager.progress = progress } @JvmStatic fun setSpeed( speed: Double, viewManager: LottieAnimationViewPropertyManager ) { viewManager.speed = speed.toFloat() } @JvmStatic fun setLoop( loop: Boolean, viewManager: LottieAnimationViewPropertyManager ) { viewManager.loop = loop } @JvmStatic fun setEnableMergePaths( enableMergePaths: Boolean, viewManager: LottieAnimationViewPropertyManager ) { viewManager.enableMergePaths = enableMergePaths } @JvmStatic fun setImageAssetsFolder( imageAssetsFolder: String?, viewManager: LottieAnimationViewPropertyManager ) { viewManager.imageAssetsFolder = imageAssetsFolder } @JvmStatic fun setColorFilters( colorFilters: ReadableArray?, viewManager: LottieAnimationViewPropertyManager ) { viewManager.colorFilters = colorFilters } @JvmStatic fun setTextFilters( textFilters: ReadableArray?, viewManager: LottieAnimationViewPropertyManager ) { viewManager.textFilters = textFilters } }
1
null
1
1
1cae484454d837b223ae812a68f54c149ecc2011
7,764
lottie-react-native
Apache License 2.0
app/src/main/java/gcu/product/supplevpn/repository/source/architecture/viewModels/FlowableViewModel.kt
Ilyandr
584,776,484
false
{"Java": 408363, "Kotlin": 191825, "AIDL": 15199}
package gcu.product.supplevpn.repository.source.architecture.viewModels import android.accounts.NetworkErrorException import android.annotation.SuppressLint import android.util.Log import androidx.lifecycle.ViewModel import gcu.product.supplevpn.R import gcu.product.supplevpn.repository.features.utils.unitAction import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.core.Completable import io.reactivex.rxjava3.core.Single import io.reactivex.rxjava3.schedulers.Schedulers import java.net.UnknownHostException import java.util.concurrent.TimeoutException internal abstract class FlowableViewModel<T> : ViewModel(), InteractionViewModel<T> { @SuppressLint("CheckResult") override fun <T : Any> Single<T>.simpleRequest(successAction: (T) -> Unit) { subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { successAction.invoke(it) }, { error -> Log.e("err", error.stackTraceToString());setFaultAction(error) }) } @SuppressLint("CheckResult") override fun Completable.simpleRequest(successAction: unitAction) { subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ successAction.invoke() }, { error -> setFaultAction(error) }) } override fun handleError(error: Throwable) = when (error) { is TimeoutException -> R.string.message_timeout_exception is NetworkErrorException, is UnknownHostException -> R.string.message_network_exception else -> R.string.message_unknown_exception } }
1
null
1
1
a47d4fee515c7a155cadd2eaa967f6dc38b4fed1
1,637
Supple-VPN
MIT License
mysql-async/src/main/java/com/github/mauricio/async/db/mysql/message/server/ResultSetRowMessage.kt
godpan
150,828,573
false
null
package com.github.jasync.sql.db.mysql.message.server import com.github.jasync.sql.db.util.length import io.netty.buffer.ByteBuf class ResultSetRowMessage(private val buffer: MutableList<ByteBuf?> = mutableListOf()) : ServerMessage(ServerMessage.Row) , List<ByteBuf?> by buffer { fun length(): Int = buffer.length fun add(elem: ByteBuf?): ResultSetRowMessage { this.buffer.add(elem) return this } }
1
null
1
1
c16a5772b46331c582c4d14939e6c4cad09edb98
441
jasync-sql
Apache License 2.0
rximagepicker_support/src/main/java/com/qingmei2/rximagepicker_extension/model/AlbumCollection.kt
vannesschancc
142,116,631
true
{"Kotlin": 249656, "Java": 357}
/* * Copyright (C) 2014 nohana, Inc. * Copyright 2017 Zhihu 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 &quot;AS IS&quot; 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.qingmei2.rximagepicker_extension.model import android.content.Context import android.database.Cursor import android.os.Bundle import android.support.v4.app.FragmentActivity import android.support.v4.app.LoaderManager import android.support.v4.content.Loader import com.qingmei2.rximagepicker_extension.loader.AlbumLoader import java.lang.ref.WeakReference class AlbumCollection : LoaderManager.LoaderCallbacks<Cursor> { private var mContext: WeakReference<Context>? = null private var mLoaderManager: LoaderManager? = null private var mCallbacks: AlbumCallbacks? = null var currentSelection: Int = 0 private set override fun onCreateLoader(id: Int, args: Bundle?): Loader<Cursor> { return AlbumLoader.newInstance(mContext?.get()) } override fun onLoadFinished(loader: Loader<Cursor>, data: Cursor) { mCallbacks!!.onAlbumLoad(data) } override fun onLoaderReset(loader: Loader<Cursor>) { val context = mContext!!.get() ?: return mCallbacks!!.onAlbumReset() } fun onCreate(activity: FragmentActivity, callbacks: AlbumCallbacks) { mContext = WeakReference(activity) mLoaderManager = activity.supportLoaderManager mCallbacks = callbacks } fun onRestoreInstanceState(savedInstanceState: Bundle?) { if (savedInstanceState == null) { return } currentSelection = savedInstanceState.getInt(STATE_CURRENT_SELECTION) } fun onSaveInstanceState(outState: Bundle) { outState.putInt(STATE_CURRENT_SELECTION, currentSelection) } fun onDestroy() { mLoaderManager!!.destroyLoader(LOADER_ID) mCallbacks = null } fun loadAlbums() { mLoaderManager!!.initLoader(LOADER_ID, null, this) } fun setStateCurrentSelection(currentSelection: Int) { this.currentSelection = currentSelection } interface AlbumCallbacks { fun onAlbumLoad(cursor: Cursor) fun onAlbumReset() } companion object { private const val LOADER_ID = 1 private const val STATE_CURRENT_SELECTION = "state_current_selection" } }
0
Kotlin
1
0
ad6e214de6bb896672fc379b3ce48d16db487faf
2,812
RxImagePicker
MIT License
app/src/main/java/jp/takke/datastats/NotificationPresenter.kt
takke
30,529,813
false
{"Gradle": 3, "Markdown": 3, "Java Properties": 2, "Shell": 1, "Text": 3, "Ignore List": 2, "Batchfile": 2, "TOML": 1, "INI": 1, "YAML": 2, "Proguard": 1, "XML": 18, "Kotlin": 10, "Java": 8, "AIDL": 1}
package jp.takke.datastats import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.app.Service import android.content.Context import android.content.Intent import android.os.Build import android.view.View import android.widget.RemoteViews import androidx.core.app.NotificationCompat import jp.takke.util.MyLog import java.lang.ref.WeakReference internal class NotificationPresenter(service: Service) { private val mServiceRef: WeakReference<Service> = WeakReference(service) fun showNotification(visibleOverlayView: Boolean) { MyLog.d("showNotification") val service = mServiceRef.get() ?: return // 通知ウインドウをクリックした際に起動するインテント val intent = Intent(service, MainActivity::class.java) val pendingIntent = PendingIntent.getActivity(service, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT) val builder = NotificationCompat.Builder(service.applicationContext, CHANNEL_ID) // カスタムレイアウト生成 val notificationLayout = createCustomLayout(service, visibleOverlayView) builder.setContentIntent(null) builder.setCustomContentView(notificationLayout) // 端末の通知エリア(上部のアイコンが並ぶ部分)に本アプリのアイコンを表示しないようにemptyなdrawableを指定する builder.setSmallIcon(R.drawable.transparent_image) builder.setOngoing(true) builder.priority = NotificationCompat.PRIORITY_MIN builder.setContentTitle(service.getString(R.string.resident_service_running)) // builder.setContentText("表示・非表示を切り替える"); builder.setContentIntent(pendingIntent) service.startForeground(MY_NOTIFICATION_ID, builder.build()) } private fun createCustomLayout(service: Service, visibleOverlayView: Boolean): RemoteViews { val notificationLayout = RemoteViews(service.packageName, R.layout.custom_notification) // show button if (!visibleOverlayView) { val switchIntent = Intent(service, SwitchButtonReceiver::class.java) switchIntent.action = "show" val switchPendingIntent = PendingIntent.getBroadcast(service, 0, switchIntent, 0) notificationLayout.setOnClickPendingIntent(R.id.show_button, switchPendingIntent) notificationLayout.setViewVisibility(R.id.show_button, View.VISIBLE) } else { notificationLayout.setViewVisibility(R.id.show_button, View.GONE) } // hide button if (visibleOverlayView) { val switchIntent = Intent(service, SwitchButtonReceiver::class.java) switchIntent.action = "hide" val switchPendingIntent = PendingIntent.getBroadcast(service, 0, switchIntent, 0) notificationLayout.setOnClickPendingIntent(R.id.hide_button, switchPendingIntent) notificationLayout.setViewVisibility(R.id.hide_button, View.VISIBLE) } else { notificationLayout.setViewVisibility(R.id.hide_button, View.GONE) } // timer (hide and resume) button if (visibleOverlayView) { val switchIntent = Intent(service, SwitchButtonReceiver::class.java) switchIntent.action = "hide_and_resume" val switchPendingIntent = PendingIntent.getBroadcast(service, 0, switchIntent, 0) notificationLayout.setOnClickPendingIntent(R.id.hide_and_resume_button, switchPendingIntent) notificationLayout.setViewVisibility(R.id.hide_and_resume_button, View.VISIBLE) } else { notificationLayout.setViewVisibility(R.id.hide_and_resume_button, View.INVISIBLE) } return notificationLayout } fun createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val service = mServiceRef.get() ?: return val channel = NotificationChannel(CHANNEL_ID, service.getString(R.string.resident_notification), NotificationManager.IMPORTANCE_LOW) // invisible on lockscreen channel.lockscreenVisibility = Notification.VISIBILITY_SECRET val nm = service.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager nm.createNotificationChannel(channel) } } fun hideNotification() { MyLog.d("hideNotification") val service = mServiceRef.get() ?: return val nm = service.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager nm.cancel(MY_NOTIFICATION_ID) } companion object { private const val MY_NOTIFICATION_ID = 1 private const val CHANNEL_ID = "resident" } }
9
Kotlin
11
33
fe1a6c94897fb850e1108057173ae9bfc2c4bd59
4,694
DataStats
Apache License 2.0
src/commonMain/kotlin/dev/gitlive/difflib/unifieddiff/UnifiedDiff.kt
GitLiveApp
191,627,185
true
{"Kotlin": 182492, "Shell": 18161}
/* * Copyright 2019 java-diff-utils. * * 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.gitlive.difflib.unifieddiff import dev.gitlive.difflib.Predicate import dev.gitlive.difflib.patch.PatchFailedException /** * * @author <NAME> (<EMAIL>) */ class UnifiedDiff { var header: String? = null var tail: String? = null private set private val files: MutableList<UnifiedDiffFile> = ArrayList() fun addFile(file: UnifiedDiffFile) { files.add(file) } fun getFiles(): List<UnifiedDiffFile> { return files } fun setTailTxt(tailTxt: String?) { tail = tailTxt } // @Throws(PatchFailedException::class) fun applyPatchTo(findFile: Predicate<String>, originalLines: List<String>): List<String> { val file = files.asSequence() .filter { diff: UnifiedDiffFile -> findFile(diff.fromFile!!) } .firstOrNull() return file?.patch?.applyTo(originalLines) ?: originalLines } companion object { @kotlin.jvm.JvmStatic fun from(header: String?, tail: String?, vararg files: UnifiedDiffFile): UnifiedDiff { val diff = UnifiedDiff() diff.header = header diff.setTailTxt(tail) for (file in files) { diff.addFile(file) } return diff } } }
1
Kotlin
3
11
436ac1d26bfd14de01956051a72c7efb4b31ba5b
1,881
kotlin-diff-utils
Apache License 2.0
src/demo/kotlin/world/cepi/kstom/util/PositionSpreadDemo.kt
arslanarm
334,777,044
true
{"Kotlin": 59937}
package world.cepi.kstom.util import net.minestom.server.utils.Position fun old(position: Position) { val x = position.x val y = position.y val z = position.z } fun new(position: Position) { val (x, y, z) = position }
0
Kotlin
0
0
d4ec51735991b5bc0a02bc1230f7316384a7eb1b
236
KStom
MIT License
core/ui/src/main/java/org/expenny/core/ui/transformations/ExpennyDecimalVisualTransformation.kt
expenny-application
712,607,222
false
{"Kotlin": 1157225}
package org.expenny.core.ui.foundation.transformations import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.input.OffsetMapping import androidx.compose.ui.text.input.TransformedText import androidx.compose.ui.text.input.VisualTransformation import androidx.core.text.isDigitsOnly import org.expenny.core.common.extensions.isZero import java.math.BigDecimal import java.text.DecimalFormat import java.util.Locale import kotlin.math.pow class ExpennyDecimalVisualTransformation(private val scale: Int) : VisualTransformation { private val symbols = (DecimalFormat.getInstance(Locale.getDefault()) as DecimalFormat).decimalFormatSymbols private val thousandsSeparator = symbols.groupingSeparator private val decimalSeparator = symbols.decimalSeparator private val zeroDigit = symbols.zeroDigit override fun filter(text: AnnotatedString): TransformedText { val input = text.text val formattedNumber = buildString { val intPart = input .dropLast(scale) .reversed() .chunked(3) .joinToString(separator = thousandsSeparator.toString()) .reversed() .ifEmpty { zeroDigit.toString() } append(intPart) if (scale > 0) { val decimalSeparator = decimalSeparator val fractionPart = input.takeLast(scale).let { if (it.length != scale) { List(scale - it.length) { zeroDigit } .joinToString("") + it } else { it } } append(decimalSeparator) append(fractionPart) } } val newText = AnnotatedString( text = formattedNumber, spanStyles = text.spanStyles, paragraphStyles = text.paragraphStyles ) val offsetMapping = FixedCursorOffsetMapping( contentLength = text.length, formattedContentLength = formattedNumber.length ) return TransformedText(newText, offsetMapping) } private class FixedCursorOffsetMapping( private val contentLength: Int, private val formattedContentLength: Int, ) : OffsetMapping { override fun originalToTransformed(offset: Int): Int = formattedContentLength override fun transformedToOriginal(offset: Int): Int = contentLength } companion object { fun formatToOutput(output: String, scale: Int): BigDecimal { return if (output.toBigDecimalOrNull() != null) { val bigDecimal = output.ifEmpty { "0" }.toBigDecimal().setScale(scale) if (bigDecimal.isZero()) { bigDecimal } else { bigDecimal.divide(BigDecimal(1 * 10.0.pow(scale))) } } else { BigDecimal.ZERO.setScale(scale) } } fun formatToInput(value: BigDecimal): String { return value.toPlainString().filter { it.isDigit() }.let { if (it.length > 1) it.trimStart('0') else it } } fun formatToOutput(value: String): String { if (!value.isDigitsOnly()) { return if (value.isEmpty()) "0" else "" } else { if (value.startsWith("0")) { return if (value.length > 1) value.trimStart('0') else "0" } } return value } } }
0
Kotlin
3
42
f5ae94c73f652a7332ba896c697fc8d562eeca94
3,625
expenny-android
Apache License 2.0
agenda/app/src/main/java/me/diegoramos/agenda/model/Contact.kt
rdiego26
248,616,877
false
null
package me.diegoramos.agenda.model import androidx.room.Embedded import androidx.room.Entity import androidx.room.PrimaryKey import androidx.room.Relation import java.io.Serializable import java.util.* @Entity class Contact ( @PrimaryKey val id: String = UUID.randomUUID().toString(), val name: String, val lastName: String, val email: String ) : Serializable { fun fullName() = "$name $lastName" } data class ContactAndPhones ( @Embedded val contact: Contact, @Relation( parentColumn = "id", entityColumn = "contactId" ) val phones: List<Phone> = listOf() ) : Serializable
0
Kotlin
0
0
9f3072f19535071bdb944cfba4aee303ffb6e1d7
623
alura-android1
MIT License
src/main/kotlin/com/beside/daldal/domain/auth/dto/TokenResponseDTO.kt
daldal-nimble
618,776,701
false
null
package com.beside.daldal.domain.auth.dto class TokenResponseDTO( val accessToken :String, val refreshToken : String, val accessExpiration : Long, val refreshExpiration : Long )
0
Kotlin
0
3
b4bc82556bc3309e2136bca31c521ee28d5f6839
196
Nimble
Apache License 2.0
src/main/kotlin/com/cout970/reactive/nodes/SelectBox.kt
cout970
121,807,275
false
null
package com.cout970.reactive.nodes import com.cout970.reactive.core.RBuilder import com.cout970.reactive.dsl.childrenAsNodes import com.cout970.reactive.dsl.postMount import com.cout970.reactive.dsl.replaceListener import org.joml.Vector2f import org.liquidengine.legui.component.SelectBox import org.liquidengine.legui.component.misc.listener.selectbox.SelectBoxClickListener import org.liquidengine.legui.event.MouseClickEvent import org.liquidengine.legui.system.layout.LayoutManager fun RBuilder.selectBox(key: String? = null, block: ComponentBuilder<SelectBox<String>>.() -> Unit = {}) { +ComponentBuilder(SelectBox<String>()).apply(block).also { postMount { val selectBox = it.component val mouseClickEventListener = object : SelectBoxClickListener<String>(selectBox) { override fun process(event: MouseClickEvent<*>) { if (event.action == MouseClickEvent.MouseClickAction.CLICK) { val frame = event.frame val selectBoxLayer = selectBox.selectBoxLayer val collapsed = selectBox.isCollapsed selectBox.isCollapsed = !collapsed if (collapsed) { val layerSize = Vector2f(frame.container.size) selectBoxLayer.container.size = layerSize frame.addLayer(selectBoxLayer) LayoutManager.getInstance().layout(frame) } else { frame.removeLayer(selectBoxLayer) } } } } selectBox.selectionButton.listenerMap.replaceListener(MouseClickEvent::class.java, mouseClickEventListener) selectBox.expandButton.listenerMap.replaceListener(MouseClickEvent::class.java, mouseClickEventListener) selectBox.selectBoxLayer.container.listenerMap.replaceListener(MouseClickEvent::class.java, mouseClickEventListener) } it.childrenAsNodes() }.build(key) }
0
Kotlin
0
2
40cc6b38c57ca249c50aa7359a7afe0da041fa36
2,121
Reactive
MIT License
generator/src/main/kotlin/name/anton3/vkapi/generator/json/SinglePolyUnwrappedDeserializer.kt
Anton3
159,801,334
true
{"Kotlin": 1382186}
package name.anton3.vkapi.generator.json import com.fasterxml.jackson.annotation.JsonUnwrapped import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.databind.* import com.fasterxml.jackson.databind.deser.ContextualDeserializer import com.fasterxml.jackson.databind.deser.ResolvableDeserializer import com.fasterxml.jackson.databind.deser.std.StdDeserializer import com.fasterxml.jackson.databind.node.ObjectNode import com.fasterxml.jackson.databind.util.NameTransformer class SinglePolyUnwrappedDeserializer<T : Any> : JsonDeserializer<T>(), ContextualDeserializer { override fun deserialize(p: JsonParser, ctxt: DeserializationContext): T = error("Not implemented") override fun createContextual(ctxt: DeserializationContext, property: BeanProperty?): JsonDeserializer<T> = SinglePolyUnwrappedDeserializerImpl(ctxt) } private class SinglePolyUnwrappedDeserializerImpl<T : Any>(ctxt: DeserializationContext) : StdDeserializer<T>(null as JavaType?) { private val type: JavaType = ctxt.contextualType private val beanDeserializer: JsonDeserializer<T> private val ownPropertyNames: Set<String> private val unwrappedType: JavaType private val unwrappedPropertyName: String private val nameTransformer: NameTransformer init { val description: BeanDescription = ctxt.config.introspect(type) var tempUnwrappedAnnotation: JsonUnwrapped? = null val unwrappedProperties = description.findProperties().filter { prop -> listOfNotNull(prop.field, prop.mutator, prop.constructorParameter).any { member -> val unwrappedAnnotation: JsonUnwrapped? = member.getAnnotation(JsonUnwrapped::class.java) if (unwrappedAnnotation != null) { tempUnwrappedAnnotation = unwrappedAnnotation member.allAnnotations.add(notUnwrappedAnnotation) } unwrappedAnnotation != null } } val unwrappedProperty = when (unwrappedProperties.size) { 0 -> error("@JsonUnwrapped properties not found in ${type.typeName}") 1 -> unwrappedProperties.single() else -> error("Multiple @JsonUnwrapped properties found in ${type.typeName}") } nameTransformer = tempUnwrappedAnnotation!!.run { NameTransformer.simpleTransformer(prefix, suffix) } unwrappedPropertyName = unwrappedProperty.name ownPropertyNames = description.findProperties().mapTo(mutableSetOf()) { it.name } ownPropertyNames.remove(unwrappedPropertyName) ownPropertyNames.removeAll(description.ignoredPropertyNames) unwrappedType = unwrappedProperty.primaryType val rawBeanDeserializer = ctxt.factory.createBeanDeserializer(ctxt, type, description) (rawBeanDeserializer as? ResolvableDeserializer)?.resolve(ctxt) @Suppress("UNCHECKED_CAST") beanDeserializer = rawBeanDeserializer as JsonDeserializer<T> } override fun deserialize(p: JsonParser, ctxt: DeserializationContext): T { val node = p.readValueAsTree<ObjectNode>() val ownFields: MutableMap<String, JsonNode> = mutableMapOf() val unwrappedFields: MutableMap<String, JsonNode> = mutableMapOf() node.fields().forEach { (key, value) -> val transformed: String? = nameTransformer.reverse(key) if (transformed != null && key !in ownPropertyNames) { unwrappedFields[transformed] = value } else { ownFields[key] = value } } ownFields[unwrappedPropertyName] = ObjectNode(ctxt.nodeFactory, unwrappedFields) val syntheticParser = p.codec.treeAsTokens(ObjectNode(ctxt.nodeFactory, ownFields)) syntheticParser.nextToken() return beanDeserializer.deserialize(syntheticParser, ctxt) } private class NotUnwrapped( @Suppress("unused") @field:JsonUnwrapped(enabled = false) @JvmField val dummy: Nothing ) companion object { private val notUnwrappedAnnotation: JsonUnwrapped = NotUnwrapped::class.java.getField("dummy").getAnnotation(JsonUnwrapped::class.java) } }
2
Kotlin
0
8
773c89751c4382a42f556b6d3c247f83aabec625
4,232
kotlin-vk-api
MIT License
generator/src/main/kotlin/name/anton3/vkapi/generator/json/SinglePolyUnwrappedDeserializer.kt
Anton3
159,801,334
true
{"Kotlin": 1382186}
package name.anton3.vkapi.generator.json import com.fasterxml.jackson.annotation.JsonUnwrapped import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.databind.* import com.fasterxml.jackson.databind.deser.ContextualDeserializer import com.fasterxml.jackson.databind.deser.ResolvableDeserializer import com.fasterxml.jackson.databind.deser.std.StdDeserializer import com.fasterxml.jackson.databind.node.ObjectNode import com.fasterxml.jackson.databind.util.NameTransformer class SinglePolyUnwrappedDeserializer<T : Any> : JsonDeserializer<T>(), ContextualDeserializer { override fun deserialize(p: JsonParser, ctxt: DeserializationContext): T = error("Not implemented") override fun createContextual(ctxt: DeserializationContext, property: BeanProperty?): JsonDeserializer<T> = SinglePolyUnwrappedDeserializerImpl(ctxt) } private class SinglePolyUnwrappedDeserializerImpl<T : Any>(ctxt: DeserializationContext) : StdDeserializer<T>(null as JavaType?) { private val type: JavaType = ctxt.contextualType private val beanDeserializer: JsonDeserializer<T> private val ownPropertyNames: Set<String> private val unwrappedType: JavaType private val unwrappedPropertyName: String private val nameTransformer: NameTransformer init { val description: BeanDescription = ctxt.config.introspect(type) var tempUnwrappedAnnotation: JsonUnwrapped? = null val unwrappedProperties = description.findProperties().filter { prop -> listOfNotNull(prop.field, prop.mutator, prop.constructorParameter).any { member -> val unwrappedAnnotation: JsonUnwrapped? = member.getAnnotation(JsonUnwrapped::class.java) if (unwrappedAnnotation != null) { tempUnwrappedAnnotation = unwrappedAnnotation member.allAnnotations.add(notUnwrappedAnnotation) } unwrappedAnnotation != null } } val unwrappedProperty = when (unwrappedProperties.size) { 0 -> error("@JsonUnwrapped properties not found in ${type.typeName}") 1 -> unwrappedProperties.single() else -> error("Multiple @JsonUnwrapped properties found in ${type.typeName}") } nameTransformer = tempUnwrappedAnnotation!!.run { NameTransformer.simpleTransformer(prefix, suffix) } unwrappedPropertyName = unwrappedProperty.name ownPropertyNames = description.findProperties().mapTo(mutableSetOf()) { it.name } ownPropertyNames.remove(unwrappedPropertyName) ownPropertyNames.removeAll(description.ignoredPropertyNames) unwrappedType = unwrappedProperty.primaryType val rawBeanDeserializer = ctxt.factory.createBeanDeserializer(ctxt, type, description) (rawBeanDeserializer as? ResolvableDeserializer)?.resolve(ctxt) @Suppress("UNCHECKED_CAST") beanDeserializer = rawBeanDeserializer as JsonDeserializer<T> } override fun deserialize(p: JsonParser, ctxt: DeserializationContext): T { val node = p.readValueAsTree<ObjectNode>() val ownFields: MutableMap<String, JsonNode> = mutableMapOf() val unwrappedFields: MutableMap<String, JsonNode> = mutableMapOf() node.fields().forEach { (key, value) -> val transformed: String? = nameTransformer.reverse(key) if (transformed != null && key !in ownPropertyNames) { unwrappedFields[transformed] = value } else { ownFields[key] = value } } ownFields[unwrappedPropertyName] = ObjectNode(ctxt.nodeFactory, unwrappedFields) val syntheticParser = p.codec.treeAsTokens(ObjectNode(ctxt.nodeFactory, ownFields)) syntheticParser.nextToken() return beanDeserializer.deserialize(syntheticParser, ctxt) } private class NotUnwrapped( @Suppress("unused") @field:JsonUnwrapped(enabled = false) @JvmField val dummy: Nothing ) companion object { private val notUnwrappedAnnotation: JsonUnwrapped = NotUnwrapped::class.java.getField("dummy").getAnnotation(JsonUnwrapped::class.java) } }
2
Kotlin
0
8
773c89751c4382a42f556b6d3c247f83aabec625
4,232
kotlin-vk-api
MIT License
app/src/main/kotlin/com/atherton/sample/util/extension/Extensions.kt
DarrenAtherton49
75,475,835
false
null
package com.atherton.sample.util.extension import android.content.Context import android.content.SharedPreferences import android.os.Build import com.squareup.moshi.Moshi import java.util.concurrent.Executors inline fun SharedPreferences.edit(operation: (SharedPreferences.Editor) -> Unit) { val editor = this.edit() operation(editor) editor.apply() } operator fun SharedPreferences.set(key: String, value: Any?) { when (value) { is String? -> edit { it.putString(key, value) } is Int -> edit { it.putInt(key, value) } is Boolean -> edit { it.putBoolean(key, value) } is Float -> edit { it.putFloat(key, value) } is Long -> edit { it.putLong(key, value) } else -> throw UnsupportedOperationException("Not yet implemented") } } inline operator fun <reified T : Any> SharedPreferences.get(key: String, defaultValue: T? = null): T? { return when (T::class) { String::class -> getString(key, defaultValue as? String) as T? Int::class -> getInt(key, defaultValue as? Int ?: -1) as T? Boolean::class -> getBoolean(key, defaultValue as? Boolean ?: false) as T? Float::class -> getFloat(key, defaultValue as? Float ?: -1f) as T? Long::class -> getLong(key, defaultValue as? Long ?: -1) as T? else -> throw UnsupportedOperationException("Not yet implemented") } } fun onAndroidPieOrLater(): Boolean = Build.VERSION.SDK_INT >= Build.VERSION_CODES.P inline fun <reified T> Moshi.adapt(json: String): T? = this.adapter(T::class.java).fromJson(json) fun Context.readFileFromAssets(rawPath: Int): String { return this.resources.openRawResource(rawPath) .bufferedReader() .use { it.readText() } } fun ioThread(block: () -> Unit) { Executors.newSingleThreadExecutor().execute(block) }
0
Kotlin
5
22
9e770c35951b6143964d9385eb7f6ed845e5f832
1,825
android-kotlin-base
MIT License
thunder-okhttp/src/main/java/com/jeremy/thunder/OkHttpWebSocket.kt
jaeyunn15
671,450,093
false
{"Kotlin": 74753}
package com.jeremy.thunder import com.jeremy.thunder.event.WebSocketEvent import com.jeremy.thunder.ws.WebSocket import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onCompletion import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.onStart class OkHttpWebSocket internal constructor( private val provider: ConnectionProvider, private val socketListener: SocketListener, private val socketHandler: SocketHandler, ) : WebSocket { override fun open(): Flow<WebSocketEvent> = socketListener.collectEvent() .onStart { provider.provide(socketListener) }.onEach { when (it) { is WebSocketEvent.OnConnectionOpen -> { socketHandler.initWebSocket(it.webSocket as okhttp3.WebSocket) } else -> Unit } } override fun send(data: String): Boolean { return socketHandler.send(data) } override fun close(code: Int, reason: String): Boolean { return socketHandler.close(code, reason) } override fun cancel() { socketHandler.cancel() } override fun error(t: String) { // ? } class Factory( private val provider: ConnectionProvider, ) : WebSocket.Factory { override fun create(): WebSocket = OkHttpWebSocket( provider = provider , socketListener = SocketListener(), socketHandler = SocketHandler(), ) } }
0
Kotlin
1
10
c77783edd17664abaf5c1a9324e66684bce48125
1,780
Thunder
Apache License 2.0
app/src/main/java/be/digitalia/fosdem/activities/PersonInfoActivity.kt
cbeyls
15,915,146
false
null
package be.digitalia.fosdem.activities import android.content.ActivityNotFoundException import android.net.Uri import android.os.Bundle import android.view.View import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.browser.customtabs.CustomTabsIntent import androidx.fragment.app.add import androidx.fragment.app.commit import be.digitalia.fosdem.R import be.digitalia.fosdem.fragments.PersonInfoListFragment import be.digitalia.fosdem.model.Person import be.digitalia.fosdem.utils.DateUtils import be.digitalia.fosdem.utils.configureToolbarColors import be.digitalia.fosdem.viewmodels.PersonInfoViewModel class PersonInfoActivity : AppCompatActivity(R.layout.person_info) { private val viewModel: PersonInfoViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setSupportActionBar(findViewById(R.id.toolbar)) val person: Person = intent.getParcelableExtra(EXTRA_PERSON)!! viewModel.setPerson(person) supportActionBar?.setDisplayHomeAsUpEnabled(true) title = person.name findViewById<View>(R.id.fab).setOnClickListener { // Look for the first non-placeholder event in the paged list val statusEvent = viewModel.events.value?.firstOrNull { it != null } if (statusEvent != null) { val year = DateUtils.getYear(statusEvent.event.day.date.time) val url = person.getUrl(year) if (url != null) { try { CustomTabsIntent.Builder() .configureToolbarColors(this, R.color.light_color_primary) .setStartAnimations(this, R.anim.slide_in_right, R.anim.slide_out_left) .setExitAnimations(this, R.anim.slide_in_left, R.anim.slide_out_right) .build() .launchUrl(this, Uri.parse(url)) } catch (ignore: ActivityNotFoundException) { } } } } if (savedInstanceState == null) { supportFragmentManager.commit { add<PersonInfoListFragment>(R.id.content) } } } override fun onSupportNavigateUp(): Boolean { finish() return true } companion object { const val EXTRA_PERSON = "person" } }
16
Kotlin
93
123
ace3e53bf4d9afa32959ed0279152608b016572e
2,504
fosdem-companion-android
Apache License 2.0
app/src/main/java/io/gripxtech/odoojsonrpcclient/core/web/webclient/versionInfo/VersionInfoRequest.kt
kasim1011
141,334,335
false
null
package io.gripxtech.odoojsonrpcclient.core.web.webclient.versionInfo import io.gripxtech.odoojsonrpcclient.core.entities.webclient.versionInfo.VersionInfo import io.gripxtech.odoojsonrpcclient.core.entities.webclient.versionInfo.VersionInfoReqBody import io.reactivex.Observable import retrofit2.Response import retrofit2.http.Body import retrofit2.http.POST interface VersionInfoRequest { @POST("/web/webclient/version_info") fun versionInfo( @Body versionInfoReqBody: VersionInfoReqBody ): Observable<Response<VersionInfo>> }
0
Kotlin
37
61
9472f8ca146c8977de110dff29e32f419865d4b6
555
OdooJsonRpcClient
MIT License
detekt-cli/src/test/kotlin/io/gitlab/arturbosch/detekt/cli/runners/VersionPrinterSpec.kt
r4zzz4k
244,962,990
true
{"Kotlin": 1654184, "HTML": 4054, "Groovy": 3832, "Shell": 1057}
package io.gitlab.arturbosch.detekt.cli.runners import io.gitlab.arturbosch.detekt.core.Detektor import org.assertj.core.api.Assertions.assertThat import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import java.io.ByteArrayOutputStream import java.io.PrintStream import java.nio.charset.Charset class VersionPrinterSpec : Spek({ describe("version printer") { it("prints the version") { val byteArrayOutputStream = ByteArrayOutputStream() VersionPrinter(PrintStream(byteArrayOutputStream)).execute() assertThat(String(byteArrayOutputStream.toByteArray(), Charset.forName("UTF-8"))) .isEqualTo("1.6.0" + System.lineSeparator()) } } })
0
Kotlin
0
0
4ea5873cde3e1dd95affd91e09094ee50679f71d
759
detekt
Apache License 2.0
src/main/kotlin/org/celtric/kotlin/html/body.kt
celtric
121,420,012
false
null
package org.celtric.kotlin.html fun body( // Optional lang: String? = null, // Global classes: String? = null, // Custom other: Attributes = emptyMap(), data: Attributes = emptyMap(), // Content content: () -> Any ) = BlockElement("body", content(), AllAttributes(mapOf( "class" to classes, "lang" to lang ), other, data)) fun body(content: String) = body { content } fun body(content: Node) = body { content } fun body(content: List<Node>) = body { content }
1
Kotlin
3
25
70cd501bb534ad84f8c8c3a8f8fb18dddd7054e4
509
kotlin-html
Apache License 2.0
src/plugin-marklogic/main/uk/co/reecedunn/intellij/plugin/marklogic/gradle/configuration/GradleConfiguration.kt
ryanjdew
429,071,807
true
{"Kotlin": 8280141, "XQuery": 991133, "HTML": 39377, "XSLT": 6853}
/* * Copyright (C) 2020-2021 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.marklogic.configuration.gradle import com.intellij.lang.properties.IProperty import com.intellij.lang.properties.psi.PropertiesFile import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import uk.co.reecedunn.intellij.plugin.core.vfs.toPsiFile import uk.co.reecedunn.intellij.plugin.marklogic.query.rest.MarkLogicRest import uk.co.reecedunn.intellij.plugin.processor.query.settings.QueryProcessors import uk.co.reecedunn.intellij.plugin.xpm.project.configuration.XpmProjectConfiguration import uk.co.reecedunn.intellij.plugin.xpm.project.configuration.XpmProjectConfigurationFactory class GradleProjectConfiguration(private val project: Project, override val baseDir: VirtualFile) : XpmProjectConfiguration { // region ml-gradle private fun getPropertiesFile(name: String?): PropertiesFile? { val filename = name?.let { "gradle-${name}.properties" } ?: GRADLE_PROPERTIES return baseDir.findChild(filename)?.toPsiFile(project) as? PropertiesFile } private val build: PropertiesFile? = getPropertiesFile("default") // Project-specific properties private var env: PropertiesFile? = getPropertiesFile("local") // Environment-specific properties private fun getProperty(property: String): Sequence<IProperty> = sequenceOf( env?.findPropertyByKey(property), build?.findPropertyByKey(property) ).filterNotNull() private fun getPropertyValue(property: String): String? = getProperty(property).firstOrNull()?.value // endregion // region XpmProjectConfiguration override val applicationName: String? get() = getPropertyValue(ML_APP_NAME) override var environmentName: String = "local" set(name) { field = name env = getPropertiesFile(name) } override val modulePaths: Sequence<VirtualFile> get() { val modulePaths = getPropertyValue(ML_MODULE_PATHS) ?: ML_MODULE_PATHS_DEFAULT return modulePaths.split(",").asSequence().mapNotNull { baseDir.findFileByRelativePath("$it/root") } } override val processorId: Int? get() = QueryProcessors.getInstance().processors.find { it.api === MarkLogicRest && it.connection?.hostname in LOCALHOST_STRINGS }?.id override val databaseName: String? get() = getPropertyValue(ML_CONTENT_DATABASE_NAME) ?: applicationName?.let { "$it-content" } // endregion // region XpmProjectConfigurationFactory companion object : XpmProjectConfigurationFactory { override fun create(project: Project, baseDir: VirtualFile): XpmProjectConfiguration? { val properties = baseDir.findChild(GRADLE_PROPERTIES)?.toPsiFile(project) as? PropertiesFile ?: return null return properties.findPropertyByKey(ML_APP_NAME)?.let { GradleProjectConfiguration(project, baseDir) } } private const val GRADLE_PROPERTIES = "gradle.properties" private const val ML_APP_NAME = "mlAppName" private const val ML_MODULE_PATHS = "mlModulePaths" private const val ML_CONTENT_DATABASE_NAME = "mlContentDatabaseName" private const val ML_MODULE_PATHS_DEFAULT = "src/main/ml-modules" private val LOCALHOST_STRINGS = setOf("localhost", "127.0.0.1") } // endregion }
0
null
0
0
82fe25ba1a433e970f493cbe9bf03eee719e3b61
3,965
xquery-intellij-plugin
Apache License 2.0
composeApp/src/commonMain/kotlin/com/ideabaker/kmp/translator/translate/presentation/components/LanguageDropDownItem.kt
bidadh
710,622,638
false
{"Kotlin": 98552, "Swift": 595, "Shell": 228}
package com.ideabaker.kmp.translator.translate.presentation.components import androidx.compose.foundation.Image import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.Text import androidx.compose.ui.unit.dp import com.ideabaker.kmp.translator.core.presentation.UiLanguage import org.jetbrains.compose.resources.ExperimentalResourceApi import org.jetbrains.compose.resources.painterResource @OptIn(ExperimentalResourceApi::class) @Composable fun LanguageDropDownItem( language: UiLanguage, onClick: () -> Unit, modifier: Modifier = Modifier ) { DropdownMenuItem( onClick = onClick, modifier = modifier, leadingIcon = { Image( painter = painterResource(res = "drawable/${language.language.langName.lowercase()}.xml"), contentDescription = language.language.langName, modifier = Modifier.size(40.dp) ) Spacer(modifier = Modifier.width(16.dp)) }, text = { Text( text = language.language.langName ) } ) }
0
Kotlin
0
0
964b23315b74bacf6fc778be2dd9e74308975d85
1,251
translator-kmm-compose-app
Apache License 2.0
feature/src/main/java/com/hiroshisasmita/feature/data/model/response/MovieVideoResponse.kt
sasmita22
582,127,840
false
null
package com.hiroshisasmita.feature.data.model.response import com.google.gson.annotations.SerializedName data class MovieVideoResponse( @SerializedName("id") val id: Int? = null, @SerializedName("results") val result: List<VideoItem>? = null )
0
Kotlin
0
0
d79f8f5318336136002dc4dc6a9905b8e1685f61
262
MovieApp
MIT License
bignum-serialization-kotlinx/src/commonTest/kotlin/com/ionspin/kotlin/bignum/serialization/kotlinx/biginteger/BigIntegerArraySerializationTest.kt
ionspin
176,085,256
false
{"Kotlin": 984393, "Shell": 6652}
package com.ionspin.kotlin.bignum.serialization.kotlinx.biginteger import com.ionspin.kotlin.bignum.integer.BigInteger import kotlinx.serialization.Contextual import kotlinx.serialization.Serializable import kotlinx.serialization.decodeFromString import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import kotlin.test.Test import kotlin.test.assertEquals /** * Created by <NAME> * <EMAIL> * on 04-Jul-2021 */ class ArraySerializationTest { @Test fun testSerialization() { run { val testBigInteger = BigInteger.parseString("1000000000000000000000000000002000000000000000000000000000003") val json = Json { serializersModule = bigIntegerArraySerializerModule } val serialized = json.encodeToString(testBigInteger) println(serialized) val deserialized = json.decodeFromString<BigInteger>(serialized) assertEquals(testBigInteger, deserialized) } run { val testBigInteger = BigInteger.parseString("-1000000000000000000000000000002000000000000000000000000000003") val json = Json { serializersModule = bigIntegerArraySerializerModule } val serialized = json.encodeToString(testBigInteger) println(serialized) val deserialized = json.decodeFromString<BigInteger>(serialized) assertEquals(testBigInteger, deserialized) } } @Serializable data class BigIntegerArraySerializtionTestData(@Contextual val a : BigInteger, @Contextual val b : BigInteger) @Test fun testSomething() { val a = BigInteger.parseString("-1000000000000000000000000000002000000000000000000000000000003") val b = BigInteger.parseString("1000000000000000000000000000002000000000000000000000000000003") val testObject = BigIntegerArraySerializtionTestData(a, b) val json = Json { serializersModule = bigIntegerArraySerializerModule } val serialized = json.encodeToString(testObject) println(serialized) } }
27
Kotlin
42
366
e2ec7901443ace456ca457fc70b9707b9e0af478
2,139
kotlin-multiplatform-bignum
Apache License 2.0
common/src/main/java/co/railgun/common/api/ApiClient.kt
ProjectRailgun
408,317,880
false
{"Kotlin": 166353, "Java": 20380}
package co.railgun.common.api import android.util.Log import co.railgun.spica.api.internal.cookieJar import co.railgun.common.BuildConfig import okhttp3.OkHttpClient import okhttp3.ResponseBody import okhttp3.ResponseBody.Companion.toResponseBody import retrofit2.Converter import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory /** * Created by roya on 2017/5/22. */ object ApiClient { private val _instance: ApiService by lazy { create() } private lateinit var retrofit: Retrofit fun getInstance(): ApiService = _instance fun converterErrorBody(error: ResponseBody): MessageResponse? { if (!::retrofit.isInitialized) { throw IllegalStateException("ApiClient Not being initialized") } val errorConverter: Converter<ResponseBody, MessageResponse> = retrofit.responseBodyConverter( MessageResponse::class.java, arrayOfNulls<Annotation>(0) ) return try { errorConverter.convert(error) } catch (e: Throwable) { null } } private fun create(): ApiService { val okHttp = OkHttpClient.Builder() .dns(HttpsDns()) .cookieJar(cookieJar) .addInterceptor { val request = it.request() val response = it.proceed(request) val body = response.body val bodyString = body?.string() if (BuildConfig.DEBUG) Log.i("TAG", "$response Body:$bodyString") response.newBuilder() .headers(response.headers) .body(bodyString?.toResponseBody(body.contentType())) .build() } .build() retrofit = Retrofit.Builder() .client(okHttp) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .baseUrl("https://bgm.rip/") .build() return retrofit.create(ApiService::class.java) } }
0
Kotlin
0
2
394f3303fc261289a82e7a39dd77a9e413ca27ed
2,163
Spica
MIT License
Android-Kotlin/sulmun2/sulmun2/app/src/main/java/com/example/sulmun2/horror3detail/horrordetail35.kt
dkekdmf
469,109,428
false
{"Jupyter Notebook": 237657, "Python": 61277, "Kotlin": 61159, "C": 27870, "JavaScript": 7802, "EJS": 6927, "HTML": 2245, "CSS": 111}
package com.example.sulmun2.horror3detail import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.example.sulmun2.R class horrordetail35 : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.horrordetail35) }}
4
Jupyter Notebook
0
1
445ac449acd6f1bf9f3b49d37f4df4739b8feca8
348
Jaehoon
MIT License
skellig-test-step-reader/src/main/kotlin/org/skellig/teststep/reader/value/expression/StringValueExpression.kt
skellig-framework
263,021,995
false
{"Kotlin": 1283314, "CSS": 525991, "Java": 270216, "FreeMarker": 66859, "HTML": 11313, "ANTLR": 6165}
package org.skellig.teststep.reader.value.expression /** * Represents a string value expression that can be evaluated to a string value. * * @property value The string value of the expression. */ class StringValueExpression(private val value: String) : ValueExpression { override fun evaluate(context: ValueExpressionContext): Any? { return if (context.evaluationType == EvaluationType.CALL_CHAIN) context.onFunctionCall(value, context.value, emptyArray()) else value } override fun toString(): String { return value } override fun equals(other: Any?): Boolean { return if (other is StringValueExpression) value == other.value else value == other } override fun hashCode(): Int { return value.hashCode() } }
8
Kotlin
0
3
ed375268b0e444f1928f22f4ac27603e9d1fb66b
795
skellig-core
Apache License 2.0
app/src/main/java/com/nationalplasticfsm/features/weather/api/WeatherRepoProvider.kt
DebashisINT
506,900,340
false
null
package com.nationalplasticfsm.features.weather.api import com.nationalplasticfsm.features.task.api.TaskApi import com.nationalplasticfsm.features.task.api.TaskRepo object WeatherRepoProvider { fun weatherRepoProvider(): WeatherRepo { return WeatherRepo(WeatherApi.create()) } }
0
Kotlin
0
0
d437f8e247a2afa1d1cc14d8aba2bc9543a45791
296
NationalPlastic
Apache License 2.0
admobkit/src/main/java/br/com/frizeiro/admobkit/consent/ConsentGeography.kt
frizeiro
292,556,112
false
null
package com.sdk.ads.consent import com.google.android.ump.ConsentDebugSettings.DebugGeography.* enum class ConsentGeography { DISABLED, EEA, NOT_EEA, ; // region Public Variables val debugGeography by lazy { when (this) { DISABLED -> DEBUG_GEOGRAPHY_DISABLED EEA -> DEBUG_GEOGRAPHY_EEA NOT_EEA -> DEBUG_GEOGRAPHY_NOT_EEA } } // endregion }
0
Kotlin
1
8
e3be10e41e35cda370457d77a7feebc636d819e1
429
admobkit-android
MIT License
compiler/testData/diagnostics/tests/classLiteral/simpleClassLiteral.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
// FIR_IDENTICAL class A val k = A::class
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
43
kotlin
Apache License 2.0
app/src/main/java/com/realform/macropaytestpokemon/shortcuts/ShortCutsActivity.kt
IvanMedinaH
809,257,969
false
{"Kotlin": 176423}
package com.realform.macropaytestpokemon.shortcuts import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import com.realform.macropaytestpokemon.presentation.ui.theme.AppTheme import com.realform.macropaytestpokemon.presentation.ui.newPost.PostForm class ShortCutsActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { AppTheme { PostForm() } } } }
0
Kotlin
0
0
aa92d517e8f67a8cf08b0db3b009525ae3a4c4e4
560
Pokedex
MIT License
shared/src/commonMain/kotlin/com/thomaskioko/tvmaniac/presentation/model/GenreModel.kt
c0de-wizard
361,393,353
false
null
package com.thomaskioko.tvmaniac.presentation.model data class GenreModel( val id: Int, var name: String )
3
Kotlin
1
16
051aaba6359199cb8f9815feb6e96e0f5580d589
116
tv-maniac
Apache License 2.0
src/test/kotlin/g0201_0300/s0289_game_of_life/SolutionTest.kt
javadev
190,711,550
false
{"Kotlin": 4901773, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0201_0300.s0289_game_of_life import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.junit.jupiter.api.Test internal class SolutionTest { @Test fun gameOfLife() { val board = arrayOf(intArrayOf(0, 1, 0), intArrayOf(0, 0, 1), intArrayOf(1, 1, 1), intArrayOf(0, 0, 0)) Solution().gameOfLife(board) assertThat( board, equalTo(arrayOf(intArrayOf(0, 0, 0), intArrayOf(1, 0, 1), intArrayOf(0, 1, 1), intArrayOf(0, 1, 0))) ) } @Test fun gameOfLife2() { val board = arrayOf(intArrayOf(1, 1), intArrayOf(1, 0)) Solution().gameOfLife(board) assertThat(board, equalTo(arrayOf(intArrayOf(1, 1), intArrayOf(1, 1)))) } }
0
Kotlin
20
43
471d45c60f669ea1a2e103e6b4d8d54da55711df
764
LeetCode-in-Kotlin
MIT License
marker/src/main/java/com/utsman/geolib/marker/adapter/MarkerBitmapAdapter.kt
utsmannn
334,631,862
false
null
/* * Created on 4/13/21 1:46 AM * Copyright (c) Muhammad Utsman 2021 All rights reserved. */ package com.utsman.geolib.marker.adapter import android.view.View import com.google.android.gms.maps.model.BitmapDescriptor import com.google.android.gms.maps.model.BitmapDescriptorFactory import com.utsman.geolib.marker.createBitmapMarkerFromLayout abstract class MarkerBitmapAdapter { suspend fun getIconView(): BitmapDescriptor { val bitmap = createBitmapMarkerFromLayout(this) return BitmapDescriptorFactory.fromBitmap(bitmap) } abstract suspend fun createView(): View abstract fun maxWidth(): Int abstract fun maxHeight(): Int }
0
Kotlin
12
98
10d6f591b54c386d16bc643028759ae0f8fe8ac6
670
geolib
Apache License 2.0
src/jvmMain/kotlin/matt/shell/commands/curl/curl.kt
mgroth0
640,054,316
false
{"Kotlin": 78810}
package matt.shell.commands.curl import matt.shell.Shell fun <R> Shell<R>.curl(vararg args: String): R = sendCommand( this::curl.name, *args )
0
Kotlin
0
0
837c0f2d61ab927b83c7876871a5d8dcd9073112
154
shell
MIT License
trackingview/src/main/java/com/github/fajaragungpramana/trackingview/TrackingView.kt
fajaragungpramana
347,670,299
false
{"Kotlin": 8206}
package com.github.fajaragungpramana.trackingview import android.content.Context import android.graphics.Color import android.util.AttributeSet import android.view.Gravity import android.widget.LinearLayout class TrackingView(context: Context, attrs: AttributeSet?) : LinearLayout(context, attrs) { private val mIndicator: Indicator private val mLine: Line var isDashedEnabled: Boolean = false get() = mLine.isDashed set(value) { field = value mLine.isDashed = field } var lineWidth: Int = 2 get() = mLine.width set(value) { field = value mIndicator.lineSize = field mLine.lineWidth = field } var indicatorColor: Int = Color.RED get() = mLine.lineColor set(value) { field = value mIndicator.indicatorColor = field mLine.lineColor = field } var indicatorSize: Int = 32 get() = mIndicator.indicatorSize set(value) { field = value mIndicator.indicatorSize = field } var isDestinationEnabled: Boolean = false get() = mIndicator.isDestination set(value) { field = value mIndicator.isDestination = field } init { orientation = VERTICAL gravity = Gravity.CENTER_HORIZONTAL mIndicator = Indicator(context) mLine = Line(context) addView(mIndicator) addView(mLine) context.obtainStyledAttributes(attrs, R.styleable.TrackingView).also { isDashedEnabled = it.getBoolean(R.styleable.TrackingView_dashed, false) lineWidth = it.getDimension(R.styleable.TrackingView_lineWidth, 4F).toInt() indicatorColor = it.getColor(R.styleable.TrackingView_indicatorColor, Color.RED) indicatorSize = it.getDimension(R.styleable.TrackingView_indicatorSize, 32F).toInt() }.recycle() } fun set(position: Int, itemCount: Int) { if (position == (itemCount - 1)) { mLine.visibility = GONE mIndicator.isDestination = true } } }
0
Kotlin
0
2
77a1e1c021cce04cd486c809f2025be6670547a3
2,172
tracking-view
Apache License 2.0
app/src/main/java/com/example/whatisup/src/ui/dialog/NewActivityDialog.kt
knatola
173,893,801
false
null
package com.example.whatisup.src.ui.dialog import android.app.Dialog import android.content.Context import android.os.Bundle import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import com.example.whatisup.R import com.example.whatisup.src.data.model.PhysicalActivity import kotlinx.android.synthetic.main.add_activity_dialog_layout.* import java.util.concurrent.TimeUnit class NewActivityDialog(context: Context): Dialog(context) { private lateinit var callBack: NewActivityCallback override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.add_activity_dialog_layout) val adapter = ArrayAdapter.createFromResource(context, R.array.activites, android.R.layout.simple_spinner_dropdown_item) adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) activity_type_spinner.adapter = adapter activity_type_spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{ override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { when (position) { 0 -> activity_icon.setImageDrawable(context.getDrawable(R.drawable.activity_walking)) 1 -> activity_icon.setImageDrawable(context.getDrawable(R.drawable.activity_running)) 2 -> activity_icon.setImageDrawable(context.getDrawable(R.drawable.activity_gym)) 3 -> activity_icon.setImageDrawable(context.getDrawable(R.drawable.activity_swimming)) 4 -> activity_icon.setImageDrawable(context.getDrawable(R.drawable.activity_cycling)) } } override fun onNothingSelected(parent: AdapterView<*>?) { } } activity_save_btn.setOnClickListener { val hours = activity_hour_input.text.toString() val minutes = activity_minute_input.text.toString() if (hours != "" && minutes != "") { val type = activity_type_spinner.selectedItemPosition val duration = TimeUnit.MINUTES.toMillis(minutes.toLong()) + TimeUnit.HOURS.toMillis(minutes.toLong()) // val duration = "$hours:$minutes" val newActivity = PhysicalActivity(type, duration) callBack.onNewActivity(newActivity) this.cancel() } else { activity_save_btn.setTextColor(context.getColor(R.color.red)) } } } fun setCallback(callBack: NewActivityCallback) { this.callBack = callBack } interface NewActivityCallback { fun onNewActivity(activity: PhysicalActivity) } }
0
Kotlin
0
0
3e13e4f651cce7c6e41e8c9a8cd6c2303c5f944c
2,784
mobile_computing_2019
MIT License
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/WeaklyConnectedGraphQ.kt
Danilo-Araujo-Silva
271,904,885
false
null
package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction /** *```` * * Name: WeaklyConnectedGraphQ * * Full name: System`WeaklyConnectedGraphQ * * Usage: WeaklyConnectedGraphQ[g] yields True if the graph g is weakly connected, and False otherwise. * * Options: None * * Attributes: Protected * * local: paclet:ref/WeaklyConnectedGraphQ * Documentation: web: http://reference.wolfram.com/language/ref/WeaklyConnectedGraphQ.html * * Definitions: None * * Own values: None * * Down values: None * * Up values: None * * Sub values: None * * Default value: None * * Numeric values: None */ fun weaklyConnectedGraphQ(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction { return MathematicaFunction("WeaklyConnectedGraphQ", arguments.toMutableList(), options) }
2
Kotlin
0
3
4fcf68af14f55b8634132d34f61dae8bb2ee2942
1,042
mathemagika
Apache License 2.0
finder/kotlin/src/main/kotlin/pro/truongsinh/appium_flutter/finder/FlutterElement.kt
appium
197,505,662
false
null
package appium_flutter.finder import org.openqa.selenium.remote.RemoteWebElement public class FlutterElement : RemoteWebElement { private var _rawMap: Map<String, *> constructor(m: Map<String, *>) { _rawMap = m id = serialize(m) } fun getRawMap(): Map<String, *> { return _rawMap } }
70
null
178
434
b8037cb1a9a1297245e11e250f914c7442ef6f36
302
appium-flutter-driver
MIT License
RailArea/src/main/kotlin/city/newnan/railarea/utils/AreaVisualizer.kt
NewNanCity
467,094,551
false
null
package city.newnan.railarea.utils import city.newnan.railarea.PluginMain import city.newnan.railarea.octree.Point3D import city.newnan.railarea.octree.Range3D import me.lucko.helper.Schedulers import org.bukkit.Particle import org.bukkit.World fun Range3DWorld.visualize(particle: Particle, second: Int) = this.range.visualize(this.world, particle, second) fun Range3D.visualize(world: World, particle: Particle, second: Int) { if (second <= 0) return var counter = second shl 1 Schedulers.sync().runRepeating({ task -> // spawn particles to visualize area val minXv = minX.toDouble() val maxXv = maxX.toDouble()+1 val minZv = minZ.toDouble() val maxZv = maxZ.toDouble()+1 val minYv = minY.toDouble() val maxYv = maxY.toDouble()+1 for (x in minX..(maxX+1)) { val xv = x.toDouble() world.spawnParticle(particle, xv, minYv, minZv, 1, 0.0, 0.0, 0.0, 0.0) world.spawnParticle(particle, xv, minYv, maxZv, 1, 0.0, 0.0, 0.0, 0.0) world.spawnParticle(particle, xv, maxYv, minZv, 1, 0.0, 0.0, 0.0, 0.0) world.spawnParticle(particle, xv, maxYv, maxZv, 1, 0.0, 0.0, 0.0, 0.0) } for (y in minY..(maxY+1)) { val yv = y.toDouble() world.spawnParticle(particle, minXv, yv, minZv, 1, 0.0, 0.0, 0.0, 0.0) world.spawnParticle(particle, minXv, yv, maxZv, 1, 0.0, 0.0, 0.0, 0.0) world.spawnParticle(particle, maxXv, yv, minZv, 1, 0.0, 0.0, 0.0, 0.0) world.spawnParticle(particle, maxXv, yv, maxZv, 1, 0.0, 0.0, 0.0, 0.0) } for (z in minZ..(maxZ+1)) { val zv = z.toDouble() world.spawnParticle(particle, minXv, minYv, zv, 1, 0.0, 0.0, 0.0, 0.0) world.spawnParticle(particle, minXv, maxYv, zv, 1, 0.0, 0.0, 0.0, 0.0) world.spawnParticle(particle, maxXv, minYv, zv, 1, 0.0, 0.0, 0.0, 0.0) world.spawnParticle(particle, maxXv, maxYv, zv, 1, 0.0, 0.0, 0.0, 0.0) } if (--counter < 0) task.close() }, 0, 10).bindWith(PluginMain.INSTANCE) } fun Point3DWorld.visualize(particle: Particle, second: Int) = this.point.visualize(this.world, particle, second) fun Point3D.visualize(world: World, particle: Particle, second: Int) { if (second <= 0) return var counter = second shl 1 val xO = x.toDouble() val yO = y.toDouble() val zO = z.toDouble() val xs = listOf(xO, xO+0.5, xO+1.0) val ys = listOf(yO, yO+0.5, yO+1.0) val zs = listOf(zO, zO+0.5, zO+1.0) Schedulers.sync().runRepeating({ task -> if (particle == Particle.BARRIER) { world.spawnParticle(particle, xs[1], ys[1], zs[1], 1, 0.0, 0.0, 0.0, 0.0) } else { for (x in xs) for (y in ys) for (z in zs) world.spawnParticle(particle, x, y, z, 1, 0.0, 0.0, 0.0, 0.0) } if (--counter < 0) task.close() }, 0, 10).bindWith(PluginMain.INSTANCE) }
0
Kotlin
0
5
64a016d822c281ab74d060606f957f93947d958a
2,995
Plugins
MIT License
debug-cache/src/main/kotlin/com/healthmetrix/deident/debug/cache/DebugCacheInserter.kt
smart4health
593,625,191
false
null
package com.healthmetrix.deident.debug.cache import com.healthmetrix.deident.commons.HarmonizedEvent import org.springframework.context.annotation.Profile import org.springframework.context.event.EventListener import org.springframework.stereotype.Component /** * Takes HarmonizedEvents as it's the last one before being uploaded to the research platform. * This should only be active on test environments */ @Profile("debug-cache & !production & !prod") @Component class DebugCacheInserter( private val inMemoryDebugCache: InMemoryDebugCache, ) { @EventListener fun onEvent(harmonizedEvent: HarmonizedEvent) { inMemoryDebugCache.put( InMemoryDebugCache.CacheItem( context = harmonizedEvent.context, fhirBundle = harmonizedEvent.transaction.asBundle(), ), ) } }
0
Kotlin
0
1
9223a1f12f8a3d5d14d91f8400444946a031490f
855
dataprovision-deident-service
MIT License
app/src/main/java/com/savlanet/gratisshops/navigation/NavGraphBuilder.kt
KabirSayyada
744,099,100
false
{"Kotlin": 255272}
package com.savlanet.gratisshops.navigation import androidx.compose.runtime.Composable import androidx.navigation.NavBackStackEntry import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import com.savlanet.gratisshops.MainDestinations import com.savlanet.pickstant.navigation.BottomNavSections @Composable fun GratisNavGraph( navController: NavHostController, onProductSelected: (Long, NavBackStackEntry) -> Unit, upPress: () -> Unit ){ NavHost( navController = navController, startDestination = MainDestinations.SPLASH_ROUTE//BottomNavSections.HOME.screen_route ) { addSplashScreen( navController = navController, this ) addHomeScreen( navController = navController, this, onProductSelected = onProductSelected ) addVendorScreen( navController = navController, this, onProductSelected = onProductSelected ) addSearchScreen( navController = navController, this, onProductSelected = onProductSelected ) addCartScreen( navController = navController, this, onProductSelected = onProductSelected ) addYouScreen( navController = navController, this, ) addCheckoutScreen( navController = navController, this ) addOnboardingScreen( navController = navController, this ) addMapScreen( navController = navController, this ) addEditProfileScreen( navController = navController, this ) addProductDetailScreen( navController = navController, this, upPress = upPress ) } }
0
Kotlin
0
0
940dbcf642c698d3783da6b54a4b54eb9b675391
1,954
GratisShops
MIT License
vertigram-telegram-client/src/main/kotlin/ski/gagar/vertigram/telegram/methods/GetFile.kt
gagarski
314,041,476
false
{"Kotlin": 698498}
package ski.gagar.vertigram.telegram.methods import com.fasterxml.jackson.annotation.JsonIgnore import ski.gagar.vertigram.telegram.types.File import ski.gagar.vertigram.util.NoPosArgs /** * Telegram [getFile](https://core.telegram.org/bots/api#getfile) method. * * For up-to-date documentation please consult the official Telegram docs. */ data class GetFile( @JsonIgnore private val noPosArgs: NoPosArgs = NoPosArgs.INSTANCE, val fileId: String ) : JsonTelegramCallable<File>()
0
Kotlin
0
0
0c34a50bb61513126a3154135bb044b900c6d026
498
vertigram
Apache License 2.0
app/charpad-processor/src/main/kotlin/com/github/c64lib/retroassembler/charpad_processor/model/ColouringMethod.kt
Cumbayah
405,651,085
true
{"Kotlin": 274338, "Shell": 560}
/* MIT License Copyright (c) 2018-2022 c64lib: The Ultimate Commodore 64 Library Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.github.c64lib.retroassembler.charpad_processor.model import com.github.c64lib.retroassembler.charpad_processor.InvalidCTMFormatException enum class ColouringMethod(val value: Byte) { Global(0), PerTile(1), PerChar(2) } internal fun colouringMethodFrom(value: Byte): ColouringMethod = when (value) { ColouringMethod.Global.value -> ColouringMethod.Global ColouringMethod.PerTile.value -> ColouringMethod.PerTile ColouringMethod.PerChar.value -> ColouringMethod.PerChar else -> throw InvalidCTMFormatException("Unknown colouring method: $value.") }
0
Kotlin
0
0
d9d66768bab1a1899a4fbe30d25c8cd30c342f56
1,709
gradle-retro-assembler-plugin
MIT License
app/src/main/java/com/example/foursquaretest/data/repository/NearPlacesRepository.kt
arenas782
470,315,873
false
{"Kotlin": 47046}
package com.example.foursquaretest.data.repository import com.example.foursquaretest.data.api.NearPlacesAPI import com.example.foursquaretest.data.model.responses.Place import com.example.foursquaretest.data.room.PlaceDao import kotlinx.coroutines.flow.Flow import javax.inject.Inject class NearPlacesRepository @Inject constructor(private val placesDao : PlaceDao, private val nearPlacesAPI: NearPlacesAPI) { suspend fun getNearbyPlaces(location : String) = nearPlacesAPI.getNearBySeattle(location =location,limit = "10") fun getFavoritePlaces(): Flow<List<Place>> = placesDao.getPlaces() suspend fun addFavoritePlace(place : Place){ placesDao.insertFavoritePlace(place) } suspend fun deleteFavoritePlace(place : Place){ placesDao.deleteFavoritePlace(place) } }
0
Kotlin
0
0
92e136a698dfbf8b0a8be1404b32232b38bcd41e
810
foursquaretest
MIT License
daggie-moshi/src/main/java/com/nextfaze/daggie/moshi/AndroidAdapters.kt
BurleighCreative
492,653,857
true
{"Kotlin": 195018, "Java": 122}
package com.nextfaze.daggie.moshi import android.net.Uri import com.nextfaze.daggie.Configurator import com.nextfaze.daggie.Ordered import com.squareup.moshi.FromJson import com.squareup.moshi.Moshi import com.squareup.moshi.ToJson import dagger.Module import dagger.Provides import dagger.multibindings.IntoSet /** * Installs Moshi adapters for the following common Android types: * * [Uri] */ @Module class AndroidAdaptersModule { @Provides @IntoSet internal fun configurator() = Ordered<Configurator<Moshi.Builder>>(0) { add(UriAdapter) } } private object UriAdapter { @ToJson fun toJson(uri: Uri): String = uri.toString() @FromJson fun fromJson(value: String): Uri = Uri.parse(value) }
0
null
0
0
833ff0cb478a03af60cc004f090e8b90bc1d1744
712
daggie
Apache License 2.0
app/src/main/java/com/hashapps/cadenas/ui/cache/MessageCache.kt
GaloisInc
873,867,559
false
{"Kotlin": 297817}
package com.hashapps.cadenas.ui.cache import java.time.Instant interface MessageCache { fun insertMessage(message: Message) fun updateMessages(channelId: Long, cacheTime: Int): List<Message> fun clearMessages(channelId: Long) } /** * Instance of cache we'll use to track the encoded and decoded * messages. Currently displayed on each channel processing page, * and deleted when the timer for that channel runs out. */ class ActiveMessageCache() : MessageCache { private var messages: List<Message> = emptyList<Message>() /** * Add a new message to the cache. */ override fun insertMessage(message: Message) { messages = messages.plus(message) } /** * Get all the messages that belong to the given channel. * (Removing from cache any that have expired.) */ override fun updateMessages(channelId: Long, cacheTime: Int): List<Message> { //if there are any messages that have expired, delete them first messages = messages.filter { (it.channelId != channelId) || (it.channelId == channelId && it.time.plusMillis(cacheTime.toLong()).isAfter(Instant.now())) } //now return the list for the given channel return messages.filter { it.channelId == channelId } } /** * Remove all messages of the given channel from the chache. */ override fun clearMessages(channelId: Long) { messages = messages.filter { (it.channelId != channelId) } } }
1
Kotlin
0
0
13bec2fb2959936fce8d3461518cc2b3e542540c
1,548
Cadenas
MIT License
library/src/main/java/com/silverhetch/aura/media/AuraMediaPlayerImpl.kt
fossabot
268,971,220
false
{"Gradle": 4, "Markdown": 6, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "YAML": 1, "Proguard": 2, "Kotlin": 127, "XML": 43, "Java": 41}
package com.silverhetch.aura.media import android.content.Context import android.graphics.Point import android.media.MediaPlayer import android.net.Uri import android.os.Handler import android.view.SurfaceHolder import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import java.util.concurrent.TimeUnit.SECONDS /** * Implementation of [AuraMediaPlayer] */ class AuraMediaPlayerImpl(private val context: Context) : AuraMediaPlayer, PlaybackControl { private val state = MutableLiveData<State>().apply { value = ConstState() } private var buffered: Int = 0 private var completed: Boolean = false // Note: this state will be publish only one time if true private var videoSize = MutableLiveData<Point>().apply { Point(0, 0) } private val handler = Handler() private var mediaPlayer: MediaPlayer = MediaPlayer() private var attemptPlay = false private lateinit var dataSource: Uri private val progressRunnable = object : Runnable { override fun run() { state.value = ConstState( mediaPlayer.isPlaying || attemptPlay, if (mediaPlayer.duration != 0) mediaPlayer.duration else 0, buffered, if (mediaPlayer.currentPosition != 0) mediaPlayer.currentPosition else 0, completed ) completed = false handler.postDelayed(this, SECONDS.toMillis(1)) } } override fun load(uri: String) { dataSource = Uri.parse(uri) mediaPlayer.stop() mediaPlayer.release() mediaPlayer = MediaPlayer() mediaPlayer.setDataSource(context, dataSource) mediaPlayer.setOnVideoSizeChangedListener { _, width, height -> videoSize.value = Point(width, height) } mediaPlayer.setOnBufferingUpdateListener { _, percent -> buffered = percent } mediaPlayer.setOnPreparedListener { if (attemptPlay) { mediaPlayer.start() } mediaPlayer.setOnCompletionListener { completed = true } } mediaPlayer.prepareAsync() handler.postDelayed(progressRunnable, SECONDS.toMillis(1)) } override fun play() { attemptPlay = true mediaPlayer.start() } override fun pause() { attemptPlay = false mediaPlayer.pause() } override fun seekTo(position: Int) { mediaPlayer.seekTo(position) } override fun state(): LiveData<State> { return state } override fun attachDisplay(surfaceHolder: SurfaceHolder) { mediaPlayer.setDisplay(surfaceHolder) if (!mediaPlayer.isPlaying && ::dataSource.isInitialized) { // To draw current frame on surface mediaPlayer.seekTo(mediaPlayer.currentPosition) } } override fun detachDisplay() { mediaPlayer.setDisplay(null) } override fun release() { attemptPlay = false handler.removeCallbacks(progressRunnable) mediaPlayer.release() } override fun videoSize(): LiveData<Point> { return videoSize } override fun playback(): PlaybackControl { return this } }
9
null
2
1
fb00fe41a2b32dbbd9fcc88d0fcd8d531c9b0638
3,209
Aura
MIT License
app/src/main/java/com/riteshakya/milestones/utils/FontCache.kt
riteshakya037
170,620,128
false
null
package com.riteshakya.milestones.utils import android.content.Context import android.graphics.Typeface import java.util.* object FontCache { private val fontCache = Hashtable<String, Typeface>() operator fun get(name: String, context: Context): Typeface { return if (fontCache.contains(name)) fontCache[name]!! else { val tf: Typeface? try { tf = Typeface.createFromAsset(context.assets, "fonts/$name") } catch (e: Exception) { throw RuntimeException(e) } fontCache[name] = tf tf } } }
0
Kotlin
0
1
639654e285788e29484631196e384c61be205520
643
milestones
MIT License
httplib/src/main/java/dev/entao/kan/http/HttpResult.kt
yangentao
181,056,404
false
null
package dev.entao.kan.http import dev.entao.kan.base.closeSafe import dev.entao.kan.json.YsonArray import dev.entao.kan.json.YsonObject import dev.entao.kan.log.loge import org.json.JSONArray import org.json.JSONException import org.json.JSONObject import java.io.File import java.io.FileOutputStream import java.net.NoRouteToHostException import java.net.SocketException import java.net.SocketTimeoutException import java.net.URLDecoder import java.nio.charset.Charset import java.util.concurrent.TimeoutException /** * Created by <EMAIL> on 16/4/29. */ class HttpResult { var response: ByteArray? = null//如果Http.request参数给定了文件参数, 则,response是null var responseCode: Int = 0//200 var responseMsg: String? = null//OK var contentType: String? = null //text/html;charset=utf-8 set(value) { field = value if (value != null && value.startsWith("text/html")) { needDecode = true } } var contentLength: Int = 0//如果是gzip格式, 这个值!=response.length var headerMap: Map<String, List<String>>? = null var exception: Exception? = null var needDecode: Boolean = false val errorMsg: String? get() { val ex = exception return when (ex) { null -> httpMsgByCode(responseCode) is NoRouteToHostException -> "网络不可达" is TimeoutException -> "请求超时" is SocketTimeoutException -> "请求超时" is SocketException -> "网络错误" else -> ex.message } } var OK: Boolean = false get() = responseCode >= 200 && responseCode < 300 fun OK(): Boolean { return OK } //Content-Type: text/html; charset=GBK val contentCharset: Charset? get() { val ct = contentType ?: return null val ls: List<String> = ct.split(";".toRegex()).dropLastWhile { it.isEmpty() } for (item in ls) { val ss = item.trim(); if (ss.startsWith("charset")) { val charset = ss.substringAfterLast('=', "").trim() if (charset.length >= 2) { return Charset.forName(charset) } } } return null } fun needDecode(): HttpResult { this.needDecode = true return this } fun str(defCharset: Charset): String? { if (OK()) { val resp = response ?: return null val ct = contentCharset ?: defCharset var s = String(resp, ct) if (needDecode) { s = URLDecoder.decode(s, defCharset.name()) } return s } return null } fun strISO8859_1(): String? = str(Charsets.ISO_8859_1) fun strUtf8(): String? = str(Charsets.UTF_8) fun <T> castText(block: (String) -> T?): T? { if (OK()) { val s = strUtf8() if (s != null && s.isNotEmpty()) { try { return block(s) } catch (e: Exception) { e.printStackTrace() } } } return null } fun ysonObject(): YsonObject? { return castText { YsonObject(it) } } fun ysonArray(): YsonArray? { return castText { YsonArray(it) } } fun jsonObject(): JSONObject? { if (OK()) { val s = strUtf8() if (s != null && s.isNotEmpty()) { try { return JSONObject(s) } catch (e: JSONException) { e.printStackTrace() } } } return null } fun jsonArray(): JSONArray? { if (OK()) { val s = strUtf8() if (s != null && s.isNotEmpty()) { try { return JSONArray(s) } catch (e: JSONException) { e.printStackTrace() } } } return null } fun bytes(): ByteArray? { if (OK()) { return response } return null } fun saveTo(file: File): Boolean { if (OK()) { val dir = file.parentFile if (dir != null) { if (!dir.exists()) { if (!dir.mkdirs()) { loge("创建目录失败") return false } } } var fos: FileOutputStream? = null try { fos = FileOutputStream(file) fos.write(response) fos.flush() } catch (ex: Exception) { ex.printStackTrace() } finally { fos.closeSafe() } } return false } }
0
Kotlin
0
0
5d27deb6934e1600c8f1905311153700f6482e6e
4,915
http
MIT License
app/src/main/java/com/ninaestoye/findfun/di/NetworkModule.kt
ninamanalo19
419,203,332
false
{"Kotlin": 19924}
package com.ninaestoye.findfun.di import com.ninaestoye.findfun.network.FFInterceptor import com.ninaestoye.findfun.network.SimpleAPI import com.ninaestoye.findfun.utils.Constants import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import javax.inject.Named import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object NetworkModule { @Singleton @Provides fun provideAPI(httpClient: OkHttpClient): SimpleAPI { return Retrofit.Builder() .baseUrl(Constants.BASE_URL) .client(httpClient) .addConverterFactory(GsonConverterFactory.create()) .build() .create(SimpleAPI::class.java); } @Singleton @Provides @Named("auth_token") fun provideAuthToken(): String { return "Token" } @Singleton @Provides fun provideHttpClient() : OkHttpClient { return OkHttpClient.Builder() .addInterceptor(FFInterceptor()) .build(); } }
0
Kotlin
0
1
5414592ffdac7e2dc328b982a1094c3af0ed4918
1,174
android-FindFun
MIT License
src/main/kotlin/Main.kt
Daniel0110000
702,220,698
false
{"Kotlin": 250956, "Lex": 15630}
import com.dr10.common.ui.ThemeApp import com.dr10.common.ui.UIManagerConfig import com.dr10.common.utilities.ColorUtils.toAWTColor import com.dr10.common.utilities.DocumentsManager import com.dr10.database.di.databaseModule import com.dr10.editor.di.editorModule import com.dr10.settings.di.settingsModule import di.appModule import org.koin.core.context.GlobalContext.startKoin import ui.CodeEditorScreen import java.awt.Toolkit import javax.swing.JFrame import javax.swing.SwingUtilities import javax.swing.WindowConstants fun main() = SwingUtilities.invokeLater { // Set the necessary properties of the UI Manager UIManagerConfig.config() val toolkit = Toolkit.getDefaultToolkit().screenSize // Create the necessary directories for the program DocumentsManager.createNecessaryDirectories() // Initialize Koin startKoin { modules(appModule, databaseModule, settingsModule, editorModule) } val window = JFrame().apply { defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE setSize(toolkit.width - 100, toolkit.height - 100) contentPane.background = ThemeApp.colors.background.toAWTColor() title = "DeepCode Studio" } CodeEditorScreen(window) window.isVisible = true }
1
Kotlin
3
30
5114314c76455ddedce4af0762b37ca7730a598f
1,256
DeepCodeStudio
Apache License 2.0
app/src/main/java/com/example/bettergeeks/screens/review/ReviewQuestionFragment.kt
vylhart
644,937,601
false
null
package com.example.bettergeeks.screens.review import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.example.bettergeeks.R class ReviewQuestionFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View { return inflater.inflate(R.layout.fragment_review_question, container, false) } }
0
Kotlin
0
0
1cc769867b655970bf1d2ed26dafc3e3328236bf
519
BetterGeeks
Apache License 2.0
src/main/kotlin/com/banking/poc/application/usecase/wallet/WalletCreateUseCase.kt
afuentecruz
783,323,978
false
{"Kotlin": 118208}
package com.banking.poc.application.usecase.wallet import com.banking.poc.application.service.UserService import com.banking.poc.application.service.WalletService import com.banking.poc.infrastructure.rest.wallet.dto.WalletResponse import com.banking.poc.infrastructure.rest.wallet.dto.fromDomain class WalletCreateUseCase(private val userService: UserService, private val walletService: WalletService) { fun createUserWallet(username: String): WalletResponse = userService.findUsername(username).let { user -> walletService.createWallet(user).let { WalletResponse.fromDomain(it) } } }
0
Kotlin
0
0
14a55d20e82f598eff9b7c27c5f28d5ada083107
624
banking-poc
Apache License 2.0
di/src/commonTest/kotlin/ivy/di/testsupport/di/FakeDiModule.kt
Ivy-Apps
845,095,104
false
{"Kotlin": 62636}
package ivy.di.testsupport.di import ivy.di.Di import ivy.di.Di.register import ivy.di.testsupport.FakeModuleDep object FakeDiModule : Di.Module { override fun init() = Di.appScope { register { FakeModuleDep() } } }
0
Kotlin
4
22
8ed767dcaef28cdeaa3974040a20649282b90c67
233
di
Apache License 2.0
designcompose/src/main/java/com/android/designcompose/DesignOverlay.kt
google
624,923,090
false
{"Rust": 1763771, "Kotlin": 1216076, "HTML": 128407, "TypeScript": 127202, "Shell": 24988, "CSS": 12423, "JavaScript": 6781, "Java": 4313, "Python": 3507}
/* * Copyright 2023 Google LLC * * 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.designcompose import android.util.Log import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import com.android.designcompose.proto.OverlayBackgroundInteractionEnum import com.android.designcompose.proto.OverlayPositionEnum import com.android.designcompose.proto.overlayBackgroundInteractionFromInt import com.android.designcompose.proto.overlayPositionEnumFromInt import com.android.designcompose.serdegen.FrameExtras @Composable internal fun DesignOverlay( overlay: FrameExtras, interactionState: InteractionState, content: @Composable () -> Unit, ) { val alignment = when (overlayPositionEnumFromInt(overlay.overlay_position_type)) { OverlayPositionEnum.TOP_LEFT -> Alignment.TopStart OverlayPositionEnum.TOP_CENTER -> Alignment.TopCenter OverlayPositionEnum.TOP_RIGHT -> Alignment.TopEnd OverlayPositionEnum.CENTER -> Alignment.Center OverlayPositionEnum.BOTTOM_LEFT -> Alignment.BottomStart OverlayPositionEnum.BOTTOM_CENTER -> Alignment.BottomCenter OverlayPositionEnum.BOTTOM_RIGHT -> Alignment.BottomEnd else -> Alignment.TopStart } val closeOnTapOutside = overlayBackgroundInteractionFromInt(overlay.overlay_background_interaction) == OverlayBackgroundInteractionEnum.CLOSE_ON_CLICK_OUTSIDE var boxModifier = Modifier.fillMaxSize().clickable( interactionSource = remember { MutableInteractionSource() }, indication = null, ) { // Always be clickable, because it also prevents taps and drags from going thru to views // behind the overlay background. if (closeOnTapOutside) interactionState.close(null) } overlay.overlay_background.ifPresent { it.color.ifPresent { color -> boxModifier = boxModifier.background(Color(color.r, color.g, color.b, color.a)) } } DisposableEffect(Unit) { // Similar to a root view, tell the layout manager to defer layout computations until all // child views have been added to the overlay Log.d(TAG, "Overlay start") onDispose {} } Box(boxModifier, contentAlignment = alignment) { content() } DisposableEffect(Unit) { // Similar to a root view, tell the layout manager to that child views have been added so // that layout can be computed Log.d(TAG, "Overlay end") onDispose {} } }
164
Rust
16
113
81fee085d1f83e7b38fb5e0d4d629d42ea6bcdd1
3,555
automotive-design-compose
Apache License 2.0
src/main/kotlin/raft/war/plugin/openapi/projectRoots/PluginSdkType.kt
WarRaft
713,961,790
false
{"Kotlin": 411257, "Java": 270296, "Lex": 23791, "HTML": 185}
package raft.war.plugin.openapi.projectRoots import com.intellij.openapi.projectRoots.* import raft.war.language.jass.icons.JassIcons import org.jdom.Element import org.jetbrains.annotations.Nls import javax.swing.Icon // https://plugins.jetbrains.com/docs/intellij/sdk.html#working-with-a-custom-sdk // https://intellij-support.jetbrains.com/hc/en-us/community/posts/206773745-Custom-SDK-Setup class PluginSdkType : SdkType("JASS SDK") { override fun suggestHomePath(): String? = null override fun isValidSdkHome(s: String): Boolean { return true } override fun suggestSdkName(s: String?, s1: String): String = "JASS SDK" override fun createAdditionalDataConfigurable( sdkModel: SdkModel, sdkModificator: SdkModificator ): AdditionalDataConfigurable? = null override fun getPresentableName(): @Nls(capitalization = Nls.Capitalization.Title) String = "JASS SDK" override fun setupSdkPaths(sdk: Sdk, sdkModel: SdkModel): Boolean { val modificator = sdk.sdkModificator modificator.versionString = getVersionString(sdk) modificator.commitChanges() return true } override fun getVersionString(sdk: Sdk): String = "1.0.0" override fun saveAdditionalData(sdkAdditionalData: SdkAdditionalData, element: Element) = Unit override fun getIcon(): Icon = JassIcons.FILE override fun getDefaultDocumentationUrl(sdk: Sdk): String = "https://warraft.github.io/AngelScript-doc" override fun getDownloadSdkUrl(): String = "https://warraft.github.io/AngelScript-doc" }
0
Kotlin
0
2
d4dc28fe0cdcabe7fca99477a1f1183af76a0434
1,576
IntelliJASS
MIT License
src/main/kotlin/com/ekino/oss/recaptcha/client/ReCaptchaResponseDto.kt
ekino
257,331,394
false
null
package com.ekino.oss.recaptcha.client import java.time.OffsetDateTime /** * ReCaptcha response DTO. */ data class ReCaptchaResponseDto( val success: Boolean? = false, val challengeTs: OffsetDateTime? = null, val hostName: String? = null, val errorCodes: List<String> = emptyList() )
0
Kotlin
1
0
c9fe9192ebdac2e3fc04f38b19312d37fd1fe51e
296
spring-recaptcha
MIT License
web/src/main/kotlin/com/sgzmd/flibustier/web/config/EmailConfig.kt
sgzmd
228,894,992
false
null
package com.sgzmd.flibustier.web.config import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Value import org.springframework.context.annotation.Bean import org.springframework.mail.javamail.JavaMailSender import org.springframework.mail.javamail.JavaMailSenderImpl import org.springframework.stereotype.Component @Component class EmailConfig( @Value("\${smtp.username}") val username: String, @Value("\${smtp.password}") val password: String, @Value("\${smtp.host}") val host: String) { val log = LoggerFactory.getLogger(EmailConfig::class.java) @Bean fun getEmailSender() : JavaMailSender { log.info("Creating EmailSender") val mailSender = JavaMailSenderImpl() mailSender.host = host mailSender.port = 25 mailSender.username = username mailSender.password = <PASSWORD> val props = mailSender.javaMailProperties props.put("mail.transport.protocol", "smtp") props.put("mail.smtp.auth", "true") props.put("mail.debug", "true") return mailSender } }
0
Kotlin
0
0
438354ee1b2a1a4656982e7cbc37819e2839141c
1,050
flibustier
MIT License
android/app/src/main/java/br/com/zup/officehoursdemo/MainActivity.kt
joaojaco
355,308,048
false
{"Kotlin": 12843, "Swift": 7102, "Ruby": 429}
package br.com.zup.officehoursdemo import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import br.com.zup.beagle.android.utils.newServerDrivenIntent import br.com.zup.beagle.android.view.ScreenRequest import br.com.zup.beagle.android.view.ServerDrivenActivity import br.com.zup.beagle.scaffold.BeagleIntent class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val intent = this.newServerDrivenIntent<ServerDrivenActivity>(ScreenRequest(url = "/zipCode")) startActivity(intent) finish() } }
0
Kotlin
0
0
1355076412b9c8e1499589a7f926673f9a5ca417
677
OfficeHoursDemo
Apache License 2.0
samples/star/src/test/kotlin/com/slack/circuit/star/petdetail/PetDetailUiTest.kt
slackhq
523,011,227
false
null
// Copyright (C) 2022 Slack Technologies, LLC // SPDX-License-Identifier: Apache-2.0 package com.slack.circuit.star.petdetail import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.assertTextEquals import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.compose.ui.test.performTouchInput import androidx.compose.ui.test.swipeUp import androidx.test.platform.app.InstrumentationRegistry import coil.annotation.ExperimentalCoilApi import com.google.common.truth.Truth.assertThat import com.slack.circuit.foundation.Circuit import com.slack.circuit.foundation.CircuitCompositionLocals import com.slack.circuit.overlay.ContentWithOverlays import com.slack.circuit.sample.coil.test.CoilRule import com.slack.circuit.star.R import com.slack.circuit.star.petdetail.PetDetailTestConstants.ANIMAL_CONTAINER_TAG import com.slack.circuit.star.petdetail.PetDetailTestConstants.FULL_BIO_TAG import com.slack.circuit.star.petdetail.PetDetailTestConstants.PROGRESS_TAG import com.slack.circuit.star.petdetail.PetDetailTestConstants.UNKNOWN_ANIMAL_TAG import com.slack.circuit.star.petdetail.PetPhotoCarouselTestConstants.CAROUSEL_TAG import com.slack.circuit.test.TestEventSink import kotlinx.collections.immutable.persistentListOf import kotlinx.coroutines.test.runTest import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @OptIn(ExperimentalCoilApi::class) @RunWith(RobolectricTestRunner::class) class PetDetailUiTest { @get:Rule val composeTestRule = createComposeRule() @get:Rule val coilRule = CoilRule(R.drawable.dog2) // TODO this seems like not the greatest test pattern, maybe something we can offer better // solutions for via semantics. private var carouselScreen: PetPhotoCarouselScreen? = null private val circuit = Circuit.Builder() .setOnUnavailableContent { screen, modifier -> when (screen) { is PetPhotoCarouselScreen -> { PetPhotoCarousel(PetPhotoCarouselScreen.State(screen), modifier) carouselScreen = screen } } } .build() @Test fun petDetail_show_progress_indicator_for_loading_state() { composeTestRule.run { setContent { CircuitCompositionLocals(circuit) { PetDetail(PetDetailScreen.State.Loading) } } onNodeWithTag(PROGRESS_TAG).assertIsDisplayed() onNodeWithTag(UNKNOWN_ANIMAL_TAG).assertDoesNotExist() onNodeWithTag(ANIMAL_CONTAINER_TAG).assertDoesNotExist() } } @Test fun petDetail_show_message_for_unknown_animal_state() { composeTestRule.run { setContent { CircuitCompositionLocals(circuit) { PetDetail(PetDetailScreen.State.UnknownAnimal) } } onNodeWithTag(PROGRESS_TAG).assertDoesNotExist() onNodeWithTag(ANIMAL_CONTAINER_TAG).assertDoesNotExist() onNodeWithTag(UNKNOWN_ANIMAL_TAG) .assertIsDisplayed() .assertTextEquals( InstrumentationRegistry.getInstrumentation() .targetContext .getString(R.string.unknown_animals) ) } } @Test fun petDetail_show_animal_for_success_state() { val success = PetDetailScreen.State.Success( url = "url", photoUrls = persistentListOf("http://some.url"), photoUrlMemoryCacheKey = null, name = "Baxter", description = "Grumpy looking Australian Terrier", tags = persistentListOf("dog", "terrier", "male"), eventSink = {} ) val expectedScreen = PetPhotoCarouselScreen( name = success.name, photoUrls = success.photoUrls, photoUrlMemoryCacheKey = null ) composeTestRule.run { setContent { CircuitCompositionLocals(circuit) { ContentWithOverlays { PetDetail(success) } } } onNodeWithTag(PROGRESS_TAG).assertDoesNotExist() onNodeWithTag(UNKNOWN_ANIMAL_TAG).assertDoesNotExist() onNodeWithTag(CAROUSEL_TAG).assertIsDisplayed().performTouchInput { swipeUp() } onNodeWithText(success.name).assertIsDisplayed() onNodeWithText(success.description).assertIsDisplayed() assertThat(carouselScreen).run { isNotNull() isEqualTo(expectedScreen) } } } @Test fun petDetail_emits_event_when_tapping_on_full_bio_button() = runTest { val testSink = TestEventSink<PetDetailScreen.Event>() val success = PetDetailScreen.State.Success( url = "url", photoUrls = persistentListOf("http://some.url"), photoUrlMemoryCacheKey = null, name = "Baxter", description = "Grumpy looking Australian Terrier", tags = persistentListOf("dog", "terrier", "male"), eventSink = testSink ) val circuit = Circuit.Builder() .setOnUnavailableContent { screen, modifier -> PetPhotoCarousel(PetPhotoCarouselScreen.State(screen as PetPhotoCarouselScreen), modifier) } .build() composeTestRule.run { setContent { CircuitCompositionLocals(circuit) { ContentWithOverlays { PetDetail(success) } } } onNodeWithTag(CAROUSEL_TAG).assertIsDisplayed().performTouchInput { swipeUp() } onNodeWithTag(FULL_BIO_TAG, true).assertIsDisplayed().performClick() testSink.assertEvent(PetDetailScreen.Event.ViewFullBio(success.url)) } } }
28
null
38
997
ba829880215a7ee0d8f70f86a8aa4278d0207827
5,508
circuit
Apache License 2.0
api/src/main/java/com/vk/sdk/api/messages/MessagesService.kt
VKCOM
16,025,583
false
null
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.messages import com.google.gson.reflect.TypeToken import com.vk.api.sdk.requests.VKRequest import com.vk.sdk.api.GsonHolder import com.vk.sdk.api.NewApiRequest import com.vk.sdk.api.base.dto.BaseBoolInt import com.vk.sdk.api.base.dto.BaseOkResponse import com.vk.sdk.api.base.dto.BaseUserGroupFields import com.vk.sdk.api.messages.dto.FilterParam import com.vk.sdk.api.messages.dto.IntentParam import com.vk.sdk.api.messages.dto.MediaTypeParam import com.vk.sdk.api.messages.dto.MessagesDeleteChatPhotoResponse import com.vk.sdk.api.messages.dto.MessagesDeleteConversationResponse import com.vk.sdk.api.messages.dto.MessagesGetByConversationMessageIdResponse import com.vk.sdk.api.messages.dto.MessagesGetByIdExtendedResponse import com.vk.sdk.api.messages.dto.MessagesGetByIdResponse import com.vk.sdk.api.messages.dto.MessagesGetChatPreviewResponse import com.vk.sdk.api.messages.dto.MessagesGetConversationMembersResponse import com.vk.sdk.api.messages.dto.MessagesGetConversationsByIdExtendedResponse import com.vk.sdk.api.messages.dto.MessagesGetConversationsByIdResponse import com.vk.sdk.api.messages.dto.MessagesGetConversationsResponse import com.vk.sdk.api.messages.dto.MessagesGetHistoryAttachmentsResponse import com.vk.sdk.api.messages.dto.MessagesGetHistoryExtendedResponse import com.vk.sdk.api.messages.dto.MessagesGetHistoryResponse import com.vk.sdk.api.messages.dto.MessagesGetImportantMessagesExtendedResponse import com.vk.sdk.api.messages.dto.MessagesGetImportantMessagesResponse import com.vk.sdk.api.messages.dto.MessagesGetIntentUsersResponse import com.vk.sdk.api.messages.dto.MessagesGetInviteLinkResponse import com.vk.sdk.api.messages.dto.MessagesGetLongPollHistoryResponse import com.vk.sdk.api.messages.dto.MessagesIsMessagesFromGroupAllowedResponse import com.vk.sdk.api.messages.dto.MessagesJoinChatByInviteLinkResponse import com.vk.sdk.api.messages.dto.MessagesLastActivity import com.vk.sdk.api.messages.dto.MessagesLongpollParams import com.vk.sdk.api.messages.dto.MessagesPinnedMessage import com.vk.sdk.api.messages.dto.MessagesSearchConversationsExtendedResponse import com.vk.sdk.api.messages.dto.MessagesSearchConversationsResponse import com.vk.sdk.api.messages.dto.MessagesSearchExtendedResponse import com.vk.sdk.api.messages.dto.MessagesSearchResponse import com.vk.sdk.api.messages.dto.MessagesSetChatPhotoResponse import com.vk.sdk.api.messages.dto.RevParam import com.vk.sdk.api.messages.dto.TypeParam import com.vk.sdk.api.users.dto.UsersFields import kotlin.Any import kotlin.Boolean import kotlin.Float import kotlin.Int import kotlin.String import kotlin.collections.List class MessagesService { /** * Adds a new user to a chat. * * @param chatId - Chat ID. * @param userId - ID of the user to be added to the chat. * @param visibleMessagesCount * @return [VKRequest] with [BaseOkResponse] */ fun messagesAddChatUser( chatId: Int, userId: Int? = null, visibleMessagesCount: Int? = null ): VKRequest<BaseOkResponse> = NewApiRequest("messages.addChatUser") { GsonHolder.gson.fromJson(it, BaseOkResponse::class.java) } .apply { addParam("chat_id", chatId) userId?.let { addParam("user_id", it) } visibleMessagesCount?.let { addParam("visible_messages_count", it) } } /** * Allows sending messages from community to the current user. * * @param groupId - Group ID. * @param key * @return [VKRequest] with [BaseOkResponse] */ fun messagesAllowMessagesFromGroup(groupId: Int, key: String? = null): VKRequest<BaseOkResponse> = NewApiRequest("messages.allowMessagesFromGroup") { GsonHolder.gson.fromJson(it, BaseOkResponse::class.java) } .apply { addParam("group_id", groupId) key?.let { addParam("key", it) } } /** * Creates a chat with several participants. * * @param userIds - IDs of the users to be added to the chat. * @param title - Chat title. * @param groupId * @return [VKRequest] with [Int] */ fun messagesCreateChat( userIds: List<Int>? = null, title: String? = null, groupId: Int? = null ): VKRequest<Int> = NewApiRequest("messages.createChat") { GsonHolder.gson.fromJson(it, Int::class.java) } .apply { userIds?.let { addParam("user_ids", it) } title?.let { addParam("title", it) } groupId?.let { addParam("group_id", it) } } /** * Deletes one or more messages. * * @param messageIds - Message IDs. * @param spam - '1' - to mark message as spam. * @param groupId - Group ID (for group messages with user access token) * @param deleteForAll - '1' - delete message for for all. * @return [VKRequest] with [Any] */ fun messagesDelete( messageIds: List<Int>? = null, spam: Boolean? = null, groupId: Int? = null, deleteForAll: Boolean? = null ): VKRequest<Any> = NewApiRequest("messages.delete") { GsonHolder.gson.fromJson(it, Any::class.java) } .apply { messageIds?.let { addParam("message_ids", it) } spam?.let { addParam("spam", it) } groupId?.let { addParam("group_id", it) } deleteForAll?.let { addParam("delete_for_all", it) } } /** * Deletes a chat's cover picture. * * @param chatId - Chat ID. * @param groupId * @return [VKRequest] with [MessagesDeleteChatPhotoResponse] */ fun messagesDeleteChatPhoto(chatId: Int, groupId: Int? = null): VKRequest<MessagesDeleteChatPhotoResponse> = NewApiRequest("messages.deleteChatPhoto") { GsonHolder.gson.fromJson(it, MessagesDeleteChatPhotoResponse::class.java) } .apply { addParam("chat_id", chatId) groupId?.let { addParam("group_id", it) } } /** * Deletes all private messages in a conversation. * * @param userId - User ID. To clear a chat history use 'chat_id' * @param peerId - Destination ID. "For user: 'User ID', e.g. '12345'. For chat: '2000000000' + * 'chat_id', e.g. '2000000001'. For community: '- community ID', e.g. '-12345'. " * @param groupId - Group ID (for group messages with user access token) * @return [VKRequest] with [MessagesDeleteConversationResponse] */ fun messagesDeleteConversation( userId: Int? = null, peerId: Int? = null, groupId: Int? = null ): VKRequest<MessagesDeleteConversationResponse> = NewApiRequest("messages.deleteConversation") { GsonHolder.gson.fromJson(it, MessagesDeleteConversationResponse::class.java) } .apply { userId?.let { addParam("user_id", it) } peerId?.let { addParam("peer_id", it) } groupId?.let { addParam("group_id", it) } } /** * Denies sending message from community to the current user. * * @param groupId - Group ID. * @return [VKRequest] with [BaseOkResponse] */ fun messagesDenyMessagesFromGroup(groupId: Int): VKRequest<BaseOkResponse> = NewApiRequest("messages.denyMessagesFromGroup") { GsonHolder.gson.fromJson(it, BaseOkResponse::class.java) } .apply { addParam("group_id", groupId) } /** * Edits the message. * * @param peerId - Destination ID. "For user: 'User ID', e.g. '12345'. For chat: '2000000000' + * 'chat_id', e.g. '2000000001'. For community: '- community ID', e.g. '-12345'. " * @param message - (Required if 'attachments' is not set.) Text of the message. * @param lat - Geographical latitude of a check-in, in degrees (from -90 to 90). * @param long - Geographical longitude of a check-in, in degrees (from -180 to 180). * @param attachment - (Required if 'message' is not set.) List of objects attached to the * message, separated by commas, in the following format: "<owner_id>_<media_id>", '' - Type of * media attachment: 'photo' - photo, 'video' - video, 'audio' - audio, 'doc' - document, 'wall' - * wall post, '<owner_id>' - ID of the media attachment owner. '<media_id>' - media attachment ID. * Example: "photo100172_166443618" * @param keepForwardMessages - '1' - to keep forwarded, messages. * @param keepSnippets - '1' - to keep attached snippets. * @param groupId - Group ID (for group messages with user access token) * @param dontParseLinks * @param messageId * @param conversationMessageId * @param template * @param keyboard * @return [VKRequest] with [BaseBoolInt] */ fun messagesEdit( peerId: Int, message: String? = null, lat: Float? = null, long: Float? = null, attachment: String? = null, keepForwardMessages: Boolean? = null, keepSnippets: Boolean? = null, groupId: Int? = null, dontParseLinks: Boolean? = null, messageId: Int? = null, conversationMessageId: Int? = null, template: String? = null, keyboard: String? = null ): VKRequest<BaseBoolInt> = NewApiRequest("messages.edit") { GsonHolder.gson.fromJson(it, BaseBoolInt::class.java) } .apply { addParam("peer_id", peerId) message?.let { addParam("message", it) } lat?.let { addParam("lat", it) } long?.let { addParam("long", it) } attachment?.let { addParam("attachment", it) } keepForwardMessages?.let { addParam("keep_forward_messages", it) } keepSnippets?.let { addParam("keep_snippets", it) } groupId?.let { addParam("group_id", it) } dontParseLinks?.let { addParam("dont_parse_links", it) } messageId?.let { addParam("message_id", it) } conversationMessageId?.let { addParam("conversation_message_id", it) } template?.let { addParam("template", it) } keyboard?.let { addParam("keyboard", it) } } /** * Edits the title of a chat. * * @param chatId - Chat ID. * @param title - New title of the chat. * @return [VKRequest] with [BaseOkResponse] */ fun messagesEditChat(chatId: Int, title: String? = null): VKRequest<BaseOkResponse> = NewApiRequest("messages.editChat") { GsonHolder.gson.fromJson(it, BaseOkResponse::class.java) } .apply { addParam("chat_id", chatId) title?.let { addParam("title", it) } } /** * Returns messages by their IDs within the conversation. * * @param peerId - Destination ID. "For user: 'User ID', e.g. '12345'. For chat: '2000000000' + * 'chat_id', e.g. '2000000001'. For community: '- community ID', e.g. '-12345'. " * @param conversationMessageIds - Conversation message IDs. * @param fields - Profile fields to return. * @param groupId - Group ID (for group messages with group access token) * @return [VKRequest] with [MessagesGetByConversationMessageIdResponse] */ fun messagesGetByConversationMessageId( peerId: Int, conversationMessageIds: List<Int>, fields: List<UsersFields>? = null, groupId: Int? = null ): VKRequest<MessagesGetByConversationMessageIdResponse> = NewApiRequest("messages.getByConversationMessageId") { GsonHolder.gson.fromJson(it, MessagesGetByConversationMessageIdResponse::class.java) } .apply { addParam("peer_id", peerId) addParam("conversation_message_ids", conversationMessageIds) val fieldsJsonConverted = fields?.map { it.value } fieldsJsonConverted?.let { addParam("fields", it) } groupId?.let { addParam("group_id", it) } } /** * Returns messages by their IDs. * * @param messageIds - Message IDs. * @param previewLength - Number of characters after which to truncate a previewed message. To * preview the full message, specify '0'. "NOTE: Messages are not truncated by default. Messages * are truncated by words." * @param fields - Profile fields to return. * @param groupId - Group ID (for group messages with group access token) * @return [VKRequest] with [MessagesGetByIdResponse] */ fun messagesGetById( messageIds: List<Int>, previewLength: Int? = null, fields: List<UsersFields>? = null, groupId: Int? = null ): VKRequest<MessagesGetByIdResponse> = NewApiRequest("messages.getById") { GsonHolder.gson.fromJson(it, MessagesGetByIdResponse::class.java) } .apply { addParam("message_ids", messageIds) previewLength?.let { addParam("preview_length", it) } val fieldsJsonConverted = fields?.map { it.value } fieldsJsonConverted?.let { addParam("fields", it) } groupId?.let { addParam("group_id", it) } } /** * Returns messages by their IDs. * * @param messageIds - Message IDs. * @param previewLength - Number of characters after which to truncate a previewed message. To * preview the full message, specify '0'. "NOTE: Messages are not truncated by default. Messages * are truncated by words." * @param fields - Profile fields to return. * @param groupId - Group ID (for group messages with group access token) * @return [VKRequest] with [MessagesGetByIdExtendedResponse] */ fun messagesGetByIdExtended( messageIds: List<Int>, previewLength: Int? = null, fields: List<UsersFields>? = null, groupId: Int? = null ): VKRequest<MessagesGetByIdExtendedResponse> = NewApiRequest("messages.getById") { GsonHolder.gson.fromJson(it, MessagesGetByIdExtendedResponse::class.java) } .apply { addParam("message_ids", messageIds) previewLength?.let { addParam("preview_length", it) } addParam("extended", true) val fieldsJsonConverted = fields?.map { it.value } fieldsJsonConverted?.let { addParam("fields", it) } groupId?.let { addParam("group_id", it) } } /** * @param peerId * @param link - Invitation link. * @param fields - Profile fields to return. * @return [VKRequest] with [MessagesGetChatPreviewResponse] */ fun messagesGetChatPreview( peerId: Int? = null, link: String? = null, fields: List<UsersFields>? = null ): VKRequest<MessagesGetChatPreviewResponse> = NewApiRequest("messages.getChatPreview") { GsonHolder.gson.fromJson(it, MessagesGetChatPreviewResponse::class.java) } .apply { peerId?.let { addParam("peer_id", it) } link?.let { addParam("link", it) } val fieldsJsonConverted = fields?.map { it.value } fieldsJsonConverted?.let { addParam("fields", it) } } /** * Returns a list of IDs of users participating in a chat. * * @param peerId - Peer ID. * @param offset - Offset * @param count - Count * @param fields - Profile fields to return. * @param groupId - Group ID (for group messages with group access token) * @return [VKRequest] with [MessagesGetConversationMembersResponse] */ fun messagesGetConversationMembers( peerId: Int, offset: Int? = null, count: Int? = null, fields: List<UsersFields>? = null, groupId: Int? = null ): VKRequest<MessagesGetConversationMembersResponse> = NewApiRequest("messages.getConversationMembers") { GsonHolder.gson.fromJson(it, MessagesGetConversationMembersResponse::class.java) } .apply { addParam("peer_id", peerId) offset?.let { addParam("offset", it) } count?.let { addParam("count", it) } val fieldsJsonConverted = fields?.map { it.value } fieldsJsonConverted?.let { addParam("fields", it) } groupId?.let { addParam("group_id", it) } } /** * Returns a list of the current user's conversations. * * @param offset - Offset needed to return a specific subset of conversations. * @param count - Number of conversations to return. * @param filter - Filter to apply: 'all' - all conversations, 'unread' - conversations with * unread messages, 'important' - conversations, marked as important (only for community messages), * 'unanswered' - conversations, marked as unanswered (only for community messages) * @param startMessageId - ID of the message from what to return dialogs. * @param fields - Profile and communities fields to return. * @param groupId - Group ID (for group messages with group access token) * @return [VKRequest] with [MessagesGetConversationsResponse] */ fun messagesGetConversations( offset: Int? = null, count: Int? = null, filter: FilterParam? = null, startMessageId: Int? = null, fields: List<BaseUserGroupFields>? = null, groupId: Int? = null ): VKRequest<MessagesGetConversationsResponse> = NewApiRequest("messages.getConversations") { GsonHolder.gson.fromJson(it, MessagesGetConversationsResponse::class.java) } .apply { offset?.let { addParam("offset", it) } count?.let { addParam("count", it) } filter?.let { addParam("filter", it.value) } startMessageId?.let { addParam("start_message_id", it) } val fieldsJsonConverted = fields?.map { it.value } fieldsJsonConverted?.let { addParam("fields", it) } groupId?.let { addParam("group_id", it) } } /** * Returns conversations by their IDs * * @param peerIds - Destination IDs. "For user: 'User ID', e.g. '12345'. For chat: * '2000000000' + 'chat_id', e.g. '2000000001'. For community: '- community ID', e.g. '-12345'. " * @param fields - Profile and communities fields to return. * @param groupId - Group ID (for group messages with group access token) * @return [VKRequest] with [MessagesGetConversationsByIdResponse] */ fun messagesGetConversationsById( peerIds: List<Int>, fields: List<BaseUserGroupFields>? = null, groupId: Int? = null ): VKRequest<MessagesGetConversationsByIdResponse> = NewApiRequest("messages.getConversationsById") { GsonHolder.gson.fromJson(it, MessagesGetConversationsByIdResponse::class.java) } .apply { addParam("peer_ids", peerIds) val fieldsJsonConverted = fields?.map { it.value } fieldsJsonConverted?.let { addParam("fields", it) } groupId?.let { addParam("group_id", it) } } /** * Returns conversations by their IDs * * @param peerIds - Destination IDs. "For user: 'User ID', e.g. '12345'. For chat: * '2000000000' + 'chat_id', e.g. '2000000001'. For community: '- community ID', e.g. '-12345'. " * @param fields - Profile and communities fields to return. * @param groupId - Group ID (for group messages with group access token) * @return [VKRequest] with [MessagesGetConversationsByIdExtendedResponse] */ fun messagesGetConversationsByIdExtended( peerIds: List<Int>, fields: List<BaseUserGroupFields>? = null, groupId: Int? = null ): VKRequest<MessagesGetConversationsByIdExtendedResponse> = NewApiRequest("messages.getConversationsById") { GsonHolder.gson.fromJson(it, MessagesGetConversationsByIdExtendedResponse::class.java) } .apply { addParam("peer_ids", peerIds) addParam("extended", true) val fieldsJsonConverted = fields?.map { it.value } fieldsJsonConverted?.let { addParam("fields", it) } groupId?.let { addParam("group_id", it) } } /** * Returns message history for the specified user or group chat. * * @param offset - Offset needed to return a specific subset of messages. * @param count - Number of messages to return. * @param userId - ID of the user whose message history you want to return. * @param peerId * @param startMessageId - Starting message ID from which to return history. * @param rev - Sort order: '1' - return messages in chronological order. '0' - return messages * in reverse chronological order. * @param fields - Profile fields to return. * @param groupId - Group ID (for group messages with group access token) * @return [VKRequest] with [MessagesGetHistoryResponse] */ fun messagesGetHistory( offset: Int? = null, count: Int? = null, userId: Int? = null, peerId: Int? = null, startMessageId: Int? = null, rev: RevParam? = null, fields: List<UsersFields>? = null, groupId: Int? = null ): VKRequest<MessagesGetHistoryResponse> = NewApiRequest("messages.getHistory") { GsonHolder.gson.fromJson(it, MessagesGetHistoryResponse::class.java) } .apply { offset?.let { addParam("offset", it) } count?.let { addParam("count", it) } userId?.let { addParam("user_id", it) } peerId?.let { addParam("peer_id", it) } startMessageId?.let { addParam("start_message_id", it) } rev?.let { addParam("rev", it.value) } val fieldsJsonConverted = fields?.map { it.value } fieldsJsonConverted?.let { addParam("fields", it) } groupId?.let { addParam("group_id", it) } } /** * Returns message history for the specified user or group chat. * * @param offset - Offset needed to return a specific subset of messages. * @param count - Number of messages to return. * @param userId - ID of the user whose message history you want to return. * @param peerId * @param startMessageId - Starting message ID from which to return history. * @param rev - Sort order: '1' - return messages in chronological order. '0' - return messages * in reverse chronological order. * @param fields - Profile fields to return. * @param groupId - Group ID (for group messages with group access token) * @return [VKRequest] with [MessagesGetHistoryExtendedResponse] */ fun messagesGetHistoryExtended( offset: Int? = null, count: Int? = null, userId: Int? = null, peerId: Int? = null, startMessageId: Int? = null, rev: RevParam? = null, fields: List<UsersFields>? = null, groupId: Int? = null ): VKRequest<MessagesGetHistoryExtendedResponse> = NewApiRequest("messages.getHistory") { GsonHolder.gson.fromJson(it, MessagesGetHistoryExtendedResponse::class.java) } .apply { offset?.let { addParam("offset", it) } count?.let { addParam("count", it) } userId?.let { addParam("user_id", it) } peerId?.let { addParam("peer_id", it) } startMessageId?.let { addParam("start_message_id", it) } rev?.let { addParam("rev", it.value) } addParam("extended", true) val fieldsJsonConverted = fields?.map { it.value } fieldsJsonConverted?.let { addParam("fields", it) } groupId?.let { addParam("group_id", it) } } /** * Returns media files from the dialog or group chat. * * @param peerId - Peer ID. ", For group chat: '2000000000 + chat ID' , , For community: * '-community ID'" * @param mediaType - Type of media files to return: *'photo',, *'video',, *'audio',, *'doc',, * *'link'.,*'market'.,*'wall'.,*'share' * @param startFrom - Message ID to start return results from. * @param count - Number of objects to return. * @param photoSizes - '1' - to return photo sizes in a * @param fields - Additional profile [vk.com/dev/fields|fields] to return. * @param groupId - Group ID (for group messages with group access token) * @param preserveOrder * @param maxForwardsLevel * @return [VKRequest] with [MessagesGetHistoryAttachmentsResponse] */ fun messagesGetHistoryAttachments( peerId: Int, mediaType: MediaTypeParam? = null, startFrom: String? = null, count: Int? = null, photoSizes: Boolean? = null, fields: List<UsersFields>? = null, groupId: Int? = null, preserveOrder: Boolean? = null, maxForwardsLevel: Int? = null ): VKRequest<MessagesGetHistoryAttachmentsResponse> = NewApiRequest("messages.getHistoryAttachments") { GsonHolder.gson.fromJson(it, MessagesGetHistoryAttachmentsResponse::class.java) } .apply { addParam("peer_id", peerId) mediaType?.let { addParam("media_type", it.value) } startFrom?.let { addParam("start_from", it) } count?.let { addParam("count", it) } photoSizes?.let { addParam("photo_sizes", it) } val fieldsJsonConverted = fields?.map { it.value } fieldsJsonConverted?.let { addParam("fields", it) } groupId?.let { addParam("group_id", it) } preserveOrder?.let { addParam("preserve_order", it) } maxForwardsLevel?.let { addParam("max_forwards_level", it) } } /** * Returns a list of user's important messages. * * @param count - Amount of needed important messages. * @param offset * @param startMessageId * @param previewLength - Maximum length of messages body. * @param fields - Actors fields to return. * @param groupId - Group ID (for group messages with group access token) * @return [VKRequest] with [MessagesGetImportantMessagesResponse] */ fun messagesGetImportantMessages( count: Int? = null, offset: Int? = null, startMessageId: Int? = null, previewLength: Int? = null, fields: List<BaseUserGroupFields>? = null, groupId: Int? = null ): VKRequest<MessagesGetImportantMessagesResponse> = NewApiRequest("messages.getImportantMessages") { GsonHolder.gson.fromJson(it, MessagesGetImportantMessagesResponse::class.java) } .apply { count?.let { addParam("count", it) } offset?.let { addParam("offset", it) } startMessageId?.let { addParam("start_message_id", it) } previewLength?.let { addParam("preview_length", it) } val fieldsJsonConverted = fields?.map { it.value } fieldsJsonConverted?.let { addParam("fields", it) } groupId?.let { addParam("group_id", it) } } /** * Returns a list of user's important messages. * * @param count - Amount of needed important messages. * @param offset * @param startMessageId * @param previewLength - Maximum length of messages body. * @param fields - Actors fields to return. * @param groupId - Group ID (for group messages with group access token) * @return [VKRequest] with [MessagesGetImportantMessagesExtendedResponse] */ fun messagesGetImportantMessagesExtended( count: Int? = null, offset: Int? = null, startMessageId: Int? = null, previewLength: Int? = null, fields: List<BaseUserGroupFields>? = null, groupId: Int? = null ): VKRequest<MessagesGetImportantMessagesExtendedResponse> = NewApiRequest("messages.getImportantMessages") { GsonHolder.gson.fromJson(it, MessagesGetImportantMessagesExtendedResponse::class.java) } .apply { count?.let { addParam("count", it) } offset?.let { addParam("offset", it) } startMessageId?.let { addParam("start_message_id", it) } previewLength?.let { addParam("preview_length", it) } val fieldsJsonConverted = fields?.map { it.value } fieldsJsonConverted?.let { addParam("fields", it) } addParam("extended", true) groupId?.let { addParam("group_id", it) } } /** * @param intent * @param subscribeId * @param offset * @param count * @param nameCase * @param fields * @return [VKRequest] with [MessagesGetIntentUsersResponse] */ fun messagesGetIntentUsers( intent: IntentParam, subscribeId: Int? = null, offset: Int? = null, count: Int? = null, nameCase: List<String>? = null, fields: List<String>? = null ): VKRequest<MessagesGetIntentUsersResponse> = NewApiRequest("messages.getIntentUsers") { GsonHolder.gson.fromJson(it, MessagesGetIntentUsersResponse::class.java) } .apply { addParam("intent", intent.value) subscribeId?.let { addParam("subscribe_id", it) } offset?.let { addParam("offset", it) } count?.let { addParam("count", it) } nameCase?.let { addParam("name_case", it) } fields?.let { addParam("fields", it) } } /** * @param peerId - Destination ID. * @param reset - 1 - to generate new link (revoke previous), 0 - to return previous link. * @param groupId - Group ID * @return [VKRequest] with [MessagesGetInviteLinkResponse] */ fun messagesGetInviteLink( peerId: Int, reset: Boolean? = null, groupId: Int? = null ): VKRequest<MessagesGetInviteLinkResponse> = NewApiRequest("messages.getInviteLink") { GsonHolder.gson.fromJson(it, MessagesGetInviteLinkResponse::class.java) } .apply { addParam("peer_id", peerId) reset?.let { addParam("reset", it) } groupId?.let { addParam("group_id", it) } } /** * Returns a user's current status and date of last activity. * * @param userId - User ID. * @return [VKRequest] with [MessagesLastActivity] */ fun messagesGetLastActivity(userId: Int): VKRequest<MessagesLastActivity> = NewApiRequest("messages.getLastActivity") { GsonHolder.gson.fromJson(it, MessagesLastActivity::class.java) } .apply { addParam("user_id", userId) } /** * Returns updates in user's private messages. * * @param ts - Last value of the 'ts' parameter returned from the Long Poll server or by using * [vk.com/dev/messages.getLongPollHistory|messages.getLongPollHistory] method. * @param pts - Lsat value of 'pts' parameter returned from the Long Poll server or by using * [vk.com/dev/messages.getLongPollHistory|messages.getLongPollHistory] method. * @param previewLength - Number of characters after which to truncate a previewed message. To * preview the full message, specify '0'. "NOTE: Messages are not truncated by default. Messages * are truncated by words." * @param onlines - '1' - to return history with online users only. * @param fields - Additional profile [vk.com/dev/fields|fields] to return. * @param eventsLimit - Maximum number of events to return. * @param msgsLimit - Maximum number of messages to return. * @param maxMsgId - Maximum ID of the message among existing ones in the local copy. Both * messages received with API methods (for example, , ), and data received from a Long Poll server * (events with code 4) are taken into account. * @param groupId - Group ID (for group messages with user access token) * @param lpVersion * @param lastN * @param credentials * @return [VKRequest] with [MessagesGetLongPollHistoryResponse] */ fun messagesGetLongPollHistory( ts: Int? = null, pts: Int? = null, previewLength: Int? = null, onlines: Boolean? = null, fields: List<UsersFields>? = null, eventsLimit: Int? = null, msgsLimit: Int? = null, maxMsgId: Int? = null, groupId: Int? = null, lpVersion: Int? = null, lastN: Int? = null, credentials: Boolean? = null ): VKRequest<MessagesGetLongPollHistoryResponse> = NewApiRequest("messages.getLongPollHistory") { GsonHolder.gson.fromJson(it, MessagesGetLongPollHistoryResponse::class.java) } .apply { ts?.let { addParam("ts", it) } pts?.let { addParam("pts", it) } previewLength?.let { addParam("preview_length", it) } onlines?.let { addParam("onlines", it) } val fieldsJsonConverted = fields?.map { it.value } fieldsJsonConverted?.let { addParam("fields", it) } eventsLimit?.let { addParam("events_limit", it) } msgsLimit?.let { addParam("msgs_limit", it) } maxMsgId?.let { addParam("max_msg_id", it) } groupId?.let { addParam("group_id", it) } lpVersion?.let { addParam("lp_version", it) } lastN?.let { addParam("last_n", it) } credentials?.let { addParam("credentials", it) } } /** * Returns data required for connection to a Long Poll server. * * @param needPts - '1' - to return the 'pts' field, needed for the * [vk.com/dev/messages.getLongPollHistory|messages.getLongPollHistory] method. * @param groupId - Group ID (for group messages with user access token) * @param lpVersion - Long poll version * @return [VKRequest] with [MessagesLongpollParams] */ fun messagesGetLongPollServer( needPts: Boolean? = null, groupId: Int? = null, lpVersion: Int? = null ): VKRequest<MessagesLongpollParams> = NewApiRequest("messages.getLongPollServer") { GsonHolder.gson.fromJson(it, MessagesLongpollParams::class.java) } .apply { needPts?.let { addParam("need_pts", it) } groupId?.let { addParam("group_id", it) } lpVersion?.let { addParam("lp_version", it) } } /** * Returns information whether sending messages from the community to current user is allowed. * * @param groupId - Group ID. * @param userId - User ID. * @return [VKRequest] with [MessagesIsMessagesFromGroupAllowedResponse] */ fun messagesIsMessagesFromGroupAllowed(groupId: Int, userId: Int): VKRequest<MessagesIsMessagesFromGroupAllowedResponse> = NewApiRequest("messages.isMessagesFromGroupAllowed") { GsonHolder.gson.fromJson(it, MessagesIsMessagesFromGroupAllowedResponse::class.java) } .apply { addParam("group_id", groupId) addParam("user_id", userId) } /** * @param link - Invitation link. * @return [VKRequest] with [MessagesJoinChatByInviteLinkResponse] */ fun messagesJoinChatByInviteLink(link: String): VKRequest<MessagesJoinChatByInviteLinkResponse> = NewApiRequest("messages.joinChatByInviteLink") { GsonHolder.gson.fromJson(it, MessagesJoinChatByInviteLinkResponse::class.java) } .apply { addParam("link", link) } /** * Marks and unmarks conversations as unanswered. * * @param peerId - ID of conversation to mark as important. * @param answered - '1' - to mark as answered, '0' - to remove the mark * @param groupId - Group ID (for group messages with group access token) * @return [VKRequest] with [BaseOkResponse] */ fun messagesMarkAsAnsweredConversation( peerId: Int, answered: Boolean? = null, groupId: Int? = null ): VKRequest<BaseOkResponse> = NewApiRequest("messages.markAsAnsweredConversation") { GsonHolder.gson.fromJson(it, BaseOkResponse::class.java) } .apply { addParam("peer_id", peerId) answered?.let { addParam("answered", it) } groupId?.let { addParam("group_id", it) } } /** * Marks and unmarks messages as important (starred). * * @param messageIds - IDs of messages to mark as important. * @param important - '1' - to add a star (mark as important), '0' - to remove the star * @return [VKRequest] with [Unit] */ fun messagesMarkAsImportant(messageIds: List<Int>? = null, important: Int? = null): VKRequest<List<Int>> = NewApiRequest("messages.markAsImportant") { val typeToken = object: TypeToken<List<Int>>() {}.type GsonHolder.gson.fromJson<List<Int>>(it, typeToken) } .apply { messageIds?.let { addParam("message_ids", it) } important?.let { addParam("important", it) } } /** * Marks and unmarks conversations as important. * * @param peerId - ID of conversation to mark as important. * @param important - '1' - to add a star (mark as important), '0' - to remove the star * @param groupId - Group ID (for group messages with group access token) * @return [VKRequest] with [BaseOkResponse] */ fun messagesMarkAsImportantConversation( peerId: Int, important: Boolean? = null, groupId: Int? = null ): VKRequest<BaseOkResponse> = NewApiRequest("messages.markAsImportantConversation") { GsonHolder.gson.fromJson(it, BaseOkResponse::class.java) } .apply { addParam("peer_id", peerId) important?.let { addParam("important", it) } groupId?.let { addParam("group_id", it) } } /** * Marks messages as read. * * @param messageIds - IDs of messages to mark as read. * @param peerId - Destination ID. "For user: 'User ID', e.g. '12345'. For chat: '2000000000' + * 'chat_id', e.g. '2000000001'. For community: '- community ID', e.g. '-12345'. " * @param startMessageId - Message ID to start from. * @param groupId - Group ID (for group messages with user access token) * @param markConversationAsRead * @return [VKRequest] with [BaseOkResponse] */ fun messagesMarkAsRead( messageIds: List<Int>? = null, peerId: Int? = null, startMessageId: Int? = null, groupId: Int? = null, markConversationAsRead: Boolean? = null ): VKRequest<BaseOkResponse> = NewApiRequest("messages.markAsRead") { GsonHolder.gson.fromJson(it, BaseOkResponse::class.java) } .apply { messageIds?.let { addParam("message_ids", it) } peerId?.let { addParam("peer_id", it) } startMessageId?.let { addParam("start_message_id", it) } groupId?.let { addParam("group_id", it) } markConversationAsRead?.let { addParam("mark_conversation_as_read", it) } } /** * Pin a message. * * @param peerId - Destination ID. "For user: 'User ID', e.g. '12345'. For chat: '2000000000' + * 'Chat ID', e.g. '2000000001'. For community: '- Community ID', e.g. '-12345'. " * @param messageId - Message ID * @param conversationMessageId - Conversation message ID * @return [VKRequest] with [MessagesPinnedMessage] */ fun messagesPin( peerId: Int, messageId: Int? = null, conversationMessageId: Int? = null ): VKRequest<MessagesPinnedMessage> = NewApiRequest("messages.pin") { GsonHolder.gson.fromJson(it, MessagesPinnedMessage::class.java) } .apply { addParam("peer_id", peerId) messageId?.let { addParam("message_id", it) } conversationMessageId?.let { addParam("conversation_message_id", it) } } /** * Allows the current user to leave a chat or, if the current user started the chat, allows the * user to remove another user from the chat. * * @param chatId - Chat ID. * @param userId - ID of the user to be removed from the chat. * @param memberId * @return [VKRequest] with [BaseOkResponse] */ fun messagesRemoveChatUser( chatId: Int, userId: Int? = null, memberId: Int? = null ): VKRequest<BaseOkResponse> = NewApiRequest("messages.removeChatUser") { GsonHolder.gson.fromJson(it, BaseOkResponse::class.java) } .apply { addParam("chat_id", chatId) userId?.let { addParam("user_id", it) } memberId?.let { addParam("member_id", it) } } /** * Restores a deleted message. * * @param messageId - ID of a previously-deleted message to restore. * @param groupId - Group ID (for group messages with user access token) * @return [VKRequest] with [BaseOkResponse] */ fun messagesRestore(messageId: Int, groupId: Int? = null): VKRequest<BaseOkResponse> = NewApiRequest("messages.restore") { GsonHolder.gson.fromJson(it, BaseOkResponse::class.java) } .apply { addParam("message_id", messageId) groupId?.let { addParam("group_id", it) } } /** * Returns a list of the current user's private messages that match search criteria. * * @param q - Search query string. * @param peerId - Destination ID. "For user: 'User ID', e.g. '12345'. For chat: '2000000000' + * 'chat_id', e.g. '2000000001'. For community: '- community ID', e.g. '-12345'. " * @param date - Date to search message before in Unixtime. * @param previewLength - Number of characters after which to truncate a previewed message. To * preview the full message, specify '0'. "NOTE: Messages are not truncated by default. Messages * are truncated by words." * @param offset - Offset needed to return a specific subset of messages. * @param count - Number of messages to return. * @param fields * @param groupId - Group ID (for group messages with group access token) * @return [VKRequest] with [MessagesSearchResponse] */ fun messagesSearch( q: String? = null, peerId: Int? = null, date: Int? = null, previewLength: Int? = null, offset: Int? = null, count: Int? = null, fields: List<String>? = null, groupId: Int? = null ): VKRequest<MessagesSearchResponse> = NewApiRequest("messages.search") { GsonHolder.gson.fromJson(it, MessagesSearchResponse::class.java) } .apply { q?.let { addParam("q", it) } peerId?.let { addParam("peer_id", it) } date?.let { addParam("date", it) } previewLength?.let { addParam("preview_length", it) } offset?.let { addParam("offset", it) } count?.let { addParam("count", it) } fields?.let { addParam("fields", it) } groupId?.let { addParam("group_id", it) } } /** * Returns a list of the current user's private messages that match search criteria. * * @param q - Search query string. * @param peerId - Destination ID. "For user: 'User ID', e.g. '12345'. For chat: '2000000000' + * 'chat_id', e.g. '2000000001'. For community: '- community ID', e.g. '-12345'. " * @param date - Date to search message before in Unixtime. * @param previewLength - Number of characters after which to truncate a previewed message. To * preview the full message, specify '0'. "NOTE: Messages are not truncated by default. Messages * are truncated by words." * @param offset - Offset needed to return a specific subset of messages. * @param count - Number of messages to return. * @param fields * @param groupId - Group ID (for group messages with group access token) * @return [VKRequest] with [MessagesSearchExtendedResponse] */ fun messagesSearchExtended( q: String? = null, peerId: Int? = null, date: Int? = null, previewLength: Int? = null, offset: Int? = null, count: Int? = null, fields: List<String>? = null, groupId: Int? = null ): VKRequest<MessagesSearchExtendedResponse> = NewApiRequest("messages.search") { GsonHolder.gson.fromJson(it, MessagesSearchExtendedResponse::class.java) } .apply { q?.let { addParam("q", it) } peerId?.let { addParam("peer_id", it) } date?.let { addParam("date", it) } previewLength?.let { addParam("preview_length", it) } offset?.let { addParam("offset", it) } count?.let { addParam("count", it) } addParam("extended", true) fields?.let { addParam("fields", it) } groupId?.let { addParam("group_id", it) } } /** * Returns a list of the current user's conversations that match search criteria. * * @param q - Search query string. * @param count - Maximum number of results. * @param fields - Profile fields to return. * @param groupId - Group ID (for group messages with user access token) * @return [VKRequest] with [MessagesSearchConversationsResponse] */ fun messagesSearchConversations( q: String? = null, count: Int? = null, fields: List<UsersFields>? = null, groupId: Int? = null ): VKRequest<MessagesSearchConversationsResponse> = NewApiRequest("messages.searchConversations") { GsonHolder.gson.fromJson(it, MessagesSearchConversationsResponse::class.java) } .apply { q?.let { addParam("q", it) } count?.let { addParam("count", it) } val fieldsJsonConverted = fields?.map { it.value } fieldsJsonConverted?.let { addParam("fields", it) } groupId?.let { addParam("group_id", it) } } /** * Returns a list of the current user's conversations that match search criteria. * * @param q - Search query string. * @param count - Maximum number of results. * @param fields - Profile fields to return. * @param groupId - Group ID (for group messages with user access token) * @return [VKRequest] with [MessagesSearchConversationsExtendedResponse] */ fun messagesSearchConversationsExtended( q: String? = null, count: Int? = null, fields: List<UsersFields>? = null, groupId: Int? = null ): VKRequest<MessagesSearchConversationsExtendedResponse> = NewApiRequest("messages.searchConversations") { GsonHolder.gson.fromJson(it, MessagesSearchConversationsExtendedResponse::class.java) } .apply { q?.let { addParam("q", it) } count?.let { addParam("count", it) } addParam("extended", true) val fieldsJsonConverted = fields?.map { it.value } fieldsJsonConverted?.let { addParam("fields", it) } groupId?.let { addParam("group_id", it) } } /** * Sends a message. * * @param userId - User ID (by default - current user). * @param randomId - Unique identifier to avoid resending the message. * @param peerId - Destination ID. "For user: 'User ID', e.g. '12345'. For chat: '2000000000' + * 'chat_id', e.g. '2000000001'. For community: '- community ID', e.g. '-12345'. " * @param peerIds - IDs of message recipients. (See peer_id) * @param domain - User's short address (for example, 'illarionov'). * @param chatId - ID of conversation the message will relate to. * @param userIds - IDs of message recipients (if new conversation shall be started). * @param message - (Required if 'attachments' is not set.) Text of the message. * @param lat - Geographical latitude of a check-in, in degrees (from -90 to 90). * @param long - Geographical longitude of a check-in, in degrees (from -180 to 180). * @param attachment - (Required if 'message' is not set.) List of objects attached to the * message, separated by commas, in the following format: "<owner_id>_<media_id>", '' - Type of * media attachment: 'photo' - photo, 'video' - video, 'audio' - audio, 'doc' - document, 'wall' - * wall post, '<owner_id>' - ID of the media attachment owner. '<media_id>' - media attachment ID. * Example: "photo100172_166443618" * @param replyTo * @param forwardMessages - ID of forwarded messages, separated with a comma. Listed messages of * the sender will be shown in the message body at the recipient's. Example: "123,431,544" * @param forward - JSON describing the forwarded message or reply * @param stickerId - Sticker id. * @param groupId - Group ID (for group messages with group access token) * @param keyboard * @param template * @param payload * @param contentSource - JSON describing the content source in the message * @param dontParseLinks * @param disableMentions * @param intent * @param subscribeId * @return [VKRequest] with [Int] */ fun messagesSend( userId: Int? = null, randomId: Int? = null, peerId: Int? = null, peerIds: List<Int>? = null, domain: String? = null, chatId: Int? = null, userIds: List<Int>? = null, message: String? = null, lat: Float? = null, long: Float? = null, attachment: String? = null, replyTo: Int? = null, forwardMessages: List<Int>? = null, forward: String? = null, stickerId: Int? = null, groupId: Int? = null, keyboard: String? = null, template: String? = null, payload: String? = null, contentSource: String? = null, dontParseLinks: Boolean? = null, disableMentions: Boolean? = null, intent: IntentParam? = null, subscribeId: Int? = null ): VKRequest<Int> = NewApiRequest("messages.send") { GsonHolder.gson.fromJson(it, Int::class.java) } .apply { userId?.let { addParam("user_id", it) } randomId?.let { addParam("random_id", it) } peerId?.let { addParam("peer_id", it) } peerIds?.let { addParam("peer_ids", it) } domain?.let { addParam("domain", it) } chatId?.let { addParam("chat_id", it) } userIds?.let { addParam("user_ids", it) } message?.let { addParam("message", it) } lat?.let { addParam("lat", it) } long?.let { addParam("long", it) } attachment?.let { addParam("attachment", it) } replyTo?.let { addParam("reply_to", it) } forwardMessages?.let { addParam("forward_messages", it) } forward?.let { addParam("forward", it) } stickerId?.let { addParam("sticker_id", it) } groupId?.let { addParam("group_id", it) } keyboard?.let { addParam("keyboard", it) } template?.let { addParam("template", it) } payload?.let { addParam("payload", it) } contentSource?.let { addParam("content_source", it) } dontParseLinks?.let { addParam("dont_parse_links", it) } disableMentions?.let { addParam("disable_mentions", it) } intent?.let { addParam("intent", it.value) } subscribeId?.let { addParam("subscribe_id", it) } } /** * @param eventId * @param userId * @param peerId * @param eventData * @return [VKRequest] with [BaseOkResponse] */ fun messagesSendMessageEventAnswer( eventId: String, userId: Int, peerId: Int, eventData: String? = null ): VKRequest<BaseOkResponse> = NewApiRequest("messages.sendMessageEventAnswer") { GsonHolder.gson.fromJson(it, BaseOkResponse::class.java) } .apply { addParam("event_id", eventId) addParam("user_id", userId) addParam("peer_id", peerId) eventData?.let { addParam("event_data", it) } } /** * Changes the status of a user as typing in a conversation. * * @param userId - User ID. * @param type - 'typing' - user has started to type. * @param peerId - Destination ID. "For user: 'User ID', e.g. '12345'. For chat: '2000000000' + * 'chat_id', e.g. '2000000001'. For community: '- community ID', e.g. '-12345'. " * @param groupId - Group ID (for group messages with group access token) * @return [VKRequest] with [BaseOkResponse] */ fun messagesSetActivity( userId: Int? = null, type: TypeParam? = null, peerId: Int? = null, groupId: Int? = null ): VKRequest<BaseOkResponse> = NewApiRequest("messages.setActivity") { GsonHolder.gson.fromJson(it, BaseOkResponse::class.java) } .apply { userId?.let { addParam("user_id", it) } type?.let { addParam("type", it.value) } peerId?.let { addParam("peer_id", it) } groupId?.let { addParam("group_id", it) } } /** * Sets a previously-uploaded picture as the cover picture of a chat. * * @param file - Upload URL from the 'response' field returned by the * [vk.com/dev/photos.getChatUploadServer|photos.getChatUploadServer] method upon successfully * uploading an image. * @return [VKRequest] with [MessagesSetChatPhotoResponse] */ fun messagesSetChatPhoto(file: String): VKRequest<MessagesSetChatPhotoResponse> = NewApiRequest("messages.setChatPhoto") { GsonHolder.gson.fromJson(it, MessagesSetChatPhotoResponse::class.java) } .apply { addParam("file", file) } /** * @param peerId * @param groupId * @return [VKRequest] with [BaseOkResponse] */ fun messagesUnpin(peerId: Int, groupId: Int? = null): VKRequest<BaseOkResponse> = NewApiRequest("messages.unpin") { GsonHolder.gson.fromJson(it, BaseOkResponse::class.java) } .apply { addParam("peer_id", peerId) groupId?.let { addParam("group_id", it) } } }
66
null
3
439
20d4c142c2ed65487429967d9fada6f91a1b2f00
54,626
vk-android-sdk
MIT License
app/src/main/java/com/keshavindustryfsmfsm/features/powerSavingSettings/PowerSavingSettingsActivity.kt
DebashisINT
683,953,107
false
{"Kotlin": 14053215, "Java": 1002345}
package com.keshavindustryfsmfsm.features.powerSavingSettings import android.content.Context import android.content.Intent import android.location.LocationManager import android.os.Bundle import android.os.Handler import android.provider.Settings import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.RelativeLayout import com.keshavindustryfsmfsm.R import com.keshavindustryfsmfsm.base.presentation.BaseActivity import com.keshavindustryfsmfsm.base.presentation.BaseFragment import com.keshavindustryfsmfsm.features.dashboard.presentation.DashboardActivity import com.keshavindustryfsmfsm.widgets.AppCustomTextView import net.alexandroid.gps.GpsStatusDetector class PowerSavingSettingsActivity : BaseActivity(){ private lateinit var mContext: Context private lateinit var tv_power_gps: AppCustomTextView private lateinit var rl_power_main: RelativeLayout override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.fragment_power_savings_screen) rl_power_main = findViewById(R.id.rl_power_main) rl_power_main.setOnClickListener(null) tv_power_gps =findViewById(R.id.tv_power_gps) tv_power_gps.setOnClickListener({ startActivity(Intent(Settings.ACTION_SETTINGS)) }) } }
0
Kotlin
0
0
8c286f0ac88c5a0f00b205041edfdf54bda899e3
1,381
KeshavIndustry
Apache License 2.0
composeApp/src/commonMain/kotlin/dev/senk0n/moerisuto/App.kt
senk0n
606,822,939
false
{"Kotlin": 50292, "Batchfile": 2675, "Ruby": 1767, "Swift": 532, "HTML": 281}
package dev.senk0n.moerisuto import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import dev.senk0n.moerisuto.root.RootComponentImpl @Composable internal fun App() { Column(modifier = Modifier.fillMaxSize()) { Text("hello from old template") } }
5
Kotlin
0
0
24ddc2ccb6a69157b9811901fe7191e3deedc18f
432
moe-risuto-app
MIT License
report-service/src/main/kotlin/ru/morkovka/report/entity/dto/CommentsDto.kt
MorkovkAs
258,515,761
false
null
package ru.morkovka.report.entity.dto data class CommentsDto(val comments: ArrayList<HashMap<String, Any>>)
8
Kotlin
1
1
ce891dddc3a7b40e1076450646b6ed55690dc0ed
108
jira-report-tools
Apache License 2.0
app/src/main/java/com/andriiginting/crossfademusic/data/CrossFadeMusicResponse.kt
andriiginting
421,495,030
false
{"Kotlin": 54938}
package com.andriiginting.crossfademusic.data import com.google.gson.annotations.SerializedName data class CrossFadeMusicResponse( @SerializedName("musics") val playlist: List<MusicResponse> ) data class MusicResponse( @SerializedName("track") val track: String, @SerializedName("streamUrl") val streamUrl: String, @SerializedName("artist") val artist: String, @SerializedName("cover") val coverUrl: String )
0
Kotlin
0
4
d0e9b2f7ec82086ff372500fa704fa3d4b02eef1
432
crossfade-player
MIT License
lib/src/main/java/me/ibrahimsn/lib/OnItemSelectedListener.kt
Milad-Akarie
586,878,944
false
{"Kotlin": 274890}
package me.ibrahimsn.lib interface OnItemSelectedListener { fun onItemSelect(pos: Int): Boolean }
4
Kotlin
19
2
e73e9eb6d86590b20e0547291c628a11702860b4
103
SmoothBottomBar
MIT License
app/src/main/java/com/example/coding_challenge/data/network/BaseRepository.kt
umarata
575,282,637
false
{"Kotlin": 28373}
package com.example.coding_challenge.data.network import com.example.coding_challenge.domain.AcromineRemoteDataSource import javax.inject.Inject /** * This BaseRepository provides the getAcromine(sf: String) function for fetching the details of acromine from api, in this repository webService: WebService is injected in constructor */ class BaseRepository @Inject constructor( private val webService: WebService ) { suspend fun getAcromine(sf: String) = AcromineRemoteDataSource(webService, sf).invoke() }
0
Kotlin
0
0
b87ea185c5e5005a3dc26f4ccfdbe7afda0db26f
518
CodingChallenge
Apache License 2.0
ktsnake.kt
TheRealBanana
134,801,080
false
{"Kotlin": 9710}
import org.lwjgl.glfw.GLFW.* import org.lwjgl.opengl.GL import org.lwjgl.opengl.GL11.* import org.lwjgl.system.MemoryUtil.NULL import java.util.* import kotlin.math.floor fun randgrid(end: Int) = Random().nextInt(end) data class ColorTuple(val r: Float, val g: Float, val b: Float) data class Grid(val row: Int, val col: Int) data class Point(val x: Int, val y: Int) data class Vertices(val br: Point, private val side_size_px: Int) { val tr: Point = Point(br.x, br.y - side_size_px) val tl: Point = Point(br.x - side_size_px, br.y - side_size_px) val bl: Point = Point(br.x - side_size_px, br.y) } enum class GridElementTypes(val color: ColorTuple){ DEFAULT_COLOR(ColorTuple(0.0f,0.0f,0.0f)), SNAKE_HEAD(ColorTuple(0.25882f,1.0f,0.0f)), SNAKE_TAIL(ColorTuple(0.15686f,0.58823f,0.0f)), OBJECTIVE(ColorTuple(0.0f,0.32941f,0.65098f)), DEAD_HEAD(ColorTuple(1.0f,0.0f,0.0f)) } enum class Directions(val dir: String) { DOWN("down"), UP("up"), RIGHT("right"), LEFT("left") } class GameGrid(private val snake: Snake, private val rows: Int, private val cols: Int, private val sidesizepx: Int) { val maxobjectives: Int = 10 private val activeGridElements: MutableMap<Grid, GridElement> = mutableMapOf() val objectiveList: MutableList<Grid> = mutableListOf() fun addObjective() { if (objectiveList.size == maxobjectives) { deleteGridElement((objectiveList.elementAt(0))) objectiveList.removeAt(0) } //Create random new grid thats not already taken var newobjgrid = Grid(randgrid(rows), randgrid(cols)) while (newobjgrid in objectiveList || newobjgrid in snake.snakegrids) { newobjgrid = Grid(randgrid(rows), randgrid(cols)) } objectiveList.add(newobjgrid) createGridElement(GridElementTypes.OBJECTIVE, newobjgrid) } private fun createGridElement(element_type: GridElementTypes, grid_index: Grid): Boolean{ if (activeGridElements.containsKey(grid_index)) { deleteGridElement(grid_index) } val xcoord: Int = sidesizepx * grid_index.row + sidesizepx val ycoord: Int = sidesizepx * grid_index.col + sidesizepx val origincoords = Point(xcoord, ycoord) val newgridelement = GridElement(element_type.color, origincoords, sidesizepx) activeGridElements[grid_index] = newgridelement return true } private fun deleteGridElement(grid_index: Grid){ if (activeGridElements.containsKey(grid_index)) { activeGridElements.remove(grid_index) } else { throw Exception("Tried to delete non-existent grid at index $grid_index") } } fun redrawGrid() { glClear(GL_COLOR_BUFFER_BIT) for ((_, grid_element) in activeGridElements) { grid_element.draw() } } fun moveSnake(): Boolean{ val nextmove: Grid = snake.getMove() //Check if we hit the wall if (nextmove.row !in 0..rows){ snake.alive = false println("Hit a wall, we ded fam X(") return false } else if (nextmove.col !in 0..cols){ snake.alive = false println("Hit a wall, we ded fam X(") return false } // check if we hit ourselves if (nextmove in snake.snakegrids) { snake.alive = false println("Hit ourselves, we ded fam X(") return false } //Good move so far, lets make it happen createGridElement(GridElementTypes.SNAKE_HEAD, nextmove) createGridElement(GridElementTypes.SNAKE_TAIL, snake.currentgrid) //delete any grids excess grids if we are too long (truncate snake) snake.snakegrids.add(nextmove) snake.currentgrid = nextmove if (snake.snakegrids.size == snake.length) { deleteGridElement(snake.snakegrids[0]) snake.snakegrids.removeAt(0) } //collected an objective, increase size if (nextmove in objectiveList) { objectiveList.remove(nextmove) snake.length += 1 } return true } fun gameOver() { // We died, show score and wait for user to exit // Also color the snake head red so we know we ded createGridElement(GridElementTypes.DEAD_HEAD, snake.snakegrids[snake.snakegrids.size-1]) redrawGrid() println("Final Score: ${snake.length-5}") //subtract initial snake size } } class GridElement (type: ColorTuple, origin_coords: Point, size_px: Int) { private val color: ColorTuple = type private val vertices: Vertices = Vertices(origin_coords, size_px) fun draw() { // Figure out our vertices glColor3f(color.r, color.g, color.b) glBegin(GL_QUADS) glVertex2i(vertices.br.x, vertices.br.y) glVertex2i(vertices.tr.x, vertices.tr.y) glVertex2i(vertices.tl.x, vertices.tl.y) glVertex2i(vertices.bl.x, vertices.bl.y) glEnd() } } class Snake(start_grid: Grid, start_direction: Directions) { var alive: Boolean = true var currentgrid: Grid = start_grid private var direction: Directions = start_direction var length: Int = 5 //initial snake size val snakegrids: MutableList<Grid> = mutableListOf() init { this.snakegrids.add(start_grid) } fun getMove(dir: Directions = this.direction): Grid { return when (dir.dir) { "down" -> Grid(currentgrid.row, currentgrid.col+1) "up" -> Grid(currentgrid.row, currentgrid.col-1) "right" -> Grid(currentgrid.row+1, currentgrid.col) else -> Grid(currentgrid.row-1, currentgrid.col) // Using else instead of "left" cause kotlin doesn't like the ambiguity. } } private fun changeDirection(newdir: Directions) { if (alive) { if (snakegrids.size > 1) { if (getMove(newdir) != snakegrids[snakegrids.size-2] ) { this.direction = newdir } } else { this.direction = newdir } } } //I know scancode and mods are unused, need them anyway //In python we could use underscores in function declaration. Kotlin only allows that in lambda expressions. @Suppress("UNUSED_PARAMETER") fun glfwKeypressCallback(window: Long, key: Int, scancode: Int, action: Int, mods: Int) { if (action == GLFW_PRESS) { when (key) { GLFW_KEY_UP -> changeDirection(Directions.UP) GLFW_KEY_DOWN -> changeDirection(Directions.DOWN) GLFW_KEY_LEFT -> changeDirection(Directions.LEFT) GLFW_KEY_RIGHT -> changeDirection(Directions.RIGHT) GLFW_KEY_ESCAPE -> glfwSetWindowShouldClose(window, true) } } } } object SnakeGame { private const val WINDOW_SIZE_WIDTH: Int = 500 private const val WINDOW_SIZE_HEIGHT: Int = 500 private const val side_size_px: Int = 15 private var tickno: Int = 0 private val rows: Int = floor(WINDOW_SIZE_WIDTH.toFloat()/side_size_px.toFloat()).toInt() private val cols: Int = floor(WINDOW_SIZE_HEIGHT.toFloat()/side_size_px.toFloat()).toInt() private val snake: Snake = Snake(Grid(0,0), Directions.RIGHT) private val gameGrid: GameGrid = GameGrid(snake, rows, cols, side_size_px) private var window: Long = NULL fun startGame() { //initialize GLFW init(WINDOW_SIZE_WIDTH, WINDOW_SIZE_HEIGHT) //Add half the number of objectives at the start while (gameGrid.objectiveList.size < gameGrid.maxobjectives/2) { gameGrid.addObjective() } //Draw it! while (!glfwWindowShouldClose(window) && snake.alive) { tickno += 1 glfwPollEvents() // Get keypresses if (tickno % 30 == 0){ // Add new objective every 10 ticks gameGrid.addObjective() } gameGrid.moveSnake() gameGrid.redrawGrid() glfwSwapBuffers(window) //if we are dead fall right through, no sleep if (snake.alive) { Thread.sleep(100L) } } // Game over man! GAME OVER! gameGrid.gameOver() // Swap buffers one last time to update the grid with our dead snake glfwSwapBuffers(window) while (!glfwWindowShouldClose(window)){ glfwPollEvents() Thread.sleep(50) //Dont let this while drive the CPU usage up too much } glfwDestroyWindow(window) glfwTerminate() } private fun init(windowSizeW: Int, windowSizeH: Int) { if ( !glfwInit() ) { throw Exception("Failed to initialize GLFW.") } glfwDefaultWindowHints() //Do not allow resize glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE) window = glfwCreateWindow(windowSizeW, windowSizeH, "KtSnake", 0, 0) if (window == NULL) { throw Exception("Failed to initialize window.") } glfwMakeContextCurrent(window) glfwSetKeyCallback(window, snake::glfwKeypressCallback) // GL configuration comes AFTER we make the window our current context, otherwise errors GL.createCapabilities() glClearColor(0.0f,0.0f,0.0f,1.0f) glOrtho(0.0, WINDOW_SIZE_WIDTH.toDouble(), WINDOW_SIZE_HEIGHT.toDouble(), 0.0, -1.0, 1.0) glViewport(0, 0, WINDOW_SIZE_WIDTH, WINDOW_SIZE_HEIGHT) glfwShowWindow(window) } } fun main(args: Array<String>) { println("here we go again lol") SnakeGame.startGame() }
0
Kotlin
0
0
71dfdfec03e46a55d1ef8273e9bb2c9a286348a0
9,710
KtSnake
MIT License
app/src/main/java/tool/xfy9326/schedule/content/js/JSCourseParser.kt
XFY9326
325,915,275
false
null
package tool.xfy9326.schedule.content.js import io.github.xfy9326.atools.base.nullIfBlank import kotlinx.serialization.json.Json import tool.xfy9326.schedule.beans.Course import tool.xfy9326.schedule.beans.ScheduleImportContent import tool.xfy9326.schedule.beans.ScheduleTime import tool.xfy9326.schedule.beans.WeekDay import tool.xfy9326.schedule.content.base.AbstractCourseParser import tool.xfy9326.schedule.content.beans.JSConfig import tool.xfy9326.schedule.content.beans.JSParams import tool.xfy9326.schedule.content.utils.CourseAdapterException import tool.xfy9326.schedule.content.utils.CourseAdapterException.Companion.report import tool.xfy9326.schedule.content.utils.CourseAdapterUtils import tool.xfy9326.schedule.content.utils.CourseImportHelper import tool.xfy9326.schedule.content.utils.CourseParseResult import tool.xfy9326.schedule.content.utils.toBooleanArray import tool.xfy9326.schedule.json.parser.ai.AiScheduleResult class JSCourseParser : AbstractCourseParser<JSParams>() { fun processJSResult(data: String) = try { when (requireParams().jsType) { JSConfig.TYPE_AI_SCHEDULE -> processAiScheduleResult(data) JSConfig.TYPE_PURE_SCHEDULE -> CourseImportHelper.parsePureScheduleJSON( data, requireParams().combineCourse, requireParams().combineCourseTime ) else -> error("Unsupported JS Type! ${requireParams().jsType}") } } catch (e: Exception) { CourseAdapterException.Error.JS_RESULT_PARSE_ERROR.report(e) } private fun processAiScheduleResult(data: String): ScheduleImportContent { val json = Json { ignoreUnknownKeys = true } val scheduleData = try { json.decodeFromString<AiScheduleResult>(data) } catch (e: Exception) { CourseAdapterException.Error.JSON_PARSE_ERROR.report(e) } val scheduleTimes = ArrayList<ScheduleTime>(scheduleData.sectionTimes.size) scheduleData.sectionTimes.sortedBy { it.section }.forEach { scheduleTimes.add(ScheduleTime.fromTimeStr(it.startTime, it.endTime)) } val builder = CourseParseResult.Builder(scheduleData.courseInfos.size) for (info in scheduleData.courseInfos) { builder.add { val weeks = info.weeks.toBooleanArray() val courseTimes = CourseAdapterUtils.parseMultiCourseTimes( weeks, WeekDay.of(info.day), info.sections.map { it.section }, info.position?.nullIfBlank() ) Course(info.name, info.teacher?.nullIfBlank(), courseTimes) } } return ScheduleImportContent( scheduleTimes, builder.build(requireParams().combineCourse, requireParams().combineCourseTime), CourseAdapterUtils.simpleTermFix(scheduleData.pureSchedule?.termStart, scheduleData.pureSchedule?.termEnd) ) } }
0
Kotlin
0
5
8e1fdbf481f19f7c57262d008fd0e550c58bf99f
3,095
Schedule
Apache License 2.0
backbone/src/main/java/org/researchstack/backbone/answerformat/ContinuousScaleAnswerFormat.kt
DonGiovanni83
194,921,093
true
{"Java": 1115395, "Kotlin": 17591}
package org.researchstack.backbone.answerformat import org.researchstack.backbone.ui.step.body.ContinuousScaleQuestionBody import org.researchstack.backbone.ui.step.body.IntegerQuestionBody import org.researchstack.backbone.ui.step.body.StepBody class ContinuousScaleAnswerFormat(private val minVal: Int, private val maxVal: Int) : IntegerAnswerFormat(minVal, maxVal), AnswerFormat.QuestionType { override fun getQuestionType(): QuestionType { return this } override fun getStepBodyClass(): Class<out StepBody> { return if (maxVal - minVal > 10000) { IntegerQuestionBody::class.java } else { ContinuousScaleQuestionBody::class.java } } }
0
Java
0
0
2a17e6970a41c2386ce7a509abda4d515854a9ae
715
ResearchStack
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/AdvantageCount.kt
ashtanko
203,993,092
false
null
/* * Copyright 2020 Oleksii Shtanko * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.Deque import java.util.LinkedList /** * Approach 1: Greedy * Time Complexity: O(N log N), where N is the length of a and b. * Space Complexity: O(N). */ fun advantageCount(a: IntArray, b: IntArray): IntArray { val sortedA: IntArray = a.clone(); sortedA.sort() val sortedB: IntArray = b.clone(); sortedB.sort() val assigned: MutableMap<Int, Deque<Int>> = HashMap() for (bb in b) assigned[bb] = LinkedList() val remaining: Deque<Int> = LinkedList() var j = 0 for (aa in sortedA) { if (aa > sortedB[j]) { assigned[sortedB[j++]]?.add(aa) } else { remaining.add(aa) } } val ans = IntArray(b.size) for (i in b.indices) { val bDeque = assigned.getOrDefault(b[i], LinkedList()) if (bDeque.size > 0) { ans[i] = bDeque.pop() } else { ans[i] = remaining.pop() } } return ans }
6
null
0
19
c6e2befdce892e9f2caf1d98f54dc1dd9b2c89ba
1,585
kotlab
Apache License 2.0
app/src/main/java/watermelon/focus/ui/widget/StarName.kt
Watermelon02
488,090,764
false
{"Kotlin": 85834}
package watermelon.focus.ui.widget import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import watermelon.focus.R /** * description : TODO:类的作用 * author : Watermelon02 * email : [email protected] * date : 2022/4/30 18:29 */ @Composable fun BoxScope.StarName(name:String) { Surface( color = Color(0xFFF8F8F8), shape = RoundedCornerShape(20.dp), modifier = Modifier .align(Alignment.BottomCenter) .width(100.dp) .padding(bottom = 200.dp) ) { Text( text = name, style = MaterialTheme.typography.h6, fontFamily = FontFamily(Font(R.font.store_my_stamp_number)), textAlign = TextAlign.Center,modifier = Modifier.alpha(0.5f) ) } }
0
Kotlin
8
84
490f83d9bac58b0390c9cec75543f3fc7a73c40c
1,417
ComposeFocus
MIT License
ltabview/src/main/java/liang/lollipop/ltabview/LTabView.kt
Mr-XiaoLiang
306,328,631
false
null
package liang.lollipop.ltabview import android.animation.ValueAnimator import android.content.Context import android.util.AttributeSet import android.util.Log import android.view.InflateException import android.view.View import android.widget.FrameLayout import kotlin.math.abs import kotlin.math.max import kotlin.math.min /** * @date: 2019/04/17 19:43 * @author: lollipop * TabView主体 */ class LTabView(context: Context, attr: AttributeSet?, defStyleAttr: Int, defStyleRes: Int): FrameLayout(context, attr, defStyleAttr, defStyleRes), ValueAnimator.AnimatorUpdateListener{ constructor(context: Context, attr: AttributeSet?, defStyleAttr: Int): this(context, attr, defStyleAttr, 0) constructor(context: Context, attr: AttributeSet?): this(context, attr, 0) constructor(context: Context): this(context, null) companion object { private const val MIN_PROGRESS = 0F private const val MAX_PROGRESS = 1F private const val TOLERANCE_SCOPE = 0.0001F private const val DEF_DURATION = 300L } /** * 排版样式,默认为自适应模式 */ var style = Style.Fit set(value) { field = value updateLocationByAnimator() } /** * 限制长度,保证View尺寸 */ var isLimit = true set(value) { field = value requestLayout() } /** * 是否统一宽度 */ var isUniform = false set(value) { field = value requestLayout() } private var selectedIndex = 0 private val childTargetLocation = ArrayList<Int>() private val childFromLocation = ArrayList<Int>() private val childWidth = ArrayList<ItemSize>() private val locationAnimator = ValueAnimator().apply { addUpdateListener(this@LTabView) } private val itemAnimators = HashMap<LTabItem, ItemAnimatorHelper>() var onSelectedListener: OnSelectedListener? = null var animationDuration = DEF_DURATION set(value) { field = value locationAnimator.duration = value itemAnimators.values.forEach { it.duration(value) } } var space = 0 set(value) { field = value requestLayout() } private fun reLayout() { updateChildLocation() val top = paddingTop val bottom = height - paddingBottom for (index in 0 until childCount) { val child = getChildAt(index) val loc = childTargetLocation[index] // log("reLayout: $index: [${child.left}, ${child.top}, ${child.right}, ${child.bottom}]") val childWidth = getChildWidthAt(index) child.layout(loc, top, loc + childWidth, bottom) // log("reLayout: $index: [${child.left}, ${child.top}, ${child.right}, ${child.bottom}]") child.translationX = 0F val item = child as LTabItem val animHelper = itemAnimators[item] if (index == selectedIndex) { animHelper?.progress = 1F } else { animHelper?.progress = 0F } } } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val heightMode = MeasureSpec.getMode(heightMeasureSpec) if (heightMode == MeasureSpec.UNSPECIFIED) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) return } val height = MeasureSpec.getSize(heightMeasureSpec) val widthMode = MeasureSpec.getMode(widthMeasureSpec) if (widthMode == MeasureSpec.EXACTLY) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) return } var left = paddingLeft val usedHeight = height - paddingBottom - paddingTop var maxItem = 0 for (index in 0 until childCount) { val child = getChildAt(index) if (child.visibility == View.GONE) { continue } child.measure(widthMeasureSpec, heightMeasureSpec) val item = child as LTabItem val childExpend = child.measuredWidth - item.miniSize if (maxItem < childExpend) { maxItem = childExpend } left += max(usedHeight, item.miniSize) left += space } left += maxItem left -= space left += paddingRight val width = if (widthMode == MeasureSpec.AT_MOST) { min(MeasureSpec.getSize(widthMeasureSpec), left) } else { style = Style.Start left } setMeasuredDimension(width, height) } override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { limit() reLayout() } private fun updateChildLocation() { when (style) { Style.Start -> layoutByStart() Style.End -> layoutByEnd() Style.Fit -> layoutByFit() Style.Center -> layoutByCenter() } } private fun limit() { // 如果不做限制,那么直接返回 if (!isLimit) { childWidth.forEach { it.max = -1 it.min = -1 } return } // 测定每一个item的最大可用宽度 for (index in 0 until childCount) { limitByIndex(index) childWidth[index].min = -1 } // 如果要求均一宽度,那么需要再次进行一次遍历,得到最大宽度中的最小值 if (isUniform) { var uniformSize = 0 childWidth.forEach { if (it.max > uniformSize) { uniformSize = it.max } } val width = this.width - paddingLeft - paddingRight for (index in 0 until childCount) { if (uniformSize > width - childWidth[index].unavailable) { uniformSize = width - childWidth[index].unavailable } } childWidth.forEach { it.max = uniformSize it.min = uniformSize } } } private fun limitByIndex(index: Int) { var selectedSize = 0 var unselectedSize = 0 val width = this.width - paddingLeft - paddingRight for (i in 0 until childCount) { val child = getChildAt(i) if (child.visibility == View.GONE) { continue } if (i == index) { selectedSize = child.measuredWidth } else { unselectedSize += (child as LTabItem).miniSize } } if (width - unselectedSize < selectedSize) { selectedSize = width - unselectedSize } childWidth[index].max = selectedSize childWidth[index].unavailable = unselectedSize } private fun layoutByStart() { var left = paddingLeft val height = this.height - paddingBottom - paddingTop for (index in 0 until childCount) { val child = getChildAt(index) if (child.visibility == View.GONE) { continue } val item = child as LTabItem var itemHorizontal = ((height - item.miniSize) * 0.5F).toInt() if (itemHorizontal < 0) { itemHorizontal = 0 } val itemLeft = left + itemHorizontal childTargetLocation[index] = itemLeft if (index == selectedIndex) { left += getChildWidthAt(index) left -= item.miniSize } left += max(height, item.miniSize) left += space } } private fun layoutByEnd() { var right = this.right - paddingRight val height = this.height - paddingBottom - paddingTop for (index in (childCount - 1) downTo 0) { val child = getChildAt(index) if (child.visibility == View.GONE) { continue } val item = child as LTabItem var itemHorizontal = ((height - item.miniSize) * 0.5F).toInt() if (itemHorizontal < 0) { itemHorizontal = 0 } val childWidth = getChildWidthAt(index) val itemRight = if (index == selectedIndex) { right - itemHorizontal } else { right - itemHorizontal - item.miniSize + childWidth } childTargetLocation[index] = itemRight - childWidth if (index == selectedIndex) { right -= childWidth right += item.miniSize } right -= max(height, item.miniSize) right -= space } } private fun layoutByFit() { var left = paddingLeft val right = this.right - this.left - paddingRight val width = right - left var effectiveWidth = 0 for (index in 0 until childCount) { val child = getChildAt(index) if (child.visibility == View.GONE) { continue } effectiveWidth += if (index == selectedIndex) { getChildWidthAt(index) } else { (child as LTabItem).miniSize } } val itemHorizontal = (width - effectiveWidth) * 1F / (childCount + 1) left = (left + itemHorizontal).toInt() for (index in 0 until childCount) { val child = getChildAt(index) if (child.visibility == View.GONE) { continue } childTargetLocation[index] = left left += if (index == selectedIndex) { getChildWidthAt(index) } else { (child as LTabItem).miniSize } left = (left + itemHorizontal).toInt() } } private fun layoutByCenter() { var left = paddingLeft val right = this.right - this.left - paddingRight val width = right - left var effectiveWidth = 0 for (index in 0 until childCount) { val child = getChildAt(index) if (child.visibility == View.GONE) { continue } effectiveWidth += if (index == selectedIndex) { getChildWidthAt(index) + (height - (child as LTabItem).miniSize) } else { height } } left += (width - effectiveWidth) / 2 for (index in 0 until childCount) { val child = getChildAt(index) if (child.visibility == View.GONE) { continue } val item = child as LTabItem var itemHorizontal = ((height - item.miniSize) * 0.5F).toInt() if (itemHorizontal < 0) { itemHorizontal = 0 } childTargetLocation[index] = left + itemHorizontal if (index == selectedIndex) { left += getChildWidthAt(index) left -= item.miniSize } left += height } } private fun getChildWidthAt(index: Int): Int { return childWidth[index].limit(getChildAt(index).measuredWidth) } override fun onViewRemoved(child: View?) { super.onViewRemoved(child) if (child == null) { return } val item = child as LTabItem itemAnimators.remove(item) childTargetLocation.removeAt(0) childFromLocation.removeAt(0) childWidth.removeAt(0) requestLayout() } override fun onViewAdded(child: View?) { super.onViewAdded(child) if (child == null) { return } if (child !is LTabItem) { throw InflateException("LTabView does not allow adding views other than LTabItem") } val item = child as LTabItem itemAnimators[item] = ItemAnimatorHelper(item, animationDuration) childTargetLocation.add(0) childFromLocation.add(0) childWidth.add(ItemSize()) item.onTabClick { for (i in 0 until childCount) { if (getChildAt(i) == it) { selected(i) break } } } requestLayout() } fun selected(index: Int) { if (selectedIndex == index) { return } selectedIndex = index updateLocationByAnimator() onSelectedListener?.onTabSelected(index) } private fun updateLocationByAnimator() { if (locationAnimator.isRunning) { locationAnimator.cancel() } updateLocation() for (i in 0 until childCount) { val child = getChildAt(i) val helper = itemAnimators[child as LTabItem]?:continue if (i == selectedIndex) { helper.open() } else { helper.close() } } locationAnimator.setFloatValues(MIN_PROGRESS, MAX_PROGRESS) locationAnimator.start() } private fun updateLocation() { for (i in 0 until childCount) { val child = getChildAt(i) childFromLocation[i] = child.x.toInt() log("selected: $i: from = ${childFromLocation[i]}, to = ${childTargetLocation[i]}") } updateChildLocation() } override fun onAnimationUpdate(animation: ValueAnimator?) { if (animation == locationAnimator) { val value = locationAnimator.animatedValue as Float moveChildByOffset(value) } } private fun moveChildByOffset(value: Float) { for (i in 0 until childCount) { val from = childFromLocation[i] val to = childTargetLocation[i] val child = getChildAt(i) val offset = (to - from) * value + from - child.x child.offsetLeftAndRight(offset.toInt()) } } override fun generateDefaultLayoutParams(): LayoutParams { return LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT) } interface OnSelectedListener { fun onTabSelected(index: Int) } private class ItemAnimatorHelper(private val item: LTabItem, animationDuration: Long): ValueAnimator.AnimatorUpdateListener { private val tabAnimator = ValueAnimator().apply { addUpdateListener(this@ItemAnimatorHelper) } private var duration = animationDuration var progress = 0F set(value) { field = value update() } fun close() { tabAnimator.cancel() if (abs(progress - MIN_PROGRESS) < TOLERANCE_SCOPE) { progress = MIN_PROGRESS return } tabAnimator.setFloatValues(progress, MIN_PROGRESS) tabAnimator.duration = ((progress - MIN_PROGRESS) / (MAX_PROGRESS - MIN_PROGRESS) * duration).toLong() tabAnimator.start() } fun open() { tabAnimator.cancel() if (abs(progress - MAX_PROGRESS) < TOLERANCE_SCOPE) { progress = MAX_PROGRESS return } tabAnimator.setFloatValues(progress, MAX_PROGRESS) tabAnimator.duration = ((MAX_PROGRESS - progress) / (MAX_PROGRESS - MIN_PROGRESS) * duration).toLong() tabAnimator.start() } override fun onAnimationUpdate(animation: ValueAnimator?) { if (animation == tabAnimator) { progress = animation.animatedValue as Float } } private fun update() { item.schedule(progress) } fun duration(value: Long) { duration = value } fun cancel() { tabAnimator.cancel() } } enum class Style(val value: Int) { /** * 从头排列 */ Start(1), /** * 从尾排列 */ End(2), /** * 按照权重排列 */ Fit(3), /** * 居中排列 */ Center(4), } class ItemSize(var max: Int = -1, var min: Int = -1, var unavailable: Int = 0) { fun limit(value: Int): Int { if (max in 1 until value) { return max } if (min > 0 && value < min) { return min } return value } } private fun log(value: String) { Log.d("Lollipop", "LTabView: $value") } }
0
Kotlin
4
9
7e22e2d0eaf40172dbd65a0c06e08eeb3bc0017c
16,585
SmartIconPack
Apache License 2.0
app/src/main/java/com/ch4019/jdaapp/ui/screen/language/LanguageConfiguration.kt
CH4019
650,575,082
false
{"Kotlin": 143537}
package com.ch4019.jdaapp.ui.screen.language import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBackIosNew import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.navigation.NavHostController @OptIn(ExperimentalMaterial3Api::class) @Composable fun LanguageConfiguration( mainNavController: NavHostController ) { Scaffold( topBar = { TopAppBar( title = { Text("语言") }, navigationIcon = { IconButton( onClick = { mainNavController.navigateUp() } ) { Icon( imageVector = Icons.Filled.ArrowBackIosNew, contentDescription = null ) } }, ) } ) { LanguageView(it) } } @Composable fun LanguageView( paddingValues: PaddingValues ) { Column ( modifier = Modifier.padding(paddingValues) .padding(horizontal = 16.dp) ){ Text(text = "待补充") } }
0
Kotlin
1
2
6844a27e9d8097e27aff80f7f9c44d7e2a4647f1
1,619
JdaApp
MIT License
src/main/java/com/github/zametki/ajax/CreateNoteAjaxCall.kt
zametki
79,764,010
false
{"Java": 134437, "TypeScript": 88096, "Kotlin": 43405, "CSS": 29349, "HTML": 21603, "JavaScript": 1634}
package com.github.zametki.ajax import com.github.zametki.Context import com.github.zametki.annotation.MountPath import com.github.zametki.annotation.Post import com.github.zametki.model.Group import com.github.zametki.model.Zametka import java.time.Instant @Post @MountPath("/ajax/create-note") class CreateNoteAjaxCall : BaseNNGroupActionAjaxCall() { override fun getResponseTextNN(group: Group): String { val text = getParameter("text").toString("") if (text.length < Zametka.MIN_CONTENT_LEN || text.length > Zametka.MAX_CONTENT_LEN) { return error("Illegal text length: " + text.length) } val z = Zametka() z.groupId = group.id!! z.creationDate = Instant.now() z.userId = userId z.content = text Context.getZametkaDbi().create(z) return AjaxApiUtils.getNotesAndGroupsAsResponse(userId, group.id!!) } }
1
null
1
1
8799ac1c3b5076016f58a12772b7a5dab6678a89
912
zametki
Apache License 2.0
app/src/full/java/com/celzero/bravedns/ui/fragment/RethinkLogFragment.kt
celzero
270,683,546
false
null
/* Copyright 2023 RethinkDNS and its authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.celzero.bravedns.ui.fragment import android.os.Bundle import android.view.View import androidx.appcompat.widget.SearchView import androidx.fragment.app.Fragment import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import by.kirich1409.viewbindingdelegate.viewBinding import com.celzero.bravedns.R import com.celzero.bravedns.adapter.RethinkLogAdapter import com.celzero.bravedns.database.RethinkLogRepository import com.celzero.bravedns.databinding.ActivityConnectionTrackerBinding import com.celzero.bravedns.service.PersistentState import com.celzero.bravedns.util.Constants import com.celzero.bravedns.util.UIUtils.formatToRelativeTime import com.celzero.bravedns.util.Utilities import com.celzero.bravedns.viewmodel.RethinkLogViewModel import com.google.android.material.dialog.MaterialAlertDialogBuilder import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import org.koin.android.ext.android.inject import org.koin.androidx.viewmodel.ext.android.viewModel class RethinkLogFragment : Fragment(R.layout.activity_connection_tracker), SearchView.OnQueryTextListener { private val b by viewBinding(ActivityConnectionTrackerBinding::bind) private var layoutManager: RecyclerView.LayoutManager? = null private val viewModel: RethinkLogViewModel by viewModel() private val rethinkLogRepository by inject<RethinkLogRepository>() private val persistentState by inject<PersistentState>() companion object { fun newInstance(param: String): RethinkLogFragment { val args = Bundle() args.putString(Constants.SEARCH_QUERY, param) val fragment = RethinkLogFragment() fragment.arguments = args return fragment } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initView() if (arguments != null) { val query = arguments?.getString(Constants.SEARCH_QUERY) ?: return b.connectionSearch.setQuery(query, true) } } private fun initView() { // no need to show filter options for rethink logs b.connectionFilterIcon.visibility = View.GONE if (!persistentState.logsEnabled) { b.connectionListLogsDisabledTv.visibility = View.VISIBLE b.connectionCardViewTop.visibility = View.GONE return } b.connectionListLogsDisabledTv.visibility = View.GONE b.connectionCardViewTop.visibility = View.VISIBLE b.recyclerConnection.setHasFixedSize(true) layoutManager = LinearLayoutManager(requireContext()) b.recyclerConnection.layoutManager = layoutManager val recyclerAdapter = RethinkLogAdapter(requireContext()) viewLifecycleOwner.lifecycleScope.launch { repeatOnLifecycle(Lifecycle.State.STARTED) { viewModel.rlogList.observe(viewLifecycleOwner) { it -> recyclerAdapter.submitData(lifecycle, it) } } } b.recyclerConnection.adapter = recyclerAdapter setupRecyclerScrollListener() b.connectionSearch.setOnQueryTextListener(this) b.connectionDeleteIcon.setOnClickListener { showDeleteDialog() } } private fun setupRecyclerScrollListener() { val scrollListener = object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) if (recyclerView.getChildAt(0)?.tag == null) return val tag: Long = recyclerView.getChildAt(0).tag as Long b.connectionListScrollHeader.text = formatToRelativeTime(requireContext(), tag) b.connectionListScrollHeader.visibility = View.VISIBLE } override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { super.onScrollStateChanged(recyclerView, newState) if (newState == RecyclerView.SCROLL_STATE_IDLE) { b.connectionListScrollHeader.visibility = View.GONE } } } b.recyclerConnection.addOnScrollListener(scrollListener) } override fun onQueryTextSubmit(query: String): Boolean { viewModel.setFilter(query) return true } override fun onQueryTextChange(query: String): Boolean { Utilities.delay(500, lifecycleScope) { if (this.isAdded) { viewModel.setFilter(query) } } return true } private fun showDeleteDialog() { val builder = MaterialAlertDialogBuilder(requireContext()) builder.setTitle(R.string.conn_track_clear_logs_title) builder.setMessage(R.string.conn_track_clear_logs_message) builder.setCancelable(true) builder.setPositiveButton(getString(R.string.dns_log_dialog_positive)) { _, _ -> io { rethinkLogRepository.clearAllData() } } builder.setNegativeButton(getString(R.string.lbl_cancel)) { _, _ -> } builder.create().show() } private fun io(f: suspend () -> Unit) { lifecycleScope.launch(Dispatchers.IO) { f() } } }
361
null
148
2,928
d618c0935011642592e958d2b420d5d154e0cd79
6,106
rethink-app
Apache License 2.0
src/main/kotlin/operation/volumeaccessgroup/ListVolumeAccessGroupOperation.kt
liujiahua123123
502,188,554
false
null
package operation.volumeaccessgroup import operation.AuthedHttpOperation import operation.request.Requester import utils.KeyExchangeService import utils.VolumeAccessGroup @kotlinx.serialization.Serializable data class ListVolumeAccessGroupReq( @kotlinx.serialization.Transient val clusterId: String = "" ) @kotlinx.serialization.Serializable class ListVolumeAccessGroupResp( val data: List<VolumeAccessGroup> ) class ListVolumeAccessGroupOperation: AuthedHttpOperation<ListVolumeAccessGroupReq, ListVolumeAccessGroupResp>( method = Requester.Method.GET, path = "/v1/volume-access-groups" ) { override suspend fun invoke(input: ListVolumeAccessGroupReq): ListVolumeAccessGroupResp = getRequester().apply { addPathParameter(input.clusterId) }.send(input).parse() }
0
Kotlin
0
0
484c8d107382703fd2e121e32b8929a474818f8c
803
HCDProject
The Unlicense
utbot-python/src/main/kotlin/org/utbot/python/framework/api/python/PythonApi.kt
UnitTestBot
480,810,501
false
null
package org.utbot.python.framework.api.python import org.utbot.framework.plugin.api.ClassId import org.utbot.framework.plugin.api.Coverage import org.utbot.framework.plugin.api.DocStatement import org.utbot.framework.plugin.api.EnvironmentModels import org.utbot.framework.plugin.api.MethodId import org.utbot.framework.plugin.api.UtExecution import org.utbot.framework.plugin.api.UtExecutionResult import org.utbot.framework.plugin.api.UtModel import org.utbot.python.framework.api.python.util.comparePythonTree import org.utbot.python.framework.api.python.util.moduleOfType /** * PythonClassId represents Python type. * NormalizedPythonAnnotation represents annotation after normalization. * * Example of PythonClassId, but not NormalizedPythonAnnotation: * builtins.list (normalized annotation is typing.List[typing.Any]) */ const val pythonBuiltinsModuleName = "builtins" class PythonClassId( val moduleName: String, val typeName: String, ) : ClassId("$moduleName.$typeName") { constructor(fullName: String) : this( moduleOfType(fullName) ?: pythonBuiltinsModuleName, fullName.removePrefix(moduleOfType(fullName) ?: pythonBuiltinsModuleName).removePrefix(".") ) override fun toString(): String = canonicalName val rootModuleName: String = moduleName.split(".").first() override val simpleName: String = typeName override val canonicalName = name override val packageName = moduleName val prettyName: String = if (rootModuleName == pythonBuiltinsModuleName) name.split(".", limit=2).last() else name } open class RawPythonAnnotation( annotation: String ): ClassId(annotation) class NormalizedPythonAnnotation( annotation: String ) : RawPythonAnnotation(annotation) class PythonMethodId( override val classId: PythonClassId, // may be a fake class for top-level functions override val name: String, override val returnType: RawPythonAnnotation, override val parameters: List<RawPythonAnnotation>, ) : MethodId(classId, name, returnType, parameters) { val moduleName: String = classId.moduleName val rootModuleName: String = this.toString().split(".")[0] override fun toString(): String = if (moduleName.isNotEmpty()) "$moduleName.$name" else name } sealed class PythonModel(classId: PythonClassId): UtModel(classId) { open val allContainingClassIds: Set<PythonClassId> = setOf(classId) } class PythonTreeModel( val tree: PythonTree.PythonTreeNode, classId: PythonClassId, ): PythonModel(classId) { constructor(tree: PythonTree.PythonTreeNode) : this(tree, tree.type) override val allContainingClassIds: Set<PythonClassId> get() { return findAllContainingClassIds(setOf(this.tree)) } private fun findAllContainingClassIds(visited: Set<PythonTree.PythonTreeNode>): Set<PythonClassId> { val children = tree.children.map { PythonTreeModel(it, it.type) } val newVisited = (visited + setOf(this.tree)).toMutableSet() val childrenClassIds = children.filterNot { newVisited.contains(it.tree) }.flatMap { newVisited.add(it.tree) it.findAllContainingClassIds(newVisited) } return super.allContainingClassIds + childrenClassIds } override fun equals(other: Any?): Boolean { if (other !is PythonTreeModel) { return false } return comparePythonTree(tree, other.tree) } override fun hashCode(): Int { return tree.hashCode() } } class PythonUtExecution( val stateInit: EnvironmentModels, stateBefore: EnvironmentModels, stateAfter: EnvironmentModels, val diffIds: List<Long>, result: UtExecutionResult, coverage: Coverage? = null, summary: List<DocStatement>? = null, testMethodName: String? = null, displayName: String? = null ) : UtExecution(stateBefore, stateAfter, result, coverage, summary, testMethodName, displayName)
352
Kotlin
26
85
8227e23a0924a519ce87c5d42b3491aa7db41d0c
3,941
UTBotJava
Apache License 2.0
src/main/java/org/radarbase/output/accounting/OffsetFilePersistence.kt
RADAR-base
88,144,691
false
null
/* * Copyright 2017 The Hyve * * 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.radarbase.output.accounting import org.radarbase.output.target.TargetStorage import org.radarbase.output.util.PostponedWriter import org.radarbase.output.util.Timer.time import org.slf4j.LoggerFactory import java.io.IOException import java.nio.file.Files import java.nio.file.Path import java.time.Instant import java.util.concurrent.TimeUnit import java.util.regex.Pattern /** * Accesses a OffsetRange file using the CSV format. On writing, this will create the file if * not present. */ class OffsetFilePersistence( private val targetStorage: TargetStorage ): OffsetPersistenceFactory { override fun read(path: Path): OffsetRangeSet? { return try { if (targetStorage.status(path) != null) { OffsetRangeSet().also { set -> targetStorage.newBufferedReader(path).use { br -> // ignore header br.readLine() ?: return@use generateSequence { br.readLine() } .map(::parseLine) .forEach(set::add) } } } else null } catch (ex: IOException) { logger.error("Error reading offsets file. Processing all offsets.", ex) null } } override fun writer( path: Path, startSet: OffsetRangeSet? ): OffsetPersistenceFactory.Writer = FileWriter(path, startSet) private fun parseLine(line: String): TopicPartitionOffsetRange { val cols = COMMA_PATTERN.split(line) var topic = cols[3] while (topic[0] == '"') { topic = topic.substring(1) } while (topic[topic.length - 1] == '"') { topic = topic.substring(0, topic.length - 1) } val lastModified = if (cols.size >= 5) { Instant.parse(cols[4]) } else Instant.now() return TopicPartitionOffsetRange( topic, cols[2].toInt(), cols[0].toLong(), cols[1].toLong(), lastModified) } companion object { private val COMMA_PATTERN: Pattern = Pattern.compile(",") private val logger = LoggerFactory.getLogger(OffsetFilePersistence::class.java) } private inner class FileWriter( private val path: Path, startSet: OffsetRangeSet? ): PostponedWriter("offsets", 1, TimeUnit.SECONDS), OffsetPersistenceFactory.Writer { override val offsets: OffsetRangeSet = startSet ?: OffsetRangeSet() override fun doWrite() = time("accounting.offsets") { try { val tmpPath = Files.createTempFile("offsets", ".csv") Files.newBufferedWriter(tmpPath).use { writer -> writer.append("offsetFrom,offsetTo,partition,topic\n") offsets.forEach { topicPartition, offsetIntervals -> offsetIntervals.forEach { offsetFrom, offsetTo, lastModified -> writer.write(offsetFrom.toString()) writer.write(','.code) writer.write(offsetTo.toString()) writer.write(','.code) writer.write(topicPartition.partition.toString()) writer.write(','.code) writer.write(topicPartition.topic) writer.write(','.code) writer.write(lastModified.toString()) writer.write('\n'.code) } } } targetStorage.store(tmpPath, path) } catch (e: IOException) { logger.error("Failed to write offsets: {}", e.toString()) } } } }
4
Kotlin
0
1
b0fe1100baaef6d9fcb1c0f0609d82fc6f39202a
4,511
radar-output-restructure
Apache License 2.0
app/src/main/java/com/kslimweb/testfacematching/models/FormRequestData.kt
limkhashing
204,187,838
false
null
package com.kslimweb.testfacematching.models import okhttp3.MultipartBody import okhttp3.RequestBody data class FormRequestData(val imagePart: MultipartBody.Part, val videoPart: MultipartBody.Part, val thresholdFormData: RequestBody, val toleranceFormData: RequestBody)
0
Kotlin
0
0
2fff71fbd9436235747e8233e116b80644fecc6c
355
Face-Matching-App
MIT License
Demo/src/main/java/com/paypal/android/api/model/ClientId.kt
paypal
390,097,712
false
{"Kotlin": 299789}
package com.paypal.android.api.model data class ClientId( val value: String )
22
Kotlin
41
74
dcc46f92771196e979f7863b9b8d3fa3d6dc1a7d
83
paypal-android
Apache License 2.0
mario/zelda-server2/src/main/kotlin/server/Application.kt
MikeDepies
325,124,905
false
{"CSS": 7942948, "Kotlin": 700526, "Python": 545415, "TypeScript": 76204, "Svelte": 50830, "JavaScript": 6857, "HTML": 2446, "Dockerfile": 772}
package server import Auth0Config import MessageWriter import PopulationEvolver import UserRef import io.ktor.application.* import io.ktor.features.* import io.ktor.http.* import io.ktor.http.cio.websocket.* import io.ktor.response.* import io.ktor.routing.* import io.ktor.serialization.* import io.ktor.util.* import io.ktor.util.date.* import kotlinx.coroutines.* import kotlinx.coroutines.channels.* import kotlinx.serialization.* import kotlinx.serialization.Serializable import kotlinx.serialization.json.* import mu.* import neat.* import neat.model.* import neat.novelty.* import org.jetbrains.exposed.sql.* import org.koin.ktor.ext.* import server.message.* import server.message.endpoints.* import server.server.* import java.io.* import java.time.* import java.time.format.* import java.util.* import kotlin.random.* fun main(args: Array<String>): Unit = io.ktor.server.cio.EngineMain.main(args) private val logger = KotlinLogging.logger { } val minSpeices = 5 val maxSpecies = 40 val speciesThresholdDelta = .15f val cppnGeneRuler = CPPNGeneRuler(weightCoefficient = 1f, disjointCoefficient = 1f) var distanceFunction = cppnGeneRuler::measure var speciesSharingDistance = 1f var shFunction = shFunction(speciesSharingDistance) @KtorExperimentalAPI @Suppress("unused") // Referenced in application.conf @kotlin.jvm.JvmOverloads fun Application.module(testing: Boolean = false) { install(io.ktor.websocket.WebSockets) { pingPeriod = Duration.ofSeconds(15) timeout = Duration.ofSeconds(15) maxFrameSize = Long.MAX_VALUE masking = false } install(CORS) { method(HttpMethod.Options) method(HttpMethod.Get) method(HttpMethod.Put) method(HttpMethod.Delete) method(HttpMethod.Patch) header(HttpHeaders.Authorization) allowCredentials = true allowSameOrigin = true anyHost() // @TODO: Don't do this in production if possible. Try to limit it. } install(CallLogging) { // level = Level.INFO } val application = this install(Koin) { modules(applicationModule, org.koin.dsl.module { single { application } single { Json { encodeDefaults = true } } single { with(environment.config) { Auth0Config( property("ktor.auth0.clientID").getString(), property("ktor.auth0.clientSecret").getString(), property("ktor.auth0.audience").getString(), property("ktor.auth0.grantType").getString() ) } } }) } install(ContentNegotiation) { json(get()) } //connectAndCreateDatabase() // println(get<Channel<FrameUpdate>>(qualifier<FrameUpdate>())) // println(get<Channel<FrameOutput>>(qualifier<FrameOutput>())) val format = DateTimeFormatter.ofPattern("YYYYMMdd-HHmm") val runFolder = LocalDateTime.now().let { File("runs/run-${it.format(format)}") } runFolder.mkdirs() get<WebSocketManager>().attachWSRoute() // val controller1 = get<IOController>(parameters = { DefinitionParameters(listOf(0)) }) // val controller2 = get<IOController>(parameters = { DefinitionParameters(listOf(1)) }) // fun IOController.simulationForController(populationSize: Int) = get<Simulation>(parameters = { // DefinitionParameters( // listOf(controllerId, populationSize) // ) // }) // val (initialPopulation, populationEvolver, adjustedFitness) = controller1.simulationForController(500) val evaluationChannels = get<EvaluationChannels>() val evaluationChannels2 = get<EvaluationChannels>() val evaluationMessageProcessor = get<EvaluationMessageProcessor>() // generateFakeData(evaluationChannels) // val b = Json { }.decodeFromString<List<ActionBehavior>>( // File("population/1_noveltyArchive.json").bufferedReader().lineSequence().joinToString("") // ) // networkEvaluatorOutputBridgeLoop(evaluationMessageProcessor, listOf(controller1)) val evaluationId = 0 val populationSize = 200 val mateChance = .4f val survivalThreshold = .4f val stagnation = 80 val randomSeed: Int = 40 + evaluationId val addConnectionAttempts = 5 val activationFunctions = Activation.CPPN.functions val random = Random(randomSeed) // // val models = loadPopulation(File("population/population.json"), 0).models // logger.info { "population loaded with size of: ${models.size}" } // val maxNodeInnovation = models.map { model -> model.connections.maxOf { it.innovation } }.maxOf { it } + 1 // val maxInnovation = models.map { model -> model.nodes.maxOf { it.node } }.maxOf { it } + 1 // val simpleNeatExperiment = simpleNeatExperiment( // random, maxInnovation, maxNodeInnovation, activationFunctions, // addConnectionAttempts // ) // var population = models.map { it.toNeatMutator() }.mapIndexed { index, neatMutator -> // NetworkWithId(neatMutator, UUID.randomUUID().toString()) // } // val behaviors = Json { }.decodeFromString<List<MarioDiscovery>>( // File("population/noveltyArchive.json").bufferedReader().lineSequence().joinToString("") // ) val simpleNeatExperiment = simpleNeatExperiment(random, 0, 0, activationFunctions, addConnectionAttempts) var population = simpleNeatExperiment.generateInitialPopulation2( populationSize, 6, 2, activationFunctions ).mapIndexed { index, neatMutator -> NetworkWithId(neatMutator, UUID.randomUUID().toString()) } var settings = Settings(0f) var mapIndexed = population.mapIndexed { index, neatMutator -> neatMutator.id to neatMutator }.toMap() var finishedScores = population.mapIndexed { index, neatMutator -> neatMutator.id to false }.toMap().toMutableMap() // createTaskNetwork(population.first().toNetwork()) val simulation = createSimulation( evaluationId, population.map { it.neatMutator }, distanceFunction, shFunction, mateChance, survivalThreshold, stagnation ) with(simulation.populationEvolver) { speciationController.speciate( population.map { it.neatMutator }, speciesLineage, generation, standardCompatibilityTest(shFunction, distanceFunction) ) } var scores = mutableListOf<FitnessModel<NeatMutator>>() var seq = population.iterator() var activeModel: NetworkWithId = population.first() val knnNoveltyArchive = KNNNoveltyArchive<ZeldaDiscovery>(400, settings.noveltyThreshold) { a, b -> val euclidean = euclidean(a.toVector(), b.toVector()) euclidean } // knnNoveltyArchive.behaviors.addAll(behaviors) fun processPopulation(populationEvolver: PopulationEvolver) { if (scores.size == populationSize) { logger.info { "New generation ${populationEvolver.generation}" } val toModelScores = scores.toModelScores( adjustedFitnessCalculation( simulation.populationEvolver.speciationController, distanceFunction, shFunction ) ) population = evolve( populationEvolver, toModelScores, simpleNeatExperiment, population.size ).mapIndexed { index, neatMutator -> NetworkWithId(neatMutator, UUID.randomUUID().toString()) }.shuffled() mapIndexed = population.mapIndexed { index, neatMutator -> neatMutator.id to neatMutator }.toMap() finishedScores = population.mapIndexed { index, neatMutator -> neatMutator.id to false }.toMap().toMutableMap() seq = population.iterator() scores = mutableListOf() writeGenerationToDisk(population.map { it.neatMutator }, runFolder, populationEvolver, "") runFolder.resolve("${evaluationId}_noveltyArchive.json").bufferedWriter().use { val json = Json { prettyPrint = true } it.write(json.encodeToString(knnNoveltyArchive.behaviors)) it.flush() } } } val modelChannel = Channel<NetworkDescription>(40) val neatMutatorChannel = Channel<NetworkWithId>(Channel.UNLIMITED) launch { var lastRefill = getTimeMillis() while (true) { if (seq.hasNext()) { neatMutatorChannel.send(seq.next()) } else if (neatMutatorChannel.isEmpty && modelChannel.isEmpty && !seq.hasNext() && getTimeMillis() - lastRefill > 15_000) { seq = finishedScores.filter { !it.value }.mapNotNull { mapIndexed[it.key] }.iterator() lastRefill = getTimeMillis() } } } repeat(10) { launch(Dispatchers.Default) { while (true) { val network = neatMutatorChannel.receive() val message = try { createTaskNetwork(network.neatMutator.toNetwork(), network.id) } catch (e: Exception) { NetworkDescription(setOf(), setOf(), network.id, null, listOf()) } // logger.info { "added model... ${message.id}" } modelChannel.send(message) } } } val scoreChannel = Channel<ZeldaDiscovery>(Channel.UNLIMITED) routing { get("/model") { val model = modelChannel.receive() call.respond(model) } post<DeadNetwork>("/dead") { val a = mapIndexed[it.id] if (a != null) { scores += FitnessModel(a.neatMutator, 0f) finishedScores[it.id] = true } call.respond("ok") } post<ZeldaDiscovery>("/score") { scoreChannel.send(it) } get("behaviors") { val numberOfBehaviors = call.parameters["n"] val message = if (numberOfBehaviors == null) { knnNoveltyArchive.behaviors } else knnNoveltyArchive.behaviors.takeLast(numberOfBehaviors.toInt()) call.respond(message) } get("settings") { call.respond(settings) } post<Settings>("settings") { settings = it knnNoveltyArchive.noveltyThreshold = settings.noveltyThreshold logger.info { "$it applied" } } } launch(Dispatchers.Default) { for (it in scoreChannel) { val populationEvolver = simulation.populationEvolver val score = if (knnNoveltyArchive.size > 0) { val addBehavior = knnNoveltyArchive.addBehavior(it) (if (addBehavior < knnNoveltyArchive.noveltyThreshold) 0f else addBehavior) // + it.mushrooms * 15 + it.fireFlowers * 35 } else { knnNoveltyArchive.addBehavior(it) // euclidean(toVector(it), toVector(it).map { 0f}) euclidean(it.toVector(), it.toVector().map { 0f}) } val model = mapIndexed[it.id]?.neatMutator if (finishedScores[it.id] != true && model != null) { scores += FitnessModel(model, score) finishedScores[it.id] = true val species = if (populationEvolver.speciationController.hasSpeciesFor(model)) "${ populationEvolver.speciationController.species((model)) }" else "No Species" logger.info { "[G${populationEvolver.generation}][S${species} / ${populationEvolver.speciationController.speciesSet.size}] Model (${scores.size}) Score: $score " } logger.info { "$it" } } processPopulation(populationEvolver) } } } @Serializable data class Settings(val noveltyThreshold: Float) data class DeadNetwork(val id: String) data class NetworkWithId(val neatMutator: NeatMutator, val id: String) fun evolve( populationEvolver: PopulationEvolver, modelScores: List<ModelScore>, neatExperiment: NeatExperiment, populationSize: Int ): List<NeatMutator> { populationEvolver.sortPopulationByAdjustedScore(modelScores) populationEvolver.updateScores(modelScores) var newPopulation = populationEvolver.evolveNewPopulation(modelScores, neatExperiment) while (newPopulation.size < populationSize) { newPopulation = newPopulation + newPopulation.first().clone() } if (populationEvolver.speciationController.speciesSet.size < minSpeices) { if (speciesSharingDistance > speciesThresholdDelta) { speciesSharingDistance -= speciesThresholdDelta } } else if (populationEvolver.speciationController.speciesSet.size > maxSpecies) { speciesSharingDistance += speciesThresholdDelta } logger.info { "Species (${populationEvolver.speciationController.speciesSet.size}) Sharing Function Distance: $speciesSharingDistance" } shFunction = neat.shFunction(speciesSharingDistance) populationEvolver.speciate(newPopulation, standardCompatibilityTest(shFunction, distanceFunction)) if (newPopulation.size > populationSize) { val dropList = newPopulation.drop(populationSize) val speciationController = populationEvolver.speciationController speciationController.speciesSet.forEach { species -> val speciesPopulation = speciationController.getSpeciesPopulation(species) speciesPopulation.filter { it in dropList }.forEach { neatMutator -> speciesPopulation.remove(neatMutator) } } } return newPopulation.take(populationSize) } @Serializable data class ZeldaDiscovery( val id: String, val currentLevel: Int, val xPos: Int, val yPos: Int, val killedEnemies: Int, val numberOfDeaths: Int, val sword: String, val numberOfBombs: Int, val hasBow: Boolean, val hasWhistle: Boolean, val hasFood: Boolean, val hasMagicRod: Boolean, val hasRaft: Boolean, val hasMagicBook: Boolean, val hasStepLadder: Boolean, val hasMagicKey: Boolean, val hasLetter: Boolean, val hasPowerBracelet: Boolean, val isClockPossessed: Boolean, val rupees: Int, val keys: Int, val heartContainers: Int, val hearts: Float, val hasBoomerang: Boolean, val hasMagicBoomerang: Boolean, val hasMagicShield: Boolean, val maxNumberOfBombs: Int, val mapLocation: Int ) val ZeldaDiscovery.swordValue get() = when(sword) { "None" -> 0 "Sword" -> 1 "White Sword" -> 2 "Magical Sword" -> 3 else -> 0 } fun Boolean.toFloat() = if (this) 1.toFloat() else 0.toFloat() fun ZeldaDiscovery.toVector(): List<Float> { return listOf<Float>( currentLevel.toFloat() * 10, xPos.toFloat() / 256, yPos.toFloat() /256, killedEnemies.toFloat(), numberOfDeaths.toFloat(), swordValue.toFloat() * 5, numberOfBombs.toFloat(), rupees.toFloat(), keys.toFloat(), heartContainers.toFloat(), hearts, maxNumberOfBombs.toFloat(), hasBow.toFloat(), hasBoomerang.toFloat(), hasFood.toFloat(), hasLetter.toFloat(), hasRaft.toFloat(), hasMagicBook.toFloat(), hasMagicBoomerang.toFloat(), hasMagicKey.toFloat(), hasMagicRod.toFloat(), hasMagicShield.toFloat(), hasStepLadder.toFloat(), hasPowerBracelet.toFloat(), hasWhistle.toFloat(), isClockPossessed.toFloat(), (mapLocation / 16).toFloat(), (mapLocation % 16).toFloat(), ) } fun Int.squared() = this * this fun List<Int>.actionString() = map { it.toChar() }.joinToString("") private fun Application.connectAndCreateDatabase() { launch { fun dbProp(propName: String) = environment.config.property("ktor.database.$propName") fun dbPropString(propName: String) = dbProp(propName).getString() Database.connect( url = dbPropString("url"), driver = dbPropString("driver"), user = dbPropString("user"), password = <PASSWORD>("<PASSWORD>") ) } } fun evaluationContext( controllers: List<IOController>, evaluationId: Int ) = EvaluationContext(evaluationId, controllers.map { it.controllerId }) @Serializable data class EvaluationContext(val evaluationId: Int, val controllers: List<Int>) class EvaluationMessageProcessor( val evaluationChannels: EvaluationChannels, val inputChannel: ReceiveChannel<MarioData>, val messageWriter: MessageWriter ) { suspend fun processOutput(controller: IOController) { for (frameOutput in controller.frameOutputChannel) { messageWriter.sendAllMessage( BroadcastMessage("simulation.frame.output", frameOutput), MarioOutput.serializer() ) } } suspend fun processPopulation() { for (frame in evaluationChannels.populationChannel) { messageWriter.sendPlayerMessage( userMessage = TypedUserMessage( userRef = UserRef("dashboard"), topic = "simulation.event.population.new", data = frame ), serializer = PopulationModels.serializer() ) } } suspend fun processAgentModel() { for (frame in evaluationChannels.agentModelChannel) { messageWriter.sendPlayerMessage( userMessage = TypedUserMessage( userRef = UserRef("dashboard"), topic = "simulation.event.agent.new", data = frame ), serializer = AgentModel.serializer() ) } } suspend fun processScores() { try { for (frame in evaluationChannels.scoreChannel) { messageWriter.sendPlayerMessage( userMessage = TypedUserMessage( userRef = UserRef("dashboard"), topic = "simulation.event.score.new", data = frame ), serializer = EvaluationScore.serializer() ) } } catch (e: Exception) { logger.error(e) { "Score processor crashed..." } } } suspend fun processFrameData(frameUpdateChannels: List<IOController>) { for (frame in inputChannel) { //forward to evaluation and broadcast data to dashboard frameUpdateChannels.forEach { it.frameUpdateChannel.send(frame) } // evaluationChannels.player1.frameUpdateChannel.send(frame) // evaluationChannels.player2.frameUpdateChannel.send(frame) messageWriter.sendPlayerMessage( userMessage = TypedUserMessage( userRef = UserRef("dashboard"), topic = "simulation.event.frame.update", data = frame ), serializer = MarioData.serializer() ) } } } private fun Application.networkEvaluatorOutputBridgeLoop( evaluationMessageProcessor: EvaluationMessageProcessor, controllers: List<IOController> ) { controllers.forEach { launch { evaluationMessageProcessor.processOutput(it) } } launch { evaluationMessageProcessor.processFrameData(controllers) } // launch { evaluationMessageProcessor.processEvaluationClocks() } launch { evaluationMessageProcessor.processPopulation() } launch { evaluationMessageProcessor.processAgentModel() } launch { evaluationMessageProcessor.processScores() } } fun previewMessage(frame: Frame.Text): String { val readText = frame.readText() val frameLength = readText.length return when { frameLength < 101 -> readText else -> { val messagePreview = readText.take(100) "$messagePreview...\n[[[rest of message has been trimmed]]]" } } } @Serializable data class Manifest(val scoreKeeperModel: SpeciesScoreKeeperModel, val scoreLineageModel: SpeciesLineageModel) /* launch(Dispatchers.IO) { var population = initialPopulation while (!receivedAnyMessages) { delay(100) } while (true) { launch(Dispatchers.IO) { val modelPopulationPersist = population.toModel() val savePopulationFile = runFolder.resolve("${populationEvolver.generation + 168}.json") val json = Json { prettyPrint = true } val encodedModel = json.encodeToString(modelPopulationPersist) savePopulationFile.bufferedWriter().use { it.write(encodedModel) it.flush() } val manifestFile = runFolder.resolve("manifest.json") val manifestData = Manifest( populationEvolver.scoreKeeper.toModel(), populationEvolver.speciesLineage.toModel() ) manifestFile.bufferedWriter().use { it.write(json.encodeToString(manifestData)) it.flush() } } val modelScores = evaluationArena.evaluatePopulation(population) { simulationFrame -> inAirFromKnockback(simulationFrame) opponentInAirFromKnockback(simulationFrame) processDamageDone(simulationFrame) processStockTaken(simulationFrame) processStockLoss(simulationFrame) if (simulationFrame.aiLoseGame) { gameLostFlag = true lastDamageDealt = 0f } }.toModelScores(adjustedFitness) populationEvolver.sortPopulationByAdjustedScore(modelScores) populationEvolver.updateScores(modelScores) var newPopulation = populationEvolver.evolveNewPopulation(modelScores) populationEvolver.speciate(newPopulation) while (newPopulation.size < population.size) { newPopulation = newPopulation + newPopulation.first().clone() } population = newPopulation } } */ @Serializable sealed class A() { abstract val a: String } @Serializable class B(override val a: String) : A() { }
0
CSS
0
3
215f13fd4140e32b882e3a8c68900b174d388d9f
22,327
NeatKotlin
Apache License 2.0
src/main/kotlin/org/lexem/angmar/parser/descriptive/expressions/macros/MacroCheckPropsNode.kt
lexemlang
184,409,059
false
{"Kotlin": 3049940}
package org.lexem.angmar.parser.descriptive.expressions.macros import com.google.gson.* import org.lexem.angmar.* import org.lexem.angmar.analyzer.nodes.descriptive.expressions.macros.* import org.lexem.angmar.config.* import org.lexem.angmar.errors.* import org.lexem.angmar.parser.* import org.lexem.angmar.parser.functional.expressions.macros.* import org.lexem.angmar.parser.literals.* /** * Parser for macro 'check props'. */ internal class MacroCheckPropsNode private constructor(parser: LexemParser, parent: ParserNode, parentSignal: Int) : ParserNode(parser, parent, parentSignal) { lateinit var value: PropertyStyleObjectBlockNode override fun toString() = StringBuilder().apply { append(macroName) append(value) }.toString() override fun toTree(): JsonObject { val result = super.toTree() result.add("value", value.toTree()) return result } override fun analyze(analyzer: LexemAnalyzer, signal: Int) = MacroCheckPropsAnalyzer.stateMachine(analyzer, signal, this) companion object { const val signalEndValue = 1 const val macroName = "check_props${MacroExpressionNode.macroSuffix}" // METHODS ------------------------------------------------------------ /** * Parses a macro 'check props'. */ fun parse(parser: LexemParser, parent: ParserNode, parentSignal: Int): MacroCheckPropsNode? { parser.fromBuffer(parser.reader.currentPosition(), MacroCheckPropsNode::class.java)?.let { it.parent = parent it.parentSignal = parentSignal return@parse it } val initCursor = parser.reader.saveCursor() val result = MacroCheckPropsNode(parser, parent, parentSignal) if (!parser.readText(macroName)) { return null } result.value = PropertyStyleObjectBlockNode.parse(parser, result, signalEndValue) ?: throw AngmarParserException( AngmarParserExceptionType.MacroCheckPropsWithoutPropertyStyleBlockAfterMacroName, "A property-style block was expected after the macro name '$macroName'.") { val fullText = parser.reader.readAllText() addSourceCode(fullText, parser.reader.getSource()) { title = Consts.Logger.codeTitle highlightSection(initCursor.position(), parser.reader.currentPosition() - 1) } addSourceCode(fullText, null) { title = Consts.Logger.hintTitle highlightCursorAt(parser.reader.currentPosition()) message = "Try adding an empty property-style block here '${PropertyStyleObjectBlockNode.startToken}${PropertyStyleObjectBlockNode.endToken}'" } } return parser.finalizeNode(result, initCursor) } } }
0
Kotlin
0
2
45fb563507a00c3eada89be9ab6e17cfe1701958
3,132
angmar
MIT License
app/src/main/java/com/okta/idx/android/sdk/IdxViewRegistry.kt
pauloscarin1972
349,203,216
true
{"Kotlin": 140007}
/* * Copyright 2021-Present Okta, 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.okta.idx.android.sdk import com.okta.idx.android.sdk.steps.ButtonStep import com.okta.idx.android.sdk.steps.ButtonViewFactory import com.okta.idx.android.sdk.steps.ChallengeAuthenticatorStep import com.okta.idx.android.sdk.steps.ChallengeAuthenticatorViewFactory import com.okta.idx.android.sdk.steps.EnrollAuthenticatorStep import com.okta.idx.android.sdk.steps.EnrollAuthenticatorViewFactory import com.okta.idx.android.sdk.steps.EnrollProfileStep import com.okta.idx.android.sdk.steps.EnrollProfileViewFactory import com.okta.idx.android.sdk.steps.IdentifyUsernameAndPasswordStep import com.okta.idx.android.sdk.steps.IdentifyUsernameAndPasswordViewFactory import com.okta.idx.android.sdk.steps.IdentifyUsernameStep import com.okta.idx.android.sdk.steps.IdentifyUsernameViewFactory import com.okta.idx.android.sdk.steps.SelectAuthenticatorStep import com.okta.idx.android.sdk.steps.SelectAuthenticatorViewFactory import com.okta.idx.sdk.api.model.RemediationOption import com.okta.idx.sdk.api.response.IDXResponse object IdxViewRegistry { private class FactoryWrapper<S : Step>( val stepFactory: StepFactory<S>, val viewFactory: ViewFactory<S>, ) { fun displayableStep(remediationOption: RemediationOption): DisplayableStep<S>? { val step = stepFactory.get(remediationOption) if (step != null) { return DisplayableStep(viewFactory, step) } return null } } private val stepHandlers = mutableMapOf<Class<*>, FactoryWrapper<*>>() init { register(ChallengeAuthenticatorStep.Factory(), ChallengeAuthenticatorViewFactory()) register( IdentifyUsernameAndPasswordStep.Factory(), IdentifyUsernameAndPasswordViewFactory() ) register(IdentifyUsernameStep.Factory(), IdentifyUsernameViewFactory()) register(SelectAuthenticatorStep.Factory(), SelectAuthenticatorViewFactory()) register(EnrollAuthenticatorStep.Factory(), EnrollAuthenticatorViewFactory()) register(ButtonStep.Factory(), ButtonViewFactory()) register(EnrollProfileStep.Factory(), EnrollProfileViewFactory()) } fun <S : Step> register( stepFactory: StepFactory<S>, viewFactory: ViewFactory<S>, ) { stepHandlers[stepFactory.javaClass] = FactoryWrapper(stepFactory, viewFactory) } fun asDisplaySteps(idxResponse: IDXResponse): List<DisplayableStep<*>> { val result = mutableListOf<DisplayableStep<*>>() val remediations = idxResponse.remediation()?.remediationOptions() if (remediations == null || remediations.isEmpty()) { throw IllegalStateException("Response not handled.") } for (remediation in remediations) { var handled = false for (stepHandler in stepHandlers.values) { val displayWrapper = stepHandler.displayableStep(remediation) if (displayWrapper != null) { result += displayWrapper handled = true break } } if (!handled) { val message = "remediationOption not handled. ${remediation.name}" throw IllegalStateException(message) } } return result } }
0
null
0
0
82b653b3d2457fa9b8683824ee5b45d9175e5a6c
3,959
okta-idx-android
Apache License 2.0
core/component-controller/src/main/kotlin/com/merxury/blocker/core/controllers/ifw/IfwController.kt
lihenggui
115,417,337
false
null
/* * Copyright 2023 Blocker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.merxury.blocker.core.controllers.ifw import android.content.ComponentName import android.content.pm.ComponentInfo import android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED import android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED import com.merxury.blocker.core.controllers.IController import com.merxury.core.ifw.IIntentFirewall import timber.log.Timber import javax.inject.Inject import javax.inject.Singleton @Singleton class IfwController @Inject constructor( private val intentFirewall: IIntentFirewall, ) : IController { override suspend fun switchComponent( packageName: String, componentName: String, state: Int, ): Boolean { return when (state) { COMPONENT_ENABLED_STATE_DISABLED -> intentFirewall.add(packageName, componentName) COMPONENT_ENABLED_STATE_ENABLED -> intentFirewall.remove(packageName, componentName) else -> false } } override suspend fun enable(packageName: String, componentName: String): Boolean { return switchComponent( packageName, componentName, COMPONENT_ENABLED_STATE_ENABLED, ) } override suspend fun disable(packageName: String, componentName: String): Boolean { return switchComponent( packageName, componentName, COMPONENT_ENABLED_STATE_DISABLED, ) } override suspend fun batchEnable( componentList: List<ComponentInfo>, action: suspend (info: ComponentInfo) -> Unit, ): Int { if (componentList.isEmpty()) { Timber.w("No component to enable") return 0 } var succeededCount = 0 val list = componentList.map { ComponentName(it.packageName, it.name) } intentFirewall.removeAll(list) { succeededCount++ action( ComponentInfo().apply { packageName = it.packageName name = it.className }, ) } return succeededCount } override suspend fun batchDisable( componentList: List<ComponentInfo>, action: suspend (info: ComponentInfo) -> Unit, ): Int { if (componentList.isEmpty()) { Timber.w("No component to disable") return 0 } var succeededCount = 0 val list = componentList.map { ComponentName(it.packageName, it.name) } intentFirewall.addAll(list) { succeededCount++ action( ComponentInfo().apply { packageName = it.packageName name = it.className }, ) } return succeededCount } override suspend fun checkComponentEnableState( packageName: String, componentName: String, ): Boolean { return intentFirewall.getComponentEnableState(packageName, componentName) } }
23
null
50
840
759e650c55a84ffa985837653cb6798878b53889
3,614
blocker
Apache License 2.0
depcare-supplier/src/main/kotlin/com/appga/depcare/supplier/utils/Metrics.kt
grzegorz-aniol
362,205,169
false
{"Kotlin": 71412}
package com.appga.depcare.supplier.utils import mu.KLogging import org.springframework.stereotype.Component import java.util.concurrent.atomic.AtomicLong @Component class Metrics { private companion object : KLogging() private val mvnRepoPages = AtomicLong() private val mvnDocumentsFetched = AtomicLong() private val libraryAdded = AtomicLong() private val versionAdded = AtomicLong() fun mvnRepoPageVisited(url: String) { val cnt = mvnRepoPages.incrementAndGet() logger.debug { "Page visited $url (total: $cnt)"} } fun mvnRepoDocumentFetched(url: String) { val cnt = mvnDocumentsFetched.incrementAndGet() logger.debug { "Document fetched $url (total: $cnt)" } } fun dbLibraryAdded(name: String) { val cnt = libraryAdded.incrementAndGet() logger.debug { "Library added $name (total: $cnt)"} } fun dbVersionAdded(name: String) { val cnt = versionAdded.incrementAndGet() logger.debug { "Version added $name (total: $cnt)"} } }
3
Kotlin
0
0
f3735ab79a446556a3e7678f96091526fbb06ecc
967
depcare
Apache License 2.0
investor/src/main/java/com/mityushov/investor/screens/stockFragment/StockFragment.kt
NikitaMityushov
391,630,324
false
null
package com.mityushov.investor.screens.stockFragment import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.lifecycle.ViewModelProvider import com.mityushov.investor.data.StockRepository import com.mityushov.investor.databinding.FragmentStockBinding import com.mityushov.investor.navigation.navigator import com.mityushov.investor.models.CacheStockPurchase import java.util.* import com.mityushov.investor.utils.setTextColorRedOrGreen import timber.log.Timber private const val ARG_STOCK_ID = "stock_id" class StockFragment private constructor() : Fragment() { private lateinit var binding: FragmentStockBinding private lateinit var viewModel: StockFragmentViewModel private lateinit var viewModelFactory: StockFragmentViewModelFactory private lateinit var id: UUID override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val stockId: UUID = arguments?.getSerializable(ARG_STOCK_ID) as UUID id = stockId viewModelFactory = StockFragmentViewModelFactory(id, StockRepository.get()) Timber.i("StockFragments args bundle stock ID: $stockId") } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View { binding = FragmentStockBinding.inflate(inflater, container, false) viewModel = ViewModelProvider(this, viewModelFactory).get(StockFragmentViewModel::class.java) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel.data.observe(viewLifecycleOwner, { stock -> updateUI(stock) }) binding.fragmentStockDeleteBtn.setOnClickListener { viewModel.deleteStock() Toast.makeText(context, "Successfully deleted", Toast.LENGTH_SHORT).show() this.activity?.onBackPressed() } binding.fragmentStockUpdateBtn.setOnClickListener { Timber.d("Update button is pressed") this.navigator().onUpdateButtonPressed(viewModel.getStockPurchase()) } } private fun updateUI(stock: CacheStockPurchase) { Timber.d("UpdateUI is called, stock is $stock") binding.apply { fragmentStockTickerValueTv.text = stock.ticker fragmentStockAmountValueTv.text = stock.amount.toString() fragmentStockPurchaseCurrencyValueTv.text = String.format("%.2f", stock.purchaseCurrency) fragmentStockPurchasePriceValueTv.text = String.format("%.2f", stock.purchasePrice) fragmentStockPurchaseTaxValueTv.text = String.format("%.2f", stock.purchaseTax) fragmentStockCurrentCurrencyValueTv.text = String.format("%.2f", stock.currentCurrency) fragmentStockCurrentPriceValueTv.text = String.format("%.2f", stock.currentPrice) fragmentStockTotalProfitValueTv.apply { val value = stock.totalProfit text = String.format("%.2f", value) setTextColorRedOrGreen(value, this) } fragmentStockProfitabilityValueTv.apply { val value = stock.profitability text = String.format("%.2f%%", value) setTextColorRedOrGreen(value, this) } } } companion object { fun newInstance(stockId: UUID): StockFragment { Timber.i("newInstance is called") val args = Bundle().apply { putSerializable(ARG_STOCK_ID, stockId) } return StockFragment().apply { arguments = args } } } }
0
Kotlin
0
0
97cb04c80682e923cc910531f079b347c5c3d6e6
3,933
AndroidClasses
MIT License
source-code/final-project/app/src/main/java/com/droidcon/graphqlmaster/data/ApolloGraphQlClientImpl.kt
droidcon-academy
788,308,556
false
{"Kotlin": 101794, "Python": 10111, "Dockerfile": 1172, "Procfile": 60}
package com.droidcon.graphqlmaster.data import com.apollographql.apollo3.ApolloClient import com.apollographql.apollo3.api.ApolloResponse import com.apollographql.apollo3.exception.ApolloHttpException import com.droidcon.DeleteCollegeMutation import com.droidcon.GetCollegesByCollegeIdQuery import com.droidcon.GetCollegesQuery import com.droidcon.GetFragmentStudentsByCollegeIdQuery import com.droidcon.GetPaginatedCollegesQuery import com.droidcon.SubscribeCollegeSubscription import com.droidcon.graphqlmaster.domain.IGraphQLClient import com.droidcon.graphqlmaster.domain.model.CollegeEntity import com.droidcon.graphqlmaster.domain.model.CollegeRequestEntity import com.droidcon.graphqlmaster.domain.model.PaginationCollegeEntity import com.droidcon.graphqlmaster.domain.model.StudentEntity import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.flow class ApolloGraphQlClientImpl ( private val apolloClient: ApolloClient, private val apolloClientWS: ApolloClient ): IGraphQLClient { override suspend fun getCollegeByCollegeId(collegeId: Int): CollegeEntity? { return try { apolloClient .query(GetCollegesByCollegeIdQuery(collegeId)) .execute() .data ?.collegeById ?.toCollegeEntity() } catch (e: ApolloHttpException) { null } } override suspend fun getColleges(): List<CollegeEntity> { return try { apolloClient .query(GetCollegesQuery()) .execute() .data ?.colleges ?.map { it.toCollegeEntity() } ?: emptyList() } catch (e: ApolloHttpException) { emptyList() } } override suspend fun getFragmentStudentByCollegeId(collegeId: Int): CollegeEntity? { return try { apolloClient .query(GetFragmentStudentsByCollegeIdQuery(collegeId)) .execute() .data ?.collegeWithStudents?.toCollegeEntity() } catch (e: ApolloHttpException) { null } } override suspend fun getPaginationColleges(limit: Int, skip: Int): PaginationCollegeEntity? { return try { apolloClient .query(GetPaginatedCollegesQuery(limit, skip)) .execute() .data ?.paginationColleges?.toPaginationCollegeEntity() } catch (e: ApolloHttpException) { null } } override suspend fun addCollege(collegeRequestEntity: CollegeRequestEntity): CollegeEntity? { return try { apolloClient .mutation(collegeRequestEntity.toCreateCollegeMutation()) .execute() .data ?.createCollege?.toCreateCollegeEntity()!! } catch (e: ApolloHttpException) { null } } override suspend fun updateCollege(collegeRequestEntity: CollegeRequestEntity): CollegeEntity? { return try { apolloClient .mutation(collegeRequestEntity.toUpdateCollegeMutation()) .execute() .data ?.updateCollege?.toUpdateCollegeEntity()!! } catch (e: ApolloHttpException) { null } } override suspend fun deleteCollege(collegeId: Int): Boolean { return try { apolloClient .mutation(DeleteCollegeMutation(collegeId)) .execute() .data ?.deleteCollege?.let { true } ?: false } catch (e: ApolloHttpException) { false } } override suspend fun subscribeToCollege(collegeId: Int): Flow<StudentEntity> = flow { val subscription = SubscribeCollegeSubscription(collegeId) try { apolloClientWS.subscription(subscription) .toFlow().catch { print(it.message) } .collect { response: ApolloResponse<SubscribeCollegeSubscription.Data> -> print(response) response.data?.subscribeCollege?.let { emit(StudentEntity( id = it.id, name = it.name, dob = it.dob, collegeId = it.collegeId, profileUrl = it.profileUrl, gender = it.gender )) } } } catch (e: ApolloHttpException) { // TODO } } }
0
Kotlin
0
0
96a9fd35681f65ca3fbf7ecdf03f1424782983df
4,517
android-mc-graphql
Apache License 2.0
src/main/kotlin/com/github/bjansen/intellij/pebble/formatting/PebbleFormattingModelBuilder.kt
lb321
281,162,588
true
{"Kotlin": 161453, "Java": 29139, "ANTLR": 6647, "HTML": 343}
package com.github.bjansen.intellij.pebble.formatting import com.github.bjansen.intellij.pebble.psi.PebbleParserDefinition import com.github.bjansen.pebble.parser.PebbleLexer import com.intellij.formatting.Alignment import com.intellij.formatting.Indent import com.intellij.formatting.Wrap import com.intellij.formatting.templateLanguages.* import com.intellij.lang.ASTNode import com.intellij.psi.codeStyle.CodeStyleSettings import com.intellij.psi.formatter.xml.SyntheticBlock /** * Creates formatting blocks for Pebble code and templated language code. */ class PebbleFormattingModelBuilder : TemplateLanguageFormattingModelBuilder() { override fun createTemplateLanguageBlock(node: ASTNode, wrap: Wrap?, alignment: Alignment?, foreignChildren: MutableList<DataLanguageBlockWrapper>?, codeStyleSettings: CodeStyleSettings) = PebbleBlock(this, codeStyleSettings, node, foreignChildren) } class PebbleBlock(blockFactory: TemplateLanguageBlockFactory, settings: CodeStyleSettings, node: ASTNode, foreignChildren: MutableList<DataLanguageBlockWrapper>?) : TemplateLanguageBlock(blockFactory, settings, node, foreignChildren) { override fun getTemplateTextElementType() = PebbleParserDefinition.tokens[PebbleLexer.CONTENT] override fun getIndent(): Indent? { // If the parent is a block coming from another language, keep its child indent val foreignParent = getForeignBlockParent(true) if (foreignParent != null) { return Indent.getIndent(Indent.Type.NONE, 0, true, false) } return Indent.getNoneIndent() } /** * Returns this block's first "real" foreign block parent if it exists, and null otherwise. (By "real" here, we mean that this method * skips SyntheticBlock blocks inserted by the template formatter) * * @param immediate Pass true to only check for an immediate foreign parent, false to look up the hierarchy. */ private fun getForeignBlockParent(immediate: Boolean): DataLanguageBlockWrapper? { var foreignBlockParent: DataLanguageBlockWrapper? = null var parent: BlockWithParent? = parent while (parent != null) { if (parent is DataLanguageBlockWrapper && parent.original !is SyntheticBlock) { foreignBlockParent = parent break } else if (immediate && parent is PebbleBlock) { break } parent = parent.parent } return foreignBlockParent } }
0
null
0
0
b4c761f8ab51e62dc220ab5a378d3234578e8de1
2,639
pebble-intellij
MIT License
library/src/main/java/com/freakyaxel/nfc/api/CardReader.kt
alexpopa95
574,745,516
false
null
package com.freakyaxel.nfc.api import android.content.Context import android.nfc.tech.IsoDep import com.freakyaxel.nfc.card.CardData import com.freakyaxel.nfc.intent.NfcIntentProvider import com.freakyaxel.nfc.provider.TransceiverProvider import com.freakyaxel.nfc.reader.CardReaderImpl import com.github.devnied.emvnfccard.parser.EmvTemplate interface CardReader { fun getCard(isoDep: IsoDep): CardData fun getCardResult(isoDep: IsoDep): Result<CardData> fun openNfcSettings(context: Context) companion object { fun newInstance(): CardReader { val config = EmvTemplate.Config() .setContactLess(true) // Enable contact less reading .setReadAllAids(false) // Read all aids in card .setReadTransactions(false) // Read all transactions .setRemoveDefaultParsers(false) // Remove default parsers (GeldKarte and Emv) .setReadAt(true) // To extract ATS or ATR .setReadCplc(false) // To read CPLC data. Not for contactless cards. return CardReaderImpl( config = config, builder = EmvTemplate.Builder(), provider = TransceiverProvider(), intentProvider = NfcIntentProvider() ) } } }
0
Kotlin
0
2
8c27dc1b4da6f095ecc5e3f7fb82463e8d3ef4aa
1,311
nfc-card-reader
MIT License
repository/src/test/java/com/sukhaikoh/reborn/repository/RebornMaybeTest.kt
bossmansingh
224,263,231
false
{"Kotlin": 126308}
/* * Copyright (C) 2019 <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.sukhaikoh.reborn.repository import com.sukhaikoh.reborn.result.Result import com.sukhaikoh.reborn.testhelper.SchedulersTestExtension import io.reactivex.Maybe import io.reactivex.exceptions.CompositeException import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(SchedulersTestExtension::class) class RebornMaybeTest { @Test fun `when Maybe result with data then downstream receive Result success with upstream data`() { val data = "data" Maybe.just(data) .result() .test() .assertValues(Result.success(data)) } @Test fun `when Maybe result with empty upstream then downstream receive Result success with no data`() { Maybe.empty<Nothing>() .result() .test() .assertValues(Result.success()) } @Test fun `when Maybe result with upstream error then downstream receive Result error`() { val throwable = Throwable() Maybe.error<Nothing>(throwable) .result() .test() .assertValues(Result.error(throwable)) } @Test fun `when Maybe doOnSuccess with Result success then call mapper`() { val data = "data" var called = false Maybe.just(Result.success(data)) .doOnResultSuccess { assertEquals(Result.success(data), it) called = true } .test() .assertComplete() assertTrue(called) } @Test fun `when Maybe doOnSuccess with Result loading then do not call mapper`() { var called = false Maybe.just(Result.loading<Nothing>()) .doOnResultSuccess { called = true } .test() .assertComplete() assertFalse(called) } @Test fun `when Maybe doOnSuccess with Result error then do not call mapper`() { var called = false Maybe.just(Result.error<Nothing>(Throwable())) .doOnResultSuccess { called = true } .test() .assertComplete() assertFalse(called) } @Test fun `when Maybe doOnFailure with Result error then call mapper`() { val data = "data" val throwable = Throwable() var called = false Maybe.just(Result.error(throwable, data)) .doOnFailure { assertEquals(Result.error(throwable, data), it) called = true } .test() .assertComplete() assertTrue(called) } @Test fun `when Maybe doOnFailure with Result loading then do not call mapper`() { var called = false Maybe.just(Result.loading<Nothing>()) .doOnFailure { called = true } .test() .assertComplete() assertFalse(called) } @Test fun `when Maybe doOnFailure with Result success then do not call mapper`() { var called = false Maybe.just(Result.success<Nothing>()) .doOnFailure { called = true } .test() .assertComplete() assertFalse(called) } @Test fun `when Maybe doOnLoading with Result loading then call mapper`() { val data = "data" var called = false Maybe.just(Result.loading(data)) .doOnLoading { assertEquals(Result.loading(data), it) called = true } .test() .assertComplete() assertTrue(called) } @Test fun `when Maybe doOnLoading with Result error then do not call mapper`() { var called = false Maybe.just(Result.error<Nothing>(Throwable())) .doOnLoading { called = true } .test() .assertComplete() assertFalse(called) } @Test fun `when Maybe doOnLoading with Result success then do not call mapper`() { var called = false Maybe.just(Result.success<Nothing>()) .doOnLoading { called = true } .test() .assertComplete() assertFalse(called) } @Test fun `when Maybe load with skip return true then do no call mapper`() { var called = false val data = "data" val data1 = "data1" Maybe.just(Result.success(data)) .load({ true }) { called = true Maybe.just(Result.success(data1)) } .test() .assertValues(Result.success(data)) assertFalse(called) } @Test fun `when Maybe load with skip return false then call mapper`() { val data1 = "data1" val data2 = "data2" Maybe.just(Result.success(data1)) .load({ false }) { Maybe.just(Result.success(data2)) } .test() .assertValues(Result.success(data2)) } @Test fun `when Maybe load and mapper throws error then map to Result error`() { val throwable = Throwable() val data = "data" Maybe.just(Result.success(data)) .load { throw throwable } .test() .assertValues(Result.error(throwable, data)) } @Test fun `when Maybe load and mapper emit error then map to Result error`() { val throwable = Throwable() val data = "data" Maybe.just(Result.success(data)) .load { Maybe.error(throwable) } .test() .assertValues(Result.error(throwable, data)) } @Test fun `when Maybe load and mapper throws error and upstream also is error then map to Result CompositeException`() { val upstreamThrowable = NullPointerException() val throwable = IllegalArgumentException() val data = "data" val result = Maybe.just(Result.error(upstreamThrowable, data)) .load { throw throwable } .test() .values() .last() assertTrue(result.cause != null) assertTrue(result.cause is CompositeException) assertEquals(upstreamThrowable, (result.cause as CompositeException).exceptions[0]) assertEquals(throwable, (result.cause as CompositeException).exceptions[1]) assertEquals(data, result.data) } @Test fun `when Maybe load and mapper emit error and upstream also is error then map to Result CompositeException`() { val upstreamThrowable = NullPointerException() val throwable = IllegalArgumentException() val data = "data" val result = Maybe.just(Result.error(upstreamThrowable, data)) .load { Maybe.error(throwable) } .test() .values() .last() assertTrue(result.cause != null) assertTrue(result.cause is CompositeException) assertEquals(upstreamThrowable, (result.cause as CompositeException).exceptions[0]) assertEquals(throwable, (result.cause as CompositeException).exceptions[1]) assertEquals(data, result.data) } @Test fun `when Maybe load and mapper emit empty Maybe then map to Result success`() { val data = "data" Maybe.just(Result.success(data)) .load { Maybe.empty() } .test() .assertValues(Result.success(data)) } @Test fun `when Maybe load and mapper emit result then same result will be passed to downstream`() { val data1 = "data1" val data2 = "data2" Maybe.just(Result.success(data1)) .load { Maybe.just(data2).result() } .test() .assertValues(Result.success(data2)) } @Test fun `when Maybe execute() is called and upstream has no error then emit Result success`() { val data = "data" Maybe.just(data) .execute() .test() .assertValues(Result.success(data)) } @Test fun `when Maybe execute() is called and upstream has error then emit Result error`() { val error = Throwable() Maybe.just(123) .flatMap { Maybe.error<Int>(error) } .execute() .test() .assertValues(Result.error(error)) } }
0
null
0
0
c4f10359a3feaa18de2b948cc5152589204a668c
9,013
reborn
Apache License 2.0
domain/src/main/java/com/rsdosev/domain/model/TramStop.kt
RSDosev
301,542,543
false
null
package com.rsdosev.domain.model enum class TramStop(val abr: String, val fullName: String) { STX ("STX", "St. Stephen's Green"), HIN ("HIN", "Heuston"), HCT ("HCT", "Heuston"), TPT ("TPT", "The Point"), SDK ("SDK", "Spencer Dock"), MYS ("MYS", "Mayor Square NCI"), GDK ("GDK", "George's Dock"), CON ("CON", "Connolly"), BUS ("BUS", "Busáras"), ABB ("ABB", "Abbey Street"), JER ("JER", "Jervis"), FOU ("FOU", "Four Courts"), SMI ("SMI", "Smithfield"), MUS ("MUS", "Museum"), HEU ("HEU", "Heuston"), JAM ("JAM", "James's"), FAT ("FAT", "Fatima"), RIA ("RIA", "Rialto"), SUI ("SUI", "Suir Road"), GOL ("GOL", "Goldenbridge"), DRI ("DRI", "Drimnagh"), BLA ("BLA", "Blackhorse"), BLU ("BLU", "Bluebell"), KYL ("KYL", "Kylemore"), RED ("RED", "Red Cow"), KIN ("KIN", "Kingswood"), BEL ("BEL", "Belgard"), COO ("COO", "Cookstown"), HOS ("HOS", "Hospital"), TAL ("TAL", "Tallaght"), FET ("FET", "Fettercairn"), CVN ("CVN", "Cheeverstown"), CIT ("CIT", "Citywest Campus"), FOR ("FOR", "Fortunestown"), SAG ("SAG", "Saggart"), DEP ("DEP", "Depot"), BRO ("BRO", "Broombridge"), CAB ("CAB", "Cabra"), PHI ("PHI", "Phibsborough"), GRA ("GRA", "Grangegorman"), BRD ("BRD", "Broadstone DIT"), DOM ("DOM", "Dominick"), PAR ("PAR", "Parnell"), OUP ("OUP", "O'Connell Upper"), OGP ("OGP", "O'Connell GPO"), MAR ("MAR", "Marlborough"), WES ("WES", "Westmoreland"), TRY ("TRY", "Trinity"), DAW ("DAW", "Dawson"), STS ("STS", "St. Stephen's Green"), HAR ("HAR", "Harcourt"), CHA ("CHA", "Charlemont"), RAN ("RAN", "Ranelagh"), BEE ("BEE", "Beechwood"), COW ("COW", "Cowper"), MIL ("MIL", "Milltown"), WIN ("WIN", "Windy Arbour"), DUN ("DUN", "Dundrum"), BAL ("BAL", "Balally"), KIL ("KIL", "Kilmacud"), STI ("STI", "Stillorgan"), SAN ("SAN", "Sandyford"), CPK ("CPK", "Central Park"), GLE ("GLE", "Glencairn"), GAL ("GAL", "The Gallops"), LEO ("LEO", "Leopardstown Valley"), BAW ("BAW", "Ballyogan Wood"), RCC ("RCC", "Racecourse"), CCK ("CCK", "Carrickmines"), BRE ("BRE", "Brennanstown"), LAU ("LAU", "Laughanstown"), CHE ("CHE", "Cherrywood"), BRI ("BRI", "Bride's Glen") }
0
Kotlin
0
0
20ac1a66882ab07821326597a37aec07575bde0a
2,349
RIM-Employees-LUAS
Apache License 2.0
app/shared/google-sign-in/impl/src/androidMain/kotlin/build/wallet/google/signin/GoogleSignInClientProviderImpl.kt
proto-at-block
761,306,853
false
{"C": 10424094, "Kotlin": 7156393, "Rust": 2046237, "Swift": 700307, "Python": 331492, "HCL": 271992, "Shell": 111209, "TypeScript": 102700, "C++": 64770, "Meson": 64234, "JavaScript": 36227, "Just": 28071, "Ruby": 9428, "Dockerfile": 5731, "Makefile": 3839, "Open Policy Agent": 1552, "Procfile": 80}
package build.wallet.google.signin import build.wallet.platform.PlatformContext import com.google.android.gms.auth.api.signin.GoogleSignIn import com.google.android.gms.auth.api.signin.GoogleSignInClient import com.google.android.gms.auth.api.signin.GoogleSignInOptions import com.google.android.gms.common.Scopes import com.google.android.gms.common.api.Scope class GoogleSignInClientProviderImpl( private val platformContext: PlatformContext, ) : GoogleSignInClientProvider { override val clientForGoogleDrive: GoogleSignInClient by lazy { val options = GoogleSignInOptions.Builder() // TODO(W-701): can we avoid asking for email? .requestEmail() .requestScopes( Scope( Scopes.DRIVE_APPFOLDER ), // used by [GoogleDriveKeyValueStore] for storing encrypted app backup Scope( Scopes.DRIVE_FILE ) // used by [GoogleDriveFileStore] for storing Emergency Access Kit PDF ) .build() GoogleSignIn.getClient(platformContext.appContext, options) } }
0
C
10
98
1f9f2298919dac77e6791aa3f1dbfd67efe7f83c
1,068
bitkey
MIT License
app/src/main/java/in/developingdeveloper/timeline/eventlist/ui/components/EventList.kt
5AbhishekSaxena
624,931,376
false
null
package `in`.developingdeveloper.timeline.eventlist.ui.components import android.content.res.Configuration import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.Surface import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import `in`.developingdeveloper.timeline.core.ui.theme.TimelineTheme import `in`.developingdeveloper.timeline.eventlist.ui.models.UIEvent import java.time.LocalDateTime @Composable fun EventList( events: List<UIEvent>, modifier: Modifier = Modifier, ) { LazyColumn( verticalArrangement = Arrangement.spacedBy(12.dp), modifier = modifier.fillMaxSize(), contentPadding = PaddingValues(16.dp), ) { items(events) { event -> EventListItem(event = event) } } } @Preview( name = "Night Mode", uiMode = Configuration.UI_MODE_NIGHT_YES, ) @Preview( name = "Day Mode", uiMode = Configuration.UI_MODE_NIGHT_NO, ) @Composable @Suppress("UnusedPrivateMember", "MagicNumber") private fun EventListPreview() { val event = UIEvent( "", "Sample title", listOf("#Android", "#Kotlin"), LocalDateTime.now(), LocalDateTime.now(), ) val events = (1..10).map { event.copy(id = it.toString()) } TimelineTheme { Surface { EventList(events) } } }
9
null
3
18
44cbc20a430e0d012d982b4adb11ae626af1c404
1,689
Timeline
Apache License 2.0
src/main/kotlin/org/wfanet/panelmatch/client/launcher/ExchangeStepExecutor.kt
world-federation-of-advertisers
349,561,061
false
{"Kotlin": 9528593, "Starlark": 908739, "C++": 624137, "CUE": 164605, "HCL": 156622, "TypeScript": 101485, "Shell": 20877, "CSS": 9620, "Go": 8063, "JavaScript": 5305, "HTML": 2489}
// Copyright 2021 The Cross-Media Measurement Authors // // 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.wfanet.panelmatch.client.launcher import org.wfanet.measurement.api.v2alpha.CanonicalExchangeStepAttemptKey import org.wfanet.measurement.api.v2alpha.ExchangeStep import org.wfanet.measurement.api.v2alpha.ExchangeWorkflow /** Executes [ExchangeWorkflow.Step]s. */ interface ExchangeStepExecutor { /** Executes [step]. */ suspend fun execute(exchangeStep: ExchangeStep, attemptKey: CanonicalExchangeStepAttemptKey) }
127
Kotlin
11
33
24a8b93f7c536411e08355b766fd991fdc45aebc
1,048
cross-media-measurement
Apache License 2.0