path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
src/main/kotlin/com/theapache64/gpm/commands/subcommands/docs/DocsComponent.kt
theapache64
259,502,102
false
null
package com.theapache64.gpm.commands.subcommands.docs import com.theapache64.gpm.core.TransactionManager import com.theapache64.gpm.di.GpmJsonFile import com.theapache64.gpm.di.modules.NetworkModule import com.theapache64.gpm.di.modules.TransactionModule import dagger.Component import java.io.File import javax.inject.Singleton @Singleton @Component(modules = [TransactionModule::class, NetworkModule::class]) interface DocsComponent { fun transactionManager(): TransactionManager fun inject(docs: Docs) @GpmJsonFile fun gpmJsonFile(): File }
16
Kotlin
1
75
8c73437d7258279acc9da4d9385308f32a135bb0
563
gpm
Apache License 2.0
app/src/main/java/github/hellocsl/cursorwheellayout/widget/SimpleTextCursorWheelLayout.kt
shadygoneinsane
314,180,246
true
{"Gradle": 4, "XML": 17, "Java Properties": 2, "Shell": 1, "Ignore List": 3, "Batchfile": 1, "Text": 2, "Markdown": 1, "Proguard": 2, "Java": 4, "Kotlin": 8}
package github.hellocsl.cursorwheellayout.widget import android.content.Context import android.util.AttributeSet import android.view.View import github.hellocsl.cursorwheel.CursorWheelLayout import github.hellocsl.cursorwheellayout.R /** * * Created by chensuilun on 16-4-19. */ class SimpleTextCursorWheelLayout(context: Context, attrs: AttributeSet?) : CursorWheelLayout(context, attrs) { override fun onInnerItemSelected(v: View?) { super.onInnerItemSelected(v) val tv = v?.findViewById<View>(R.id.wheel_menu_item_tv) tv?.animate()?.scaleX(2f)?.scaleY(2f) } override fun onInnerItemUnselected(v: View?) { super.onInnerItemUnselected(v) val tv = v?.findViewById<View>(R.id.wheel_menu_item_tv) tv?.animate()?.scaleX(1f)?.scaleY(1f) } companion object { const val MENU_COUNT = 10 const val INDEX_SPEC = 9 } }
0
Kotlin
0
1
9526de065414f4225610f8120d3bc7a3a9ced95b
903
CursorWheelLayout
Apache License 2.0
app/src/main/java/github/hellocsl/cursorwheellayout/widget/SimpleTextCursorWheelLayout.kt
shadygoneinsane
314,180,246
true
{"Gradle": 4, "XML": 17, "Java Properties": 2, "Shell": 1, "Ignore List": 3, "Batchfile": 1, "Text": 2, "Markdown": 1, "Proguard": 2, "Java": 4, "Kotlin": 8}
package github.hellocsl.cursorwheellayout.widget import android.content.Context import android.util.AttributeSet import android.view.View import github.hellocsl.cursorwheel.CursorWheelLayout import github.hellocsl.cursorwheellayout.R /** * * Created by chensuilun on 16-4-19. */ class SimpleTextCursorWheelLayout(context: Context, attrs: AttributeSet?) : CursorWheelLayout(context, attrs) { override fun onInnerItemSelected(v: View?) { super.onInnerItemSelected(v) val tv = v?.findViewById<View>(R.id.wheel_menu_item_tv) tv?.animate()?.scaleX(2f)?.scaleY(2f) } override fun onInnerItemUnselected(v: View?) { super.onInnerItemUnselected(v) val tv = v?.findViewById<View>(R.id.wheel_menu_item_tv) tv?.animate()?.scaleX(1f)?.scaleY(1f) } companion object { const val MENU_COUNT = 10 const val INDEX_SPEC = 9 } }
0
Kotlin
0
1
9526de065414f4225610f8120d3bc7a3a9ced95b
903
CursorWheelLayout
Apache License 2.0
facebookimagepicker/src/main/java/com/imagepicker/facebook/view/photos/FacebookPhotosFragment.kt
oantajames
106,604,969
false
null
package com.imagepicker.facebook.view.photos import android.app.Activity import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.Bundle import android.support.v4.content.LocalBroadcastManager import android.support.v7.app.ActionBar import android.support.v7.widget.RecyclerView import android.support.v7.widget.StaggeredGridLayoutManager import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ProgressBar import android.widget.Toast import com.imagepicker.facebook.facebookimagepicker.R import com.imagepicker.facebook.jobs.jobslist.PhotosJob import com.imagepicker.facebook.jobs.FacebookJobManager import com.imagepicker.facebook.model.FacebookPhoto import com.imagepicker.facebook.view.BaseRecyclerAdapter import com.imagepicker.facebook.view.FacebookGalleryActivity import android.support.v7.app.AppCompatActivity import com.imagepicker.facebook.view.FacebookGalleryActivity.Companion.FACEBOOK_PHOTO_ITEM class FacebookPhotosFragment : android.support.v4.app.Fragment(), BaseRecyclerAdapter.EndlessScrollListener, FacebookPhotosAdapter.PhotosAction { companion object { fun getBundle(albumId: String, albumTitle: String): Bundle { val bundle = Bundle() bundle.putString(FacebookGalleryActivity.Companion.FACEBOOK_ALBUM_ID, albumId) bundle.putString(FacebookGalleryActivity.Companion.FACEBOOK_ALBUM_TITLE, albumTitle) return bundle } } val TAG: String = FacebookPhotosFragment::class.java.simpleName lateinit var facebookJobManager: FacebookJobManager lateinit var recyclerView: RecyclerView lateinit var adapter: FacebookPhotosAdapter lateinit var progressBar: ProgressBar lateinit var supportActionBar: ActionBar var albumId: String? = null var albumTitle: String? = null override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View { val view = inflater!!.inflate(R.layout.activity_facebook_album_gallery, container, false) if (arguments != null) { albumId = arguments.getString(FacebookGalleryActivity.Companion.FACEBOOK_ALBUM_ID) albumTitle = arguments.getString(FacebookGalleryActivity.Companion.FACEBOOK_ALBUM_TITLE) } supportActionBar = (activity as AppCompatActivity).supportActionBar!! supportActionBar.title = albumTitle progressBar = view.findViewById(R.id.progress_bar) recyclerView = view.findViewById(R.id.facebook_recycler_view) facebookJobManager = FacebookJobManager.getInstance() adapter = FacebookPhotosAdapter(this) adapter.setEndlessScrollListener(this) val layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL) recyclerView.layoutManager = layoutManager recyclerView.adapter = adapter if (albumId != null) facebookJobManager.getPhotos(albumId!!) return view } override fun onResume() { super.onResume() registerReceiver() } override fun onStop() { super.onStop() LocalBroadcastManager.getInstance(activity.applicationContext).unregisterReceiver(broadcastReceiver) } private val broadcastReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val action = intent.action if (action == PhotosJob.BROADCAST_PHOTOS_SUCCESS) { if (intent.extras != null) { val list: ArrayList<FacebookPhoto> = intent.extras.getParcelableArrayList(PhotosJob.PHOTOS_LIST) Log.d(TAG, list.toString()) adapter.loadMoreItems = intent.extras.getBoolean(PhotosJob.HAS_NEXT_PAGE) progressBar.visibility = View.INVISIBLE adapter.addItems(list as MutableList<FacebookPhoto>) } } else if (action == PhotosJob.BROADCAST_PHOTOS_ERROR) { destroyAndNotifyUser() } } } private fun registerReceiver() { val intentFilter = IntentFilter() intentFilter.addAction(PhotosJob.BROADCAST_PHOTOS_SUCCESS) LocalBroadcastManager.getInstance(activity.applicationContext).registerReceiver(broadcastReceiver, intentFilter) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (data != null) { FacebookJobManager.getInstance().onActivityResult(requestCode, resultCode, data, activity) } else { Log.e(TAG, "OnActivityResult data is null!") } } override fun onLoadMore() { FacebookJobManager.getInstance() .startPhotosJob(FacebookJobManager.getInstance().nextPageGraphRequest) } private fun destroyAndNotifyUser() { Toast.makeText(activity, "Something went wrong, please try again.", Toast.LENGTH_SHORT).show() activity.finish() } override fun onPhotosClicked(facebookItem: FacebookPhoto) { val intent = Intent() val bundle = Bundle() bundle.putParcelable(FACEBOOK_PHOTO_ITEM, facebookItem) intent.putExtra(FACEBOOK_PHOTO_ITEM, bundle) activity.setResult(Activity.RESULT_OK, intent) activity.finish() } }
1
null
1
2
0d4922ea13762144b737f9102dc303b00cd818f7
5,544
facebook-image-gallery-picker
MIT License
app/src/main/java/com/spaceapps/myapplication/app/services/PlayerService.kt
andriy1507
333,576,864
false
null
package com.spaceapps.myapplication.app.services import android.annotation.SuppressLint import androidx.media3.common.AudioAttributes import androidx.media3.common.MediaItem import androidx.media3.exoplayer.ExoPlayer import androidx.media3.session.MediaLibraryService import androidx.media3.session.MediaLibraryService.MediaLibrarySession.MediaLibrarySessionCallback import androidx.media3.session.MediaSession @SuppressLint("UnsafeOptInUsageError") class PlayerService : MediaLibraryService() { private val urls = listOf( "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4", "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4", "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4", "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerEscapes.mp4", "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerFun.mp4", "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerJoyrides.mp4", "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerMeltdowns.mp4", "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/SubaruOutbackOnStreetAndDirt.mp4", "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/TearsOfSteel.mp4", "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/VolkswagenGTIReview.mp4", "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/WeAreGoingOnBullrun.mp4", "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/WhatCarCanYouGetForAGrand.mp4" ) private lateinit var player: ExoPlayer private lateinit var mediaLibrarySession: MediaLibrarySession private val librarySessionCallback = PlayerMediaSessionCallback() override fun onCreate() { super.onCreate() initializeSessionAndPlayer() } override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaLibrarySession { return mediaLibrarySession } override fun onDestroy() { player.release() mediaLibrarySession.release() super.onDestroy() } private fun initializeSessionAndPlayer() { player = ExoPlayer.Builder(this) .setAudioAttributes(AudioAttributes.DEFAULT, true) .build() mediaLibrarySession = MediaLibrarySession.Builder(this, player, librarySessionCallback) .build() player.addMediaItems(urls.map { MediaItem.fromUri(it) }) } private inner class PlayerMediaSessionCallback : MediaLibrarySessionCallback }
0
Kotlin
1
0
116d1113d4714fc27f7532f430c0457256139e60
2,705
spaceApps-android
MIT License
code/core/src/main/java/com/adobe/marketing/mobile/services/ui/floatingbutton/FloatingButtonEventHandler.kt
adobe
458,293,389
false
{"Kotlin": 1649922, "Java": 1480893, "Makefile": 7304, "Shell": 3493}
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui.floatingbutton import android.graphics.Bitmap /** * Interface for taking actions on an FloatingButton presentation. */ interface FloatingButtonEventHandler { /** * Updates the current content of the floating button. * @param graphic the new content of the floating button */ fun updateGraphic(graphic: Bitmap) }
14
Kotlin
24
9
882669b9a1b6c0315d44b937d0a73b114f36ca28
995
aepsdk-core-android
Apache License 2.0
code/core/src/main/java/com/adobe/marketing/mobile/services/ui/floatingbutton/FloatingButtonEventHandler.kt
adobe
458,293,389
false
{"Kotlin": 1649922, "Java": 1480893, "Makefile": 7304, "Shell": 3493}
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui.floatingbutton import android.graphics.Bitmap /** * Interface for taking actions on an FloatingButton presentation. */ interface FloatingButtonEventHandler { /** * Updates the current content of the floating button. * @param graphic the new content of the floating button */ fun updateGraphic(graphic: Bitmap) }
14
Kotlin
24
9
882669b9a1b6c0315d44b937d0a73b114f36ca28
995
aepsdk-core-android
Apache License 2.0
app/src/main/java/com/mik2003/boukennihon/ui/locations/LocationsViewModel.kt
mik2003
766,068,069
false
{"Kotlin": 22478}
package com.mik2003.boukennihon.ui.locations import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.mik2003.boukennihon.core.* class LocationsViewModel : ViewModel() { private val _locationsWithDistance = MutableLiveData<List<LocationWithDistance>>().apply { value = emptyList() // Set an initial empty list if needed } val locationsWithDistance: LiveData<List<LocationWithDistance>> = _locationsWithDistance fun setLocationsWithDistances(locationsList: LocationsList, distancesMap: Map<String, Double>) { val locationsWithDistances = locationsList.mapNotNull { location -> distancesMap[location.name]?.let { distance -> Pair(location, distance) } }.sortedBy { it.second } .map { (location, distance) -> val formattedDistance = "%.1f km".format(distance) LocationWithDistance(location, formattedDistance) } _locationsWithDistance.value = locationsWithDistances } }
0
Kotlin
0
0
3e34bd639f12254679af73d35d47e393b7159853
1,086
bouken-nihon
MIT License
kotlin/daily-balances/src/main/kotlin/DailyBalances.kt
enolive
65,559,078
false
{"Java": 150911, "Kotlin": 130819, "TypeScript": 121966, "Groovy": 76917, "JavaScript": 53147, "C#": 40972, "Haskell": 36546, "Python": 14709, "Scala": 12193, "HTML": 11513, "Clojure": 8840, "Gherkin": 8730, "Dart": 6755, "Ruby": 5800, "CSS": 3279, "Elm": 2803, "PHP": 2211, "Svelte": 1783, "Rust": 821, "Swift": 404, "PureScript": 294, "Makefile": 220, "Sass": 128, "SCSS": 80, "Objective-C": 38}
import java.math.BigDecimal import java.time.LocalDate import java.time.temporal.ChronoUnit data class Balance(val date: LocalDate, val amount: BigDecimal) fun List<Balance>.expandToDaily(): List<Balance> { if (isEmpty()) { return this } val balancesSorted = sortedBy { it.date } return balancesSorted .zipWithNext(::fillDayGapsUpTo) .flatten() + balancesSorted.last() } private fun fillDayGapsUpTo(current: Balance, next: Balance): List<Balance> { val daysBetween = current.date.until(next.date, ChronoUnit.DAYS) return when (daysBetween) { 0L -> listOf(current) else -> current.date.datesUntil(next.date).map { current.copy(date = it) }.toList() } }
88
Java
3
9
f01141469ac86352f8dc511579ead10dc7563413
692
learning
MIT License
app/src/main/java/ro/edi/novelty/ui/MyNewsFragment.kt
ediTLJ
31,333,807
false
null
/* * Copyright 2019-2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.edi.novelty.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.recyclerview.widget.RecyclerView import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import com.google.android.material.tabs.TabLayout import ro.edi.novelty.R import ro.edi.novelty.databinding.FragmentFeedBinding import ro.edi.novelty.ui.adapter.NewsAdapter import ro.edi.novelty.ui.viewmodel.NewsViewModel import ro.edi.util.applyWindowInsetsPadding import ro.edi.util.getColorRes import timber.log.Timber.Forest.i as logi class MyNewsFragment : Fragment() { companion object { fun newInstance() = MyNewsFragment() } private val newsModel: NewsViewModel by viewModels { NewsViewModel.FACTORY } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) newsModel.apply { type = NewsViewModel.TYPE_MY_NEWS feedId = 0 } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val binding = DataBindingUtil.inflate<FragmentFeedBinding>( inflater, R.layout.fragment_feed, container, false ) binding.lifecycleOwner = viewLifecycleOwner return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val vRefresh = view.findViewById<SwipeRefreshLayout>(R.id.refresh) vRefresh.apply { setColorSchemeResources(getColorRes(view.context, R.attr.colorPrimaryVariant)) isRefreshing = false isEnabled = false } val vEmpty = view.findViewById<TextView>(R.id.empty) vEmpty.setText(R.string.empty_bookmarks) val rvNews = view.findViewById<RecyclerView>(R.id.news) rvNews.apply { applyWindowInsetsPadding( applyLeft = true, applyTop = false, applyRight = true, applyBottom = true ) // listView.setVelocityScale(2.0f) setHasFixedSize(true) setItemViewCacheSize(20) adapter = NewsAdapter(activity, newsModel).apply { setHasStableIds(true) } } newsModel.news.observe(viewLifecycleOwner) { newsList -> logi("news changed: %d news", newsList.size) val rvAdapter = rvNews.adapter as NewsAdapter rvAdapter.submitList(newsList) { if (newsList.isEmpty()) { vEmpty.visibility = View.VISIBLE rvNews.visibility = View.GONE } else { vEmpty.visibility = View.GONE rvNews.visibility = View.VISIBLE } activity?.let { val tab = it.findViewById<TabLayout>(R.id.tabs)?.getTabAt(0) if (newsList.isEmpty()) { tab?.removeBadge() } else { tab?.orCreateBadge?.number = newsList.size } } } } } }
0
Kotlin
0
2
a59ca2aa5f407f0cabb63fc56d39e8b058868f5a
4,032
novelty
Apache License 2.0
app/src/main/java/com/sunrise/app/core/BaseViewState.kt
NalediMadlopha
356,901,928
false
null
package com.sunrise.app.core import com.sunrise.app.utils.domain.Status open class BaseViewState(val baseStatus: Status, val baseError: String?) { fun isLoading() = baseStatus == Status.LOADING fun getErrorMessage() = baseError fun shouldShowErrorMessage() = baseError != null }
0
Kotlin
0
0
3f7b337f30c8f852ba98761156a79da79777ecb8
297
gk-sunrise
Apache License 2.0
api/src/main/kotlin/com/wnsgml972/strada/api/v1/account/service/UserMapper.kt
Coffee-Street
289,485,814
false
{"Kotlin": 267923, "Shell": 2546, "Dockerfile": 174}
package com.wnsgml972.strada.api.v1.account.service import com.wnsgml972.strada.api.v1.account.domain.User import com.wnsgml972.strada.exception.StradaIllegalStateException fun User.toDto() = UserDto( this.id, this.isEnabled, ) fun UserDto.toEntity() = User.of( this.id ?: throw StradaIllegalStateException("user의 id($id)는 null 일 수 없습니다."), this.isEnabled )
2
Kotlin
2
2
24422867afe6c7f547a93f98083f655ecb80c0ed
377
strada
MIT License
jput-core/src/main/java/cz/encircled/jput/recorder/ElasticsearchResultRecorder.kt
encircled
91,900,976
false
null
package cz.encircled.jput.recorder import cz.encircled.jput.JPutUtils import cz.encircled.jput.context.* import cz.encircled.jput.model.PerfTestExecution import org.elasticsearch.ElasticsearchStatusException import org.elasticsearch.action.search.SearchRequest import org.elasticsearch.client.RequestOptions import org.elasticsearch.client.Requests import org.elasticsearch.index.query.Operator import org.elasticsearch.index.query.QueryBuilders import org.elasticsearch.index.query.RangeQueryBuilder import org.elasticsearch.index.reindex.DeleteByQueryRequest import org.elasticsearch.rest.RestStatus import org.elasticsearch.search.builder.SearchSourceBuilder import org.joda.time.DateTime import org.joda.time.DateTimeZone import org.joda.time.LocalDate import org.slf4j.LoggerFactory /** * Elasticsearch-based implementation of tests execution results recorder */ class ElasticsearchResultRecorder(private val client: ElasticsearchClient) : ThreadsafeResultRecorder() { private val log = LoggerFactory.getLogger(ElasticsearchResultRecorder::class.java) private val indexName by lazy { getProperty(JPutContext.PROP_ELASTIC_INDEX, "jput") } init { Runtime.getRuntime().addShutdownHook(Thread { client.close() }) } override fun getSample(execution: PerfTestExecution): List<Long> { val conf = execution.conf.trendConfiguration!! val queryBuilder = QueryBuilders.boolQuery().filter( matches("testId", execution.conf.testId)) getCollectionProperty(JPutContext.PROP_ELASTIC_ENV_IDENTIFIERS).forEach { val envParam = getUserDefinedEnvParams()[it] ?: "" queryBuilder.filter(matches(it, envParam)) } queryBuilder.filter(matches("errorMessage", "")) val request = SearchRequest(indexName).source(SearchSourceBuilder().query(queryBuilder)) val searchResponse = try { client.search(request, RequestOptions.DEFAULT) } catch (e: ElasticsearchStatusException) { if (e.status() == RestStatus.NOT_FOUND) { return emptyList() } throw e } val sample = subList(searchResponse.hits.hits.toList(), conf.sampleSize, conf.sampleSelectionStrategy) return sample .map { it.sourceAsMap["elapsed"] } .map { if (it is Int) it.toLong() else it as Long } } override fun doFlush(data: List<PerfTestExecution>) { log.info("Flush to Elasticsearch: ${data.size} test results") val bulk = Requests.bulkRequest() val userDefined = getUserDefinedEnvParams() data.flatMap(::convertToECSDocument).forEach { it.putAll(userDefined) bulk.add(Requests.indexRequest(indexName) .type("jput") .source(it)) } client.bulk(bulk, RequestOptions.DEFAULT) log.info("Successfully flushed to Elasticsearch") } fun doCleanup() { val days = getOptionalProperty<Int>(JPutContext.PROP_ELASTIC_CLEANUP_DAYS) if (days != null) { log.info("Removing execution older than $days days from Elasticsearch...") try { val deleted = deleteExecutionsOlderThan(days) log.info("Successfully removed $deleted old entries from Elasticsearch!") } catch (e: Exception) { log.info("Error during Elasticsearch cleanup", e) } } } private fun matches(name: String, value: String) = QueryBuilders.matchQuery(name, value).operator(Operator.AND) private fun deleteExecutionsOlderThan(days: Int): Long { val request = DeleteByQueryRequest(indexName) request.setQuery(RangeQueryBuilder("executionId") .lt(LocalDate.now().minusDays(days).toDate().time)) // TODO wrong result return client.deleteByQuery(request, RequestOptions.DEFAULT).deleted } private fun convertToECSDocument(it: PerfTestExecution): List<MutableMap<String, Any?>> { return it.executionResult.values.map { repeat -> mutableMapOf( "executionId" to context.executionId, "testId" to it.conf.testId, "start" to DateTime(repeat.relativeStartTime / 1000000L, DateTimeZone.UTC).toDate(), "elapsed" to repeat.elapsedTime, "resultCode" to repeat.resultDetails.resultCode, "errorMessage" to JPutUtils.buildErrorMessage(repeat) ) } } }
2
Kotlin
1
2
6e20b962aa5adeee970fbb3152c146f39d56cd35
4,666
jPut
Apache License 2.0
inbox-persistence/src/database/kotlin/com/healthmetrix/connector/inbox/persistence/refreshtokens/RefreshTokenRepositoryTest.kt
smart4health
593,624,617
false
null
package com.healthmetrix.connector.inbox.persistence.refreshtokens import com.healthmetrix.connector.inbox.persistence.DatabaseTestConfiguration import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.autoconfigure.ImportAutoConfiguration import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest import java.util.UUID @DataJpaTest( properties = ["spring.liquibase.change-log=classpath:db/changelog.yaml"], ) @ImportAutoConfiguration(classes = [DatabaseTestConfiguration::class]) class RefreshTokenRepositoryTest { private val internalCaseId1 = UUID.randomUUID() private val refreshToken1 = RefreshToken( internalCaseId1, "test_1", null, ) private val internalCaseId2 = UUID.randomUUID() private val refreshToken2 = RefreshToken( internalCaseId2, "test_2", null, ) @Autowired private lateinit var repo: RefreshTokenRepository @Test fun `context loads`() { assertThat(repo).isNotNull } @Test fun `a single refresh token can be saved`() { val persisted = repo.save(refreshToken1) assertThat(persisted).isEqualTo(refreshToken1) } @Test fun `a single refresh token can be retrieved after saving`() { repo.save(refreshToken1) val res = repo.findByIdOrNull(internalCaseId1) assertThat(res).isEqualTo(refreshToken1) } @Test fun `multiple refresh tokens can be saved`() { val persisted = repo.saveAll(listOf(refreshToken1, refreshToken2)) assertThat(persisted).isEqualTo(listOf(refreshToken1, refreshToken2)) } @Test fun `multiple refresh tokens can be retrieved after saving`() { repo.saveAll(listOf(refreshToken1, refreshToken2)) assertThat(repo.findByIdOrNull(internalCaseId1)).isEqualTo(refreshToken1) assertThat(repo.findByIdOrNull(internalCaseId2)).isEqualTo(refreshToken2) } @Test fun `findByIdOrNull should return null when refresh token does not exist`() = assertThat(repo.findByIdOrNull(UUID.randomUUID())).isNull() @Test fun `a refresh token can be deleted`() { repo.save(refreshToken1) repo.deleteById(internalCaseId1) assertThat(repo.findByIdOrNull(internalCaseId1)).isNull() } }
0
Kotlin
0
1
976d36079fa4171da0f78ad5812181cb6e3da6bc
2,471
connector-service
MIT License
app/src/test/kotlin/com/myweatherapp/di/ModuleCheckTest.kt
Harrypulvirenti
216,081,209
true
{"Kotlin": 78199}
package com.myweatherapp.di import android.app.Application import androidx.arch.core.executor.testing.InstantTaskExecutorRule import com.myweatherapp.domain.model.weather.DailyForecastId import com.myweatherapp.ui.view.detail.DetailViewModel import org.junit.Rule import org.junit.Test import org.koin.android.ext.koin.androidContext import org.koin.core.parameter.parametersOf import org.koin.dsl.koinApplication import org.koin.test.KoinTest import org.koin.test.check.checkModules import org.mockito.Mockito.mock /** * Test Koin modules */ class ModuleCheckTest : KoinTest { // Because we have some init states @get:Rule val rule = InstantTaskExecutorRule() val mockedAndroidContext = mock(Application::class.java) val fakeUrl = "http://fake.com" val fakeId = "42" @Test fun testRemoteConfiguration() { koinApplication { printLogger() modules(onlineWeatherApp) properties(hashMapOf(Properties.SERVER_URL to fakeUrl)) }.checkModules { create<DetailViewModel> { parametersOf(DailyForecastId(fakeId)) } } } @Test fun testLocalConfiguration() { koinApplication { printLogger() androidContext(mockedAndroidContext) modules(offlineWeatherApp) properties(hashMapOf(Properties.SERVER_URL to fakeUrl)) }.checkModules { create<DetailViewModel> { parametersOf(DailyForecastId(fakeId)) } } } @Test fun testTestConfiguration() { koinApplication { printLogger() androidContext(mockedAndroidContext) modules(testWeatherApp) properties(hashMapOf(Properties.SERVER_URL to fakeUrl)) }.checkModules { create<DetailViewModel> { parametersOf(DailyForecastId(fakeId)) } } } }
0
null
0
0
24fd2c6bd575f73c8a706462fd95682fdc2c2fac
1,866
weatherapp-uniflow
Apache License 2.0
src/main/kotlin/com/kanashiro/crawler/ChessDatabaseCrawler.kt
fernandok4
277,132,663
false
null
package com.kanashiro.crawler import com.kanashiro.chess.ChessVO import com.kanashiro.http.HttpPoolConnection import com.kanashiro.utils.Exceptions import org.apache.commons.logging.LogFactory import org.apache.http.client.methods.HttpGet import org.apache.http.impl.client.HttpClients import org.apache.http.util.EntityUtils import org.jsoup.Jsoup // It's deprecated due to a better web site to crawl class ChessDatabaseCrawler { private val CHESS_GAMES_URL = "https://www.chessgames.com" val logger = LogFactory.getLog(ChessDatabaseCrawler::class.java) fun readGame(idGame: Long): MutableList<ChessVO.CrawledGameMoves> { logger.info("Starting to read game id: ${idGame}") val httpClient = HttpClients.custom().setConnectionManager(HttpPoolConnection.poolManager).build() val gameUrl = "$CHESS_GAMES_URL/perl/chessgame?gid=$idGame" val request = HttpGet(gameUrl) val response = httpClient.execute(request) val bodyResponse = EntityUtils.toString(response.entity) val gameMoves = getGameMoves(bodyResponse) logger.info("Finishing to read game id: ${idGame}") return gameMoves } fun getGameMoves(html: String): MutableList<ChessVO.CrawledGameMoves> { val document = Jsoup.parse(html) val gameInfo = document.getElementById("olga-data") if(gameInfo == null){ throw Exceptions.InexistantGame() } val attribute = gameInfo.attr("pgn").split("]").last() val turnsRegex = Regex("(\\d+. ?[O0]-[O0] [O0]-[O0]-[O0])|(\\d+. ?[O0]-[O0] [O0]-[O0])|(\\d+. ?[O0]-[O0]-[O0] [O0]-[O0])|(\\d+. ?[O0]-[O0]-[O0] [O0]-[O0]-[O0])|(\\d+. ?[O0]-[O0] \\w+\\+?)|(\\d+. ?\\w+\\+? [O0]-[O0])|(\\d+. ?[O0]-[O0]-[O0] \\w+)|(\\d+. ?\\w+\\+? [O0]-[O0]-[O0])|(\\d+. ?\\w+\\=\\D\\+? \\w+\\=\\D)|(\\d+. ?\\w+\\+? \\w+\\=\\D\\+?)|(\\d+. ?\\w+\\=\\D\\+? \\w+\\+?)|(\\d+. ?\\w+\\+? \\w+\\+?)") val gameResultRegex = Regex("(1/2-1/2)|(1-0)|(0-1)") val result = gameResultRegex.findAll(attribute).first().value val moves = turnsRegex.findAll(attribute).toList().mapTo(mutableListOf()) { val move = it.value.split(".") ChessVO.CrawledGameMoves(move.first().toInt(), move.last().removeSuffix(result)) } moves.last().dsMovement = moves.last().dsMovement.removeSuffix("1").removeSuffix("0") moves.add(ChessVO.CrawledGameMoves(moves.size, result)) return moves } }
0
Kotlin
0
0
3ec260df65349e28fe58822ab76a41b50c9c470e
2,460
chess-crawler
MIT License
src/main/kotlin/nl/bjornvanderlaan/livedemospringwebflux/repository/CoroutinesPersonRepository.kt
BjornvdLaan
507,929,903
false
{"Kotlin": 25185}
package nl.bjornvanderlaan.livedemospringwebflux.repository import nl.bjornvanderlaan.livedemospringwebflux.model.Person import org.springframework.data.repository.kotlin.CoroutineCrudRepository import org.springframework.stereotype.Repository @Repository interface CoroutinesPersonRepository : CoroutineCrudRepository<Person, Long> { override suspend fun findById(id: Long): Person? }
0
Kotlin
1
0
78872771f5d93f108b1875ed746b890af2c4a573
391
live-demo-spring-webflux-kotlin
MIT License
app/src/main/java/com/nagi/sms2api/MainActivity.kt
naagaaraajaan
524,355,372
false
null
package com.nagi.sms2api import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.Manifest import android.content.pm.PackageManager import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat class MainActivity : AppCompatActivity() { companion object { private const val REQUEST_CODE_SMS_PERMISSION = 1 } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) requestSmsPermission() } private fun requestSmsPermission() { val permission = Manifest.permission.RECEIVE_SMS val grant = ContextCompat.checkSelfPermission(this, permission) if (grant != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, arrayOf(permission), REQUEST_CODE_SMS_PERMISSION) } } }
0
Kotlin
0
0
72dd77093e8643355c8f8fd3c4eb70d37c510a5e
910
sms2api
Apache License 2.0
app/src/main/java/com/prmto/mova_movieapp/feature_movie_tv_detail/data/mapper/MovieDetailDtoMapper.kt
tolgaprm
541,709,201
false
{"Kotlin": 535214}
package com.prmto.mova_movieapp.feature_movie_tv_detail.data.mapper import com.prmto.mova_movieapp.feature_movie_tv_detail.data.dto.detail.movie.MovieDetailDto import com.prmto.mova_movieapp.feature_movie_tv_detail.domain.models.detail.MovieDetail fun MovieDetailDto.toMovieDetail(): MovieDetail { return MovieDetail( id = id, genres = genres, imdbId = imdbId, originalTitle = originalTitle, title = title, overview = overview, posterPath = posterPath, releaseDate = releaseDate, runtime = runtime, voteAverage = voteAverage, voteCount = voteCount, credit = credits.toCredit(), watchProviders = watchProviders, ) }
1
Kotlin
3
55
49dc57a50ee37a2187b743c6aaa543b1f15922d6
728
Mova-MovieApp
Apache License 2.0
app/src/main/java/com/dariopellegrini/spikeapp/model/MovieContainer.kt
dariopellegrini
98,410,078
false
null
package com.dariopellegrini.spikeapp.model /** * Created by dariopellegrini on 27/07/17. */ data class MovieContainer(val score: Double, val movie: Movie)
0
null
2
9
7fb64c76cc5a985ea3dff54a1fd4fffa39a06696
183
Spike
MIT License
sample/src/main/java/com/litesoftteam/mvvm/sample/di/RepositoryModule.kt
udfvirus
352,020,196
false
{"Kotlin": 29982}
/* * Copyright (C) 2021 Vitaliy Sychov * * 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.litesoftteam.mvvm.sample.di import com.litesoftteam.mvvm.sample.data.repository.NetworkCharacteristicRepository import com.litesoftteam.mvvm.sample.data.repository.NetworkMenuItemRepository import com.litesoftteam.mvvm.sample.domain.repository.CharacteristicRepository import com.litesoftteam.mvvm.sample.domain.repository.MenuItemRepository import org.koin.dsl.module val repositoryModule = module { single<MenuItemRepository> { NetworkMenuItemRepository(get()) } single<CharacteristicRepository> { NetworkCharacteristicRepository(get()) } }
2
Kotlin
0
1
24a5db9c7fd042c5c56e1e3e95882fdfa776a029
1,169
mvvmframework
Apache License 2.0
src/main/kotlin/HttpsReq.kt
anyrsan
166,955,774
false
{"Markdown": 2, "Gradle": 1, "Gradle Kotlin DSL": 1, "INI": 2, "XML": 7, "Batchfile": 1, "JavaScript": 1, "Java": 6, "Kotlin": 17}
import java.io.ByteArrayOutputStream import java.io.File import java.net.URL import java.security.cert.CertificateFactory import java.security.KeyStore import javax.net.ssl.* fun main(args: Array<String>) { val url = URL("https://127.0.0.1:3030/json") // Create an SSLContext that uses our TrustManager val context = SSLContext.getInstance("TLS") // Create a TrustManager that trusts the CAs in our KeyStore val tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm() val tmf = TrustManagerFactory.getInstance(tmfAlgorithm) val keyStoreType = KeyStore.getDefaultType() val keyStore = KeyStore.getInstance(keyStoreType) keyStore.load(null, null) var cf= CertificateFactory.getInstance("X.509") val fileInputStream = File("key/anyrsan.cer").inputStream() var cert = cf.generateCertificate(fileInputStream) keyStore.setCertificateEntry("anyrsan",cert) tmf.init(keyStore) context.init(null, tmf.trustManagers, null) val urlConnection = url.openConnection() as HttpsURLConnection urlConnection.sslSocketFactory = context.socketFactory urlConnection.hostnameVerifier = MyHostnameVerifier() val inputStream = urlConnection.inputStream val baos = ByteArrayOutputStream() val buffer = ByteArray(1024) var len = inputStream.read(buffer) while (len != -1 ){ baos.write(buffer,0,len) len = inputStream.read(buffer) } println("请求结果: "+ baos.toString()) } class MyHostnameVerifier :HostnameVerifier{ override fun verify(p0: String?, p1: SSLSession?): Boolean { return true } }
0
Kotlin
0
1
61b31d87732c2ee94e070065c7a586642ee25038
1,613
BaseCrypt
Apache License 2.0
components/archive/impl/src/main/java/com/flipperdevices/archive/impl/api/ArchiveFeatureEntryImpl.kt
flipperdevices
288,258,832
false
{"Kotlin": 2835556, "FreeMarker": 10084, "CMake": 1780, "C++": 1152, "Fluent": 21}
package com.flipperdevices.archive.impl.api import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.navigation.NavGraphBuilder import androidx.navigation.NavHostController import androidx.navigation.compose.composable import androidx.navigation.navigation import com.arkivanov.decompose.extensions.compose.stack.Children import com.arkivanov.decompose.extensions.compose.subscribeAsState import com.flipperdevices.archive.api.ArchiveDecomposeComponent import com.flipperdevices.archive.api.ArchiveFeatureEntry import com.flipperdevices.core.di.AppGraph import com.flipperdevices.core.ui.navigation.AggregateFeatureEntry import com.flipperdevices.ui.decompose.rememberComponentContext import com.squareup.anvil.annotations.ContributesBinding import com.squareup.anvil.annotations.ContributesMultibinding import javax.inject.Inject @ContributesBinding(AppGraph::class, ArchiveFeatureEntry::class) @ContributesMultibinding(AppGraph::class, AggregateFeatureEntry::class) class ArchiveFeatureEntryImpl @Inject constructor( private val archiveDecomposeComponentFactory: ArchiveDecomposeComponent.Factory ) : ArchiveFeatureEntry { override fun getArchiveScreen(): String { return "@${ROUTE.name}" } override fun NavGraphBuilder.navigation(navController: NavHostController) { navigation( route = ROUTE.name, startDestination = getArchiveScreen() ) { composable( route = getArchiveScreen() ) { val componentContext = rememberComponentContext() val fileManagerComponent = remember(componentContext) { archiveDecomposeComponentFactory(componentContext) as ArchiveDecomposeComponentImpl } val childStack by fileManagerComponent.stack.subscribeAsState() Children( stack = childStack ) { it.instance.Render() } } } } }
15
Kotlin
134
1,069
475cd750460100aca5d0b587f6192c1d700a4e4a
2,051
Flipper-Android-App
MIT License
components/archive/impl/src/main/java/com/flipperdevices/archive/impl/api/ArchiveFeatureEntryImpl.kt
flipperdevices
288,258,832
false
{"Kotlin": 2835556, "FreeMarker": 10084, "CMake": 1780, "C++": 1152, "Fluent": 21}
package com.flipperdevices.archive.impl.api import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.navigation.NavGraphBuilder import androidx.navigation.NavHostController import androidx.navigation.compose.composable import androidx.navigation.navigation import com.arkivanov.decompose.extensions.compose.stack.Children import com.arkivanov.decompose.extensions.compose.subscribeAsState import com.flipperdevices.archive.api.ArchiveDecomposeComponent import com.flipperdevices.archive.api.ArchiveFeatureEntry import com.flipperdevices.core.di.AppGraph import com.flipperdevices.core.ui.navigation.AggregateFeatureEntry import com.flipperdevices.ui.decompose.rememberComponentContext import com.squareup.anvil.annotations.ContributesBinding import com.squareup.anvil.annotations.ContributesMultibinding import javax.inject.Inject @ContributesBinding(AppGraph::class, ArchiveFeatureEntry::class) @ContributesMultibinding(AppGraph::class, AggregateFeatureEntry::class) class ArchiveFeatureEntryImpl @Inject constructor( private val archiveDecomposeComponentFactory: ArchiveDecomposeComponent.Factory ) : ArchiveFeatureEntry { override fun getArchiveScreen(): String { return "@${ROUTE.name}" } override fun NavGraphBuilder.navigation(navController: NavHostController) { navigation( route = ROUTE.name, startDestination = getArchiveScreen() ) { composable( route = getArchiveScreen() ) { val componentContext = rememberComponentContext() val fileManagerComponent = remember(componentContext) { archiveDecomposeComponentFactory(componentContext) as ArchiveDecomposeComponentImpl } val childStack by fileManagerComponent.stack.subscribeAsState() Children( stack = childStack ) { it.instance.Render() } } } } }
15
Kotlin
134
1,069
475cd750460100aca5d0b587f6192c1d700a4e4a
2,051
Flipper-Android-App
MIT License
app/src/main/java/com/kaiserpudding/novel2go/util/multiSelect/MultiSelectAdapter.kt
XiangRongLin
211,704,746
false
null
package com.kaiserpudding.novel2go.util.multiSelect import android.view.View import androidx.recyclerview.widget.RecyclerView import com.kaiserpudding.novel2go.util.multiSelect.MultiSelectAdapter.MultiSelectAdapterItemInteractionListener import com.kaiserpudding.novel2go.util.setSafeOnClickListener /** * An adapter handling the logic needed for a recycler view with clickable and selectable items. * * @param T They type of the items shown in the list * @property listener A listener implementing [MultiSelectAdapterItemInteractionListener] * handling onClick and onLongClick actions on the items */ abstract class MultiSelectAdapter<T>( private val listener: MultiSelectAdapterItemInteractionListener ) : RecyclerView.Adapter<MultiSelectAdapter<T>.MultiSelectViewHolder>() { private val selectedIdSet = mutableSetOf<Long>() val selectedIdArray: LongArray get() = selectedIdSet.toLongArray() val numberOfSelected: Int get() = selectedPosition.size val inSelectionMode: Boolean get() = numberOfSelected > 0 private val selectedPositionSet = mutableSetOf<Int>() val selectedPosition : IntArray get() = selectedPositionSet.toIntArray() /** * The id of the layout that is representing a single item in the recycler view */ protected abstract val viewHolderId: Int /** * The list of the items that are represented in the recycler view */ lateinit var list: List<T> override fun onBindViewHolder(holder: MultiSelectViewHolder, position: Int) { //if item at position is selected, activate it and thus show different background color holder.itemView.isActivated = selectedIdSet.contains(getItemId(position)) } /** * Remove/Add the id of the item at [position] from [selectedIdSet] depending on if its already in there. * Then notifies listeners of changes. * * @param position */ fun toggleSelectedThenNotify(position: Int) { if (selectedPositionSet.contains(position)) selectedPositionSet.remove(position) else selectedPositionSet.add(position) val id = getItemId(position) if (selectedIdSet.contains(id)) selectedIdSet.remove(id) else selectedIdSet.add(id) listener.onDataSetChanged() notifyItemChanged(position) } /** * Clear [selectedIdSet] and then notifies listeners of changes. * */ fun clearSelectedThenNotify() { selectedPositionSet.clear() selectedIdSet.clear() notifyDataSetChanged() } abstract inner class MultiSelectViewHolder(val view: View) : RecyclerView.ViewHolder(view) { init { view.setSafeOnClickListener { if (inSelectionMode) toggleSelectedThenNotify(adapterPosition) else listener.onMultiSelectAdapterInteraction(adapterPosition) } view.setOnLongClickListener { toggleSelectedThenNotify(adapterPosition); true } } } abstract override fun getItemCount(): Int /** * Interface which must be implemented to get notified of data changes and adapter interaction * */ interface MultiSelectAdapterItemInteractionListener { /** * Gets called when an item was selected or deselected. */ fun onDataSetChanged() /** * Gets called when an item was clicked on while adapter is not [inSelectionMode] * * @param position The position of the item that was clicked. */ fun onMultiSelectAdapterInteraction(position: Int) } }
22
Kotlin
0
0
2acca2a8571acf5bc3b14438f99fe0fbcb22df8f
3,647
Novel2Go
Apache License 2.0
server/src/main/kotlin/com/afzaln/Application.kt
AfzalivE
472,217,287
false
{"Kotlin": 12810, "Swift": 6229}
package com.afzaln import io.ktor.server.engine.* import io.ktor.server.netty.* import com.afzaln.plugins.* fun main() { embeddedServer(Netty, port = 8080, host = "0.0.0.0") { configureRouting() configureSerialization() }.start(wait = true) }
0
Kotlin
0
4
0b79fd5fdc6ea8ccbfd9057fd540c86b704f0028
269
Athleet
Apache License 2.0
src/main/java/com/dzen/campfire/api/models/publications/moderations/publications/ModerationBlock.kt
ZeonXX
381,983,751
false
{"Kotlin": 1087578}
package com.dzen.campfire.api.models.publications.moderations.publications import com.dzen.campfire.api.API import com.dzen.campfire.api.models.publications.moderations.Moderation import com.sup.dev.java.libs.json.Json class ModerationBlock : Moderation { var publicationId = 0L var publicationType = 0L var accountId = 0L var accountName = "" var accountImageId = 0L var accountBlockDate = 0L var lastPublicationsBlocked = false var checkAdminId = 0L var checkAdminName = "" var checkAdminComment = "" override fun getType() = API.MODERATION_TYPE_BLOCK constructor() constructor(comment: String, publicationId: Long, publicationType: Long, accountId: Long, accountName: String, accountImageId: Long, accountBlockDate: Long, lastPublicationsBlocked: Boolean) : super(comment) { this.publicationId = publicationId this.publicationType = publicationType this.accountId = accountId this.accountName = accountName this.accountImageId = accountImageId this.accountBlockDate = accountBlockDate this.lastPublicationsBlocked = lastPublicationsBlocked } override fun json(inp: Boolean, json: Json): Json { publicationId = json.m(inp, "unitId", publicationId) publicationType = json.m(inp, "unitType", publicationType) accountId = json.m(inp, "accountId", accountId) accountName = json.m(inp, "accountName", accountName) accountImageId = json.m(inp, "accountImageId", accountImageId) accountBlockDate = json.m(inp, "accountBlockDate", accountBlockDate) lastPublicationsBlocked = json.m(inp, "lastUnitsBlocked", lastPublicationsBlocked) checkAdminId = json.m(inp, "checkAdminId", checkAdminId) checkAdminName = json.m(inp, "checkAdminName", checkAdminName) checkAdminComment = json.m(inp, "checkAdminComment", checkAdminComment) return super.json(inp, json) } override fun fillResourcesList(list: ArrayList<Long>) { } }
0
Kotlin
2
5
6f3b371624fb66a065bcbaa6302830c574c55e9f
2,035
CampfireApi
Apache License 2.0
domain/src/main/java/com/jyproject/domain/features/place/usecase/GetPeopleRateUseCase.kt
JunYeong0314
778,833,940
false
{"Kotlin": 103252}
package com.jyproject.domain.features.place.usecase import com.jyproject.domain.features.place.PlaceRepository import javax.inject.Inject class GetPlaceInfoUseCase @Inject constructor( private val placeRepository: PlaceRepository ) { suspend operator fun invoke( place: String ) = placeRepository.getPlaceInfo(place) }
0
Kotlin
0
0
76706c9a8fcbf6fafb036d4bb4c9504a79e154b3
340
PlacePick
MIT License
src/main/java/com/cumulocity/client/api/LoginOptionsApi.kt
SoftwareAG
525,378,320
false
null
// Copyright (c) 2014-2022 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, and/or its subsidiaries and/or its affiliates and/or their licensors. // Use, reproduction, transfer, publication or disclosure is prohibited except as specifically provided for in your License Agreement with Software AG. package com.cumulocity.client.api import retrofit2.converter.scalars.ScalarsConverterFactory import retrofit2.converter.gson.ExtendedGsonConverterFactory import retrofit2.Retrofit import retrofit2.Call import retrofit2.http.GET import retrofit2.http.POST import retrofit2.http.PUT import retrofit2.http.Query import retrofit2.http.Body import retrofit2.http.Path import retrofit2.http.Headers import okhttp3.OkHttpClient import retrofit2.converter.gson.ReadOnlyProperties import com.cumulocity.client.model.AuthConfig import com.cumulocity.client.model.AuthConfigAccess import com.cumulocity.client.model.LoginOptionCollection /** * API methods to retrieve the login options configured in the tenant. * * More detailed information about the parameters and their meaning can be found in [Administration > Changing settings](https://cumulocity.com/guides/users-guide/administration/#changing-settings) in the *Users guide*. * > **&#9432; Info:** If OAuth external is the only login option shown in the response, the user will be automatically redirected to the SSO login screen. * </br> * */ interface LoginOptionsApi { companion object Factory { fun create(baseUrl: String): LoginOptionsApi { return create(baseUrl, null) } fun create(baseUrl: String, clientBuilder: OkHttpClient.Builder?): LoginOptionsApi { val retrofitBuilder = Retrofit.Builder().baseUrl(baseUrl) .addConverterFactory(ExtendedGsonConverterFactory()) .addConverterFactory(ScalarsConverterFactory.create()) if (clientBuilder != null) { retrofitBuilder.client(clientBuilder.build()) } return retrofitBuilder.build().create(LoginOptionsApi::class.java) } } /** * Retrieve the login options </br> * Retrieve the login options available in the tenant. * * <br>The following table gives an overview of the possible response codes and their meanings:</br> * <ul> * <li>200 The request has succeeded and the login options are sent in the response.</li> * <li>400 Bad request – invalid parameters.</li> * </ul> * * @param management If this is set to `true`, the management tenant login options will be returned. > **&#9432; Info:** The `tenantId` parameter must not be present in the request when using the `management` parameter, otherwise it will cause an error. * @param tenantId Unique identifier of a Cumulocity IoT tenant. */ @Headers("Accept:application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.loginoptioncollection+json") @GET("/tenant/loginOptions") fun getLoginOptions( @Query("management") management: Boolean? = null, @Query("tenantId") tenantId: String? = null ): Call<LoginOptionCollection> /** * Create a login option </br> * Create an authentication configuration on your tenant. <section><h5>Required roles</h5> ROLE_TENANT_ADMIN <b>OR</b> ROLE_TENANT_MANAGEMENT_ADMIN </section> * * <br>The following table gives an overview of the possible response codes and their meanings:</br> * <ul> * <li>200 A login option was created.</li> * <li>400 Duplicated – The login option already exists.</li> * <li>401 Authentication information is missing or invalid.</li> * <li>422 Unprocessable Entity – invalid payload.</li> * </ul> * * @param body */ @Headers(*["Content-Type:application/vnd.com.nsn.cumulocity.authconfig+json", "Accept:application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.authconfig+json"]) @POST("/tenant/loginOptions") @ReadOnlyProperties("self") fun createLoginOption( @Body body: AuthConfig ): Call<AuthConfig> /** * Update a tenant's access to the login option </br> * Update the tenant's access to the authentication configuration. <section><h5>Required roles</h5> ROLE_TENANT_MANAGEMENT_ADMIN <b>AND</b> is the management tenant </section> * * <br>The following table gives an overview of the possible response codes and their meanings:</br> * <ul> * <li>200 The login option was updated.</li> * <li>403 Not authorized to perform this operation.</li> * <li>404 Tenant not found.</li> * </ul> * * @param body * @param typeOrId The type or ID of the login option. The type's value is case insensitive and can be `OAUTH2`, `OAUTH2_INTERNAL` or `BASIC`. * @param targetTenant Unique identifier of a Cumulocity IoT tenant. */ @Headers(*["Content-Type:application/json", "Accept:application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.authconfig+json"]) @PUT("/tenant/loginOptions/{type_or_id}/restrict") fun updateLoginOption( @Body body: AuthConfigAccess, @Path("type_or_id") typeOrId: String, @Query("targetTenant") targetTenant: String ): Call<AuthConfig> }
0
Kotlin
0
2
ca48e21dc65698a38aedf39ea728f7d7d0372f14
5,036
cumulocity-clients-kotlin
Apache License 2.0
glata/src/main/java/com/yalantis/glata/primitive/Color.kt
Yalantis
165,843,008
false
null
package com.yalantis.glata.primitive class Color() { var r: Float = 1f var g: Float = 1f var b: Float = 1f var a: Float = 1f constructor(r: Int, g: Int, b: Int, a: Int) : this() { this.r = r.toFloat() / 255f this.g = g.toFloat() / 255f this.b = b.toFloat() / 255f this.a = a.toFloat() / 255f } constructor(r: Float, g: Float, b: Float, a: Float) : this() { this.r = r this.g = g this.b = b this.a = a } fun set(r: Float, g: Float, b: Float, a: Float) { this.r = r this.g = g this.b = b this.a = a } }
1
Kotlin
13
83
f022e7348afb381ac567ff6954164ef47438edf1
640
GLata
The Unlicense
korona-junit5/src/test/kotlin/com/ancientlightstudios/korona/junit5/SearchTest.kt
derkork
124,192,168
false
null
package com.ancientlightstudios.korona.junit5 import com.ancientlightstudios.korona.KoronaTest import com.ancientlightstudios.korona.pages.automationpractice.pages.HomePage import com.ancientlightstudios.korona.pages.automationpractice.pages.SearchResultPage import org.junit.jupiter.api.Test import kotlin.test.assertEquals class SearchTest : KoronaTest("http://automationpractice.com") { @Test fun narf() { visit(HomePage()) { searchField.value = "dress" searchButton.click() } at(SearchResultPage()) { assertEquals(7, products.size) println(products.map { it.productName.value }) println(products.map { it.productPrice.value }) } } }
0
Kotlin
0
0
ead9a699bfffb9c65be0751974a5c3b6b5dc240b
745
korona
MIT License
relateddigital-google/src/main/java/com/relateddigital/relateddigital_google/network/requestHandler/RetentionRequest.kt
relateddigital
570,038,292
false
{"Kotlin": 1495397, "HTML": 21295}
package com.relateddigital.relateddigital_google.network.requestHandler import android.content.Context import android.os.Build import android.util.Log import com.relateddigital.relateddigital_google.RelatedDigital import com.relateddigital.relateddigital_google.constants.Constants import com.relateddigital.relateddigital_google.network.RequestSender import com.relateddigital.relateddigital_google.model.Retention import com.relateddigital.relateddigital_google.push.RetentionType import com.relateddigital.relateddigital_google.util.GoogleUtils import com.relateddigital.relateddigital_google.util.RetryCounterManager object RetentionRequest { private const val LOG_TAG = "RetentionRequest" private var latestDeliverPushId: String = "" private var latestOpenPushId: String = "" fun createRetentionRequest( context: Context, type: RetentionType, pushId: String?, emPushSp: String? ) { if (Build.VERSION.SDK_INT < Constants.SDK_MIN_API_VERSION) { Log.e(LOG_TAG, "RelatedDigital SDK requires min API level 21!") return } val latestPushId: String = when(type) { RetentionType.DELIVER, RetentionType.SILENT -> { latestDeliverPushId } else -> { latestOpenPushId } } if(!pushId.isNullOrEmpty() && pushId != latestPushId) { when (type) { RetentionType.DELIVER, RetentionType.SILENT -> { latestDeliverPushId = pushId } else -> { latestOpenPushId = pushId } } val retention = Retention() if(GoogleUtils.checkPlayService(context)) { retention.key = RelatedDigital.getRelatedDigitalModel(context).getGoogleAppAlias() } else { retention.key = RelatedDigital.getRelatedDigitalModel(context).getHuaweiAppAlias() } retention.pushId = pushId when (type) { RetentionType.DELIVER -> { retention.status = "D" retention.deliver = 1 } RetentionType.SILENT -> { retention.status = "S" retention.deliver = 1 } else -> { retention.status = "O" retention.deliver = 0 } } retention.token = RelatedDigital.getRelatedDigitalModel(context).getToken() retention.actionBtn = 0 retention.isMobile = 1 if(!emPushSp.isNullOrEmpty()) { retention.emPushSp = emPushSp } RequestSender.sendRetentionRequest(context, retention, RetryCounterManager.counterId) } } }
0
Kotlin
0
3
c9a36991f6e29797cff3ddafd6776442fb650b75
2,869
relateddigital-google
Amazon Digital Services License
src/main/kotlin/com/kopyl/commit/IssueValidator.kt
anatolykopyl
695,275,163
false
{"Kotlin": 10030}
package com.kopyl.commit import com.atlassian.jira.rest.client.api.domain.Issue class IssueValidator(private val issue: Issue) { fun valid(): Boolean { // TODO return error message as well, eg: {valid: false, message: "Components missing"} if (issue.summary == null || issue.summary.isEmpty()) { return false } if (issue.components == null || !issue.components.iterator().hasNext()) { return false } return true } }
0
Kotlin
0
0
bf7c4589d2ddec13dd85cf4e4cee369ea590c1ba
499
auto-commit-message-plugin
Apache License 2.0
pathshapeview/src/main/java/shape/path/view/point/converter/CoordinateConverter.kt
MuhammadAmmad
122,162,405
true
{"Kotlin": 63638, "Java": 393}
package shape.path.view.point.converter import android.graphics.Matrix import android.graphics.PointF /** * Created by root on 1/9/18. */ class CoordinateConverter(var originScreenW: Float, var originScreenH: Float) : PointConverter() { private var screenScaleFactorX = 1f private var screenScaleFactorY = 1f override fun setScreenSize(screenWidth: Float, screenHeight: Float) { super.setScreenSize(screenWidth, screenHeight) screenScaleFactorX = screenWidth / originScreenW screenScaleFactorY = screenHeight / originScreenH matrix.setScale(screenScaleFactorX, screenScaleFactorY) } /*override fun convertPoint(originPoint: PointF): PointF { val x = originPoint.x * screenScaleFactorX val y = originPoint.y * screenScaleFactorY return PointF(x, y) }*/ override fun getMatrix(): Matrix { return matrix } }
0
Kotlin
0
0
85e1afbfa98e7c3e810bddb6b64309012f5fd382
908
Android-PathShapeView
Apache License 2.0
maven/hello-world/src/test/kotlin/HelloTest.kt
burnasheva
146,253,901
true
{"Kotlin": 69741, "Java": 4856, "JavaScript": 1378, "HTML": 227}
package hello.tests import hello.getHelloString import kotlin.test.assertEquals import org.junit.Test import kotlin.test.assertFalse import kotlin.test.assertTrue class HelloTest { @Test fun testAssert() : Unit { assertEquals("Hello, world!", getHelloString()) } @Test fun `function is recursively called on all children` () { assertTrue ( false, "Something went wrong!" ) } @Test fun `function throws an error when everything is bad` () { assertFalse (true, "Something went wrong again!") } @Test fun `this test should pass` () { assertFalse (false, "Something went wrong again!") } }
0
Kotlin
0
0
74fc73855ae136d1257eeb1047db17fb90b290db
655
kotlin-examples
Apache License 2.0
FrameIcon/src/main/kotlin/example/App.kt
aterai
158,348,575
false
null
package example import java.awt.* // ktlint-disable no-wildcard-imports import javax.swing.* // ktlint-disable no-wildcard-imports fun makeUI(): Component { val cl = Thread.currentThread().contextClassLoader val icon = Toolkit.getDefaultToolkit().createImage(cl.getResource("example/16x16.png")) val check = JCheckBox("setIconImage") check.addActionListener { e -> (e.source as? JCheckBox)?.also { (it.topLevelAncestor as? Window)?.setIconImage(if (it.isSelected) icon else null) } } val p = JPanel() p.border = BorderFactory.createTitledBorder("Window#setIconImage(Image)") p.add(check) return JPanel(BorderLayout()).also { it.add(p, BorderLayout.NORTH) it.border = BorderFactory.createEmptyBorder(5, 5, 5, 5) it.preferredSize = Dimension(320, 240) } } fun main() { EventQueue.invokeLater { runCatching { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()) }.onFailure { it.printStackTrace() Toolkit.getDefaultToolkit().beep() } JFrame().apply { defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE contentPane.add(makeUI()) pack() setLocationRelativeTo(null) isVisible = true } } }
0
Kotlin
1
9
47a0c684f64c3db2c8b631b2c20c6c7f9205bcab
1,224
kotlin-swing-tips
MIT License
bluetape4k/junit5/src/main/kotlin/io/bluetape4k/junit5/awaitility/AwaitilityCoroutineSupport.kt
debop
625,161,599
false
{"Kotlin": 7504333, "HTML": 502995, "Java": 2273, "JavaScript": 1351, "Shell": 1301, "CSS": 444, "Dockerfile": 121, "Mustache": 82}
package io.bluetape4k.junit5.awaitility import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.isActive import org.awaitility.core.ConditionFactory /** * suspend 함수가 true 를 반환할 때까지 대기한다 * * @param block 판단을 위한 코드 블럭 */ suspend inline infix fun ConditionFactory.awaiting(crossinline block: suspend () -> Unit) = untilSuspending { block(); true } /** * suspend 함수가 true 를 반환할 때까지 대기한다 * * @param block 판단을 위한 코드 블럭 */ suspend inline infix fun ConditionFactory.untilSuspending( crossinline block: suspend () -> Boolean, ) = coroutineScope { while (isActive) { if (block()) { break } delay(10) } }
0
Kotlin
0
1
ce3da5b6bddadd29271303840d334b71db7766d2
701
bluetape4k
MIT License
vector/src/main/java/vmodev/clearkeep/viewmodels/RoomViewModel.kt
telred-llc
194,596,139
false
null
package vmodev.clearkeep.viewmodels import androidx.lifecycle.LiveData import androidx.lifecycle.MediatorLiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Transformations import vmodev.clearkeep.repositories.RoomRepository import vmodev.clearkeep.repositories.RoomUserJoinRepository import vmodev.clearkeep.repositories.UserRepository import vmodev.clearkeep.viewmodelobjects.Resource import vmodev.clearkeep.viewmodelobjects.Room import vmodev.clearkeep.viewmodelobjects.RoomListUser import vmodev.clearkeep.viewmodelobjects.User import vmodev.clearkeep.viewmodels.interfaces.AbstractRoomViewModel import javax.inject.Inject class RoomViewModel @Inject constructor(roomRepository: RoomRepository, private val roomUserJoinRepository: RoomUserJoinRepository, private val userRepository: UserRepository) : AbstractRoomViewModel() { private val _filters = MutableLiveData<RoomFilters>(); private val _id = MutableLiveData<String>(); private val _joinRoom = MutableLiveData<String>(); private val _leaveRoom = MutableLiveData<String>(); private val _otherUserId = MutableLiveData<String>(); private val _createNewRoom = MutableLiveData<RoomRepository.CreateNewRoomObject>(); private val _inviteUserToRoom = MutableLiveData<RoomRepository.InviteUsersToRoomObject>(); private val _findByText = MutableLiveData<String>(); private val _addToFavourite = MutableLiveData<String>(); private val _removeFromFavourite = MutableLiveData<String>(); private val _roomIdForGetUser = MutableLiveData<String>(); private val rooms: LiveData<Resource<List<Room>>> = Transformations.switchMap(_filters) { input -> roomRepository.loadListRoom(input.filters, input.loadType); } private val roomFind: LiveData<Resource<Room>> = Transformations.switchMap(_id) { input -> roomRepository.loadRoom(input) } private val roomJoin: LiveData<Resource<Room>> = Transformations.switchMap(_joinRoom) { input -> roomRepository.joinRoom(input) } private val roomLeave: LiveData<Resource<String>> = Transformations.switchMap(_leaveRoom) { input -> roomRepository.leaveRoom(input) } private val inviteUser: LiveData<Resource<Room>> = Transformations.switchMap(_otherUserId) { input -> roomRepository.createDirectChatRoom(input); } private val createNewRoom: LiveData<Resource<Room>> = Transformations.switchMap(_createNewRoom) { input -> roomRepository.createNewRoom(input.name, input.topic, input.visibility) } private val inviteUsersToRoom: LiveData<Resource<Room>> = Transformations.switchMap(_inviteUserToRoom) { input -> roomRepository.inviteUsersToRoom(input); } private val findBytTextResult: LiveData<Resource<List<String>>> = Transformations.switchMap(_findByText) { input -> roomRepository.findListRoomWithText(input) } private val addToFavourite: LiveData<Resource<Room>> = Transformations.switchMap(_addToFavourite) { input -> roomRepository.addToFavourite(input); } private val removeFromFavourite: LiveData<Resource<Room>> = Transformations.switchMap(_removeFromFavourite) { input -> roomRepository.removeFromFavourite(input); } private val usersFromRoomId: LiveData<Resource<List<User>>> = Transformations.switchMap(_roomIdForGetUser) { input -> userRepository.getListUserInRoomFromNetwork(input); } private val roomMerge = MediatorLiveData<Resource<Room>>(); init { roomMerge.addSource(roomFind) { t -> roomMerge.value = t } roomMerge.addSource(roomJoin) { t -> roomMerge.value = t } } override fun setFilter(filters: Array<Int>, loadType: Int) { _filters.value = RoomFilters(filters, loadType); } override fun getRoomsData(): LiveData<Resource<List<Room>>> { return rooms; } override fun getFilterData(): LiveData<RoomFilters> { return _filters; } override fun getRoom(): LiveData<Resource<Room>> { return roomMerge; } override fun setRoomId(id: String) { if (_id.value != id) _id.value = id; } override fun joinRoom(id: String) { if (_joinRoom.value != id) _joinRoom.value = id; } override fun getInviteUserToDirectChat(): LiveData<Resource<Room>> { return inviteUser; } override fun setInviteUserToDirectChat(id: String) { if (_otherUserId.value != id) _otherUserId.value = id; } override fun createNewRoom(): LiveData<Resource<Room>> { return createNewRoom; } override fun setCreateNewRoom(name: String, topic: String, visibility: String) { _createNewRoom.value = RoomRepository.CreateNewRoomObject(name, topic, visibility); } override fun setInviteUsersToRoom(roomId: String, userIds: List<String>) { _inviteUserToRoom.value = RoomRepository.InviteUsersToRoomObject(roomId, userIds); } override fun getInviteUsersToRoomResult(): LiveData<Resource<Room>> { return inviteUsersToRoom; } override fun setLeaveRoom(id: String) { if (_leaveRoom.value != id) _leaveRoom.value = id; } override fun getLeaveRoom(): LiveData<Resource<String>> { return roomLeave; } override fun setTextForFindByText(keyword: String) { if (_findByText.value != keyword) _findByText.value = keyword; } override fun getFindByTextResult(): LiveData<Resource<List<String>>> { return findBytTextResult; } override fun setAddToFavourite(roomId: String) { _addToFavourite.value = roomId; } override fun getAddToFavouriteResult(): LiveData<Resource<Room>> { return addToFavourite; } override fun setRemoveFromFavourite(roomId: String) { _removeFromFavourite.value = roomId; } override fun getRemoveFromFavouriteResult(): LiveData<Resource<Room>> { return removeFromFavourite; } override fun getGetUserFromRoomIdResult(): LiveData<Resource<List<User>>> { return usersFromRoomId; } override fun setGetUserFromRoomId(roomId: String) { _roomIdForGetUser.value = roomId; } override fun getRoomListUserFindByID(roomId: String): LiveData<Resource<RoomListUser>> { return roomUserJoinRepository.getRoomListUserFindByID(roomId) } class RoomFilters constructor(val filters: Array<Int>, val loadType: Int = 0) }
5
null
1
3
2d20e94e9711b51aee89fa569efd61449cc7e9c3
6,432
clearkeep-android
Apache License 2.0
app/src/main/java/com/kgurgul/cpuinfo/features/processes/ProcessesViewModel.kt
maxhigh
109,428,409
true
{"Kotlin": 217571, "Java": 174138}
/* * Copyright 2017 KG Soft * * 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.kgurgul.cpuinfo.features.processes import android.arch.lifecycle.ViewModel import com.kgurgul.cpuinfo.common.Prefs import com.kgurgul.cpuinfo.common.list.AdapterArrayList import io.reactivex.Flowable import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers import kotlinx.coroutines.experimental.android.UI import kotlinx.coroutines.experimental.async import org.jetbrains.anko.coroutines.experimental.asReference import org.jetbrains.anko.coroutines.experimental.bg import timber.log.Timber import java.io.IOException import java.util.* import java.util.concurrent.TimeUnit import javax.inject.Inject /** * ViewModel for [ProcessesFragment] * * @author kgurgul */ class ProcessesViewModel @Inject constructor(private val prefs: Prefs) : ViewModel() { private val SORTING_PROCESSES_KEY = "SORTING_PROCESSES_KEY" val processList = AdapterArrayList<ProcessItem>() private val ref = asReference() private var isSortingAsc = prefs.get(SORTING_PROCESSES_KEY, true) private var refreshingDisposable: Disposable? = null /** * Start refreshing processes (every 5s) */ @Synchronized fun startProcessRefreshing() { if (refreshingDisposable == null || refreshingDisposable?.isDisposed == true) { refreshingDisposable = Flowable.interval(0, 5, TimeUnit.SECONDS) .onBackpressureDrop() .flatMapSingle { getProcessListSingle() } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ newProcessList -> Timber.i("Processes refreshed") processList.replace(newProcessList) }, { throwable -> Timber.e(throwable) }) } } /** * Stop processes refreshing. */ fun stopProcessRefreshing() { refreshingDisposable?.dispose() } /** * Change process list sorting type from ascending to descending or or vice versa */ fun changeProcessSorting() { async(UI) { val result = bg { getAppSortedList() } val sortedAppList = result.await() ref().processList.replace(sortedAppList) } } /** * @return sorted list of the apps from [processList] */ private fun getAppSortedList(): List<ProcessItem> { val processListCopy = ArrayList<ProcessItem>(processList) isSortingAsc = !isSortingAsc prefs.insert(SORTING_PROCESSES_KEY, isSortingAsc) if (isSortingAsc) { processListCopy.sortBy { it.name.toUpperCase() } } else { processListCopy.sortByDescending { it.name.toUpperCase() } } return processListCopy } /** * Return [Single] with process list */ private fun getProcessListSingle(): Single<List<ProcessItem>> { return Single.fromCallable({ val processesList = ArrayList<ProcessItem>() processesList.addAll(readPs()) if (isSortingAsc) { processesList.sortBy { it.name.toUpperCase() } } else { processesList.sortByDescending { it.name.toUpperCase() } } processesList }) } /** * Old method for reading ps output. Should be rewritten. */ private fun readPs(): List<ProcessItem> { val processesList = ArrayList<ProcessItem>() try { val args = arrayListOf("/system/bin/ps", "-p") val cmd = ProcessBuilder(args) val process = cmd.start() val bis = process.inputStream.bufferedReader() val lines = bis.readLines() lines.forEachIndexed { i, line -> if (i > 0) { val st = StringTokenizer(line) // It is bad. Refactor this! var iterator = 0 var user = "" var name = "" var pid = "" var ppid = "" var niceness = "" var rss = "" var vsize = "" while (st.hasMoreTokens()) { when (iterator) { 0 -> user = st.nextToken() 1 -> pid = st.nextToken() 2 -> ppid = st.nextToken() 3 -> vsize = st.nextToken() 4 -> rss = st.nextToken() 6 -> niceness = st.nextToken() 12 -> name = st.nextToken() else -> st.nextToken() } iterator++ } processesList.add(ProcessItem(name, pid, ppid, niceness, user, rss, vsize)) } } bis.close() } catch (e: IOException) { Timber.e(e) } return processesList } override fun onCleared() { super.onCleared() refreshingDisposable?.dispose() } }
0
Kotlin
0
0
28db3a83c1ef9c37a6c259e6a0ad909756bce1d6
5,889
cpu-info
Apache License 2.0
kamp-core/src/test/kotlin/ch/leadrian/samp/kamp/core/api/util/TextDrawsTest.kt
Double-O-Seven
142,487,686
false
{"Kotlin": 3854710, "C": 23964, "C++": 23699, "Java": 4753, "Dockerfile": 769, "Objective-C": 328, "Batchfile": 189}
package ch.leadrian.samp.kamp.core.api.util import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.CsvSource internal class TextDrawsTest { @ParameterizedTest @CsvSource( "'Hi there~~~', 'Hi there???'", "'Hallo, wie geht es dir?', 'Hallo, wie geht es dir?'" ) fun shouldSanitizeString(text: String, expectedSanitizedText: String) { val sanitizedText = text.sanitizeForTextDraw() assertThat(sanitizedText) .isEqualTo(expectedSanitizedText) } }
1
Kotlin
1
7
af07b6048210ed6990e8b430b3a091dc6f64c6d9
608
kamp
Apache License 2.0
functions/src/main/kotlin/io/ashdavies/playground/google/CollectionReference.kt
ashdavies
36,688,248
false
null
package io.ashdavies.playground.google import com.google.cloud.firestore.CollectionReference import com.google.cloud.firestore.WriteResult suspend fun CollectionReference.delete( childPath: String, ): WriteResult = document(childPath) .delete() .await() suspend fun <T : Any> CollectionReference.write( childPath: String, value: T, ): WriteResult = document(childPath) .set(value) .await()
10
Kotlin
32
107
bed73969ca5ec5ec76bdac04592994f847ee2991
420
data-binding
Apache License 2.0
analytics-impl/src/main/java/com/grappim/hateitorrateit/analyticsimpl/HomeScreenAnalyticsImpl.kt
Grigoriym
704,244,986
false
{"Kotlin": 339796}
package com.grappim.hateitorrateit.analyticsimpl import com.grappim.hateitorrateit.analyticsapi.AnalyticsController import com.grappim.hateitorrateit.analyticsapi.HomeScreenAnalytics import javax.inject.Inject import javax.inject.Singleton @Singleton class HomeScreenAnalyticsImpl @Inject constructor( private val analyticsController: AnalyticsController ) : HomeScreenAnalytics { override fun trackHomeScreenStart() { analyticsController.trackEvent("home_screen_start") } override fun trackProductClicked() { analyticsController.trackEvent("home_product_clicked") } }
6
Kotlin
0
0
d84b032336a2576f816d62c473dd14581481730e
608
HateItOrRateIt
Apache License 2.0
src/main/kotlin/org/jetbrains/research/smtlib/psi/SmtLibFileRoot.kt
Saloed
225,314,384
false
null
package org.jetbrains.research.smtlib.psi import com.intellij.extapi.psi.PsiFileBase import com.intellij.psi.FileViewProvider import org.jetbrains.research.smtlib.Icons import org.jetbrains.research.smtlib.SmtLibFileType import org.jetbrains.research.smtlib.SmtLibLanguage class SmtLibFileRoot(viewProvider: FileViewProvider) : PsiFileBase(viewProvider, SmtLibLanguage) { override fun getFileType() = SmtLibFileType override fun toString() = "SmtLib Language file" override fun getIcon(flags: Int) = Icons.SMTLIB_ICON }
0
Kotlin
0
1
aa05be0432186a786a8d9bfad89b8671136a66ac
537
smtlib-intellij-plugin
Apache License 2.0
app/src/main/java/dev/jylha/station/model/Station.kt
jylha
292,642,089
false
{"Kotlin": 392658}
package dev.jylha.station.model import androidx.compose.runtime.Immutable /** * Domain Model for station information. * * @param passengerTraffic Whether station supports commercial passenger traffic. * @param type Station type. * @param name Station name. * @param shortCode Short station code. * @param code Country specific UIC code of the station [1-9999]. * @param countryCode Country code. * @param longitude Longitude in WGS-84 format. * @param latitude Latitude in WGS-84 format. */ @Immutable data class Station( val passengerTraffic: Boolean, val type: Type, val name: String, val shortCode: String, val code: Int, val countryCode: String, val longitude: Double, val latitude: Double ) { companion object; /** Secondary constructor for creating stations in Finland that have passenger traffic. */ constructor(name: String, shortCode: String, code: Int, longitude: Double, latitude: Double) : this( passengerTraffic = true, type = Type.Station, name, shortCode, code, countryCode = "FI", longitude, latitude ) sealed class Type(val value: String) { object Station : Type("STATION") object StoppingPoint : Type("STOPPING_POINT") object TurnoutInTheOpenLine : Type("TURNOUT_IN_THE_OPEN_LINE") companion object { fun of(value: String): Type { return when (value) { Station.value -> Station StoppingPoint.value -> StoppingPoint TurnoutInTheOpenLine.value -> TurnoutInTheOpenLine else -> throw IllegalArgumentException("Unknown station type: '$value'") } } } override fun toString(): String = value } }
0
Kotlin
0
1
8b7df4d11ea3013c55d5c3b6b824403a6d5410c4
1,912
station
Apache License 2.0
app/src/main/java/com/nadia/frenzy/ui/askquestion/QuestionViewModel.kt
NadiaBelhaj
558,358,508
false
{"Kotlin": 125841}
package com.nadia.frenzy.ui.askquestion import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.nadia.frenzy.data.QuestionData import com.nadia.frenzy.data.ResponseType import com.nadia.frenzy.data.source.QuestionRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class QuestionViewModel @Inject constructor( private val questionRepository: QuestionRepository ) : ViewModel() { private val questionLiveData: MutableLiveData<ResponseType> = MutableLiveData() fun askNewQuestion(token: String, questionData: QuestionData) { viewModelScope.launch { val result = questionRepository.createNewQuestion(token, questionData) if (result.isSuccess) { val response = result.getOrNull() when (response?.code()) { 200 -> questionLiveData.postValue(ResponseType.SUCCESS) 401 -> questionLiveData.postValue(ResponseType.NO_AUTH) else -> questionLiveData.postValue(ResponseType.FAILURE) } } else { questionLiveData.postValue(ResponseType.FAILURE) } } } fun getQuestionLiveData() = questionLiveData }
0
Kotlin
1
0
57bbb11812e5d38710393413fa2296d393a52985
1,355
Frenzy-Android-App-Front-end
MIT License
kwicket-core/src/main/kotlin/org/kwicket/model/PropModel.kt
ageery
87,933,631
false
null
package org.kwicket.model import org.apache.wicket.WicketRuntimeException import org.apache.wicket.model.IModel import java.io.Serializable import kotlin.reflect.KMutableProperty1 import kotlin.reflect.KProperty1 import kotlin.reflect.jvm.javaGetter import kotlin.reflect.jvm.javaMethod import kotlin.reflect.jvm.jvmErasure /** * [IModel] that applies the [props] to the [model] for getting and setting the model's value. * * @param T type of the [IModel]'s value/object * @param model [IModel] whose value is * @param props [PropChain] that is applied to the [model] value to get the value of the [IModel] */ class PropModel<T>(val model: IModel<*>, private val props: PropChain<T>) : IModel<T> { constructor(model: IModel<*>, prop: KProperty1<*, T>) : this(model = model, props = PropChain { +prop }) override fun getObject(): T = if (model.value == null) null as T else props.getValue(model.value) override fun setObject(value: T) = props.setValue(model.value, value) } /** * Represents a [Serializable] chain of properties. */ class PropChain<T>(init: PropChainBuilder.() -> KProperty1<*, T>) : Serializable { private val getters: List<String> private val setter: SetterInfo<T>? init { val builder = PropChainBuilder() val lastProp = init(builder) getters = builder.getterNamees.toList() @Suppress("UNCHECKED_CAST") setter = if (lastProp !is KMutableProperty1) null else SetterInfo( name = lastProp.setter.javaMethod!!.name, type = lastProp.setter.parameters[1].type.jvmErasure.java as Class<out T> ) } @Suppress("UNCHECKED_CAST") private fun computeValue(obj: Any?, getters: List<String>): T = getters.fold(obj, { value, getterName -> value?.let { it::class.java.getMethod(getterName).invoke(value) } }) as T fun getValue(obj: Any?): T = computeValue(obj, getters) fun setValue(obj: Any?, value: T) { if (setter != null) { val setterParentValue = computeValue(obj, getters.subList(0, getters.size - 1)) if (setterParentValue != null) { setter.setValue(setterParentValue, value) } else { throw WicketRuntimeException("Parent object is null") } } else { throw WicketRuntimeException("There is no setter") } } } /** * Builder for creating a [PropChain] object. */ class PropChainBuilder { private var props: MutableList<KProperty1<*, *>> = mutableListOf() operator fun <T, R> KProperty1<T, R>.unaryPlus(): KProperty1<T, R> { props.add(this) return this } operator fun <T, S, R> KProperty1<T, R>.plus(other: KProperty1<S, R>): KProperty1<S, R> { if (props.isEmpty()) { props.add(this) } props.add(other) return other } val getterNamees: Sequence<String> get() = props.asSequence().map { it.javaGetter!!.name } } private class SetterInfo<T>(val name: String, val type: Class<out T>) : Serializable { fun setValue(obj: Any, value: T) { obj::class.java.getMethod(name, type).invoke(obj, value) } }
1
Kotlin
0
12
58b90cfa0474b452a622c21d7972034e6235db4f
3,206
kwicket
Apache License 2.0
src/test/java/org/jitsi/rtp/rtcp/RtcpIteratorTest.kt
bbaldino
173,043,170
true
{"Kotlin": 349802}
/* * Copyright @ 2018 - present 8x8, 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 org.jitsi.rtp.rtcp import io.kotlintest.IsolationMode import io.kotlintest.matchers.beInstanceOf import io.kotlintest.matchers.beOfType import io.kotlintest.matchers.haveSize import io.kotlintest.should import io.kotlintest.shouldBe import io.kotlintest.shouldThrow import io.kotlintest.specs.ShouldSpec import org.jitsi.rtp.rtcp.rtcpfb.RtcpFbPacket import java.nio.ByteBuffer internal class RtcpIteratorTest : ShouldSpec() { override fun isolationMode(): IsolationMode? = IsolationMode.InstancePerLeaf private val compoundPacketBuf = ByteBuffer.wrap(byteArrayOf( 0x81.toByte(), 0xC9.toByte(), 0x00.toByte(), 0x07.toByte(), 0x50.toByte(), 0x63.toByte(), 0x13.toByte(), 0xDE.toByte(), 0x48.toByte(), 0xCA.toByte(), 0xF9.toByte(), 0xD1.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x10.toByte(), 0x8C.toByte(), 0x00.toByte(), 0x00.toByte(), 0x04.toByte(), 0x68.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x81.toByte(), 0xCD.toByte(), 0x00.toByte(), 0x03.toByte(), 0x50.toByte(), 0x63.toByte(), 0x13.toByte(), 0xDE.toByte(), 0x48.toByte(), 0xCA.toByte(), 0xF9.toByte(), 0xD1.toByte(), 0x10.toByte(), 0x8D.toByte(), 0x00.toByte(), 0x00.toByte() )) private val singlePacketBuf = ByteBuffer.wrap(byteArrayOf( 0x80.toByte(), 0xC8.toByte(), 0x00.toByte(), 0x06.toByte(), 0x36.toByte(), 0x13.toByte(), 0xF6.toByte(), 0xF6.toByte(), 0xDF.toByte(), 0x21.toByte(), 0x7D.toByte(), 0xF0.toByte(), 0x7F.toByte(), 0x5E.toByte(), 0x41.toByte(), 0xD5.toByte(), 0x90.toByte(), 0x31.toByte(), 0x59.toByte(), 0xF3.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x08.toByte(), 0x00.toByte(), 0x00.toByte(), 0x01.toByte(), 0x14.toByte() )) private val blah = ByteBuffer.wrap(byteArrayOf( 0x8F.toByte(), 0xCD.toByte(), 0x00.toByte(), 0x21.toByte(), 0x72.toByte(), 0x45.toByte(), 0x7C.toByte(), 0xE5.toByte(), 0x03.toByte(), 0xA3.toByte(), 0x76.toByte(), 0x0E.toByte(), 0x00.toByte(), 0x01.toByte(), 0x00.toByte(), 0x58.toByte(), 0x11.toByte(), 0xE8.toByte(), 0xC2.toByte(), 0x00.toByte(), 0xD5.toByte(), 0x55.toByte(), 0xD5.toByte(), 0x55.toByte(), 0xD5.toByte(), 0x55.toByte(), 0xD5.toByte(), 0x55.toByte(), 0xD5.toByte(), 0x55.toByte(), 0xD5.toByte(), 0x55.toByte(), 0xD5.toByte(), 0x55.toByte(), 0xD5.toByte(), 0x55.toByte(), 0xD5.toByte(), 0x55.toByte(), 0xD5.toByte(), 0x55.toByte(), 0xD5.toByte(), 0x55.toByte(), 0xD5.toByte(), 0x55.toByte(), 0xD5.toByte(), 0x40.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte() )) init { "when parsing a compound packet" { val iter = RtcpIterator(compoundPacketBuf) "next" { should("get the next packet") { iter.next() should beInstanceOf<RtcpRrPacket>() iter.next() should beInstanceOf<RtcpFbPacket>() shouldThrow<Exception> { iter.next() } } } "hasNext" { should("correctly report if there is another packet") { iter.hasNext() shouldBe true iter.next() iter.hasNext() shouldBe true iter.next() iter.hasNext() shouldBe false } } "getAll" { should("return all packets") { val pkts = iter.getAll() pkts should haveSize(2) iter.hasNext() shouldBe false } } } "when parsing a packet with only a single RTCP packet" { val iter = RtcpIterator(singlePacketBuf) val pkt = iter.next() pkt should beOfType<RtcpSrPacket>() iter.hasNext() shouldBe false } } }
0
Kotlin
0
0
b8226d21296d773b792eaff18add487c27d35b1c
6,230
jitsi-rtp-1
Apache License 2.0
app/src/test/java/com/quintatecnica/pokedex/dao/PokemonRepositoryTest.kt
carlosabreu
401,113,792
false
null
package com.quintatecnica.pokedex.dao import com.quintatecnica.pokedex.generator.KantoGenerator import com.quintatecnica.pokedex.model.Pokemon import org.junit.Test import org.mockito.Mockito import org.mockito.Mockito.never class PokemonRepositoryTest { private val repository = PokemonRepository() @Test fun should_CallCallback_WhenPokemonIsGenerated() { val function: (List<Pokemon>) -> Unit = {} val callback = Mockito.mock(function::class.java) repository.generate(KantoGenerator(), callback) Mockito.verify(callback)(Mockito.anyList()) } @Test fun should_NotCallCallback_WhenPokemonNoPokemonIsGenerated() { val function: (List<Pokemon>) -> Unit = {} val callback = Mockito.mock(function::class.java) val generator = Mockito.spy(KantoGenerator()) Mockito.`when`(generator.generate()).thenReturn(ArrayList()) repository.generate(generator, callback) Mockito.verify(callback, never())(Mockito.anyList()) } }
0
Kotlin
0
2
75c7f6c7ff1a9c404296529a392fb5f8f9fab61c
1,023
pokedex
Apache License 2.0
src/main/kotlin/dev/crashteam/uzumanalytics/repository/clickhouse/model/ChSellerOrderDynamic.kt
crashteamdev
647,366,680
false
{"Kotlin": 562208, "Dockerfile": 743}
package dev.crashteam.uzumanalytics.repository.clickhouse.model import java.time.LocalDate data class ChSellerOrderDynamic( val date: LocalDate, val orderAmount: Long, )
3
Kotlin
0
0
4cb72dfc2684db539dba47031b9e70038d10d8bb
180
uzum-analytics
Apache License 2.0
filelogger/src/main/java/abbasi/android/filelogger/interceptor/LogInterceptor.kt
aabolfazl
466,665,945
false
{"Gradle": 4, "Java Properties": 1, "Shell": 1, "Ignore List": 3, "Batchfile": 1, "Text": 2, "Markdown": 1, "INI": 2, "Proguard": 2, "Kotlin": 19, "XML": 12, "Java": 6}
package abbasi.android.filelogger.interceptor import abbasi.android.filelogger.file.LogLevel interface LogInterceptor { fun intercept(level: LogLevel, tag: String, message: String, e: Throwable?): String }
0
Java
1
13
6b2a76a792a362e6c1314efea1492f50e2716452
211
FileLogger
MIT License
app/src/main/java/com/benforino/trailtrackerv2/TrailViewFragment.kt
BenForino
604,647,388
false
null
package com.benforino.trailtrackerv2 import android.Manifest import android.app.AlertDialog import android.content.Context import android.content.pm.PackageManager import android.location.Address import android.location.Geocoder import android.location.Location import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.EditText import android.widget.Toast import androidx.core.app.ActivityCompat import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.benforino.trailtrackerv2.adaptor.trailAdaptor import com.benforino.trailtrackerv2.database.Trail import com.benforino.trailtrackerv2.databinding.FragmentTrailViewBinding import com.benforino.trailtrackerv2.services.TrackService import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.LocationCallback import com.google.android.gms.location.LocationResult import com.google.android.gms.location.LocationServices import com.google.android.gms.location.Priority import com.google.android.gms.maps.model.LatLng import com.google.android.gms.tasks.CancellationTokenSource import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.ktx.auth import com.google.firebase.firestore.QuerySnapshot import com.google.firebase.firestore.ktx.firestore import com.google.firebase.ktx.Firebase import com.pixelcarrot.base64image.Base64Image import java.io.IOException import java.util.Locale import java.util.UUID class TrailViewFragment : Fragment() { private lateinit var firebaseAuth: FirebaseAuth private var db= Firebase.firestore lateinit var fusedLocationProviderClient: FusedLocationProviderClient private var _binding: FragmentTrailViewBinding? = null private lateinit var geocoder: Geocoder private val binding get() = _binding!! private lateinit var trailRecycler: RecyclerView; override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) firebaseAuth = Firebase.auth fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(requireContext()) geocoder = Geocoder(requireContext(), Locale.getDefault()) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment _binding = FragmentTrailViewBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.locationAuto.setOnClickListener{ startRecyclerView() } binding.locationManual.setOnClickListener{ getLatLngFromStr() } } private fun startRecyclerView(){ if (ActivityCompat.checkSelfPermission( requireContext(), Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission( requireContext(), Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) { return } fusedLocationProviderClient.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY,CancellationTokenSource().token) .addOnSuccessListener { getTrails(it) } } private fun getTrails(position: Location){ val trails = db.collection("Trails") val latLongBounds = calculateLatLngBounds(position) trails.whereLessThanOrEqualTo("finalLat", latLongBounds.second.latitude) .whereGreaterThanOrEqualTo("finalLat",latLongBounds.first.latitude) .get() .addOnSuccessListener { documents -> for (document in documents) { if ( document.get("finalLon").toString().toDouble() >= latLongBounds.first.longitude && document.get("finalLon").toString().toDouble() <= latLongBounds.second.longitude){ Log.d("Testing", "DocumentSnapshot data: ${document.data}") } } getImages(documents) } .addOnFailureListener { exception -> Log.w("Testing", "Error getting documents: ", exception) } } private fun getTrails(position: LatLng){ val trails = db.collection("Trails") val latLongBounds = calculateLatLngBounds(position) trails.whereLessThanOrEqualTo("finalLat", latLongBounds.second.latitude) .whereGreaterThanOrEqualTo("finalLat",latLongBounds.first.latitude) .get() .addOnSuccessListener { documents -> if(!documents.isEmpty) { for (document in documents) { if (document.get("finalLon").toString() .toDouble() >= latLongBounds.first.longitude && document.get("finalLon").toString() .toDouble() <= latLongBounds.second.longitude ) { Log.d("Testing", "DocumentSnapshot data: ${document.data}") } } getImages(documents) }else{ Toast.makeText(requireContext(), "No Trails found in this location", Toast.LENGTH_SHORT).show() } } .addOnFailureListener { exception -> Log.w("Testing", "Error getting documents: ", exception) } } private fun getLatLngFromStr(){ val builder = AlertDialog.Builder(requireContext()) val inflater = layoutInflater val dialogLayout = inflater.inflate(R.layout.enter_address_layout,null) val editText = dialogLayout.findViewById<EditText>(R.id.address) with(builder){ setTitle("Enter address to find trails") setPositiveButton("Save"){dialog, which -> var address = editText.text.toString() if(address.isEmpty()){ Toast.makeText(requireContext(), "No input found, try again", Toast.LENGTH_SHORT).show() }else{ val loc = geocoder.getFromLocationName(address,1,) if (loc != null) { if(loc.isNotEmpty()){ val coordinates = LatLng(loc.first().latitude,loc.first().longitude) getTrails(coordinates) }else{ Toast.makeText(requireContext(), "Address not found, try again", Toast.LENGTH_SHORT).show() } } } } setView(dialogLayout) show() } } private fun getImages(documents:QuerySnapshot){ val trailArray = arrayListOf<Trail>() val idList = mutableListOf<String>() trailRecycler = binding.trailRecycler trailRecycler.layoutManager = LinearLayoutManager(requireContext()) for (document in documents) { idList.add(document.id) } val images = db.collection("Trail_Images") images.whereIn("id",idList) .get() .addOnSuccessListener { documents1 -> if(!documents1.isEmpty) { for (document1 in documents1) { val imgStr = document1.get("img").toString() for (document in documents) { if (document.id == document1.id) { var name = "unnamed_trail" if (document.get("name") !== null) { name = document.get("name")!!.toString() } val trail = Trail( document1.id, document.get("distance").toString().toFloat(), imgStr, name ) trailArray.add(trail) break } } } trailRecycler.adapter = trailAdaptor(trailArray) }else{ Toast.makeText(requireContext(), "No Trails found in this location", Toast.LENGTH_SHORT).show() } } .addOnFailureListener { exception -> Log.w("Testing", "Error getting documents: ", exception) } } private fun calculateLatLngBounds(latLng: Location, distanceKM:Int = 10):Pair<LatLng,LatLng>{ val latMin = latLng.latitude - 0.045 val latMax = latLng.latitude + 0.045 val longMin = latLng.longitude - (0.045 / Math.cos(latLng.latitude*Math.PI/180)) val longMax = latLng.longitude + (0.045 / Math.cos(latLng.latitude*Math.PI/180)) val latLonMin = LatLng(latMin,longMin) val latLonMax = LatLng(latMax,longMax) return Pair(latLonMin,latLonMax) } private fun calculateLatLngBounds(latLng: LatLng, distanceKM:Int = 10):Pair<LatLng,LatLng>{ val latMin = latLng.latitude - 0.045 val latMax = latLng.latitude + 0.045 val longMin = latLng.longitude - (0.045 / Math.cos(latLng.latitude*Math.PI/180)) val longMax = latLng.longitude + (0.045 / Math.cos(latLng.latitude*Math.PI/180)) val latLonMin = LatLng(latMin,longMin) val latLonMax = LatLng(latMax,longMax) return Pair(latLonMin,latLonMax) } }
0
Kotlin
0
0
b36c2f660ae8fabef0201c01b9a0af2d006382b1
9,988
Trail-Tracker
MIT License
src/main/kotlin/ch/icken/processor/GenerationOptions.kt
Thijsiez
699,910,580
false
{"Kotlin": 85947}
/* * Copyright 2023-2024 <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 ch.icken.processor import ch.icken.processor.ClassNames.GeneratedClassName import com.squareup.kotlinpoet.AnnotationSpec import java.time.LocalDateTime object GenerationOptions { const val ADD_GENERATED_ANNOTATION = "addGeneratedAnnotation" fun <T : Any> generatedAnnotation( generator: Class<T>, date: LocalDateTime = LocalDateTime.now(), comments: String = "Generated using panache-kotlin-dsl" ) = AnnotationSpec.builder(GeneratedClassName) .addMember("%S", generator.name) .addMember("%S", date.toString()) .addMember("%S", comments) .build() }
0
Kotlin
0
1
730c2fd001db3cb85967cefe7886d4cdce095d7e
1,222
panache-kotlin-dsl
Apache License 2.0
src/dataStructures/trees/Segment.kt
timurmaio
277,170,802
false
{"Kotlin": 54229, "PLpgSQL": 4095}
package dataStructures.trees import algorithms.isPowerOfTwo /** * Дерево отрезков. */ class Segment(collection: Iterable<Int>) { /** * Массив с узлами дерева. * * Дерево на самом деле виртуальное. Отображение индексов: * левый потомок: 2*i + 1 * правый потомок: 2*i + 2 * родитель: (i-1)/2 */ private val nodes: Array<Int> /** * Создание дерева отрезков из коллекции. * * Для правильности работы алгоритмов необходимо, чтобы размер коллекция был равен степени двойки. * Следовательно, если это не так, необходимо выровнять её до ближайшей большей степени двойки. */ init { // дополнение длины массива до степени двойки var length = collection.count() while (!isPowerOfTwo(length.toLong())) { length++ } // дерево будет иметь размер (выровненная длина)*2-1 nodes = Array(length * 2 - 1, { 0 }) // копирование элементов массива в листья дерева var j = length - 1 for (item in collection) { nodes[j] = item j++ } // заполнение пустых листов дерева в зависимости от задачи // для поиска минимума - максимальными значениями и т.д. for (i in length - 1 + collection.count() until nodes.size) { nodes[i] = Int.MAX_VALUE } // выстраивание дерева вверх от листьев к корню // downTo 1 - корневая вершина не требует обновления родителей // step 2 - чтобы не обновлять родителя дважды от обоих потомков for (i in nodes.size - 1 downTo 1 step 2) { updateParent(i) } } /** * Функция над двумя узлами дерева, результат которой соответствует значению родительского узла для двух данных. */ private fun function(x: Int, y: Int): Int = if (x < y) x else y /** * Вычисление значения для отрезка по узлам дерева. * * @param curIndex Индекс текущего узла. * @param curNodeL Левая граница отрезка, на котором подсчитана функция и записана в данном узле. * @param curNodeR Правая граница отрезка, на котором подсчитана функция и записана в данном узле. * @param l Левая граница отрезка, на котором необходимо вычислить функцию. * @param r Правая граница отрезка, на котором необходимо вычислить функцию. * * @return Значение, вычисленное для заданного отрезка. */ private fun queryInternal(curIndex: Int, curNodeL: Int, curNodeR: Int, l: Int, r: Int): Int { // отрезок, для которого вершина хранит значение, // лежит в запрашиваемом отрезке if (curNodeL >= l && curNodeR <= r) { return nodes[curIndex] } // отрезок, для которого вершина хранит значение, // никак не связан с запрашиваемым отрезком // возвращаем нейтральное значение для функции if (curNodeL > r || curNodeR < l) { return Int.MAX_VALUE } // передаём запросы потомкам // TODO: возможно здесь можно сделать оптимизацию и не вычислять значения // для тех потомков, которые не лежат в запрашиваемом отрезке val lResult = queryInternal(2 * curIndex + 1, curNodeL, (curNodeL + curNodeR) / 2, l, r) val rResult = queryInternal(2 * curIndex + 2, (curNodeL + curNodeR) / 2 + 1, curNodeR, l, r) return function(lResult, rResult) } /** * Обновление значения у родителя узла дерева по одному из его потомков, * а также, возможно, и всех родителей узла до корня. * * @param currentIndex Индекс узла дерева в массиве узлов. * @param updateAllParents Обновлять только непосредственно родительский узел или * также все родительские узлы до корня. */ private fun updateParent(currentIndex: Int, updateAllParents: Boolean = false) { var index = currentIndex while (index != 0) { val parentIndex = (index - 1)/2 // индекс вершины чётный, она является правым потомком val otherIndex = if (index%2 == 0) index - 1 else index + 1 val value = function(nodes[index], nodes[otherIndex]) nodes[parentIndex] = value if (!updateAllParents) { return } index = parentIndex } } /** * Вычисление функции на отрезке в массиве от левой до правой границы отрезка. * * Сложность: O(log(n)). */ fun query(left: Int, right: Int): Int = queryInternal(0, 0, nodes.size/2, left, right) /** * Изменение значения в массиве по индексу на новое значение. * * Сложность: O(log(n)). */ fun update(index: Int, value: Int) { // нахождение индекса (позиции) листа, который необходимо изменить val position = nodes.size / 2 + index nodes[position] = value updateParent(position, true) } }
0
null
0
0
2257a6a968bb8440f8a2a65a5fd31ff0fa5a5e8f
4,938
ads
The Unlicense
desktop/src/jvmMain/kotlin/Main.kt
geoff-powell
724,651,026
false
{"Kotlin": 49837, "Ruby": 2294, "HTML": 1133, "JavaScript": 1073, "Swift": 573, "CSS": 161}
import androidx.compose.ui.window.Window import androidx.compose.ui.window.application import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.lightColorScheme import com.greenmiststudios.common.UIShow import com.greenmiststudios.common.di.appModule import org.koin.core.context.startKoin fun main() = application { startKoin { modules(appModule()) } Window(onCloseRequest = ::exitApplication) { MaterialTheme(colorScheme = if (isSystemInDarkTheme()) darkColorScheme() else lightColorScheme()) { UIShow() } } }
4
Kotlin
0
0
7afc0b88fdbf88f7720c829216e953728ee18eeb
670
Tidy
Apache License 2.0
rounded/src/commonMain/kotlin/me/localx/icons/rounded/filled/UserRobotXmarks.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.filled import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.rounded.Icons public val Icons.Filled.UserRobotXmarks: ImageVector get() { if (_userRobotXmarks != null) { return _userRobotXmarks!! } _userRobotXmarks = Builder(name = "UserRobotXmarks", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveToRelative(20.0f, 24.0f) lineTo(4.0f, 24.0f) curveToRelative(-0.553f, 0.0f, -1.0f, -0.448f, -1.0f, -1.0f) curveToRelative(0.0f, -3.309f, 2.691f, -6.0f, 6.0f, -6.0f) horizontalLineToRelative(6.0f) curveToRelative(3.309f, 0.0f, 6.0f, 2.691f, 6.0f, 6.0f) curveToRelative(0.0f, 0.552f, -0.447f, 1.0f, -1.0f, 1.0f) close() moveTo(20.5f, 6.0f) horizontalLineToRelative(-0.5f) curveToRelative(0.0f, -2.206f, -1.794f, -4.0f, -4.0f, -4.0f) horizontalLineToRelative(-3.0f) verticalLineToRelative(-1.0f) curveToRelative(0.0f, -0.552f, -0.447f, -1.0f, -1.0f, -1.0f) reflectiveCurveToRelative(-1.0f, 0.448f, -1.0f, 1.0f) verticalLineToRelative(1.0f) horizontalLineToRelative(-3.0f) curveToRelative(-2.206f, 0.0f, -4.0f, 1.794f, -4.0f, 4.0f) horizontalLineToRelative(-0.5f) curveToRelative(-0.827f, 0.0f, -1.5f, 0.673f, -1.5f, 1.5f) verticalLineToRelative(2.0f) curveToRelative(0.0f, 0.827f, 0.673f, 1.5f, 1.5f, 1.5f) horizontalLineToRelative(0.5f) curveToRelative(0.0f, 2.206f, 1.794f, 4.0f, 4.0f, 4.0f) horizontalLineToRelative(8.0f) curveToRelative(2.206f, 0.0f, 4.0f, -1.794f, 4.0f, -4.0f) horizontalLineToRelative(0.5f) curveToRelative(0.827f, 0.0f, 1.5f, -0.673f, 1.5f, -1.5f) verticalLineToRelative(-2.0f) curveToRelative(0.0f, -0.827f, -0.673f, -1.5f, -1.5f, -1.5f) close() moveTo(10.457f, 9.043f) curveToRelative(0.391f, 0.391f, 0.391f, 1.023f, 0.0f, 1.414f) curveToRelative(-0.195f, 0.195f, -0.451f, 0.293f, -0.707f, 0.293f) reflectiveCurveToRelative(-0.512f, -0.098f, -0.707f, -0.293f) lineToRelative(-0.543f, -0.543f) lineToRelative(-0.543f, 0.543f) curveToRelative(-0.195f, 0.195f, -0.451f, 0.293f, -0.707f, 0.293f) reflectiveCurveToRelative(-0.512f, -0.098f, -0.707f, -0.293f) curveToRelative(-0.391f, -0.391f, -0.391f, -1.023f, 0.0f, -1.414f) lineToRelative(0.543f, -0.543f) lineToRelative(-0.543f, -0.543f) curveToRelative(-0.391f, -0.391f, -0.391f, -1.023f, 0.0f, -1.414f) reflectiveCurveToRelative(1.023f, -0.391f, 1.414f, 0.0f) lineToRelative(0.543f, 0.543f) lineToRelative(0.543f, -0.543f) curveToRelative(0.391f, -0.391f, 1.023f, -0.391f, 1.414f, 0.0f) reflectiveCurveToRelative(0.391f, 1.023f, 0.0f, 1.414f) lineToRelative(-0.543f, 0.543f) lineToRelative(0.543f, 0.543f) close() moveTo(17.457f, 9.043f) curveToRelative(0.391f, 0.391f, 0.391f, 1.023f, 0.0f, 1.414f) curveToRelative(-0.195f, 0.195f, -0.451f, 0.293f, -0.707f, 0.293f) reflectiveCurveToRelative(-0.512f, -0.098f, -0.707f, -0.293f) lineToRelative(-0.543f, -0.543f) lineToRelative(-0.543f, 0.543f) curveToRelative(-0.195f, 0.195f, -0.451f, 0.293f, -0.707f, 0.293f) reflectiveCurveToRelative(-0.512f, -0.098f, -0.707f, -0.293f) curveToRelative(-0.391f, -0.391f, -0.391f, -1.023f, 0.0f, -1.414f) lineToRelative(0.543f, -0.543f) lineToRelative(-0.543f, -0.543f) curveToRelative(-0.391f, -0.391f, -0.391f, -1.023f, 0.0f, -1.414f) reflectiveCurveToRelative(1.023f, -0.391f, 1.414f, 0.0f) lineToRelative(0.543f, 0.543f) lineToRelative(0.543f, -0.543f) curveToRelative(0.391f, -0.391f, 1.023f, -0.391f, 1.414f, 0.0f) reflectiveCurveToRelative(0.391f, 1.023f, 0.0f, 1.414f) lineToRelative(-0.543f, 0.543f) lineToRelative(0.543f, 0.543f) close() } } .build() return _userRobotXmarks!! } private var _userRobotXmarks: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
5,501
icons
MIT License
app/src/main/java/cn/mijack/imagedrive/fragment/BackUpFragment.kt
MiJack
88,419,422
false
null
package cn.mijack.imagedrive.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import cn.mijack.imagedrive.R import cn.mijack.imagedrive.base.BaseFragment /** * @author admin * @date 2017/8/26 */ class BackUpFragment : BaseFragment(), View.OnClickListener { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_backup, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) var btn = view.findViewById<Button>(R.id.btn) btn.setOnClickListener(this) } override fun onClick(p0: View?) { when (p0?.id) { R.id.btn -> { } } } }
1
Kotlin
0
0
837a92c983bcb3972401f8f8177df506752625f0
942
ImageDrive
Apache License 2.0
15-dagger-and-modularization/projects/starter/Busso/libs/location/rx/src/main/java/com/raywenderlich/android/location/rx/di/LocationModule.kt
aasmc
417,089,569
true
{"Kotlin": 6085897, "Shell": 1914}
package com.raywenderlich.android.location.rx.di import android.app.Application import android.content.Context import android.location.LocationManager import com.raywenderlich.android.di.scopes.ApplicationScope import com.raywenderlich.android.location.api.model.LocationEvent import com.raywenderlich.android.location.api.permissions.GeoLocationPermissionChecker import com.raywenderlich.android.location.rx.permission.GeoLocationPermissionCheckerImpl import com.raywenderlich.android.location.rx.provideRxLocationObservable import dagger.Module import dagger.Provides import io.reactivex.Observable @Module class LocationModule { @ApplicationScope @Provides fun provideLocationManager(application: Application): LocationManager = application.getSystemService(Context.LOCATION_SERVICE) as LocationManager @ApplicationScope @Provides fun providePermissionChecker(application: Application): GeoLocationPermissionChecker = GeoLocationPermissionCheckerImpl(application) @Provides fun provideLocationObservable( locationManager: LocationManager, permissionChecker: GeoLocationPermissionChecker ): Observable<LocationEvent> = provideRxLocationObservable(locationManager, permissionChecker) }
0
Kotlin
0
0
38ceb2272bcd83288d190ad2e7046acfd0166fef
1,258
dag-materials
Apache License 2.0
tools/corda-runtime-gradle-plugin/src/main/kotlin/net/corda/gradle/plugin/cordapp/CordappTasksImpl.kt
corda
346,070,752
false
null
package net.corda.gradle.plugin.cordapp import com.fasterxml.jackson.databind.DeserializationFeature import com.fasterxml.jackson.databind.ObjectMapper import net.corda.gradle.plugin.configuration.ProjectContext import net.corda.gradle.plugin.dtos.GroupPolicyDTO import net.corda.gradle.plugin.exception.CordaRuntimeGradlePluginException import java.io.File import java.io.FileInputStream class CordappTasksImpl(var pc: ProjectContext) { /** * Creates a group Policy based on the network config file and outputs it to the Group Policy json file. */ fun createGroupPolicy() { val groupPolicyFile = File(pc.groupPolicyFilePath) val networkConfigFile = File("${pc.project.rootDir}${pc.networkConfig.configFilePath}") val pluginsDir = "${pc.cordaCliBinDir}/plugins/" if (!groupPolicyFile.exists() || groupPolicyFile.lastModified() < networkConfigFile.lastModified()) { pc.logger.quiet("Creating the Group policy.") val configX500Ids = pc.networkConfig.x500Names GroupPolicyHelper().createStaticGroupPolicy( groupPolicyFile, configX500Ids, pc.javaBinDir, pluginsDir, pc.cordaCliBinDir ) } else { pc.logger.quiet("Group policy up to date.") } validateGroupPolicy() } private fun validateGroupPolicy() { val groupPolicyFile = File(pc.groupPolicyFilePath) val groupPolicy = try { val fis = FileInputStream(groupPolicyFile) val mapper = ObjectMapper() mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) mapper.readValue(fis, GroupPolicyDTO::class.java) } catch (e: Exception) { val firstLine = groupPolicyFile.useLines { it.firstOrNull() } if ((firstLine != null) && firstLine.contains("Unable to access jarfile \\S*corda-cli.jar".toRegex())) { throw CordaRuntimeGradlePluginException("Unable to find the Corda CLI, has it been installed?") } throw CordaRuntimeGradlePluginException("Failed to read GroupPolicy from group policy file with exception: $e.") } validateGroupPolicyHasAllMembers(groupPolicy) } private fun validateGroupPolicyHasAllMembers(groupPolicy: GroupPolicyDTO) { val membersNames = groupPolicy.protocolParameters?.staticNetwork?.members?.map { it.name } val requiredNodes = pc.networkConfig.vNodes if (requiredNodes.isNotEmpty() && membersNames == null) { throw CordaRuntimeGradlePluginException( "GroupPolicy File does not contain any members" ) } else { requiredNodes.forEach { requiredNode -> if (!membersNames!!.contains(requiredNode.x500Name)) { throw CordaRuntimeGradlePluginException( "GroupPolicy File does not contain member ${requiredNode.x500Name} specified in the networkConfigFile" ) } } } } /** * Creates the key pairs and keystore required to sign Cpis. */ fun createKeyStore() { val keystoreFile = File(pc.keystoreFilePath) if (!keystoreFile.exists()) { pc.logger.quiet("Creating a keystore and signing certificate.") KeyStoreHelper().generateKeyPair( pc.javaBinDir, pc.keystoreAlias, pc.keystorePassword, pc.keystoreFilePath ) pc.logger.quiet("Importing default gradle certificate") KeyStoreHelper().importKeystoreCert( pc.javaBinDir, pc.keystorePassword, pc.keystoreFilePath, pc.gradleDefaultCertAlias, pc.gradleDefaultCertFilePath ) pc.logger.quiet("Importing R3 signing certificate") KeyStoreHelper().importKeystoreCert( pc.javaBinDir, pc.keystorePassword, pc.keystoreFilePath, pc.r3RootCertKeyAlias, pc.r3RootCertFile ) KeyStoreHelper().exportCert( pc.javaBinDir, pc.keystoreAlias, pc.keystoreFilePath, pc.keystoreCertFilePath ) } else { pc.logger.quiet("Keystore and signing certificate already created.") } } /** * Builds the CPIs for the CordDapp and the Notary */ fun buildCPIs() { pc.logger.quiet("Creating ${pc.corDappCpiName} CPI.") BuildCpiHelper().createCPI( pc.javaBinDir, pc.cordaCliBinDir, pc.groupPolicyFilePath, pc.keystoreFilePath, pc.keystoreAlias, pc.keystorePassword, pc.corDappCpbFilePath, pc.corDappCpiFilePath, pc.corDappCpiName, pc.project.version.toString() ) pc.logger.quiet("Creating ${pc.notaryCpiName} CPI.") BuildCpiHelper().createCPI( pc.javaBinDir, pc.cordaCliBinDir, pc.groupPolicyFilePath, pc.keystoreFilePath, pc.keystoreAlias, pc.keystorePassword, pc.notaryCpbFilePath, pc.notaryCpiFilePath, pc.notaryCpiName, pc.project.version.toString() ) } /** * Uploads the required certificates and uploads the CorDapp and Notary CPIs */ fun deployCPIs() { val helper = DeployCpiHelper() helper.uploadCertificate( pc.cordaClusterURL, pc.cordaRestUser, pc.cordaRestPassword, pc.gradleDefaultCertAlias, pc.gradleDefaultCertFilePath ) pc.logger.quiet("Certificate '${pc.gradleDefaultCertAlias}' uploaded.") helper.uploadCertificate( pc.cordaClusterURL, pc.cordaRestUser, pc.cordaRestPassword, pc.keystoreAlias, pc.keystoreCertFilePath ) pc.logger.quiet("Certificate '${pc.keystoreAlias}' uploaded.") helper.uploadCertificate( pc.cordaClusterURL, pc.cordaRestUser, pc.cordaRestPassword, pc.r3RootCertKeyAlias, pc.r3RootCertFile ) pc.logger.quiet("Certificate '${pc.r3RootCertKeyAlias}' uploaded.") val cpiUploadStatus = helper.uploadCpi( pc.cordaClusterURL, pc.cordaRestUser, pc.cordaRestPassword, pc.corDappCpiFilePath, pc.corDappCpiName, pc.project.version.toString(), pc.corDappCpiUploadStatusFilePath, pc.cpiUploadTimeout ) pc.logger.quiet("CPI ${pc.corDappCpiName} uploaded: ${cpiUploadStatus.cpiFileChecksum}") val notaryUploadStatus = helper.uploadCpi( pc.cordaClusterURL, pc.cordaRestUser, pc.cordaRestPassword, pc.notaryCpiFilePath, pc.notaryCpiName, pc.project.version.toString(), pc.notaryCpiUploadStatusFilePath, pc.cpiUploadTimeout ) pc.logger.quiet("CPI ${pc.notaryCpiName} uploaded: ${notaryUploadStatus.cpiFileChecksum}") } }
50
null
25
56
6b5bd1a70280605ccc5106c69e58565a7daa1697
7,433
corda-runtime-os
Apache License 2.0
app/src/main/java/com/symphony/microblogging/base/presentation/view/extension/ActivityExtensions.kt
naveedahmad99
223,487,566
false
{"Gradle": 4, "YAML": 1, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 74, "XML": 15, "Java": 1}
package com.symphony.microblogging.base.presentation.view.extension import android.app.Activity import android.util.DisplayMetrics import android.view.View import android.view.inputmethod.InputMethodManager import androidx.appcompat.app.AppCompatActivity fun AppCompatActivity.onBackPresseddd() { if (supportFragmentManager.backStackEntryCount > 1) supportFragmentManager.popBackStack() else finish() } fun AppCompatActivity.hideKeyboard() { val imm = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager var view = currentFocus if (view == null) { view = View(this) } imm.hideSoftInputFromWindow(view.windowToken, 0) } fun AppCompatActivity.hideKeyboard(view: View) { val imm = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(view.windowToken, 0) } fun Activity.getWindowWidth(): Int { val displayMetrics = DisplayMetrics() windowManager.defaultDisplay.getMetrics(displayMetrics) return displayMetrics.widthPixels } fun Activity.getWindowHeight(): Int { val displayMetrics = DisplayMetrics() windowManager.defaultDisplay.getMetrics(displayMetrics) return displayMetrics.heightPixels }
0
Kotlin
0
0
8026fc67e4c226c683a6856bab9a5d1ed9907f4e
1,228
MicroBloggingProject
Apache License 2.0
app/src/main/java/com/github/meudayhegde/esputils/holders/ARPItem.kt
meudayhegde
179,924,023
false
null
package com.github.meudayhegde.esputils.holders /** * @param macAddress([String]) MAC Address of the network device * @param ipAddress([String]) IP Address of the network device * @param devNickName([String]) Device NickName stored on the app */ class ARPItem(var macAddress: String, var ipAddress: String, var devNickName: String? = null)
0
Kotlin
0
0
cfbe992ac1eda309e26906e9e8ba05ac961b4d8b
344
ESPUtils_android
Apache License 2.0
app/src/main/java/com/aprianto/dicostory/ui/dashboard/profile/WebViewActivity.kt
apriantoa917
481,275,066
false
{"Kotlin": 141212}
package com.aprianto.dicostory.ui.dashboard.profile import android.annotation.SuppressLint import android.os.Build import android.os.Bundle import android.view.KeyEvent import android.webkit.WebView import android.webkit.WebViewClient import androidx.annotation.RequiresApi import androidx.appcompat.app.AppCompatActivity import com.aprianto.dicostory.databinding.ActivityWebViewBinding import com.aprianto.dicostory.utils.Constanta import java.util.* import kotlin.concurrent.schedule @Suppress("DEPRECATION", "DEPRECATED_IDENTITY_EQUALS") class WebViewActivity : AppCompatActivity() { private lateinit var binding: ActivityWebViewBinding companion object { const val EXTRA_WEBVIEW = "EXTRA_WEBVIEW" } @SuppressLint("SetJavaScriptEnabled") @RequiresApi(Build.VERSION_CODES.O) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityWebViewBinding.inflate(layoutInflater) setContentView(binding.root) binding.webView.let { it.loadUrl(intent.getStringExtra(EXTRA_WEBVIEW) ?: Constanta.URLPortfolio) it.settings.javaScriptEnabled = true it.webViewClient = object : WebViewClient() { @Deprecated("Deprecated in Java") override fun shouldOverrideUrlLoading(view: WebView, url: String?): Boolean { view.loadUrl(url.toString()) return false } } it.webViewClient = object : WebViewClient() { override fun onPageFinished(view: WebView, url: String) { binding.toolbar.title = view.title } } } /* toolbar */ setSupportActionBar(binding.toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) binding.toolbar.setNavigationOnClickListener { onBackPressed() } binding.swipeRefresh.setOnRefreshListener { binding.webView.reload() Timer().schedule(2000) { binding.swipeRefresh.isRefreshing = false } } } /* handling back action -> if not root of URL, webview can back to previous URL */ override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean { if (event!!.action === KeyEvent.ACTION_DOWN) { when (keyCode) { KeyEvent.KEYCODE_BACK -> { if (binding.webView.canGoBack()) { binding.webView.goBack() } else { finish() } return true } } } return super.onKeyDown(keyCode, event) } }
0
Kotlin
1
6
79e0323a02e974cb781ebf68aa176b46bc432f5e
2,756
android-dicoding-BPAAI
MIT License
core/jsonrpc/base/src/main/kotlin/odoo/miem/android/core/jsonrpc/base/engine/exception/JsonRpcException.kt
19111OdooApp
546,191,502
false
null
package odoo.miem.android.core.jsonrpc.base.engine.exception import odoo.miem.android.core.jsonrpc.base.parser.ResultParser /** * [JsonRpcException] is exception, which thrown * when [ResultParser] have problems with parsing * result of response * * @author <NAME> */ class JsonRpcException( override val message: String, val code: Int, val data: Any? ) : RuntimeException(message)
0
Kotlin
0
3
66eab22e7786f52903c5679cf5d95ad27cf13b34
402
OdooApp-Android
Apache License 2.0
app/src/main/java/com/maragues/planner/recipes/hoveringPlanner/HoveringPlannerFragmentViewModel.kt
Maragues
116,593,098
false
null
package com.maragues.planner.recipes.hoveringPlanner import android.arch.lifecycle.ViewModel import android.arch.lifecycle.ViewModelProvider import android.support.annotation.VisibleForTesting import com.maragues.planner.common.BaseViewModel import com.maragues.planner.persistence.entities.MealSlotRecipe import com.maragues.planner.persistence.entities.Recipe import com.maragues.planner.recipes.model.MealSlot import com.maragues.planner.persistence.repositories.MealSlotRepository import com.maragues.planner.recipes.hoveringPlanner.HoveringWeekPlannerAdapter.ReplaceRecipeAction import com.maragues.planner.recipes.model.MealType.DINNER import com.maragues.planner.recipes.model.MealType.LUNCH import io.reactivex.Observable import io.reactivex.schedulers.Schedulers import io.reactivex.subjects.BehaviorSubject import org.threeten.bp.LocalDate import timber.log.Timber import javax.inject.Inject /** * Created by miguelaragues on 11/2/18. */ internal class HoveringPlannerFragmentViewModel(private val mealSlotRepository: MealSlotRepository) : BaseViewModel() { companion object { const val DAYS_DISPLAYED = 4L } private val startDate = LocalDate.now() private val endDate = startDate.plusDays(DAYS_DISPLAYED) private val hoveringPlannerViewStateSubject: BehaviorSubject<HoveringPlannerViewState> = BehaviorSubject.create() internal fun viewStateObservable(): Observable<HoveringPlannerViewState> { return hoveringPlannerViewStateSubject .startWith(initialViewState()) .doOnSubscribe({ loadData() }) } private fun loadData() { disposables().add( mealSlotRepository.mealsAndRecipesBetween(startDate, endDate) .map { { addMissingMealSlots(it) } } .doFinally({ Timber.d("FragmentView model finalized subscription to mealsAndRecipesBetween") }) .doOnSubscribe({ Timber.d("FragmentView model subscribed to mealsAndRecipesBetween") }) .subscribe( { hoveringPlannerViewStateSubject.onNext( HoveringPlannerViewState( true, // hoveringPlannerViewStateSubject.value.visible, it.invoke() )) }, Throwable::printStackTrace ) ) } private fun initialViewState(): HoveringPlannerViewState { return HoveringPlannerViewState.emptyForDays(DAYS_DISPLAYED) } @VisibleForTesting fun addMissingMealSlots(mealSlotAndRecipes: Map<MealSlot, List<Recipe>>): Map<MealSlot, List<Recipe>> { val mutableMap = mutableMapOf<MealSlot, List<Recipe>>() (0L until DAYS_DISPLAYED) .map { startDate.plusDays(it) } .forEach { date -> arrayOf(LUNCH, DINNER).forEach { val mealSlot = MealSlot(date, it) if (!mealSlotAndRecipes.containsKey(mealSlot)) { mutableMap.put(mealSlot, listOf()) } else { mutableMap.put(mealSlot, mealSlotAndRecipes[mealSlot]!!) } } } return mutableMap } fun addRecipeObservable(recipeAddedObservable: Observable<MealSlotRecipe>) { disposables().add( recipeAddedObservable .observeOn(Schedulers.io()) .subscribe( { mealSlotRepository.insert(it) }, Throwable::printStackTrace ) ) } fun onRecipeReplacedObservable(recipeReplacedObservable: Observable<ReplaceRecipeAction>) { disposables().add( recipeReplacedObservable .observeOn(Schedulers.io()) .subscribe( { mealSlotRepository.replaceRecipe(it.mealSlotReplaced, it.newRecipeId) } , Throwable::printStackTrace ) ) } class Factory @Inject constructor(private val mealSlotRepository: MealSlotRepository) : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(modelClass: Class<T>): T { return HoveringPlannerFragmentViewModel(mealSlotRepository) as T } } }
1
null
1
1
67735ab35f90f716b6bf3b958fdb0791b9280b56
4,750
RecipeImporter
MIT License
feature-movie-detail/src/main/java/sanchez/sanchez/sergio/feature_movie_detail/ui/FeatureMovieDetailActivityDelegate.kt
sergio11
332,195,948
false
null
package sanchez.sanchez.sergio.feature_movie_detail.ui interface FeatureMovieDetailActivityDelegate { /** * Get Movie Id */ fun getMovieId(): Long }
0
Kotlin
0
6
eef4f5b03c33f1efd937d546ebdea84c3255d445
170
MovieAddicts
MIT License
src/commonJvmMain/kotlin/com/ditchoom/socket/nio2/util/AsynchronousChannelGroupExtensions.kt
DitchOoM
420,788,296
false
{"Kotlin": 91546, "Ruby": 2318, "JavaScript": 262}
package com.ditchoom.socket.nio2.util import java.nio.channels.AsynchronousChannelGroup import java.nio.channels.AsynchronousServerSocketChannel import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException import kotlin.coroutines.suspendCoroutine suspend fun openAsyncServerSocketChannel(group: AsynchronousChannelGroup? = null): AsynchronousServerSocketChannel = suspendCoroutine { continuation -> try { continuation.resume(AsynchronousServerSocketChannel.open(group)) } catch (e: Exception) { continuation.resumeWithException(e) } }
0
Kotlin
0
3
d18979e528728efdd7445b4a4519491863fc09c8
610
socket
Apache License 2.0
kotlin-mui-icons/src/main/generated/mui/icons/material/LocalMoviesOutlined.kt
JetBrains
93,250,841
false
null
// Automatically generated - do not modify! @file:JsModule("@mui/icons-material/LocalMoviesOutlined") package mui.icons.material @JsName("default") external val LocalMoviesOutlined: SvgIconComponent
10
null
5
983
7ef1028ba3e0982dc93edcdfa6ee1edb334ddf35
202
kotlin-wrappers
Apache License 2.0
demo/src/main/kotlin/com/kotling/LibGDXDemo.kt
b005t3r
56,796,079
false
null
package com.kotling import com.badlogic.gdx.ApplicationAdapter import com.badlogic.gdx.Gdx import com.badlogic.gdx.graphics.GL20 import com.badlogic.gdx.graphics.Texture import com.badlogic.gdx.graphics.g2d.SpriteBatch class LibGDXDemo : ApplicationAdapter() { internal lateinit var batch:SpriteBatch internal lateinit var img:Texture override fun create() { batch = SpriteBatch() img = Texture("demo/assets/badlogic.jpg") } override fun render() { Gdx.gl.glClearColor(1f, 0f, 0f, 1f) Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT) batch.begin() batch.draw(img, 0f, 0f) batch.end() } }
0
Kotlin
0
1
9ff9027bd25c66a37fb7538216d685b30929532c
670
Kotling
MIT License
app/src/main/java/com/mobilescanner/main/feature_project/data/repository/ImageRepository.kt
EricMoin
706,004,415
false
{"Kotlin": 92594}
package com.mobilescanner.main.feature_project.data.repository import com.mobilescanner.main.feature_project.data.entity.ImageItem import com.mobilescanner.main.main.ui.MobileScannerApplication.Companion.context import com.mobilescanner.main.feature_home.remote.service.ImageNetwork import com.mobilescanner.main.feature_project.data.database.ImageItemDatabase import com.mobilescanner.main.main.data.repository.Repository import kotlinx.coroutines.Dispatchers import kotlin.concurrent.thread object ImageRepository :Repository(){ private val dao = ImageItemDatabase.getDataBase(context).dao fun insertHistory(item: ImageItem) = thread{ dao.insertHistory(item) } fun updateHistory(newItem: ImageItem) = local(Dispatchers.IO){ dao.updateHistory(newItem) } fun deleteHistory(item: ImageItem) = thread { dao.deleteHistory(item) } fun deleteHistoryByTitle(title:String) = thread { dao.deleteHistoryByTitle(title) } fun deleteAllHistory() = local(Dispatchers.IO) { dao.deleteAllHistory() } fun loadAllHistory() = local(Dispatchers.IO){ dao.loadAllHistory() } fun getHistoryById(id:Long) = local(Dispatchers.IO){ dao.getHistoryById(id) } fun getHistoryByTitle(title:String) = local(Dispatchers.IO){ dao.getHistoryByTitle(title) } fun enhanceImage(api:String,image:String) = fire(Dispatchers.IO){ val result = ImageNetwork.enhanceImage(api,image) if ( result.image.isNullOrEmpty() ){ Result.failure<RuntimeException>( RuntimeException("返回错误") ) }else{ Result.success(result) } } fun scanOcr(api:String,image:String) = fire(Dispatchers.IO){ val result = ImageNetwork.scanOcr(api,image) if ( result.wordsResult.isNullOrEmpty() ){ Result.failure<RuntimeException>( RuntimeException("返回错误") ) }else{ Result.success(result) } } }
0
Kotlin
0
0
c24c9f1341f2457361ce0f160c143229623b8624
2,038
Open-MobileScanner
Apache License 2.0
feature-advance-account/src/main/java/com/example/feature_advance_account/AdvanceAccountModule.kt
vinioliveirasilvapag
486,402,638
false
null
package com.example.feature_advance_account import org.koin.dsl.module object AdvanceAccountModule { val instance = module { factory { (view: AdvanceAccountActivity) -> AdvanceAccountPresenter( view = view, router = get() ) } } }
0
Kotlin
0
2
e5632176b9ca478c30af2a95fa77e867f38fac5c
311
AndroidSamples
MIT License
app/src/main/java/org/gwnu/tutorial/room/AppDatabase.kt
KimSungBeen
277,076,585
false
null
package org.gwnu.tutorial.room import androidx.room.Database import androidx.room.RoomDatabase @Database(entities = [Todo::class], version = 1) abstract class AppDatabase: RoomDatabase() { abstract fun todoDao(): TodoDao }
1
null
1
1
2a0769919d591483a2a09a0dd1a48d4665eb3f08
228
Scribbling-Repository
Apache License 2.0
src/test/kotlin/utils/Utils.kt
justyxxx
319,022,772
false
null
package utils import exception.TestException import java.io.InputStream object Utils { @Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS") fun getResourcesFile(fileName: String): InputStream { return try { Utils.javaClass.classLoader.getResourceAsStream(fileName) } catch (ex: Throwable) { throw TestException( "Файл $fileName отсутствует!\n${ex.message.toString()}" ) } } }
0
Kotlin
1
1
1f7c6403cc31d232613e7396aa0d1f1e7cf27134
473
RestAssured
MIT License
src/test/kotlin/utils/Utils.kt
justyxxx
319,022,772
false
null
package utils import exception.TestException import java.io.InputStream object Utils { @Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS") fun getResourcesFile(fileName: String): InputStream { return try { Utils.javaClass.classLoader.getResourceAsStream(fileName) } catch (ex: Throwable) { throw TestException( "Файл $fileName отсутствует!\n${ex.message.toString()}" ) } } }
0
Kotlin
1
1
1f7c6403cc31d232613e7396aa0d1f1e7cf27134
473
RestAssured
MIT License
android/app/src/main/kotlin/com/example/flutter_templete_mini/MainActivity.kt
un-pany
436,815,630
false
null
package com.example.flutter_template_mini import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
3
20
df503e95e68760ccf9713f168d12f522f1c83b7f
138
flutter-template-mini
MIT License
app/src/main/java/vn/tiki/android/androidhometest/util/Interfaces.kt
ducgao
138,876,996
false
{"Kotlin": 12290}
package vn.tiki.android.androidhometest.util import vn.tiki.android.androidhometest.data.api.response.Deal interface RemoveCallback { fun removeItem(itemIndex: Deal) } interface CountDownEndCallback { fun onCountDownEnd() } interface DownloadDealsCallback { fun onDeals(deals: ArrayList<Deal>) }
0
Kotlin
0
0
00a82a93f0ab5cb687b6256e08f3228b379826b7
311
Tiki_Home_Test
Apache License 2.0
json-lib/src/test/kotlin/angstromio/json/JSONGenerator.kt
angstromio
683,562,832
false
{"Kotlin": 302899, "Java": 4363}
package angstromio.json import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.node.ArrayNode import com.fasterxml.jackson.databind.node.IntNode import com.fasterxml.jackson.databind.node.JsonNodeFactory import com.fasterxml.jackson.databind.node.ObjectNode import com.fasterxml.jackson.databind.node.TextNode import com.fasterxml.jackson.databind.node.ValueNode import io.kotest.property.Arb import io.kotest.property.arbitrary.choice import io.kotest.property.arbitrary.filterNot import io.kotest.property.arbitrary.flatMap import io.kotest.property.arbitrary.int import io.kotest.property.arbitrary.list import io.kotest.property.arbitrary.map import io.kotest.property.arbitrary.of import io.kotest.property.arbitrary.string internal object JSONGenerator { private val jsonNodeFactory: JsonNodeFactory = JsonNodeFactory(false) /** Generate either a ArrayNode or a ObjectNode */ fun jsonNode(depth: Int): Arb<JsonNode> = Arb.choice(arrayNode(depth), objectNode(depth)) /** Generate a ArrayNode */ fun arrayNode(depth: Int): Arb<ArrayNode> = Arb.int(1, 4).flatMap { n -> values(n, depth).map { values -> ArrayNode(jsonNodeFactory).addAll(values) } } /** Generate a ObjectNode */ fun objectNode(depth: Int): Arb<ObjectNode> = Arb.int(1, 4).flatMap { n -> keys(n).flatMap { keys -> values(n, depth).map { values -> val kids: Map<String, JsonNode> = keys.zip(values).associate { it.first to it.second } ObjectNode(jsonNodeFactory, kids) } } } /** Generate a list of keys to be used in the map of a ObjectNode */ fun keys(n: Int): Arb<List<String>> = Arb.list( gen = Arb.string().filterNot { it.isEmpty() }. map { it.lowercase() } .map { randomString -> if (randomString.length > 4) randomString.substring(0, 3) else randomString }, range = 1..n) /** * Generate a list of values to be used in the map of a ObjectNode or in the list of an ArrayNode. */ fun values(n: Int, depth: Int): Arb<List<JsonNode>> = Arb.list(value(depth), 1..n) /** * Generate a value to be used in the map of a ObjectNode or in the list of an ArrayNode. */ fun value(depth: Int): Arb<JsonNode> = if (depth == 0) terminalNode() else Arb.choice(jsonNode(depth - 1), terminalNode()) /** Generate a terminal node */ private fun terminalNode(): Arb<ValueNode> = Arb.of( IntNode(4), IntNode(2), TextNode("b"), TextNode("i"), TextNode("r"), TextNode("d") ) }
0
Kotlin
0
0
9a63498ca3a7f9ffeff242093c546c0eda9eadc8
2,750
angstromio-json
Apache License 2.0
build-tools/agp-gradle-core/src/main/java/com/android/buildanalyzer/common/TaskCategory.kt
RivanParmar
526,653,590
false
null
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.buildanalyzer.common /** * Enum class for Category-Based Task Analyzer for Build Analyzer. * Each field corresponds to a specific atomic function/execution of a task. * * @param isPrimary indicates whether the category would be the primary category of some task * @param description the description of the category which is shown to the user, all primary * categories should have descriptions. **/ enum class TaskCategory(val isPrimary: Boolean = false, val description: String = "") { // --------------------------------------------------------------------------------------------- // PRIMARY CATEGORIES // --------------------------------------------------------------------------------------------- TEST(isPrimary = true, description = "Tasks related to test execution."), MANIFEST(isPrimary = true, description = "Tasks related to Android Manifest merging and compiling."), ANDROID_RESOURCES(isPrimary = true, description = "Tasks related to Android resources compilation, processing, linking and merging."), NATIVE(isPrimary = true, description = "Tasks related to Native build compilation, linking and packaging."), JAVA(isPrimary = true, description = "Tasks related to Java source compilation, processing and merging."), JAVA_RESOURCES(isPrimary = true, description = "Tasks related to Java resources merging and packaging."), JAVA_DOC(isPrimary = true, description = "Tasks related to Java Doc generation and processing."), KOTLIN(isPrimary = true, description = "Tasks related to Kotlin source compilation, processing and merging."), AIDL(isPrimary = true, description = "Tasks related to AIDL source compilation and processing."), RENDERSCRIPT(isPrimary = true, description = "Tasks related to Renderscript sources compilation and processing."), SHADER(isPrimary = true, description = "Tasks related to Shader sources compilation and processing."), DEXING(isPrimary = true, description = "Tasks related to generating Dex files."), ART_PROFILE(isPrimary = true, description = "Tasks related to ART optimization profiles compilation and processing"), LINT(isPrimary = true, description = "Tasks created by the Lint tool."), DATA_BINDING(isPrimary = true, description = "Tasks related to data binding."), METADATA(isPrimary = true, description = "Tasks related to Metadata generation and processing"), VERIFICATION(isPrimary = true, description = "Tasks that verify the project and dependencies setup."), SYNC(isPrimary = true, description = "Tasks related to syncing IDE sources with Gradle."), DEPLOYMENT(isPrimary = true, description = "Tasks related to device deployment."), HELP(isPrimary = true, description = "Tasks that provide helpful information on the project"), APK_PACKAGING(isPrimary = true, description = "Tasks related to packaging APKs."), AAR_PACKAGING(isPrimary = true, description = "Tasks related to packaging AARs."), BUNDLE_PACKAGING(isPrimary = true, description = "Tasks related to packaging bundles."), OPTIMIZATION(isPrimary = true, description = "Tasks related to shrinking sources and resources."), COMPILED_CLASSES(isPrimary = true, description = "Tasks that process the output of compilation tasks."), GRADLE(isPrimary = true, description = "Core tasks created by Gradle."), MISC(isPrimary = true, description = "Miscellaneous Android Gradle Plugin tasks."), BUILD_SCRIPT(isPrimary = true, description = "Tasks defined in the build script."), BUILD_SOURCE(isPrimary = true, description = "Tasks created by plugins defined in the buildSrc."), UNCATEGORIZED(isPrimary = true, description = "Uncategorized tasks."), // --------------------------------------------------------------------------------------------- // SECONDARY CATEGORIES // --------------------------------------------------------------------------------------------- /** * Tasks that involves compilation of files/sources. */ COMPILATION, /** * Tasks related to generating sources. */ SOURCE_GENERATION, /** * Tasks related to processing sources. */ SOURCE_PROCESSING, /** * Tasks related to packaging artifacts. */ ZIPPING, /** * Tasks related to linking artifacts. */ LINKING, /** * Tasks related to merging artifacts. */ MERGING, /** * Tasks part of fusing library. */ FUSING, }
0
null
2
17
7d6a941f82617f89cedde0ae8e10d3702f225f76
5,107
androlabs
Apache License 2.0
locallydynamic-android-lib/sample/ondemandfeature/src/main/java/com/example/locallydynamic/ondemandfeature/OnDemandFeatureImpl.kt
poovarasanvasudevan
239,129,218
true
{"Kotlin": 319796, "Java": 302260, "Shell": 7767}
package com.example.locallydynamic.ondemandfeature import android.content.Context import android.content.Intent import androidx.fragment.app.Fragment import com.example.locallydynamic.Feature import com.example.locallydynamic.InstallTimeFeature import com.example.locallydynamic.OnDemandFeature import com.example.locallydynamic.info import com.google.auto.service.AutoService @AutoService(OnDemandFeature::class) class OnDemandFeatureImpl : OnDemandFeature { override fun getMainScreen(): Fragment = OnDemandFragment() override fun getLaunchIntent(context: Context): Intent = Intent(context, OnDemandActivity::class.java) override fun inject(dependencies: OnDemandFeature.Dependencies) { } }
0
null
0
0
9e52f801e8afdb88b245600dbfd4d6691fd22d95
728
LocallyDynamic
Apache License 2.0
app/src/main/java/com/fracta7/e_bookshelf/data/remote/dto/book/isbn/authors/AuthorsModel.kt
fracta7
532,576,663
false
{"Kotlin": 157376}
package com.fracta7.e_bookshelf.data.remote.dto.book.isbn.authors import androidx.annotation.Keep import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName @Keep data class AuthorsModel( @SerializedName("url") @Expose val url: String, @SerializedName("name") @Expose val name: String )
0
Kotlin
0
2
43e1b6fafa6fc7a55bccf83dfc3a9f4b781c77f7
347
e-bookshelf
MIT License
app/src/main/java/com/stripe/android/samplestore/Product.kt
stripe-samples
206,598,855
false
null
package com.stripe.android.samplestore internal enum class Product( internal val emoji: String, internal val price: Int ) { Shirt("👕", 2000), Pants("👖", 4000), Dress("👗", 3000), MansShoe("👞", 700), AthleticShoe("👟", 2000), HighHeeledShoe("👠", 1000), WomansSandal("👡", 2000), WomansBoots("👢", 2500), WomansHat("👒", 800), Bikini("👙", 3000), Lipstick("💄", 2000), TopHat("🎩", 5000), Purse("👛", 5500), Handbag("👜", 6000), Sunglasses("🕶", 2000), WomansClothes("👚", 2500) }
7
Kotlin
31
44
73025b4c5fe934845ddf80464cab483a6e98ee72
540
sample-store-android
MIT License
app/src/main/java/com/example/root/kotlin_eyepetizer/basic/api/WeixinApi.kt
jiwenjie
156,038,520
false
null
package com.example.root.kotlin_eyepetizer.basic.api import com.example.root.kotlin_eyepetizer.mvp.more_mvp.more_function_bean.WeixinChoiceListBean import io.reactivex.Observable import retrofit2.http.GET import retrofit2.http.Query /** * author:Jiwenjie * email:<EMAIL> * time:2018/12/11 * desc: * version:1.0 */ interface WeixinApi { @GET("/weixin/query") fun getWeixinChoiceList(@Query("pno") page: Int, @Query("ps") ps: Int, @Query("dtype") dttype: String, @Query("key") key: String): Observable<WeixinChoiceListBean> }
1
Kotlin
1
1
104af621e315bc5588f97206ca04438a082875b9
587
Kotlin_Eyepetizer
Apache License 2.0
app/src/main/java/com/example/androiddevchallenge/MainActivity.kt
nezih94
347,229,883
false
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.androiddevchallenge import android.os.Bundle import androidx.activity.compose.setContent import androidx.appcompat.app.AppCompatActivity import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.paddingFromBaseline import androidx.compose.foundation.layout.requiredHeight import androidx.compose.foundation.layout.requiredSize import androidx.compose.foundation.layout.requiredWidth import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyRow import androidx.compose.material.BottomNavigation import androidx.compose.material.BottomNavigationItem import androidx.compose.material.Button import androidx.compose.material.ButtonDefaults import androidx.compose.material.Checkbox import androidx.compose.material.CheckboxDefaults import androidx.compose.material.Divider import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.material.OutlinedTextField 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.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.vectorResource import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.core.view.WindowCompat import androidx.navigation.NavController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.navigate import androidx.navigation.compose.rememberNavController import com.example.androiddevchallenge.ui.theme.MyTheme class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) WindowCompat.setDecorFitsSystemWindows(window, false) setContent { MyTheme { MyApp() } } } } // Start building your app here! @Composable fun MyApp() { val navController = rememberNavController() NavHost(navController, startDestination = "welcome") { composable("welcome") { Welcome(navController) } composable("login") { Login(navController) } composable("home") { Home() } } } @Composable fun Welcome(navController: NavController) { Surface(color = MaterialTheme.colors.primary) { Box( modifier = Modifier .fillMaxWidth() .fillMaxHeight() ) { Image( modifier = Modifier .fillMaxWidth() .fillMaxHeight(), imageVector = ImageVector.vectorResource(id = R.drawable.ic_welcome_bg), contentDescription = null, contentScale = ContentScale.Crop ) } Column( modifier = Modifier .fillMaxWidth() .fillMaxHeight() ) { Image( modifier = Modifier .padding(top = 72.dp) .offset(x = 88.dp), imageVector = ImageVector.vectorResource(id = R.drawable.ic_welcome_illos), contentDescription = null, contentScale = ContentScale.Crop ) Image( modifier = Modifier .padding(top = 48.dp) .align(Alignment.CenterHorizontally), imageVector = ImageVector.vectorResource(id = R.drawable.ic_logo), contentDescription = null, contentScale = ContentScale.Crop ) Text( modifier = Modifier .paddingFromBaseline(top = 32.dp, bottom = 40.dp) .align(Alignment.CenterHorizontally), text = "Beautiful home garden solutions", style = MaterialTheme.typography.subtitle1, color = MaterialTheme.colors.onPrimary ) Button( onClick = { }, modifier = Modifier .padding(top = 0.dp, start = 16.dp, end = 16.dp) .fillMaxWidth() .requiredHeight(height = 48.dp), colors = ButtonDefaults.buttonColors(backgroundColor = MaterialTheme.colors.secondary), shape = MaterialTheme.shapes.medium ) { Text( text = "Create account", style = MaterialTheme.typography.button, color = MaterialTheme.colors.onSecondary ) } Button( onClick = { navController.navigate("login") }, modifier = Modifier .padding(top = 8.dp, start = 16.dp, end = 16.dp) .fillMaxWidth() .requiredHeight(height = 48.dp), elevation = ButtonDefaults.elevation( defaultElevation = 0.dp, pressedElevation = 0.dp ), colors = ButtonDefaults.buttonColors(backgroundColor = Color.Transparent), shape = MaterialTheme.shapes.medium ) { // requested text color is pink-900 in light theme and white in dark theme, but there is no provided material theme color attribute which corresponds to said colors so we use primaryVariant for this job as it has no other use case through the app Text( text = "Log in", style = MaterialTheme.typography.button, color = MaterialTheme.colors.primaryVariant ) } } } } @Composable fun Login(navController: NavController) { Surface(color = MaterialTheme.colors.background) { Column( modifier = Modifier .fillMaxWidth() .fillMaxHeight() ) { Text( modifier = Modifier .paddingFromBaseline(top = 184.dp) .padding(horizontal = 16.dp) .fillMaxWidth(), text = "Log in with email", textAlign = TextAlign.Center, color = MaterialTheme.colors.onBackground, style = MaterialTheme.typography.h1 ) OutlinedTextField( modifier = Modifier .padding(start = 16.dp, end = 16.dp, top = 16.dp) .requiredHeight(height = 56.dp) .fillMaxWidth(), value = "Email address", onValueChange = {}, textStyle = MaterialTheme.typography.body1 ) OutlinedTextField( modifier = Modifier .padding(start = 16.dp, end = 16.dp, top = 8.dp) .requiredHeight(height = 56.dp) .fillMaxWidth(), value = "Password (8+ characters)", onValueChange = {}, textStyle = MaterialTheme.typography.body1 ) val annotatedString = AnnotatedString.Builder("By clicking below, you agree to our Terms of Use and consent to our Privacy Policy") .apply { addStyle( style = SpanStyle(textDecoration = TextDecoration.Underline), 35, 48 ) addStyle( style = SpanStyle(textDecoration = TextDecoration.Underline), 68, 82 ) } Text( text = annotatedString.toAnnotatedString(), modifier = Modifier .paddingFromBaseline(top = 24.dp, bottom = 16.dp) .padding(horizontal = 16.dp) .fillMaxWidth(), textAlign = TextAlign.Center, color = MaterialTheme.colors.onBackground, style = MaterialTheme.typography.body2 ) Button( onClick = { navController.navigate("home") }, modifier = Modifier .padding(top = 0.dp, start = 16.dp, end = 16.dp) .fillMaxWidth() .requiredHeight(height = 48.dp), colors = ButtonDefaults.buttonColors(backgroundColor = MaterialTheme.colors.secondary), shape = MaterialTheme.shapes.medium ) { Text( text = "Log in", style = MaterialTheme.typography.button, color = MaterialTheme.colors.onSecondary ) } } } } @Composable fun Home() { Surface(color = MaterialTheme.colors.background) { Column( modifier = Modifier .fillMaxWidth() .fillMaxHeight() ) { Spacer(modifier = Modifier.requiredHeight(height = 40.dp)) OutlinedTextField( modifier = Modifier .padding(start = 16.dp, end = 16.dp, top = 0.dp) .requiredHeight(height = 56.dp) .fillMaxWidth(), value = "Search", onValueChange = {}, textStyle = MaterialTheme.typography.body1, leadingIcon = { Icon( modifier = Modifier.requiredSize(18.dp), imageVector = ImageVector.vectorResource(id = R.drawable.ic_search_24), contentDescription = null ) } ) Text( text = "Browse themes", modifier = Modifier .paddingFromBaseline(top = 32.dp, bottom = 0.dp) .padding(horizontal = 16.dp) .fillMaxWidth(), textAlign = TextAlign.Start, color = MaterialTheme.colors.onBackground, style = MaterialTheme.typography.h1 ) Spacer(modifier = Modifier.requiredHeight(16.dp)) LazyRow( modifier = Modifier .requiredHeight(136.dp) .fillMaxWidth(), contentPadding = PaddingValues(start = 16.dp, bottom = 1.dp), horizontalArrangement = Arrangement.spacedBy(8.dp), content = { for (data in horizontalItems) { item { Surface( modifier = Modifier.requiredSize(136.dp), shape = MaterialTheme.shapes.small, color = MaterialTheme.colors.background, elevation = 1.dp ) { Column() { Image( modifier = Modifier .requiredHeight(height = 96.dp) .requiredWidth(136.dp), painter = painterResource(id = data.imgres), contentDescription = null, contentScale = ContentScale.Crop ) Box( modifier = Modifier .weight(1f, true) .padding(start = 16.dp) ) { Text( modifier = Modifier .fillMaxWidth() .align(Alignment.CenterStart), text = data.title, color = MaterialTheme.colors.onBackground, style = MaterialTheme.typography.h2 ) } } } } } } ) Row( modifier = Modifier .fillMaxWidth() .requiredHeight(56.dp), horizontalArrangement = Arrangement.SpaceBetween ) { Text( text = "Design your home garden", modifier = Modifier .paddingFromBaseline(top = 40.dp, bottom = 0.dp) .padding(start = 16.dp), textAlign = TextAlign.Start, color = MaterialTheme.colors.onBackground, style = MaterialTheme.typography.h1 ) Icon( modifier = Modifier .padding(end = 16.dp) .requiredSize(24.dp) .align(Alignment.CenterVertically), imageVector = ImageVector.vectorResource(id = R.drawable.ic_filter_list_24), contentDescription = null ) } LazyColumn( contentPadding = PaddingValues(bottom = 56.dp, start = 16.dp, end = 16.dp), verticalArrangement = Arrangement.spacedBy(8.dp), content = { verticalItems.forEachIndexed { index, item -> item { Row( Modifier .fillMaxWidth() .requiredHeight(56.dp), horizontalArrangement = Arrangement.SpaceBetween ) { Row() { Image( modifier = Modifier .requiredHeight(height = 56.dp) .requiredWidth(56.dp) .clip(MaterialTheme.shapes.small), painter = painterResource(id = item.imgres), contentDescription = null, contentScale = ContentScale.Crop ) Column(verticalArrangement = Arrangement.SpaceBetween) { Text( text = item.title, modifier = Modifier .paddingFromBaseline(top = 24.dp, bottom = 0.dp) .padding(start = 16.dp), textAlign = TextAlign.Start, color = MaterialTheme.colors.onBackground, style = MaterialTheme.typography.h2 ) Text( text = "This is a description", modifier = Modifier .paddingFromBaseline(top = 0.dp, bottom = 24.dp) .padding(start = 16.dp), textAlign = TextAlign.Start, color = MaterialTheme.colors.onBackground, style = MaterialTheme.typography.body1 ) } } Checkbox( modifier = Modifier.align(Alignment.CenterVertically), checked = index == 0, colors = CheckboxDefaults.colors(checkmarkColor = MaterialTheme.colors.onSecondary), onCheckedChange = { }, ) } Divider(color = Color.Gray, thickness = 1.dp, startIndent = 72.dp) } } } ) } Box( modifier = Modifier .fillMaxHeight() .fillMaxWidth() ) { BottomNavigation( modifier = Modifier.align(Alignment.BottomCenter), elevation = 16.dp, backgroundColor = MaterialTheme.colors.primary ) { BottomNavigationItem( selected = true, onClick = { }, icon = { Icon( modifier = Modifier.requiredSize(24.dp), imageVector = ImageVector.vectorResource(id = R.drawable.ic_home_24), contentDescription = null ) }, label = { Text( text = "Home", style = MaterialTheme.typography.caption, color = MaterialTheme.colors.onPrimary ) } ) BottomNavigationItem( selected = false, onClick = { }, icon = { Icon( modifier = Modifier.requiredSize(24.dp), imageVector = ImageVector.vectorResource(id = R.drawable.ic_favorite_border_24), contentDescription = null ) }, label = { Text( text = "Favorites", style = MaterialTheme.typography.caption, color = Color.Gray ) } ) BottomNavigationItem( selected = false, onClick = { }, icon = { Icon( modifier = Modifier.requiredSize(24.dp), imageVector = ImageVector.vectorResource(id = R.drawable.ic_account_circle_24), contentDescription = null ) }, label = { Text( text = "Profile", style = MaterialTheme.typography.caption, color = Color.Gray ) } ) BottomNavigationItem( selected = false, onClick = { }, icon = { Icon( modifier = Modifier.requiredSize(24.dp), imageVector = ImageVector.vectorResource(id = R.drawable.ic_shopping_cart_24), contentDescription = null ) }, label = { Text( text = "Cart", style = MaterialTheme.typography.caption, color = Color.Gray ) } ) } } } } @Preview("Light Theme", widthDp = 360, heightDp = 640) @Composable fun LightPreview() { MyTheme { MyApp() } } @Preview("Dark Theme", widthDp = 360, heightDp = 640) @Composable fun DarkPreview() { MyTheme(darkTheme = true) { MyApp() } } data class Item(val imgres: Int, val title: String) val verticalItems = listOf( Item(R.drawable.img6, title = "Monstera"), Item(R.drawable.img7, title = "Aglaonema"), Item(R.drawable.img8, title = "Peace lily"), Item(R.drawable.img9, title = "Fiddle leaf tree"), Item(R.drawable.img10, title = "Snake plant"), Item(R.drawable.img11, title = "Pothos") ) val horizontalItems = listOf( Item(R.drawable.img1, title = "Desert chic"), Item(R.drawable.img2, title = "Tiny terraiums"), Item(R.drawable.img3, title = "Jungle vibes"), Item(R.drawable.img4, title = "Easy care"), Item(R.drawable.img5, title = "Statements") )
0
Kotlin
0
0
871f6e16bc650536b65fcaf807c58668bb42cc7b
22,699
arriba
Apache License 2.0
contracts/src/main/kotlin/com/template/contracts/TemplateContract.kt
george-penkov
229,980,080
true
{"HTML": 201646, "JavaScript": 102308, "CoffeeScript": 98463, "CSS": 41775, "Kotlin": 12375, "Shell": 1147}
package com.template.contracts import com.template.states.TemplateState import net.corda.core.contracts.CommandData import net.corda.core.contracts.Contract import net.corda.core.transactions.LedgerTransaction // ************ // * Contract * // ************ class TemplateContract : Contract { companion object { // Used to identify our contract when building a transaction. const val ID = "com.template.contracts.TemplateContract" } // A transaction is valid if the verify() function of the contract of all the transaction's input and output states // does not throw an exception. override fun verify(tx: LedgerTransaction) { val out = tx.outputsOfType<TemplateState>().single() require(out.appear.isNotEmpty()){"Error 1"} require(out.appearance!=out.administration){"Error 2"} } // Used to indicate the transaction's intent. interface Commands : CommandData { class Action : Commands } }
0
HTML
0
0
30e51df0b950846384e08ce6de59879fe7ec5c2b
977
ProjectForBigData-1
Apache License 2.0
tiny-postgresql-event-store/src/main/kotlin/ru/quipy/PostgresClientEventStore.kt
andrsuh
498,475,206
false
{"Kotlin": 420728, "PLpgSQL": 1840, "Dockerfile": 242}
package ru.quipy import org.postgresql.util.PSQLException import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.dao.DuplicateKeyException import org.springframework.transaction.annotation.Transactional import ru.quipy.converter.EntityConverter import ru.quipy.converter.ResultSetToEntityMapper import ru.quipy.core.exceptions.DuplicateEventIdException import ru.quipy.database.EventStore import ru.quipy.domain.ActiveEventStreamReader import ru.quipy.domain.EventRecord import ru.quipy.domain.EventStreamReadIndex import ru.quipy.domain.Snapshot import ru.quipy.domain.Unique import ru.quipy.domain.Versioned import ru.quipy.executor.QueryExecutor import ru.quipy.query.QueryBuilder import ru.quipy.query.select.SelectQuery import ru.quipy.tables.ActiveEventStreamReaderDto import ru.quipy.tables.DtoCreator import ru.quipy.tables.EventRecordDto import ru.quipy.tables.EventRecordTable import ru.quipy.tables.EventStreamActiveReadersTable import ru.quipy.tables.EventStreamReadIndexDto import ru.quipy.tables.SnapshotDto import java.sql.ResultSet import kotlin.reflect.KClass open class PostgresClientEventStore( private val eventStoreSchemaName: String, private val resultSetToEntityMapper: ResultSetToEntityMapper, private val entityConverter: EntityConverter, private val executor: QueryExecutor ) : EventStore { companion object { val logger: Logger = LoggerFactory.getLogger(PostgresClientEventStore::class.java) } override fun insertEventRecord(aggregateTableName: String, eventRecord: EventRecord) { try { executor.execute( QueryBuilder.insert( eventStoreSchemaName, EventRecordDto(eventRecord, aggregateTableName, entityConverter)) ) } catch (e : DuplicateKeyException) { throw DuplicateEventIdException("There is record with such an id. Record cannot be saved $eventRecord", e) } } @Transactional override fun insertEventRecords(aggregateTableName: String, eventRecords: List<EventRecord>) { try { executor.execute( QueryBuilder.batchInsert(eventStoreSchemaName, EventRecordTable.name, eventRecords.map { EventRecordDto(it, aggregateTableName, entityConverter) }) ) } catch (e : DuplicateKeyException) { throw DuplicateEventIdException( "There is record with such an id. Record set cannot be saved $eventRecords", e ) } } override fun tableExists(aggregateTableName: String): Boolean { return true // TODO partition? } override fun updateSnapshotWithLatestVersion(tableName: String, snapshot: Snapshot) { executor.execute( QueryBuilder.insertOrUpdateWithLatestVersionQuery( eventStoreSchemaName, SnapshotDto(snapshot, tableName, entityConverter)) ) } override fun findEventRecordsWithAggregateVersionGraterThan( aggregateTableName: String, aggregateId: Any, aggregateVersion: Long ): List<EventRecord> { val query = QueryBuilder.select(eventStoreSchemaName, EventRecordTable.name) .andWhere("${EventRecordTable.aggregateId.name} = '$aggregateId'") .andWhere("${EventRecordTable.aggregateTableName.name} = '$aggregateTableName'") .andWhere("${EventRecordTable.aggregateVersion.name} > $aggregateVersion") return executor.executeAndProcessResultSet(query) { resultSetToEntityMapper.convertMany(it, EventRecord::class) } ?: listOf() } override fun findBatchOfEventRecordAfter( aggregateTableName: String, eventSequenceNum: Long, batchSize: Int ): List<EventRecord> { val query = QueryBuilder.select(eventStoreSchemaName, EventRecordTable.name) .andWhere("${EventRecordTable.aggregateTableName.name} = '$aggregateTableName'") .andWhere("${EventRecordTable.createdAt.name} > $eventSequenceNum") .orderBy(EventRecordTable.createdAt.name, SelectQuery.SortingOrder.ASCENDING) .limit(batchSize) return executor.executeAndProcessResultSet(query) { resultSetToEntityMapper.convertMany(it, EventRecord::class) } ?: listOf() } override fun findSnapshotByAggregateId(snapshotsTableName: String, aggregateId: Any): Snapshot? { return findEntityById(aggregateId, Snapshot::class) } override fun findStreamReadIndex(streamName: String): EventStreamReadIndex? { return findEntityById(streamName, EventStreamReadIndex::class) } override fun getActiveStreamReader(streamName: String): ActiveEventStreamReader? { return findEntityById(streamName, ActiveEventStreamReader::class) } override fun tryUpdateActiveStreamReader(updatedActiveReader: ActiveEventStreamReader): Boolean { return executor.executeReturningBoolean( QueryBuilder.insertOrUpdateByIdAndVersionQuery(eventStoreSchemaName, updatedActiveReader.id, updatedActiveReader.version - 1, ActiveEventStreamReaderDto(updatedActiveReader)) ) } override fun tryReplaceActiveStreamReader( expectedVersion: Long, newActiveReader: ActiveEventStreamReader ): Boolean { return tryReplaceWithOptimisticLock(EventStreamActiveReadersTable.name, expectedVersion, newActiveReader) } override fun commitStreamReadIndex(readIndex: EventStreamReadIndex): Boolean { return executor.executeReturningBoolean( QueryBuilder.insertOrUpdateWithLatestVersionQuery(eventStoreSchemaName, EventStreamReadIndexDto(readIndex)) ) } private fun <T: Any> findEntityById(id: Any, clazz: KClass<T>) : T? { val query = QueryBuilder.findEntityByIdQuery(eventStoreSchemaName, id, clazz) return executor.executeAndProcessResultSet(query) { rs: ResultSet? -> resultSetToEntityMapper.convert(rs, clazz) } } private fun <E> tryReplaceWithOptimisticLock( tableName: String, expectedVersion: Long, entity: E ): Boolean where E : Versioned, E : Unique<*> { while (true) { val existingEntity = findEntityById(entity.id!!, entity::class) return if (existingEntity != null) { val query = QueryBuilder.insertOrUpdateByIdAndVersionQuery(eventStoreSchemaName, entity.id!!, expectedVersion, DtoCreator.create(entity, tableName, entityConverter)) executor.executeReturningBoolean(query) } else { try { val query = QueryBuilder.insert(eventStoreSchemaName, DtoCreator.create(entity, tableName, entityConverter)) executor.execute(query) true } catch (e: PSQLException) { logger.info("Entity concurrent update led to clashing. Entity: $entity, table name: $tableName", e) continue } } } } }
13
Kotlin
17
34
880796f04bb6e27aab615c8efccd709d5ca22193
7,123
tiny-event-sourcing
Apache License 2.0
src/backend/paas/project/api-project/src/main/kotlin/com/heapoverflow/project/pojo/user/ProjectUser.kt
panfairy
577,309,391
false
null
package com.heapoverflow.project.pojo.user data class ProjectUser( val id: Long, val username: String )
0
Kotlin
0
0
56d79e57246ff6e34e9902952eb7276e71b372f9
113
ho-base
MIT License
backend/src/main/kotlin/com/nicolaspetras/splfantasy/service/scorer/calculator/player/GamePointsCalculator.kt
npetras
385,915,477
false
{"Kotlin": 130500, "TypeScript": 13523, "HTML": 5058, "Dockerfile": 1748, "JavaScript": 1425, "Java": 353, "Shell": 193, "CSS": 80}
package com.nicolaspetras.splfantasy.service.scorer.calculator.player /** * For game-wide points like top assists on team, top kills in game, top damage on team etc. */ class GamePointsCalculator { }
0
Kotlin
0
0
afe7ac7aeb00d0ccc1546af305ce7a30ff5dc058
202
smite-fantasy-league
MIT License
android/src/main/java/com/reactnativeaudioremove/AudioRemovePackage.kt
abhi3691
532,260,717
false
{"YAML": 5, "JSON with Comments": 1, "JSON": 7, "JavaScript": 5, "Ruby": 3, "Markdown": 6, "Text": 1, "Ignore List": 1, "Git Attributes": 1, "EditorConfig": 1, "Shell": 4, "TSX": 4, "Java Properties": 2, "Gradle": 4, "Batchfile": 2, "INI": 2, "XML": 9, "Kotlin": 2, "Gemfile.lock": 1, "Proguard": 1, "Java": 6, "C++": 7, "Makefile": 1, "Swift": 2, "C": 1, "OpenStep Property List": 2, "Objective-C": 4, "Objective-C++": 1}
package com.reactnativeaudioremove import com.facebook.react.ReactPackage import com.facebook.react.bridge.JavaScriptModule import com.facebook.react.bridge.NativeModule import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.uimanager.ViewManager class AudioRemovePackage : ReactPackage { override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> { return listOf(AudioRemoveModule(reactContext)) } override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> { return emptyList() } }
6
Java
1
1
920f6f298277787d933953bbb57ccb9d9de4924e
616
react-native-audio-remove
Apache License 2.0
runtime/src/main/kotlin/io/github/seggan/myxal/runtime/list/MyxalList.kt
seanpm2001
706,446,894
true
{"Gradle Kotlin DSL": 8, "Shell": 1, "Markdown": 3, "Git Attributes": 1, "Batchfile": 1, "Text": 3, "Ignore List": 1, "C++": 10, "YAML": 1, "Kotlin": 42, "Java": 19, "INI": 1, "ANTLR": 2, "Proguard": 1}
package io.github.seggan.myxal.runtime.list import io.github.seggan.myxal.runtime.ProgramStack import io.github.seggan.myxal.runtime.math.BigComplex import io.github.seggan.myxal.runtime.myxal import io.github.seggan.myxal.runtime.plus import java.math.BigInteger abstract class MyxalList : Collection<Any> { companion object { fun create(generator: Iterator<Any>): MyxalList { return LazyList(generator) } @JvmStatic fun create(vararg array: Any): MyxalList { return FiniteList(listOf(*array)) } @JvmStatic fun create(collection: Collection<Any>): MyxalList { return FiniteList(collection.toList()) } @JvmStatic @Suppress("UNNECESSARY_NOT_NULL_ASSERTION") fun create(stack: ProgramStack): MyxalList { val list = ArrayList<Any>(stack.size) while (!stack.isEmpty()) { list.add(stack.removeLast()!!) } return FiniteList(list) } fun create(): MyxalList { return FiniteList() } /** * Create an infinite list */ fun createInf(generator: () -> Any): MyxalList { return LazyList(object : Iterator<Any> { override fun hasNext(): Boolean { return true } override fun next(): Any { return generator() } }) } fun range(start: BigComplex, end: BigComplex): MyxalList { return LazyList(object : Iterator<BigComplex> { var current = start override fun hasNext(): Boolean { return current < end } override fun next(): BigComplex { val result = current current += 1 return result } }) } fun range(start: Int, end: Int): MyxalList { return LazyList(object : Iterator<BigComplex> { var current = start override fun hasNext(): Boolean { return current < end } override fun next(): BigComplex { val result = current++ return result.myxal() } }) } fun fromIterableLazy(iterable: Iterable<Any>): MyxalList { return LazyList(iterable.iterator()) } } protected fun vyxalListFormat(list: List<Any>): String { val sb = StringBuilder() sb.append("⟨") val it = list.iterator() var isFirst = true while (it.hasNext()) { if (isFirst) { isFirst = false } else { sb.append(" | ") } sb.append(it.next()) } sb.append("⟩") return sb.toString() } /** * Whether there exists an element at the given index */ abstract fun hasInd(ind: Int): Boolean abstract fun isLazy(): Boolean abstract fun toNonLazy(): MyxalList abstract operator fun get(ind: Int): Any abstract operator fun get(ind: IntProgression): MyxalList abstract fun hasAtLeast(amount: Int): Boolean abstract fun listIterator(): ListIterator<Any> override fun iterator(): Iterator<Any> { return listIterator() } abstract fun remove(ind: Int): MyxalList abstract fun map(f: (Any) -> Any): MyxalList abstract fun filter(pred: (Any) -> Boolean): MyxalList abstract fun add(ind: BigInteger, value: Any): MyxalList abstract fun add(value: Any): MyxalList abstract fun addAll(iterable: Iterable<Any>): MyxalList fun zip(iterable: Iterable<Any>): MyxalList { return zipmap(iterable, MyxalList::create) } abstract fun zipmap(iterable: Iterable<Any>, f: (Any, Any) -> Any): MyxalList override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is MyxalList) return false val it1 = this.iterator() val it2 = other.iterator() while (it1.hasNext() && it2.hasNext()) { if (it1.next() != it2.next()) { return false } } return !it1.hasNext() && !it2.hasNext() } abstract override fun hashCode(): Int override fun containsAll(elements: Collection<Any>): Boolean { for (element in elements) { if (!this.contains(element)) { return false } } return true } override fun isEmpty(): Boolean { return !this.iterator().hasNext() } }
0
null
0
1
b53015699278ef5fc2800447106581ca34ecbdea
4,758
Vyxal_Myxal
Apache License 2.0
clients/kotlin/generated/src/main/kotlin/org/openapitools/client/models/CatalogsHotelItemsFilter.kt
oapicf
489,369,143
false
{"Markdown": 13009, "YAML": 64, "Text": 6, "Ignore List": 43, "JSON": 688, "Makefile": 2, "JavaScript": 2261, "F#": 1305, "XML": 1120, "Shell": 44, "Batchfile": 10, "Scala": 4677, "INI": 23, "Dockerfile": 14, "Maven POM": 22, "Java": 13384, "Emacs Lisp": 1, "Haskell": 75, "Swift": 551, "Ruby": 1149, "Cabal Config": 2, "OASv3-yaml": 16, "Go": 2224, "Go Checksums": 1, "Go Module": 4, "CMake": 9, "C++": 6688, "TOML": 3, "Rust": 556, "Nim": 541, "Perl": 540, "Microsoft Visual Studio Solution": 2, "C#": 1645, "HTML": 545, "Xojo": 1083, "Gradle": 20, "R": 1079, "JSON with Comments": 8, "QMake": 1, "Kotlin": 3280, "Python": 1, "Crystal": 1060, "ApacheConf": 2, "PHP": 3940, "Gradle Kotlin DSL": 1, "Protocol Buffer": 538, "C": 1598, "Ada": 16, "Objective-C": 1098, "Java Properties": 2, "Erlang": 1097, "PlantUML": 1, "robots.txt": 1, "HTML+ERB": 2, "Lua": 1077, "SQL": 512, "AsciiDoc": 1, "CSS": 3, "PowerShell": 1083, "Elixir": 5, "Apex": 1054, "Visual Basic 6.0": 3, "TeX": 1, "ObjectScript": 1, "OpenEdge ABL": 1, "Option List": 2, "Eiffel": 583, "Gherkin": 1, "Dart": 538, "Groovy": 539, "Elm": 31}
/** * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. * */ @file:Suppress( "ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport" ) package org.openapitools.client.models import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** * * * @param catalogType * @param hotelIds * @param catalogId Catalog id pertaining to the hotel item. If not provided, default to oldest hotel catalog */ data class CatalogsHotelItemsFilter ( @Json(name = "catalog_type") val catalogType: CatalogsHotelItemsFilter.CatalogType, @Json(name = "hotel_ids") val hotelIds: kotlin.collections.List<kotlin.String>, /* Catalog id pertaining to the hotel item. If not provided, default to oldest hotel catalog */ @Json(name = "catalog_id") val catalogId: kotlin.String? = null ) { /** * * * Values: HOTEL */ @JsonClass(generateAdapter = false) enum class CatalogType(val value: kotlin.String) { @Json(name = "HOTEL") HOTEL("HOTEL"); } }
0
Java
0
2
dcd328f1e62119774fd8ddbb6e4bad6d7878e898
1,152
pinterest-sdk
MIT License
library/verification-core/src/main/java/com/sinch/verification/core/auth/AuthorizationInterceptor.kt
sinch
353,915,754
false
null
package com.sinch.verification.core.auth import okhttp3.Interceptor import okhttp3.Response /** * Okhttp interceptor that uses specified [AuthorizationMethod] to authorize API requests. * @param authorizationMethod Method used to authorize the call. */ class AuthorizationInterceptor(private val authorizationMethod: AuthorizationMethod) : Interceptor { override fun intercept(chain: Interceptor.Chain): Response = chain.proceed(authorizationMethod.onAuthorize(chain.request())) }
0
Kotlin
1
0
4c9d56358da68633ae1c3896e5d8c9f2af2e39c4
499
verification-android-sdk
Apache License 2.0
app/src/main/java/com/hms/quickline/ui/call/VoiceCallActivity.kt
Explore-In-HMS
519,198,080
false
{"Kotlin": 190120, "Java": 6564}
/* * Copyright 2022. Explore in HMS. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.hms.quickline.ui.call import android.os.Bundle import android.os.Handler import android.os.Looper import android.os.SystemClock import android.util.Log import androidx.appcompat.app.AppCompatActivity import com.bumptech.glide.Glide import com.hms.quickline.R import com.hms.quickline.core.adapter.loadImage import com.hms.quickline.core.util.Constants import com.hms.quickline.core.util.Constants.MEETING_ID import com.hms.quickline.core.util.Constants.NAME import com.hms.quickline.core.util.invisible import com.hms.quickline.core.util.visible import com.hms.quickline.databinding.ActivityVoiceCallBinding import com.hms.quickline.data.webrtc.RTCAudioManager import com.hms.quickline.data.webrtc.SignalingClient import com.hms.quickline.data.webrtc.WebRtcClient import com.hms.quickline.data.webrtc.listener.SignalingListenerObserver import com.hms.quickline.data.webrtc.observer.DataChannelObserver import com.hms.quickline.data.webrtc.observer.PeerConnectionObserver import com.hms.quickline.data.webrtc.util.PeerConnectionUtil import dagger.hilt.android.AndroidEntryPoint import org.webrtc.* import java.util.* import javax.inject.Inject import kotlin.properties.Delegates @AndroidEntryPoint class VoiceCallActivity : AppCompatActivity() { private lateinit var binding: ActivityVoiceCallBinding private lateinit var meetingID: String private var name: String? = null private var isJoin by Delegates.notNull<Boolean>() private lateinit var webRtcClient: WebRtcClient private lateinit var peerConnectionUtil: PeerConnectionUtil private lateinit var signalingClient: SignalingClient @Inject lateinit var eglBase: EglBase private var isMute = false private var inSpeakerMode = true private val audioManager by lazy { RTCAudioManager.create(this) } var millisecondTime = 0L var startTime = 0L var seconds = 0 var minutes = 0 var handler: Handler? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityVoiceCallBinding.inflate(layoutInflater) setContentView(binding.root) handler = Handler(Looper.getMainLooper()) receivingPreviousActivityData() initializingClasses() with(binding) { name?.let { tvCallingUser.text = name } micBtn.setOnClickListener { isMute = !isMute webRtcClient.enableAudio(!isMute) if (isMute) micBtn.setImageResource(R.drawable.ic_mic_off) else micBtn.setImageResource(R.drawable.ic_mic) } btnAudioOutput.setOnClickListener { inSpeakerMode = !inSpeakerMode if (inSpeakerMode) { btnAudioOutput.setImageResource(R.drawable.ic_hearing) audioManager.setDefaultAudioDevice(RTCAudioManager.AudioDevice.EARPIECE) } else { btnAudioOutput.setImageResource(R.drawable.ic_speaker_up) audioManager.setDefaultAudioDevice(RTCAudioManager.AudioDevice.SPEAKER_PHONE) } } endCallBtn.setOnClickListener { webRtcClient.endCall() signalingClient.removeEventsListener() signalingClient.destroy() finish() } } } private var runnable: Runnable = object : Runnable { override fun run() { millisecondTime = SystemClock.uptimeMillis() - startTime seconds = (millisecondTime / 1000).toInt() minutes = seconds / 60 seconds %= 60 if (minutes.toString().length < 2) { "0$minutes:".also { binding.tvCallingTimeMinute.text = it } } else { binding.tvCallingTimeMinute.text = minutes.toString() } if (seconds.toString().length < 2) { "0$seconds".also { binding.tvCallingTimeSecond.text = it } } else { binding.tvCallingTimeSecond.text = seconds.toString() } handler?.postDelayed(this, 0) } } private fun receivingPreviousActivityData() { intent.getStringExtra(MEETING_ID)?.let { meetingID = it } intent.getStringExtra(NAME)?.let { name = it } isJoin = intent.getBooleanExtra(Constants.IS_JOIN, false) Log.d(TAG, "receivingPreviousFragmentData: roomName = $meetingID & isJoin = $isJoin") } private fun initializingClasses() { peerConnectionUtil = PeerConnectionUtil( application, eglBase.eglBaseContext ) webRtcClient = WebRtcClient( context = application, eglBase = eglBase, meetingID = meetingID, dataChannelObserver = DataChannelObserver( onBufferedAmountChangeCallback = { Log.d(WEB_RTC_DATA_CHANNEL_TAG, "onBufferedAmountChange: called") }, onStateChangeCallback = { Log.d(WEB_RTC_DATA_CHANNEL_TAG, "onStateChange: called") webRtcClient.checkDataChannelState() }, onMessageCallback = { Log.d(WEB_RTC_DATA_CHANNEL_TAG, "onMessage: called") } ), peerConnectionObserver = PeerConnectionObserver( onIceCandidateCallback = { signalingClient.sendIceCandidateModelToUser(it, isJoin) webRtcClient.addIceCandidate(it) }, onTrackCallback = { }, onAddStreamCallback = { }, onDataChannelCallback = { dataChannel -> Log.d( WEB_RTC_DATA_CHANNEL_TAG, "onDataChannelCallback: state -> ${dataChannel.state()}" ) dataChannel.registerObserver( DataChannelObserver( onStateChangeCallback = { Log.d( WEB_RTC_DATA_CHANNEL_TAG, "onDataChannelCallback - onStateChangeCallback - remote data channel state -> ${ dataChannel.state() }" ) }, onMessageCallback = { Log.d( WEB_RTC_DATA_CHANNEL_TAG, "onDataChannelCallback - onMessageCallback -> got Message" ) } ) ) } ) ) webRtcClient.createLocalDataChannel() initVoice() } private fun initVoice() { webRtcClient.startVoice() handlingSignalingClient() } private fun handlingSignalingClient() { signalingClient = SignalingClient( meetingID = meetingID, signalingListener = SignalingListenerObserver( onConnectionEstablishedCallback = { Log.d( SIGNALING_LISTENER_TAG, "handlingSignalingClient: onConnectionEstablishedCallback called" ) binding.endCallBtn.isClickable = true }, onOfferReceivedCallback = { Log.d( SIGNALING_LISTENER_TAG, "handlingSignalingClient: onOfferReceivedCallback called" ) webRtcClient.setRemoteDescription(it) webRtcClient.answer() }, onAnswerReceivedCallback = { Log.d( SIGNALING_LISTENER_TAG, "handlingSignalingClient: onAnswerReceivedCallback called" ) webRtcClient.setRemoteDescription(it) runOnUiThread { with(binding) { imgVoiceLoading.invisible() tvCallingText.invisible() imgUserImage.visible() tvCallingTimeMinute.visible() tvCallingTimeSecond.visible() loadImage(imgUserImage,USER_IMAGE) } handler?.postDelayed(runnable, 0) startTime = SystemClock.uptimeMillis() } }, onIceCandidateReceivedCallback = { Log.d( SIGNALING_LISTENER_TAG, "handlingSignalingClient: onIceCandidateReceivedCallback called" ) webRtcClient.addIceCandidate(it) }, onCallEndedCallback = { Log.d( SIGNALING_LISTENER_TAG, "handlingSignalingClient: onCallEndedCallback called" ) webRtcClient.clearSdp() webRtcClient.clearCandidates() webRtcClient.closePeerConnection() signalingClient.removeEventsListener() signalingClient.destroy() finish() } ) ) if (!isJoin) webRtcClient.call() } override fun onDestroy() { super.onDestroy() webRtcClient.clearCandidates() webRtcClient.closePeerConnection() signalingClient.removeEventsListener() signalingClient.destroy() } companion object { private const val TAG = "ui_CallFragment" private const val WEB_RTC_DATA_CHANNEL_TAG = "ui_WebRtcDataChannel" private const val SIGNALING_LISTENER_TAG = "signalingListener" private const val PERMISSION_CODE = 101 private const val USER_IMAGE = "https://media-exp1.licdn.com/dms/image/D4D03AQEweV5ra2apTw/profile-displayphoto-shrink_800_800/0/1630667862366?e=1658361600&v=beta&t=qlNpziZO8fxddUwj5eiVQYygZJA0tNHNdFZTkBbdg-A" } }
0
Kotlin
1
5
5711f868442a1ca52259419a0e87c2761e051ded
11,149
QuickLine
Apache License 2.0
app/src/main/java/com/mdzz/hook/HKCheckUtil.kt
TinyHai
158,051,673
false
null
package com.mdzz.hook import android.text.TextUtils import com.mdzz.hook.base.BaseHook import com.mdzz.hook.util.XSharedPrefUtil import de.robv.android.xposed.XC_MethodReplacement import de.robv.android.xposed.XposedBridge import de.robv.android.xposed.XposedHelpers import java.lang.reflect.Method import java.lang.reflect.Modifier import java.util.* import kotlin.collections.ArrayList class HKCheckUtil : BaseHook() { companion object { private const val TAG = "HKCheckUtil" private val checkUtilClassName: String get() = XSharedPrefUtil.getString(CHECK_UTIL_CLASS, "")!!.trim('\n', '\r', ' ', '\t') } override fun beginHook() { val lbClass = try { if (!TextUtils.isEmpty(checkUtilClassName)) { XposedHelpers.findClass(checkUtilClassName, classLoader) } else { log(TAG, "no class name be added") return } } catch (th: Throwable) { log(TAG, th) log(TAG, "run: 模块${number}出错") null } if (lbClass == null) { log(TAG, "no Class name is $checkUtilClassName") return } hookAllStaticMethodReturnZ(lbClass) log(TAG, "run: 模块${number}工作正常") } private fun hookAllStaticMethodReturnZ(lbClass: Class<*>) { val methods = getAllMethodReturnZ(lbClass) methods.forEach { XposedBridge.hookMethod(it, XC_MethodReplacement.returnConstant(false)) } } private fun getAllMethodReturnZ(lbClass: Class<*>): List<Method> { val methods = ArrayList<Method>() val allDeclareStaticMethod = lbClass.declaredMethods allDeclareStaticMethod.forEach { log(TAG, it.toString()) val isStatic = Modifier.isStatic(it.modifiers) if (isStatic && isMethodReturnZ(it)) { methods.add(it) } } return if (methods.isNotEmpty()) { methods } else { Collections.emptyList() } } private fun isMethodReturnZ(method: Method): Boolean { val resultType = method.returnType return resultType == Boolean::class.javaPrimitiveType || resultType == Boolean::class.java } }
1
Kotlin
4
28
8eaf8ff524f62a54e5c1039aa1476ef55fbb3658
2,303
Run
Apache License 2.0
src/dev/lunarcoffee/blazelight/model/api/forums/ForumAddManager.kt
lunarcoffee
214,299,039
false
{"Kotlin": 166835, "CSS": 18966, "JavaScript": 1102}
package dev.lunarcoffee.blazelight.model.api.forums import dev.lunarcoffee.blazelight.model.api.categories.CategoryForumDataUpdater import dev.lunarcoffee.blazelight.model.internal.Database import dev.lunarcoffee.blazelight.model.internal.forums.DefaultForum import dev.lunarcoffee.blazelight.model.internal.users.User object ForumAddManager { suspend fun add(name: String, topic: String, categoryId: Long, user: User): ForumAddResult { if (!user.isAdmin) return ForumAddResult.INSUFFICIENT_PERMISSIONS if (name.length !in 1..100) return ForumAddResult.INVALID_NAME if (topic.length !in 1..1_000) return ForumAddResult.INVALID_TOPIC val forum = DefaultForum(name, topic, categoryId) CategoryForumDataUpdater.addForum(forum) Database.forumCol.insertOne(forum) ForumCache.forums.add(forum) return ForumAddResult.SUCCESS } }
0
Kotlin
0
1
3f0a227fe8d48cbeece5d677e8e36974d00e4e9c
934
Blazelight
MIT License
app/src/main/java/com/application/archelon/screens/home/HomeActivity.kt
danoc93
451,251,171
false
{"Kotlin": 104143}
package com.application.archelon.screens.home import android.annotation.SuppressLint import android.app.AlertDialog import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import com.application.archelon.BuildConfig import com.application.archelon.R import com.application.archelon.screens.splash.SplashActivity import com.application.archelon.extensions.replaceFragment import com.application.archelon.repositories.SessionRepository.clearExistingSession import com.application.archelon.system.SharedPrefs import kotlinx.android.synthetic.main.app_bar_main.* /** * HomeActivity * Activity for the Home section. Here we allow users to start new surveys, or log out. */ class HomeActivity : AppCompatActivity() { private val sharedPreferences: SharedPrefs by lazy { SharedPrefs() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar) supportActionBar?.setDisplayShowTitleEnabled(false) loadHomeFrame() } @SuppressLint("CheckResult") private fun loadHomeFrame() { replaceFragment( HomeFragment.newInstance(), R.id.main_container ) } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { //React to actions on the context menu of the top bar. when (item.itemId) { R.id.action_logout -> showConfirmationForLogout() R.id.action_about -> showAboutDialog() else -> super.onOptionsItemSelected(item) } return true } private fun showConfirmationForLogout() { val builder: AlertDialog.Builder = AlertDialog.Builder(this) builder.setMessage(R.string.logout_confirmation_message) .setCancelable(false) .setPositiveButton( R.string.logout_confirmation_text ) { _, _ -> handleLogoutAction() } .setNegativeButton( R.string.logout_cancel_text ) { dialog, _ -> dialog.cancel() } val alert: AlertDialog = builder.create() alert.show() } private fun showAboutDialog() { val details = this.getString(R.string.about_string).format(BuildConfig.VERSION_NAME) val appName = this.getString(R.string.app_name); val builder: AlertDialog.Builder = AlertDialog.Builder(this) builder.setMessage(details) .setTitle(appName) .setCancelable(true) .setNegativeButton( R.string.about_cancel ) { dialog, _ -> dialog.cancel() } val alert: AlertDialog = builder.create() alert.show() } private fun handleLogoutAction() { clearExistingSession(sharedPreferences) startActivity(Intent(this, SplashActivity::class.java)) finish() } }
0
Kotlin
0
0
682cacd8fa5280241e58cb68d8ad5c8df2f02ab8
3,120
archelonpoc
MIT License
app/src/main/java/com/rk/xededitor/MainActivity/handlers/MenuItemHandler.kt
RohitKushvaha01
761,046,569
false
{"Java": 1905118, "Kotlin": 820856, "Shell": 1606}
package com.rk.xededitor.MainActivity.handlers import android.view.Menu import androidx.lifecycle.lifecycleScope import com.rk.librunner.Runner import com.rk.xededitor.R import com.rk.xededitor.MainActivity.MainActivity import com.rk.xededitor.MainActivity.editor.TabFragment import com.rk.xededitor.MainActivity.file.FileManager.Companion.findGitRoot import io.github.rosemoe.sora.event.ContentChangeEvent import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext object MenuItemHandler { fun update(activity: MainActivity) { activity.lifecycleScope.launch(Dispatchers.Default) { //wait until the menu is Initialized while (activity.isMenuInitialized().not()) { delay(50) } withContext(Dispatchers.Main) { val menu = activity.menu val show = activity.tabViewModel.fragmentFiles.isNotEmpty() editorMenu(menu, show) if (show) { activity.adapter.getCurrentFragment()?.file?.let { menu.findItem(R.id.run).isVisible = Runner.isRunnable(it) } } else { menu.findItem(R.id.run).isVisible = false } withContext(Dispatchers.Default){ val gitRoot = findGitRoot(activity.adapter.getCurrentFragment()?.file) != null withContext(Dispatchers.Main){ menu.findItem(R.id.git).isVisible = gitRoot } } updateUndoRedo(menu, activity.adapter.getCurrentFragment(), activity) searchMenu(menu, activity.adapter.getCurrentFragment()?.isSearching() ?: false) } } } val set = HashSet<String>() private fun updateUndoRedo(menu: Menu, currentFragment: TabFragment?, activity: MainActivity) { menu.findItem(R.id.redo).isEnabled = currentFragment?.editor?.canRedo() == true menu.findItem(R.id.undo).isEnabled = currentFragment?.editor?.canUndo() == true if (currentFragment?.setListener?.not() == true) { currentFragment.let { it.editor?.subscribeAlways( ContentChangeEvent::class.java ) { menu.findItem(R.id.redo).isEnabled = currentFragment.editor?.canRedo() == true menu.findItem(R.id.undo).isEnabled = currentFragment.editor?.canUndo() == true currentFragment.lifecycleScope.launch(Dispatchers.Default) { try { val fileName = currentFragment.file.name val index = activity.tabViewModel.fragmentFiles.indexOf(currentFragment.file) if (set.contains(fileName)) { // Check if the title doesn't already contain a '*' val currentTitle = activity.tabViewModel.fragmentTitles[index] if (!currentTitle.endsWith("*")) { activity.tabViewModel.fragmentTitles[index] = "$currentTitle*" withContext(Dispatchers.Main) { activity.tabLayout.getTabAt(index)?.text = activity.tabViewModel.fragmentTitles[index] } } } else { set.add(fileName) } } catch (_: Exception) {} } } if (it.setListener.not()){ it.setListener = true } } } } private fun editorMenu(menu: Menu, show: Boolean) { with(menu) { findItem(R.id.action_save).isVisible = show findItem(R.id.action_all).isVisible = show findItem(R.id.action_print).isVisible = show findItem(R.id.batchrep).isVisible = show findItem(R.id.search).isVisible = show findItem(R.id.share).isVisible = show findItem(R.id.undo).isVisible = show findItem(R.id.redo).isVisible = show } } private fun searchMenu(menu: Menu, show: Boolean) { with(menu) { findItem(R.id.search_next).isVisible = show findItem(R.id.search_previous).isVisible = show findItem(R.id.search_close).isVisible = show findItem(R.id.replace).isVisible = show if (findItem(R.id.run).isVisible) { findItem(R.id.run).isVisible = show.not() } if (findItem(R.id.undo).isVisible) { findItem(R.id.undo).isVisible = show.not() } if (findItem(R.id.redo).isVisible) { findItem(R.id.redo).isVisible = show.not() } if (findItem(R.id.action_save).isVisible) { findItem(R.id.action_save).isVisible = show.not() } } } }
13
Java
15
246
11bd507283e0b2894240cf13069d89cf7e84b49c
4,598
Xed-Editor
MIT License
app/src/main/java/com/erivera/apps/topcharts/ui/viewmodel/SplashViewModel.kt
er-rivera
188,952,931
false
null
package com.erivera.apps.topcharts.ui.viewmodel import androidx.lifecycle.* import com.erivera.apps.topcharts.StartupRouteState import com.erivera.apps.topcharts.repository.Repository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class SplashViewModel @Inject constructor(val repository : Repository) : ViewModel() { private val _navigationLiveData: MutableLiveData<StartupRouteState> = MutableLiveData() val navigationLiveData: LiveData<StartupRouteState> get() = _navigationLiveData fun checkLoginStatus(){ viewModelScope.launch { if(repository.hasValidSpotifyClientId()){ _navigationLiveData.postValue(StartupRouteState.Home) } else { _navigationLiveData.postValue(StartupRouteState.Login) } } } }
0
Kotlin
0
0
a987851954f3536229bc09b05e7548ddb1969b06
892
SpotifyStats
MIT License
src/test/kotlin/com/github/avrokotlin/avro4k/io/PolymorphicClassIoTest.kt
avro-kotlin
194,962,508
false
{"Kotlin": 279509}
package com.github.avrokotlin.avro4k.io import com.github.avrokotlin.avro4k.Avro import com.github.avrokotlin.avro4k.schema.* import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.shouldBe import io.kotest.matchers.types.shouldBeInstanceOf import org.apache.avro.generic.GenericRecord import org.apache.avro.util.Utf8 class PolymorphicClassIoTest : StringSpec({ "read / write nested polymorphic class" { val avro = Avro(serializersModule = polymorphicModule) writeRead(ReferencingPolymorphicRoot(UnsealedChildOne("one")), ReferencingPolymorphicRoot.serializer(), avro) writeRead(ReferencingPolymorphicRoot(UnsealedChildOne("one")), ReferencingPolymorphicRoot.serializer(), avro) { val root = it["root"] as GenericRecord root.schema shouldBe avro.schema(UnsealedChildOne.serializer()) } } "read / write nested polymorphic list" { val avro = Avro(serializersModule = polymorphicModule) writeRead(PolymorphicRootInList(listOf(UnsealedChildOne("one"))), PolymorphicRootInList.serializer(), avro) writeRead(PolymorphicRootInList(listOf(UnsealedChildOne("one"))), PolymorphicRootInList.serializer(), avro) { it["listOfRoot"].shouldBeInstanceOf<List<GenericRecord>>() val unsealeadChild = (it["listOfRoot"] as List<*>)[0] as GenericRecord unsealeadChild.schema shouldBe avro.schema(UnsealedChildOne.serializer()) } } "read / write nested polymorphic map" { val avro = Avro(serializersModule = polymorphicModule) writeRead(PolymorphicRootInMap(mapOf("a" to UnsealedChildOne("one"))), PolymorphicRootInMap.serializer(), avro) writeRead( PolymorphicRootInMap(mapOf("a" to UnsealedChildOne("one"))), PolymorphicRootInMap.serializer(), avro ) { it["mapOfRoot"].shouldBeInstanceOf<Map<Utf8, GenericRecord>>() val unsealeadChild = (it["mapOfRoot"] as Map<*, *>)[Utf8("a")] as GenericRecord unsealeadChild.schema shouldBe avro.schema(UnsealedChildOne.serializer()) } } })
27
Kotlin
36
187
f550163d19c60a1071df84f5c9671cb9e35364f4
2,134
avro4k
Apache License 2.0
Chapter08/src/main/kotlin/com/rivuchk/packtpub/reactivekotlin/chapter08/chapter8_2_concurrent.kt
tymicki
175,694,440
true
{"Kotlin": 121444}
package com.rivuchk.packtpub.reactivekotlin.chapter8 import io.reactivex.Observable import io.reactivex.schedulers.Schedulers import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking fun main() { Observable.range(1, 10) .subscribeOn(Schedulers.computation()) .subscribe { item -> println("Received $item") } runBlocking { delay(10) } }
0
Kotlin
0
0
143e1bd1473c6da3fb3fe1b9373124052f87874d
410
Reactive-Programming-in-Kotlin
MIT License
build/assets/compose/vitaminassets/flags/Cc.kt
Decathlon
511,157,831
false
{"Kotlin": 4443549, "HTML": 226066, "Swift": 163852, "TypeScript": 60822, "CSS": 53872, "JavaScript": 33193, "Handlebars": 771}
package com.decathlon.vitamin.compose.vitaminassets.flags import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.group import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.decathlon.vitamin.compose.vitaminassets.FlagsGroup public val FlagsGroup.Cc: ImageVector get() { if (_cc != null) { return _cc!! } _cc = Builder(name = "Cc", defaultWidth = 28.0.dp, defaultHeight = 20.0.dp, viewportWidth = 28.0f, viewportHeight = 20.0f).apply { group { path(fill = SolidColor(Color(0xFFFFFFFF)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(28.0f, 0.0f) horizontalLineTo(0.0f) verticalLineTo(20.0f) horizontalLineTo(28.0f) verticalLineTo(0.0f) close() } path(fill = SolidColor(Color(0xFF229716)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(28.0f, 0.0f) horizontalLineTo(0.0f) verticalLineTo(20.0f) horizontalLineTo(28.0f) verticalLineTo(0.0f) close() } path(fill = SolidColor(Color(0xFFFFE244)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) { moveTo(5.3333f, 8.0f) curveTo(3.8606f, 8.0f, 2.6667f, 6.8061f, 2.6667f, 5.3333f) curveTo(2.6667f, 3.8606f, 3.8606f, 2.6667f, 5.3333f, 2.6667f) curveTo(6.8061f, 2.6667f, 8.0f, 3.8606f, 8.0f, 5.3333f) curveTo(8.0f, 6.8061f, 6.8061f, 8.0f, 5.3333f, 8.0f) close() moveTo(5.3333f, 5.3333f) curveTo(5.6109f, 5.3333f, 5.1199f, 6.7393f, 5.3333f, 6.6667f) curveTo(5.6861f, 6.5467f, 6.6667f, 4.896f, 6.6667f, 4.6667f) curveTo(6.6667f, 4.2985f, 6.0697f, 4.0f, 5.3333f, 4.0f) curveTo(4.597f, 4.0f, 4.0f, 4.2985f, 4.0f, 4.6667f) curveTo(4.0f, 5.0349f, 4.597f, 5.3333f, 5.3333f, 5.3333f) close() } path(fill = SolidColor(Color(0xFFFFE244)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) { moveTo(21.3334f, 17.3334f) lineTo(20.3905f, 17.6095f) lineTo(20.6667f, 16.6667f) lineTo(20.3905f, 15.7239f) lineTo(21.3334f, 16.0f) lineTo(22.2762f, 15.7239f) lineTo(22.0f, 16.6667f) lineTo(22.2762f, 17.6095f) lineTo(21.3334f, 17.3334f) close() } path(fill = SolidColor(Color(0xFFFFE244)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) { moveTo(21.3334f, 4.6667f) lineTo(20.3905f, 4.9428f) lineTo(20.6667f, 4.0f) lineTo(20.3905f, 3.0572f) lineTo(21.3334f, 3.3333f) lineTo(22.2762f, 3.0572f) lineTo(22.0f, 4.0f) lineTo(22.2762f, 4.9428f) lineTo(21.3334f, 4.6667f) close() } path(fill = SolidColor(Color(0xFFFFE244)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) { moveTo(25.3334f, 8.6667f) lineTo(24.3905f, 8.9428f) lineTo(24.6667f, 8.0f) lineTo(24.3905f, 7.0572f) lineTo(25.3334f, 7.3334f) lineTo(26.2762f, 7.0572f) lineTo(26.0f, 8.0f) lineTo(26.2762f, 8.9428f) lineTo(25.3334f, 8.6667f) close() } path(fill = SolidColor(Color(0xFFFFE244)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) { moveTo(18.6667f, 10.0f) lineTo(17.7239f, 10.2762f) lineTo(18.0f, 9.3334f) lineTo(17.7239f, 8.3905f) lineTo(18.6667f, 8.6667f) lineTo(19.6095f, 8.3905f) lineTo(19.3334f, 9.3334f) lineTo(19.6095f, 10.2762f) lineTo(18.6667f, 10.0f) close() } path(fill = SolidColor(Color(0xFFFFE244)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) { moveTo(23.3333f, 11.6666f) lineTo(22.8619f, 11.8047f) lineTo(23.0f, 11.3333f) lineTo(22.8619f, 10.8619f) lineTo(23.3333f, 11.0f) lineTo(23.8047f, 10.8619f) lineTo(23.6667f, 11.3333f) lineTo(23.8047f, 11.8047f) lineTo(23.3333f, 11.6666f) close() } path(fill = SolidColor(Color(0xFFFFE244)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) { moveTo(16.0818f, 7.3966f) curveTo(15.5114f, 6.9398f, 14.7876f, 6.6667f, 14.0f, 6.6667f) curveTo(12.1591f, 6.6667f, 10.6667f, 8.159f, 10.6667f, 10.0f) curveTo(10.6667f, 11.8409f, 12.1591f, 13.3333f, 14.0f, 13.3333f) curveTo(14.7876f, 13.3333f, 15.5114f, 13.0602f, 16.0818f, 12.6035f) curveTo(15.7796f, 12.7162f, 15.4526f, 12.7778f, 15.1111f, 12.7778f) curveTo(13.577f, 12.7778f, 12.3333f, 11.5341f, 12.3333f, 10.0f) curveTo(12.3333f, 8.4659f, 13.577f, 7.2222f, 15.1111f, 7.2222f) curveTo(15.4526f, 7.2222f, 15.7796f, 7.2838f, 16.0818f, 7.3966f) close() } } } .build() return _cc!! } private var _cc: ImageVector? = null
1
Kotlin
5
33
852dcd924b82cac447918d2609615819d34caf82
7,857
vitamin-design
Apache License 2.0
app/src/main/java/com/phz/dev/feature/main/MainActivity.kt
PengHaiZhuo
395,591,581
false
{"Kotlin": 429882, "Java": 59576, "HTML": 10034}
package com.phz.dev.feature.main import android.Manifest import android.content.IntentFilter import android.content.pm.PackageManager import android.net.ConnectivityManager import android.os.Build import android.os.Bundle import android.os.Process import androidx.core.app.ActivityCompat import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.setupWithNavController import com.gyf.immersionbar.ktx.immersionBar import com.phz.common.ext.logE import com.phz.common.ext.showSnackShort import com.phz.common.net.manager.NetStateManager import com.phz.common.net.manager.NetStateReceiver import com.phz.common.page.activity.BasePureActivity import com.phz.common.state.NoViewModel import com.phz.dev.R import com.phz.dev.databinding.ActivityMainBinding import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch /** * @author phz * @description */ class MainActivity : BasePureActivity<NoViewModel, ActivityMainBinding>() { private lateinit var mNetStateReceiver: NetStateReceiver companion object { const val REQUEST_STORAGE = 0x115 const val REQUEST_LOCATION = 0x116 const val readPermission = Manifest.permission.READ_EXTERNAL_STORAGE const val writePermission = Manifest.permission.WRITE_EXTERNAL_STORAGE //确切定位权限 const val fineLocation = Manifest.permission.ACCESS_FINE_LOCATION //大致定位权限 const val crossLocation = Manifest.permission.ACCESS_COARSE_LOCATION //相机 实景导航要用 const val camera = Manifest.permission.CAMERA } override fun initData() { //6.0运行时权限-读写权限获取 if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.Q) { var requestPerms = arrayListOf<String>() if (checkPermission( readPermission, Process.myPid(), Process.myUid() ) != PackageManager.PERMISSION_GRANTED ) { requestPerms.add(readPermission) } if (checkPermission( writePermission, Process.myPid(), Process.myUid() ) != PackageManager.PERMISSION_GRANTED ) { requestPerms.add(writePermission) } if (requestPerms.isNotEmpty()) { requestPermissions(requestPerms.toTypedArray(), REQUEST_STORAGE) } } else { //11开始请求写权限没用了 if (checkPermission( readPermission, Process.myPid(), Process.myUid() ) != PackageManager.PERMISSION_GRANTED ) { ActivityCompat.requestPermissions( this, arrayOf(readPermission), REQUEST_STORAGE ) } } //注册网络变化监听广播 mNetStateReceiver = NetStateReceiver() registerReceiver( mNetStateReceiver, IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION) )//虽然被标记为过时,但是动态注册还是能用的 var isInit=false//用来解决第一次监听回调,没有发生变化也回调了,毕竟用了flow lifecycleScope.launch { //添加网络状态变化观察者 NetStateManager.instance.isNetAvailable.collect { if (isInit){ showSnackShort( if (it) { "有网" } else { "断网" } ) }else{ isInit=true } } } } override fun onDestroy() { super.onDestroy() //解除注册网络变化监听广播 unregisterReceiver(mNetStateReceiver) } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { if (requestCode == REQUEST_STORAGE) { for ((index, value) in grantResults.withIndex()) { when (value) { //获取权限结果打印 PackageManager.PERMISSION_GRANTED -> { "${permissions[index]} allow".logE() } PackageManager.PERMISSION_DENIED -> { "${permissions[index]} deny".logE() } } } } else super.onRequestPermissionsResult(requestCode, permissions, grantResults) } override fun initView(savedInstanceState: Bundle?) { //布局文件中使用的FragmentContainerView而不是fragment val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_container) as NavHostFragment mViewDataBinding.bottomNav.setupWithNavController(navHostFragment.navController) immersionBar { statusBarColor(R.color.colorPrimary) autoDarkModeEnable(true) } } override fun layoutId(): Int = R.layout.activity_main override fun initObserver() = Unit }
0
Kotlin
0
0
baf65155052ad759f01b24921c859dee181deaf6
5,028
lapAndroid
Apache License 2.0
joark/src/test/kotlin/no/nav/helsearbeidsgiver/inntektsmelding/joark/dokument/PdfDokumentTest.kt
navikt
495,713,363
false
null
package no.nav.helsearbeidsgiver.inntektsmelding.joark.dokument import no.nav.helsearbeidsgiver.felles.inntektsmelding.BegrunnelseIngenEllerRedusertUtbetalingKode import no.nav.helsearbeidsgiver.felles.inntektsmelding.FullLønnIArbeidsgiverPerioden import no.nav.helsearbeidsgiver.felles.inntektsmelding.InntektsmeldingDokument import no.nav.helsearbeidsgiver.felles.inntektsmelding.Naturalytelse import no.nav.helsearbeidsgiver.felles.inntektsmelding.NaturalytelseKode import no.nav.helsearbeidsgiver.felles.inntektsmelding.Periode import no.nav.helsearbeidsgiver.felles.inntektsmelding.Refusjon import no.nav.helsearbeidsgiver.felles.inntektsmelding.ÅrsakBeregnetInntektEndringKodeliste import no.nav.helsearbeidsgiver.felles.inntektsmelding.ÅrsakInnsending import org.junit.jupiter.api.Test import java.io.File import java.io.FileOutputStream import java.time.LocalDate import java.time.LocalDateTime internal class PdfDokumentTest { val dag = LocalDate.of(2022, 12, 24) val im = InntektsmeldingDokument( orgnrUnderenhet = "123456789", identitetsnummer = "12345678901", fulltNavn = "<NAME>", virksomhetNavn = "<NAME>", behandlingsdager = listOf(dag), egenmeldingsperioder = listOf( Periode(dag, dag.plusDays(2)), Periode(dag.plusDays(3), dag.plusDays(4)) ), beregnetInntektEndringÅrsak = ÅrsakBeregnetInntektEndringKodeliste.FeilInntekt, beregnetInntekt = 25000.0, fullLønnIArbeidsgiverPerioden = FullLønnIArbeidsgiverPerioden(true, begrunnelse = BegrunnelseIngenEllerRedusertUtbetalingKode.BeskjedGittForSent), refusjon = Refusjon(25000.0, dag.plusDays(3)), naturalytelser = listOf( Naturalytelse(NaturalytelseKode.Bil, dag.plusDays(5), 350.0), Naturalytelse(NaturalytelseKode.Bil, dag.plusDays(5), 350.0) ), fraværsperioder = listOf( Periode(dag, dag.plusDays(55)), Periode(dag, dag.plusDays(22)), Periode(dag, dag.plusDays(32)) ), arbeidsgiverperioder = listOf( Periode(dag, dag.plusDays(30)), Periode(dag, dag.plusDays(40)), Periode(dag, dag.plusDays(40)) ), bestemmendeFraværsdag = dag.plusDays(90), tidspunkt = LocalDateTime.now(), årsakInnsending = ÅrsakInnsending.Ny, identitetsnummerInnsender = "123123123123123" ) @Test fun `skal lage kvittering`() { // val file = File(System.getProperty("user.home"), "/Desktop/inntektsmelding.pdf") val file = File.createTempFile("kvittering", "pdf") val writer = FileOutputStream(file) writer.write(PdfDokument(im).export()) } }
0
Kotlin
0
2
7a72f63b858b6b16365cfd78e38518ac294d1fe1
2,727
helsearbeidsgiver-inntektsmelding
MIT License