repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
thermatk/FastHub-Libre
|
app/src/main/java/com/fastaccess/ui/modules/repos/projects/RepoProjectsFragmentPager.kt
|
6
|
3324
|
package com.fastaccess.ui.modules.repos.projects
import android.os.Bundle
import android.support.design.widget.TabLayout
import android.view.View
import butterknife.BindView
import com.fastaccess.R
import com.fastaccess.data.dao.FragmentPagerAdapterModel
import com.fastaccess.data.dao.TabsCountStateModel
import com.fastaccess.helper.BundleConstant
import com.fastaccess.helper.Bundler
import com.fastaccess.helper.ViewHelper
import com.fastaccess.ui.adapter.FragmentsPagerAdapter
import com.fastaccess.ui.base.BaseFragment
import com.fastaccess.ui.base.mvp.BaseMvp
import com.fastaccess.ui.base.mvp.presenter.BasePresenter
import com.fastaccess.ui.modules.repos.RepoPagerMvp
import com.fastaccess.ui.widgets.SpannableBuilder
import com.fastaccess.ui.widgets.ViewPagerView
/**
* Created by kosh on 09/09/2017.
*/
class RepoProjectsFragmentPager : BaseFragment<BaseMvp.FAView, BasePresenter<BaseMvp.FAView>>(), RepoPagerMvp.TabsBadgeListener {
@BindView(R.id.tabs) lateinit var tabs: TabLayout
@BindView(R.id.pager) lateinit var pager: ViewPagerView
private var counts: HashSet<TabsCountStateModel>? = null
override fun fragmentLayout(): Int = R.layout.centered_tabbed_viewpager
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
if (counts?.isNotEmpty() == true) {
outState.putSerializable("counts", counts)
}
}
override fun onFragmentCreated(view: View, savedInstanceState: Bundle?) {
pager.adapter = FragmentsPagerAdapter(childFragmentManager, FragmentPagerAdapterModel.buildForRepoProjects(context!!,
arguments!!.getString(BundleConstant.ID), arguments!!.getString(BundleConstant.EXTRA)))
tabs.setupWithViewPager(pager)
if (savedInstanceState != null) {
@Suppress("UNCHECKED_CAST")
counts = savedInstanceState.getSerializable("counts") as? HashSet<TabsCountStateModel>?
counts?.let {
if (!it.isEmpty()) it.onEach { updateCount(it) }
}
} else {
counts = hashSetOf()
}
}
override fun providePresenter(): BasePresenter<BaseMvp.FAView> = BasePresenter()
override fun onSetBadge(tabIndex: Int, count: Int) {
val model = TabsCountStateModel()
model.tabIndex = tabIndex
model.count = count
counts?.add(model)
tabs.let { updateCount(model) }
}
private fun updateCount(model: TabsCountStateModel) {
val tv = ViewHelper.getTabTextView(tabs, model.tabIndex)
tv.text = SpannableBuilder.builder()
.append(if (model.tabIndex == 0) getString(R.string.opened) else getString(R.string.closed))
.append(" ")
.append("(")
.bold(model.count.toString())
.append(")")
}
companion object {
val TAG = RepoProjectsFragmentPager::class.java.simpleName
fun newInstance(login: String, repoId: String? = null): RepoProjectsFragmentPager {
val fragment = RepoProjectsFragmentPager()
fragment.arguments = Bundler.start()
.put(BundleConstant.ID, repoId)
.put(BundleConstant.EXTRA, login)
.end()
return fragment
}
}
}
|
gpl-3.0
|
5bc8f18969ea634d31ae3ebb2776ee75
| 38.117647 | 129 | 0.682611 | 4.675105 | false | false | false | false |
Asteriskx/Kotlin_learning
|
Control Flow/if-else.kt
|
1
|
564
|
// Kotlin
// Traditional usage
var max = a
if (a < b) max = b
// With else
var max: Int
if (a > b) {
max = a
} else {
max = b
}
// Kotlin is Non 3 Section operators.
val max = if (a > b) {
print("Choose a")
a
} else {
print("Choose b")
b
}
// Java
//if
int max = 10;
if( max < 20 ) max = 20;
// else
int max = 10;
if( max < 20 ){
max = 20;
}
else {
max = max;
}
//3 Section operator.
int hoge = 20;
int fuga = 40;
int max = ( hoge < huga ) ? println( hoge ) : println( fuga );
|
mit
|
86a4963ad623a1e4553a0fc8120b4fc7
| 11.756098 | 63 | 0.475177 | 2.495575 | false | false | false | false |
MichBogus/PINZ-ws
|
src/main/kotlin/controller/register/RegisterControllerMappings.kt
|
1
|
1000
|
package controller.register
import controller.base.WSResponseEntity
import workflow.request.RegisterCompanyRequest
import workflow.request.RegisterUserRequest
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import javax.validation.Valid
interface RegisterControllerMappings {
@RequestMapping(value = "/registerUser",
method = arrayOf(RequestMethod.POST),
consumes = arrayOf("application/json"),
produces = arrayOf("application/json"))
fun registerUser(@Valid @RequestBody request: RegisterUserRequest): WSResponseEntity
@RequestMapping(value = "/registerCompany",
method = arrayOf(RequestMethod.POST),
consumes = arrayOf("application/json"),
produces = arrayOf("application/json"))
fun registerCompany(@Valid @RequestBody request: RegisterCompanyRequest): WSResponseEntity
}
|
apache-2.0
|
65700bbf1b09faedc0677cd5ace736e6
| 40.708333 | 94 | 0.763 | 5.319149 | false | false | false | false |
bachhuberdesign/deck-builder-gwent
|
app/src/main/java/com/bachhuberdesign/deckbuildergwent/features/cardviewer/CardFilters.kt
|
1
|
742
|
package com.bachhuberdesign.deckbuildergwent.features.cardviewer
/**
* Helper class which contains paired arguments used for filtering a list of [com.bachhuberdesign.deckbuildergwent.features.shared.model.Card].
*
* If the boolean in the pair is set to true, the corresponding Int ID should be set as it will be
* used for filtering.
*
* Example: filterByDeck = Pair(true, deckId)
*
* @author Eric Bachhuber
* @version 1.0.0
* @since 1.0.0
*/
data class CardFilters(
var filterByDeck: Pair<Boolean, Int> = Pair(false, 0),
var filterByFactions: Pair<Boolean, Int> = Pair(false, 0),
var filterByRarity: Pair<Boolean, Int> = Pair(false, 0),
var filterByCardType: Pair<Boolean, Int> = Pair(false, 0)
)
|
apache-2.0
|
1cade9941777950e4371e9a0d9868d1a
| 36.1 | 143 | 0.706199 | 3.747475 | false | false | false | false |
Reyurnible/gitsalad-android
|
app/src/main/kotlin/com/hosshan/android/salad/repository/github/service/RepositoriesService.kt
|
1
|
3148
|
package com.hosshan.android.salad.repository.github.service
import com.hosshan.android.salad.repository.github.entity.*
import com.hosshan.android.salad.repository.github.service.body.CreateRepositoryBody
import com.hosshan.android.salad.repository.github.service.body.EditRepositoryBody
import org.json.JSONObject
import retrofit2.http.*
import rx.Observable
/**
* Repository api service
* https://developer.github.com/v3/repos/#create
*/
interface RepositoriesService {
@GET("/user/repos")
fun repositories(
@Query("visibility") visibility: String? = null,
@Query("affiliation") affiliation: String? = null,
@Query("type") type: String? = null,
@Query("sort") sort: String? = null,
@Query("direction") direction: String? = null
): Observable<List<Repository>>
@GET("/users/{username}/repos")
fun userRepositories(
@Path("username") username: String,
@Query("type") type: String? = null,
@Query("sort") sort: String? = null,
@Query("direction") direction: String? = null
): Observable<List<Repository>>
@GET("/orgs/{org}/repos")
fun organizationRepositories(
@Path("org") org: String,
@Query("type") type: String? = null
): Observable<List<Repository>>
@GET("/publicRepositories")
fun publicRepositories(@Query("since") since: Long? = null): Observable<List<Repository>>
@POST("/user/repos")
fun create(@Body body: CreateRepositoryBody): Observable<Repository>
@POST("/orgs/{org}/repos")
fun create(
@Path("org") org: String,
@Body body: CreateRepositoryBody
): Observable<Repository>
@GET("/repos/{owner}/{repo}")
fun repository(
@Path("owner") owner: String,
@Path("repo") repo: String
): Observable<RepositoryDetails>
@PATCH("/repos/{owner}/{repo}")
fun edit(
@Path("owner") owner: String,
@Path("repo") repo: String,
@Body body: EditRepositoryBody
): Observable<RepositoryDetails>
@DELETE("/repos/{owner}/{repo}")
fun delete(
@Path("owner") owner: String,
@Path("repo") repo: String
): Observable<RepositoryDetails>
@GET("/repos/{owner}/{repo}/contributors")
fun contributors(
@Path("owner") owner: String,
@Path("repo") repo: String
): Observable<List<User>>
@GET("/repos/{owner}/{repo}/commits")
fun commits(
@Path("owner") owner: String,
@Path("repo") repo: String
): Observable<List<RepositoryCommit>>
@GET("/repos/{owner}/{repo}/languages")
fun languages(
@Path("owner") owner: String,
@Path("repo") repo: String
): Observable<JSONObject>
@GET("/repos/{owner}/{repo}/teams")
fun teams(
@Path("owner") owner: String,
@Path("repo") repo: String
): Observable<List<Team>>
@GET("/repos/{owner}/{repo}/tags")
fun tags(
@Path("owner") owner: String,
@Path("repo") repo: String
): Observable<List<Tag>>
}
|
mit
|
a6c22cf21381263f0911938094b80766
| 30.48 | 93 | 0.600699 | 4.142105 | false | false | false | false |
Doctoror/FuckOffMusicPlayer
|
data/src/main/java/com/doctoror/fuckoffmusicplayer/data/playback/controller/PlaybackControllerProvider.kt
|
2
|
2998
|
/*
* Copyright (C) 2018 Yaroslav Mytkalyk
*
* 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.doctoror.fuckoffmusicplayer.data.playback.controller
import com.doctoror.fuckoffmusicplayer.data.playback.unit.PlaybackServiceUnitPlayMediaFromQueue
import com.doctoror.fuckoffmusicplayer.domain.playback.PlaybackData
import com.doctoror.fuckoffmusicplayer.domain.playback.PlaybackParams
class PlaybackControllerProvider(
private val playbackData: PlaybackData,
private val playbackParams: PlaybackParams,
private val psUnitPlayMediaFromQueue: PlaybackServiceUnitPlayMediaFromQueue,
private val stopAction: Runnable) {
private var playbackController: PlaybackController? = null
/**
* Returns Playback controller based on [PlaybackParams].
*
* Users should obtain a controller before any operation to ensure the correct controller is used based on
* current [PlaybackParams] state.
*
* This value is cached and refreshed each time a new invocation is called for different [PlaybackParams].
*/
fun obtain(): PlaybackController {
var created = false
var returnValue: PlaybackController? = playbackController
if (returnValue == null) {
returnValue = if (playbackParams.isShuffleEnabled)
newPlaybackControllerShuffle()
else
newPlaybackControllerNormal()
created = true
} else if (playbackParams.isShuffleEnabled) {
if (PlaybackControllerShuffle::class.java != returnValue.javaClass) {
returnValue = newPlaybackControllerShuffle()
created = true
}
} else {
if (PlaybackControllerNormal::class.java != returnValue.javaClass) {
returnValue = newPlaybackControllerNormal()
created = true
}
}
if (created) {
returnValue.setQueue(playbackData.queue)
}
playbackController = returnValue
return returnValue
}
private fun newPlaybackControllerNormal(): PlaybackController = PlaybackControllerNormal(
playbackData,
playbackParams,
psUnitPlayMediaFromQueue,
stopAction)
private fun newPlaybackControllerShuffle(): PlaybackController = PlaybackControllerShuffle(
playbackData,
playbackParams,
psUnitPlayMediaFromQueue,
stopAction)
}
|
apache-2.0
|
f2717d583e4aaaf0d43a2c8886c21c78
| 37.935065 | 110 | 0.685457 | 5.250438 | false | false | false | false |
chrisbanes/tivi
|
ui/search/src/main/java/app/tivi/home/search/SearchViewModel.kt
|
1
|
2735
|
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.tivi.home.search
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import app.tivi.api.UiMessage
import app.tivi.api.UiMessageManager
import app.tivi.domain.interactors.SearchShows
import app.tivi.util.ObservableLoadingCounter
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
internal class SearchViewModel @Inject constructor(
private val searchShows: SearchShows
) : ViewModel() {
private val searchQuery = MutableStateFlow("")
private val loadingState = ObservableLoadingCounter()
private val uiMessageManager = UiMessageManager()
val state: StateFlow<SearchViewState> = combine(
searchQuery,
searchShows.flow,
loadingState.observable,
uiMessageManager.message,
::SearchViewState
).stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(),
initialValue = SearchViewState.Empty
)
init {
viewModelScope.launch {
searchQuery.debounce(300)
.onEach { query ->
val job = launch {
loadingState.addLoader()
searchShows(SearchShows.Params(query))
}
job.invokeOnCompletion { loadingState.removeLoader() }
job.join()
}
.catch { throwable -> uiMessageManager.emitMessage(UiMessage(throwable)) }
.collect()
}
}
fun search(searchTerm: String) {
searchQuery.value = searchTerm
}
fun clearMessage(id: Long) {
viewModelScope.launch {
uiMessageManager.clearMessage(id)
}
}
}
|
apache-2.0
|
fcc2b629e33bedef240d0a2ca48bec13
| 31.951807 | 90 | 0.69287 | 4.875223 | false | false | false | false |
italoag/qksms
|
data/src/main/java/com/moez/QKSMS/repository/ConversationRepositoryImpl.kt
|
3
|
18417
|
/*
* Copyright (C) 2017 Moez Bhatti <[email protected]>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.repository
import android.content.ContentUris
import android.content.Context
import android.provider.Telephony
import com.moez.QKSMS.compat.TelephonyCompat
import com.moez.QKSMS.extensions.anyOf
import com.moez.QKSMS.extensions.asObservable
import com.moez.QKSMS.extensions.map
import com.moez.QKSMS.extensions.removeAccents
import com.moez.QKSMS.filter.ConversationFilter
import com.moez.QKSMS.mapper.CursorToConversation
import com.moez.QKSMS.mapper.CursorToRecipient
import com.moez.QKSMS.model.Contact
import com.moez.QKSMS.model.Conversation
import com.moez.QKSMS.model.Message
import com.moez.QKSMS.model.Recipient
import com.moez.QKSMS.model.SearchResult
import com.moez.QKSMS.util.PhoneNumberUtils
import com.moez.QKSMS.util.tryOrNull
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import io.realm.Case
import io.realm.Realm
import io.realm.RealmResults
import io.realm.Sort
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class ConversationRepositoryImpl @Inject constructor(
private val context: Context,
private val conversationFilter: ConversationFilter,
private val cursorToConversation: CursorToConversation,
private val cursorToRecipient: CursorToRecipient,
private val phoneNumberUtils: PhoneNumberUtils
) : ConversationRepository {
override fun getConversations(archived: Boolean): RealmResults<Conversation> {
return Realm.getDefaultInstance()
.where(Conversation::class.java)
.notEqualTo("id", 0L)
.equalTo("archived", archived)
.equalTo("blocked", false)
.isNotEmpty("recipients")
.beginGroup()
.isNotNull("lastMessage")
.or()
.isNotEmpty("draft")
.endGroup()
.sort(
arrayOf("pinned", "draft", "lastMessage.date"),
arrayOf(Sort.DESCENDING, Sort.DESCENDING, Sort.DESCENDING)
)
.findAllAsync()
}
override fun getConversationsSnapshot(): List<Conversation> {
return Realm.getDefaultInstance().use { realm ->
realm.refresh()
realm.copyFromRealm(realm.where(Conversation::class.java)
.notEqualTo("id", 0L)
.equalTo("archived", false)
.equalTo("blocked", false)
.isNotEmpty("recipients")
.beginGroup()
.isNotNull("lastMessage")
.or()
.isNotEmpty("draft")
.endGroup()
.sort(
arrayOf("pinned", "draft", "lastMessage.date"),
arrayOf(Sort.DESCENDING, Sort.DESCENDING, Sort.DESCENDING)
)
.findAll())
}
}
override fun getTopConversations(): List<Conversation> {
return Realm.getDefaultInstance().use { realm ->
realm.copyFromRealm(realm.where(Conversation::class.java)
.notEqualTo("id", 0L)
.isNotNull("lastMessage")
.beginGroup()
.equalTo("pinned", true)
.or()
.greaterThan("lastMessage.date", System.currentTimeMillis() - TimeUnit.DAYS.toMillis(7))
.endGroup()
.equalTo("archived", false)
.equalTo("blocked", false)
.isNotEmpty("recipients")
.findAll())
.sortedWith(compareByDescending<Conversation> { conversation -> conversation.pinned }
.thenByDescending { conversation ->
realm.where(Message::class.java)
.equalTo("threadId", conversation.id)
.greaterThan("date", System.currentTimeMillis() - TimeUnit.DAYS.toMillis(7))
.count()
})
}
}
override fun setConversationName(id: Long, name: String) {
Realm.getDefaultInstance().use { realm ->
realm.executeTransaction {
realm.where(Conversation::class.java)
.equalTo("id", id)
.findFirst()
?.name = name
}
}
}
override fun searchConversations(query: CharSequence): List<SearchResult> {
val realm = Realm.getDefaultInstance()
val normalizedQuery = query.removeAccents()
val conversations = realm.copyFromRealm(realm
.where(Conversation::class.java)
.notEqualTo("id", 0L)
.isNotNull("lastMessage")
.equalTo("blocked", false)
.isNotEmpty("recipients")
.sort("pinned", Sort.DESCENDING, "lastMessage.date", Sort.DESCENDING)
.findAll())
val messagesByConversation = realm.copyFromRealm(realm
.where(Message::class.java)
.beginGroup()
.contains("body", normalizedQuery, Case.INSENSITIVE)
.or()
.contains("parts.text", normalizedQuery, Case.INSENSITIVE)
.endGroup()
.findAll())
.asSequence()
.groupBy { message -> message.threadId }
.filter { (threadId, _) -> conversations.firstOrNull { it.id == threadId } != null }
.map { (threadId, messages) -> Pair(conversations.first { it.id == threadId }, messages.size) }
.map { (conversation, messages) -> SearchResult(normalizedQuery, conversation, messages) }
.sortedByDescending { result -> result.messages }
.toList()
realm.close()
return conversations
.filter { conversation -> conversationFilter.filter(conversation, normalizedQuery) }
.map { conversation -> SearchResult(normalizedQuery, conversation, 0) } + messagesByConversation
}
override fun getBlockedConversations(): RealmResults<Conversation> {
return Realm.getDefaultInstance()
.where(Conversation::class.java)
.equalTo("blocked", true)
.findAll()
}
override fun getBlockedConversationsAsync(): RealmResults<Conversation> {
return Realm.getDefaultInstance()
.where(Conversation::class.java)
.equalTo("blocked", true)
.findAllAsync()
}
override fun getConversationAsync(threadId: Long): Conversation {
return Realm.getDefaultInstance()
.where(Conversation::class.java)
.equalTo("id", threadId)
.findFirstAsync()
}
override fun getConversation(threadId: Long): Conversation? {
return Realm.getDefaultInstance()
.apply { refresh() }
.where(Conversation::class.java)
.equalTo("id", threadId)
.findFirst()
}
override fun getConversations(vararg threadIds: Long): RealmResults<Conversation> {
return Realm.getDefaultInstance()
.where(Conversation::class.java)
.anyOf("id", threadIds)
.findAll()
}
override fun getUnmanagedConversations(): Observable<List<Conversation>> {
val realm = Realm.getDefaultInstance()
return realm.where(Conversation::class.java)
.sort("lastMessage.date", Sort.DESCENDING)
.notEqualTo("id", 0L)
.isNotNull("lastMessage")
.equalTo("archived", false)
.equalTo("blocked", false)
.isNotEmpty("recipients")
.limit(5)
.findAllAsync()
.asObservable()
.filter { it.isLoaded }
.filter { it.isValid }
.map { realm.copyFromRealm(it) }
.subscribeOn(AndroidSchedulers.mainThread())
.observeOn(Schedulers.io())
}
override fun getRecipients(): RealmResults<Recipient> {
val realm = Realm.getDefaultInstance()
return realm.where(Recipient::class.java)
.findAll()
}
override fun getUnmanagedRecipients(): Observable<List<Recipient>> {
val realm = Realm.getDefaultInstance()
return realm.where(Recipient::class.java)
.isNotNull("contact")
.findAllAsync()
.asObservable()
.filter { it.isLoaded && it.isValid }
.map { realm.copyFromRealm(it) }
.subscribeOn(AndroidSchedulers.mainThread())
}
override fun getRecipient(recipientId: Long): Recipient? {
return Realm.getDefaultInstance()
.where(Recipient::class.java)
.equalTo("id", recipientId)
.findFirst()
}
override fun getThreadId(recipient: String): Long? {
return getThreadId(listOf(recipient))
}
override fun getThreadId(recipients: Collection<String>): Long? {
return Realm.getDefaultInstance().use { realm ->
realm.refresh()
realm.where(Conversation::class.java)
.findAll()
.asSequence()
.filter { conversation -> conversation.recipients.size == recipients.size }
.find { conversation ->
conversation.recipients.map { it.address }.all { address ->
recipients.any { recipient -> phoneNumberUtils.compare(recipient, address) }
}
}?.id
}
}
override fun getOrCreateConversation(threadId: Long): Conversation? {
return getConversation(threadId) ?: getConversationFromCp(threadId)
}
override fun getOrCreateConversation(address: String): Conversation? {
return getOrCreateConversation(listOf(address))
}
override fun getOrCreateConversation(addresses: List<String>): Conversation? {
if (addresses.isEmpty()) {
return null
}
return (getThreadId(addresses) ?: tryOrNull { TelephonyCompat.getOrCreateThreadId(context, addresses.toSet()) })
?.takeIf { threadId -> threadId != 0L }
?.let { threadId ->
getConversation(threadId)
?.let(Realm.getDefaultInstance()::copyFromRealm)
?: getConversationFromCp(threadId)
}
}
override fun saveDraft(threadId: Long, draft: String) {
Realm.getDefaultInstance().use { realm ->
realm.refresh()
val conversation = realm.where(Conversation::class.java)
.equalTo("id", threadId)
.findFirst()
realm.executeTransaction {
conversation?.takeIf { it.isValid }?.draft = draft
}
}
}
override fun updateConversations(vararg threadIds: Long) {
Realm.getDefaultInstance().use { realm ->
realm.refresh()
threadIds.forEach { threadId ->
val conversation = realm
.where(Conversation::class.java)
.equalTo("id", threadId)
.findFirst() ?: return
val message = realm
.where(Message::class.java)
.equalTo("threadId", threadId)
.sort("date", Sort.DESCENDING)
.findFirst()
realm.executeTransaction {
conversation.lastMessage = message
}
}
}
}
override fun markArchived(vararg threadIds: Long) {
Realm.getDefaultInstance().use { realm ->
val conversations = realm.where(Conversation::class.java)
.anyOf("id", threadIds)
.findAll()
realm.executeTransaction {
conversations.forEach { it.archived = true }
}
}
}
override fun markUnarchived(vararg threadIds: Long) {
Realm.getDefaultInstance().use { realm ->
val conversations = realm.where(Conversation::class.java)
.anyOf("id", threadIds)
.findAll()
realm.executeTransaction {
conversations.forEach { it.archived = false }
}
}
}
override fun markPinned(vararg threadIds: Long) {
Realm.getDefaultInstance().use { realm ->
val conversations = realm.where(Conversation::class.java)
.anyOf("id", threadIds)
.findAll()
realm.executeTransaction {
conversations.forEach { it.pinned = true }
}
}
}
override fun markUnpinned(vararg threadIds: Long) {
Realm.getDefaultInstance().use { realm ->
val conversations = realm.where(Conversation::class.java)
.anyOf("id", threadIds)
.findAll()
realm.executeTransaction {
conversations.forEach { it.pinned = false }
}
}
}
override fun markBlocked(threadIds: List<Long>, blockingClient: Int, blockReason: String?) {
Realm.getDefaultInstance().use { realm ->
val conversations = realm.where(Conversation::class.java)
.anyOf("id", threadIds.toLongArray())
.equalTo("blocked", false)
.findAll()
realm.executeTransaction {
conversations.forEach { conversation ->
conversation.blocked = true
conversation.blockingClient = blockingClient
conversation.blockReason = blockReason
}
}
}
}
override fun markUnblocked(vararg threadIds: Long) {
Realm.getDefaultInstance().use { realm ->
val conversations = realm.where(Conversation::class.java)
.anyOf("id", threadIds)
.findAll()
realm.executeTransaction {
conversations.forEach { conversation ->
conversation.blocked = false
conversation.blockingClient = null
conversation.blockReason = null
}
}
}
}
override fun deleteConversations(vararg threadIds: Long) {
Realm.getDefaultInstance().use { realm ->
val conversation = realm.where(Conversation::class.java).anyOf("id", threadIds).findAll()
val messages = realm.where(Message::class.java).anyOf("threadId", threadIds).findAll()
realm.executeTransaction {
conversation.deleteAllFromRealm()
messages.deleteAllFromRealm()
}
}
threadIds.forEach { threadId ->
val uri = ContentUris.withAppendedId(Telephony.Threads.CONTENT_URI, threadId)
context.contentResolver.delete(uri, null, null)
}
}
/**
* Returns a [Conversation] from the system SMS ContentProvider, based on the [threadId]
*
* It should be noted that even if we have a valid [threadId], that does not guarantee that
* we can return a [Conversation]. On some devices, the ContentProvider won't return the
* conversation unless it contains at least 1 message
*/
private fun getConversationFromCp(threadId: Long): Conversation? {
return cursorToConversation.getConversationsCursor()
?.map(cursorToConversation::map)
?.firstOrNull { it.id == threadId }
?.let { conversation ->
val realm = Realm.getDefaultInstance()
val contacts = realm.copyFromRealm(realm.where(Contact::class.java).findAll())
val lastMessage = realm.where(Message::class.java).equalTo("threadId", threadId)
.sort("date", Sort.DESCENDING).findFirst()?.let(realm::copyFromRealm)
val recipients = conversation.recipients
.map { recipient -> recipient.id }
.map { id -> cursorToRecipient.getRecipientCursor(id) }
.mapNotNull { recipientCursor ->
// Map the recipient cursor to a list of recipients
recipientCursor?.use { recipientCursor.map { cursorToRecipient.map(recipientCursor) } }
}
.flatten()
.map { recipient ->
recipient.apply {
contact = contacts.firstOrNull {
it.numbers.any { phoneNumberUtils.compare(recipient.address, it.address) }
}
}
}
conversation.recipients.clear()
conversation.recipients.addAll(recipients)
conversation.lastMessage = lastMessage
realm.executeTransaction { it.insertOrUpdate(conversation) }
realm.close()
conversation
}
}
}
|
gpl-3.0
|
360c561902ae6baefe64e53e222b50bc
| 38.523605 | 120 | 0.554325 | 5.533954 | false | false | false | false |
JimSeker/ui
|
RecyclerViews/ModelViewRecyclerViewDemo_kt/app/src/main/java/edu/cs4730/modelviewrecyclerviewdemo_kt/myAdapter.kt
|
1
|
3441
|
package edu.cs4730.modelviewrecyclerviewdemo_kt
import android.util.Log
import androidx.recyclerview.widget.RecyclerView
import android.widget.TextView
import android.view.ViewGroup
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
/**
* this adapter is very similar to the adapters used for listview, except a ViewHolder is required
* see http://developer.android.com/training/improving-layouts/smooth-scrolling.html
* except instead having to implement a ViewHolder, it is implemented within
* the adapter.
*
* This code has a ViewModel/LiveData so that the click can be observed by the Fragment and mainActivity.
* Since the viewmodel can't be static, it is passed the viewholder.
* likely we should pass the viewmodel to the adapter instead of the fragment, but this example is showing
* how to get an instance all the three levels (activity, fragment, and adapter).
*/
class myAdapter(
private val myList: List<String>,
private val rowLayout: Int,
mFragment: Fragment
) : RecyclerView.Adapter<myAdapter.ViewHolder>() {
private val TAG = "myAdapter"
private val mViewModel: DataViewModel
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
class ViewHolder(view: View, mViewModel: DataViewModel) : RecyclerView.ViewHolder(view) {
var mName: TextView
var mButton: Button
private val TAG = "ViewHolder"
init {
mName = view.findViewById(R.id.name)
mButton = view.findViewById(R.id.myButton)
//use itemView instead of button, if you want a click listener for the whole layout.
//itemView.setOnClickListener(new View.OnClickListener() {
// Setup the click listener for the button
mButton.setOnClickListener { // Triggers the observer else where.
Log.wtf(TAG, "setting! " + mName.tag.toString())
mViewModel.setItem(mName.tag.toString())
}
}
}
// Create new views (invoked by the layout manager)
override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): ViewHolder {
val v = LayoutInflater.from(viewGroup.context).inflate(rowLayout, viewGroup, false)
return ViewHolder(v, mViewModel)
}
// Replace the contents of a view (invoked by the layout manager)
override fun onBindViewHolder(viewHolder: ViewHolder, i: Int) {
val entry = myList[i]
viewHolder.mName.text = entry
viewHolder.mName.tag = i //sample data to show.
}
// Return the size of your dataset (invoked by the layout manager)
override fun getItemCount(): Int {
return myList.size ?: 0
}
//constructor
init {
//interesting. while fragment will work, you need the activity, otherwise this viewmodel is not connected to the activity.
// key doesn't help in the get method.
//needed the activity, Doc's Creates a ViewModelProvider, which retains ViewModels while a scope of given Activity is alive.
mViewModel = ViewModelProvider(mFragment.requireActivity()).get(DataViewModel::class.java)
//likely the viewmodel should be passed the adapter instead. but it does work.
}
}
|
apache-2.0
|
a40ff8ddb217d486b9a56684c786168b
| 42.56962 | 132 | 0.70619 | 4.656292 | false | false | false | false |
mbuhot/eskotlin
|
src/main/kotlin/mbuhot/eskotlin/aggregation/NestedAggregation.kt
|
1
|
747
|
package mbuhot.eskotlin.aggregation
import org.elasticsearch.search.aggregations.AggregationBuilder
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder
data class NestedAggregationData(
var name: String? = null,
var path: String? = null,
var sub_aggregation: List<AggregationBuilder>? = null) {
fun sub_aggregation(f: () -> AggregationBuilder) {
sub_aggregation = listOf(f())
}
}
fun nested_aggregation(init: NestedAggregationData.() -> Unit): NestedAggregationBuilder {
val params = NestedAggregationData().apply(init)
return NestedAggregationBuilder(params.name, params.path).apply {
params.sub_aggregation?.forEach {
subAggregation(it)
}
}
}
|
mit
|
8c1aab1bf5e7c476be3330094654e210
| 33 | 90 | 0.722892 | 4.317919 | false | false | false | false |
laurencegw/jenjin
|
jenjin-core/src/main/kotlin/com/binarymonks/jj/core/async/FunctionClosure.kt
|
1
|
1833
|
package com.binarymonks.jj.core.async
import com.badlogic.gdx.utils.ObjectMap
import com.binarymonks.jj.core.pools.Poolable
import com.binarymonks.jj.core.pools.new
import com.binarymonks.jj.core.pools.recycle
import kotlin.reflect.KFunction
import kotlin.reflect.KParameter
/**
* Provides a closure of a function with its arguments. Can only be called once, because it recycles itself.
* This involves no object creation.
*/
fun capture(function: KFunction<*>, build: (FunctionClosureBuilder.() -> Unit)? = null): FunctionClosure {
val functionCapture = new(FunctionClosure::class).capture(function, build)
return functionCapture
}
/**
* Provides a closure of a function with its arguments. Can only be called once, because it recycles itself.
* This involves no object creation.
*/
class FunctionClosure : Poolable {
internal val args: ObjectMap<String, Any?> = ObjectMap()
internal val kparams: MutableMap<KParameter, Any?> = HashMap()
internal var function: KFunction<*>? = null
internal val argBuilder = FunctionClosureBuilder(this)
fun capture(function: KFunction<*>, build: (FunctionClosureBuilder.() -> Unit)? = null): FunctionClosure {
this.function = function
if (build != null) {
argBuilder.build()
}
return this
}
fun call() {
function!!.parameters.forEach {
if (args.containsKey(it.name)) {
kparams.put(it, args[it.name])
}
}
function!!.callBy(kparams)
recycle(this)
}
override fun reset() {
args.clear()
kparams.clear()
function = null
}
}
class FunctionClosureBuilder(
val functionClosure: FunctionClosure
) {
fun withArg(name: String, value: Any?) {
functionClosure.args.put(name, value)
}
}
|
apache-2.0
|
c29dd48f692dd2f7bb1b89edd149dd8e
| 29.065574 | 110 | 0.668849 | 4.223502 | false | false | false | false |
apiote/Bimba
|
app/src/main/java/ml/adamsprogs/bimba/models/Favourite.kt
|
1
|
5285
|
package ml.adamsprogs.bimba.models
import android.content.Context
import android.os.Parcel
import android.os.Parcelable
import ml.adamsprogs.bimba.ProviderProxy
import ml.adamsprogs.bimba.safeSplit
import java.io.File
import java.math.BigInteger
import java.security.SecureRandom
import kotlin.collections.*
class Favourite : Parcelable, ProviderProxy.OnDeparturesReadyListener {
private val cacheDir: File
private lateinit var listener: ProviderProxy.OnDeparturesReadyListener
var name: String
private set
var segments: HashSet<StopSegment>
private set
private var fullDepartures: Map<String, List<Departure>> = HashMap()
private val cache = HashMap<Plate.ID, List<Departure>>()
private var listenerId = ""
val size
get() = segments.sumBy {
it.size
}
private val providerProxy: ProviderProxy
constructor(parcel: Parcel) {
this.name = parcel.readString()!!
@Suppress("UNCHECKED_CAST")
val set = HashSet<StopSegment>()
val array = parcel.readParcelableArray(StopSegment::class.java.classLoader)!!
array.forEach {
set.add(it as StopSegment)
}
this.segments = set
this.cacheDir = File(parcel.readString())
val mapDir = File(parcel.readString())
val mapString = mapDir.readText()
val map = HashMap<String, List<Departure>>()
mapString.safeSplit("%")!!.forEach { it ->
val (k, v) = it.split("#")
map[k] = v.split("&").map { Departure.fromString(it) }
}
this.fullDepartures = map
mapDir.delete()
providerProxy = ProviderProxy()
}
constructor(name: String, segments: HashSet<StopSegment>, cache: Map<String, List<Departure>>, context: Context) {
this.fullDepartures = cache
this.name = name
this.segments = segments
this.cacheDir = context.cacheDir
providerProxy = ProviderProxy(context)
}
constructor(name: String, timetables: HashSet<StopSegment>, context: Context) {
this.name = name
this.segments = timetables
this.cacheDir = context.cacheDir
providerProxy = ProviderProxy(context)
}
override fun describeContents(): Int {
return Parcelable.CONTENTS_FILE_DESCRIPTOR
}
override fun writeToParcel(dest: Parcel?, flags: Int) {
dest?.writeString(name)
val parcelableSegments = segments.map { it }.toTypedArray()
dest?.writeParcelableArray(parcelableSegments, flags)
dest?.writeString(cacheDir.absolutePath)
val bytes = ByteArray(4) { 0 }
SecureRandom().nextBytes(bytes)
val mapFile = File(cacheDir, BigInteger(1, bytes).toString(16))
dest?.writeString(mapFile.absolutePath)
var isFirst = true
var map = ""
fullDepartures.forEach { it ->
if (isFirst)
isFirst = false
else
map += '%'
map += "${it.key}#${it.value.joinToString("&") { it.toString() }}"
}
mapFile.writeText(map)
}
fun delete(plateId: Plate.ID): Boolean {
segments.forEach {
if (!it.remove(plateId))
return false
}
removeFromCache(plateId)
return true
}
fun rename(newName: String) {
name = newName
}
companion object CREATOR : Parcelable.Creator<Favourite> {
override fun createFromParcel(parcel: Parcel): Favourite {
return Favourite(parcel)
}
override fun newArray(size: Int): Array<Favourite?> {
return arrayOfNulls(size)
}
}
fun nextDeparture() =
if (cache.isEmpty())
null
else
cache.flatMap { it.value }.let { it ->
if (it.isEmpty())
null
else
it.sortedBy { it.time }[0]
}
fun fullTimetable(): Map<String, List<Departure>> {
if (fullDepartures.isEmpty())
fullDepartures = providerProxy.getFullTimetable(segments)
return fullDepartures
}
private fun removeFromCache(plate: Plate.ID) {
val map = HashMap<String, List<Departure>>()
fullDepartures
fullDepartures.forEach { it ->
map[it.key] = it.value.filter { plate.line != it.line || plate.headsign != it.headsign }
}
fullDepartures = map
}
fun subscribeForDepartures(listener: ProviderProxy.OnDeparturesReadyListener, context: Context): String {
this.listener = listener
listenerId = providerProxy.subscribeForDepartures(segments, this, context)
return listenerId
}
override fun onDeparturesReady(departures: List<Departure>, plateId: Plate.ID?, code: Int) {
if (plateId == null) {
cache.clear()
cache[Plate.ID.dummy] = departures
} else {
cache.remove(Plate.ID.dummy)
cache[plateId] = departures
}
listener.onDeparturesReady(departures, plateId, code)
}
fun unsubscribeFromDepartures(context: Context) {
providerProxy.unsubscribeFromDepartures(listenerId, context)
}
}
|
gpl-3.0
|
ad5b61d1ab69c12f4649bf6182f5c024
| 30.272189 | 118 | 0.608136 | 4.544282 | false | false | false | false |
Groostav/sojourn-CVG
|
src/main/kotlin/com/empowerops/sojourn/sojourn.kt
|
1
|
14777
|
@file:JvmName("Sojourn")
package com.empowerops.sojourn
import com.empowerops.babel.BabelExpression
import com.microsoft.z3.Status
import kotlinx.collections.immutable.ImmutableList
import kotlinx.collections.immutable.immutableListOf
import kotlinx.collections.immutable.plus
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.produce
import kotlinx.coroutines.selects.select
import java.lang.IndexOutOfBoundsException
import java.text.DecimalFormat
import java.util.*
val SOLUTION_PAGE_SIZE = 10_000
val EASY_PATH_THRESHOLD_FACTOR = 0.1
val WARMUP_ROUNDS = 5
private data class DependencyGroup(var deps: Set<String>, var constraints: Set<BabelExpression>) {
override fun toString(): String = "DependencyGroup(deps=$deps, constraints={${constraints.joinToString { it.expressionLiteral }}})"
}
sealed class ConstraintAnalysis
sealed class Worthwhile(val results: ReceiveChannel<InputVector>): ConstraintAnalysis(), ReceiveChannel<InputVector> by results
class Satisfiable(results: ReceiveChannel<InputVector>): Worthwhile(results)
class Unknown(results: ReceiveChannel<InputVector>, val problemConstraint: BabelExpression?): Worthwhile(results)
class Unsatisfiable(val problemConstraint: BabelExpression?): ConstraintAnalysis()
fun CoroutineScope.makeSampleAgent(
inputs: List<InputVariable>,
constraints: Collection<BabelExpression>,
seeds: ImmutableList<InputVector> = immutableListOf(),
samplerSeed: Random = Random(),
improverSeed: Random = Random()
): ConstraintAnalysis {
inputs.duplicates().let { require(it.isEmpty()) { "duplicate inputs: $it" } }
val dependencyGroups = mutableListOf<DependencyGroup>()
for(constraint in constraints){
if(constraint.containsDynamicLookup){
//only the global group can solve for this one
continue
}
val merging = constraint.staticallyReferencedSymbols.flatMap { varName ->
dependencyGroups.filter { varName in it.deps }
}
when(merging.size) {
0 -> dependencyGroups += DependencyGroup(constraint.staticallyReferencedSymbols, setOf(constraint))
1 -> merging.single().apply {
this.deps += constraint.staticallyReferencedSymbols
this.constraints += constraint
}
else -> {
val receiver = merging.first()
receiver.apply {
this.deps += constraint.staticallyReferencedSymbols
this.constraints += constraint
}
val deletions = merging.drop(1)
for(deletion in deletions){
receiver.deps += deletion.deps
receiver.constraints += deletion.constraints
dependencyGroups -= deletion
}
}
}
}
trace {
"found groups ${dependencyGroups.joinToString()}"
}
val globalGroup = startAgentGroup(inputs, constraints, samplerSeed, improverSeed, seeds)
if(globalGroup is Unsatisfiable) return globalGroup
when(dependencyGroups.size) {
1 -> {
require(dependencyGroups.single().deps == inputs.map { it.name }.toSet())
return globalGroup
}
else -> {
// TODO: it might make more sense to create a kind of composite constraint solving pool,
// the reason being is that we can then use the same load balancing as previous
val parts = dependencyGroups.associate { group ->
group to (startAgentGroup(inputs.filter { it.name in group.deps }, group.constraints, samplerSeed, improverSeed, seeds) as Worthwhile)
}
require(globalGroup is Worthwhile)
val pts = globalGroup + produce<InputVector> {
try {
while (isActive) {
val pointsBySource = parts.mapValues { (_, channel) ->
channel.receiveOrNull()
}
if (null in pointsBySource.values) {
val extras = pointsBySource.filterValues { it != null }
if (extras.any()) trace {
val names = pointsBySource.entries.joinToString { (group, pt) ->
"${group.deps}->${pt?.let { "pt" } ?: "null"}"
}
"one or more dependency groups quit while one or more produced more results: $names"
}
return@produce
}
send(InputVector(pointsBySource.values.flatMap { it!!.entries }))
}
}
finally {
globalGroup.cancel()
parts.values.forEach { it.cancel() }
}
}
return when(globalGroup){
is Unsatisfiable -> TODO()
is Satisfiable -> Satisfiable(pts)
is Unknown -> Unknown(pts, globalGroup.problemConstraint)
}
}
}
}
@UseExperimental(InternalCoroutinesApi::class)
operator fun <T> ReceiveChannel<T>.plus(right: ReceiveChannel<T>) = GlobalScope.produce<T>(onCompletion = { cancel(); right.cancel() }) {
val left = this@plus
while(isActive){
val next = select<T> {
if(! left.isClosedForReceive) left.onReceive { it }
if(! right.isClosedForReceive) right.onReceive { it }
}
send(next)
if(left.isClosedForReceive && right.isClosedForReceive) break
}
}
fun <T> List<List<T>>.asTransposedRegular(): List<List<T>> = object: AbstractList<List<T>>() {
//in outputs terms
val columns = this@asTransposedRegular
init {
require(columns.isEmpty() || columns.map { it.size }.distinct().size == 1)
}
val rowCount = columns.firstOrNull()?.size ?: 0
val colCount = columns.size
override fun get(rowIndex: Int): AbstractList<T> {
if(rowIndex < 0 || rowIndex >= rowCount) throw IndexOutOfBoundsException("rowIndex=$rowIndex in matrix with $rowCount rows")
return object: AbstractList<T>() {
override fun get(columnIndex: Int): T = columns[columnIndex][rowIndex]
override val size: Int get() = colCount
}
}
override val size get() = rowCount
}
private fun <T> List<T>.duplicates(): List<T> =
groupBy { it }.filter { it.value.size >= 2 }.flatMap { it.value }
private fun CoroutineScope.startAgentGroup(
inputs: List<InputVariable>,
constraints: Collection<BabelExpression>,
samplerSeed: Random,
improverSeed: Random,
seeds: ImmutableList<InputVector>
): ConstraintAnalysis {
val inputNames = inputs.map { it.name }
val fairSampler = RandomSamplingPool.create(inputs, constraints)
val adaptiveSampler = RandomSamplingPool.Factory(samplerSeed, true).create(inputs, constraints)
val improover = RandomBoundedWalkingImproverPool.Factory(improverSeed).create(inputs, constraints)
val smt = Z3SolvingPool.create(inputs, constraints)
val smtState = smt.check()
if (smtState == Status.UNSATISFIABLE) {
trace { "unsat" }
return Unsatisfiable(smt.problem)
}
val pts = produce<InputVector>(Dispatchers.Default) {
val initialRoundTarget = SOLUTION_PAGE_SIZE
val initialResults = fairSampler.makeNewPointGeneration(initialRoundTarget, seeds)
trace { "initial-sampling gen hit ${((100.0 * initialResults.size) / initialRoundTarget).toInt()}%" }
when {
initialResults.size > EASY_PATH_THRESHOLD_FACTOR * initialRoundTarget -> {
trace { "easy: $inputNames" }
var results = initialResults
while (isActive) {
val nextGen = fairSampler.makeNewPointGeneration(SOLUTION_PAGE_SIZE, results + seeds)
results += nextGen
nextGen.forEach { send(it) }
}
}
else -> {
trace { "balancing: $inputNames" }
var pool = seeds + initialResults
var publishedPoints = immutableListOf<InputVector>()
var targets = listOf(fairSampler, adaptiveSampler, improover)
.associate { it to SOLUTION_PAGE_SIZE / 3 }
.let { it + (smt to 5) }
var roundNo = 1
var roundHadProgress = true
val inputNames = inputs.map { it.name }
while (isActive) try {
trace {
"round start: " + targets.entries.joinToString { (solver, target) -> "${solver.name}($target)" }
}
val resultsAsync: Map<ConstraintSolvingPool, Deferred<PoolResult>> = targets
.mapValues { (solver, target) ->
async(Dispatchers.Default) {
val (time, pts) = measureTime { solver.makeNewPointGeneration(target, pool) }
val (centroid, variance) = findDispersion(inputNames, pts)
PoolResult(time, pts, centroid, variance.takeIf { !it.isNaN() } ?: 0.0)
}
}
val results: Map<ConstraintSolvingPool, PoolResult> = resultsAsync
.mapValues { (_, deferred) -> deferred.await() }
val overheadStartTime = System.currentTimeMillis()
val roundResults = results.values.flatMap { (_, points) -> points }
pool += roundResults
val newQualityResults = roundResults.filter { constraints.passFor(it) }
trace {
val dispersion = findDispersion(inputNames, newQualityResults)
"round results: " +
"feasible=${newQualityResults.size}, " +
"dispersion=${dispersion.variance} " +
results.entries.joinToString { (solver, result) ->
"${solver.name}(${result.points.size}, " +
"${TwoSigFigs.format(result.timeMillis)}ms, " +
"${TwoSigFigsWithE.format(result.variance)}σ)"
}
}
if (newQualityResults.isEmpty()) {
trace { "no-yards!!" }
roundHadProgress = false
}
if (roundNo > WARMUP_ROUNDS) {
newQualityResults.forEach{ send(it) }
publishedPoints += newQualityResults
} else trace { "dropped ${newQualityResults.size} pts on warmup round $roundNo" }
// we balance on performance, unless any pool has a variance significantly worse than the others,
// then we avoid that pool
val speedSum = results.values.sumByDouble { (t, pts, _, _) -> 1.0 * pts.size / t }
targets = results.mapValues { (pool, result) ->
val speed = 1.0 * result.points.size / result.timeMillis
fail;// ok, running with 'x1 < 0.0001^(x2+1)' scares me
// notice that the improver offers a much higher variance
// but we still pick the adaptive sampler, which doenst appear to be adapting very well.
// hmm.
// i think that we should actually just publish results from the pool with the highest variance
// also, as another feature, the adaptive random sampling pool could "split" into multiple pools,
// if it is able to detect invalid regions.... does that work at 100 vars?
(SOLUTION_PAGE_SIZE * speed / speedSum).toInt()
}
val previousTargets = targets
val varianceSum = results.values.sumByDouble { it.variance }
val varianceAverage = varianceSum / results.values.size
targets = targets.mapValues { (pool, previousTime) ->
val minimumVarianceParticipation = 1.0 / (targets.size * 2)
val thisPoolVariance = results.getValue(pool).variance
if (thisPoolVariance / varianceSum < minimumVarianceParticipation) {
if (previousTargets.getValue(pool) != 0) {
trace { "dropped execution of ${pool.name} as its variance was $thisPoolVariance (average is $varianceAverage)" }
}
0
} else previousTime
}
trace {
"overhead: ${System.currentTimeMillis() - overheadStartTime}ms"
}
} finally {
if(roundHadProgress) roundNo += 1
roundHadProgress = true
}
}
}
}
return when(smtState){
Status.SATISFIABLE -> Satisfiable(pts)
Status.UNKNOWN -> Unknown(pts, smt.problem)
Status.UNSATISFIABLE -> TODO()
}
}
data class PoolResult(val timeMillis: Long, val points: List<InputVector>, val centroid: InputVector, val variance: Double)
data class Dispersion(val centroid: InputVector, val variance: Double)
fun findDispersion(names: List<String>, points: List<InputVector>): Dispersion {
val center = findCenter(names, points)
// as per a simple euclidian distence:
// https://stats.stackexchange.com/questions/13272/2d-analog-of-standard-deviation
val deviation = if(points.isEmpty()) Double.NaN else points.sumByDouble { point ->
val r = point.keys.sumByDouble { Math.pow(point[it]!! - center[it]!!, 2.0) }
return@sumByDouble Math.sqrt(r)
}
return Dispersion(center, deviation / points.size)
}
fun findCenter(names: List<String>, points: List<InputVector>): InputVector {
var center = points.firstOrNull()?.mapValues { _, _ -> 0.0 }
?: return names.associate { it to Double.NaN }.toInputVector()
for(point in points){
center = center vecPlus point
}
center /= points.size.toDouble()
return center
}
private val TwoSigFigs = DecimalFormat("0.##")
private val TwoSigFigsWithE = DecimalFormat("0.##E0")
|
apache-2.0
|
77a90660056d3ecdd96aad8947e57201
| 39.596154 | 150 | 0.569978 | 4.860526 | false | false | false | false |
rustamgaifullin/TranslateIt
|
api/src/main/kotlin/com/rm/translateit/api/translation/source/babla/BablaModule.kt
|
1
|
1303
|
package com.rm.translateit.api.translation.source.babla
import com.rm.translateit.api.translation.source.HtmlParser
import com.rm.translateit.api.translation.source.Source
import dagger.Module
import dagger.Provides
import dagger.multibindings.IntoSet
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import javax.inject.Singleton
@Module
internal class BablaModule {
@Provides
@Singleton
fun url() = BablaUrl()
@Provides
@Singleton
fun parser(): HtmlParser = BablaHtmlParser()
@Provides @IntoSet
@Singleton
fun service(
restService: BablaRestService,
url: BablaUrl,
htmlParser: HtmlParser
): Source = BablaSource(restService, url, htmlParser)
@Provides
@Singleton
fun restService(okHttpClient: OkHttpClient) = Retrofit.Builder()
.client(okHttpClient)
.baseUrl("http://bab.la")
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build()
.create(BablaRestService::class.java)
@Provides
@Singleton
fun okHttpClient(interceptor: Interceptor) = OkHttpClient.Builder()
.followRedirects(false)
.addInterceptor(interceptor)
.build()
@Provides
@Singleton
fun interceptor(): Interceptor = BablaInterceptor()
}
|
mit
|
be7859ddf7dc35d08e9cb38070bc2347
| 24.076923 | 69 | 0.755948 | 4.35786 | false | false | false | false |
tokenbrowser/token-android-client
|
app/src/main/java/com/toshi/view/activity/webView/HeaderParser.kt
|
1
|
1799
|
/*
* Copyright (c) 2017. Toshi Inc
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.toshi.view.activity.webView
import okhttp3.Response
class HeaderParser {
companion object {
const val DEFAULT_CHARSET = "text/html"
const val DEFAULT_MIME_TYPE = "utf-8"
}
fun getMimeType(contentType: String): String {
val regexResult = Regex("^.*(?=;)").find(contentType)
return regexResult?.value ?: DEFAULT_MIME_TYPE
}
fun getCharset(contentType: String): String {
val regexResult = Regex(
"charset=([a-zA-Z0-9-]+)",
RegexOption.IGNORE_CASE
).find(contentType)
val groupValues = regexResult?.groupValues ?: return DEFAULT_CHARSET
return if (groupValues.size != 2) DEFAULT_CHARSET
else regexResult.groupValues[1]
}
fun getContentTypeHeader(response: Response): String {
val headers = response.headers()
val contentType = headers.get("Content-Type")
?: headers.get("content-Type")
?: "text/html; charset=utf-8"
contentType.trim()
return contentType
}
}
|
gpl-3.0
|
7292ac642f61d434bb18625cb3e4be56
| 33.615385 | 76 | 0.645914 | 4.273159 | false | false | false | false |
sybila/biodivine-ctl
|
src/main/java/com/github/sybila/biodivine/exe/Z3Main.kt
|
1
|
9775
|
package com.github.sybila.biodivine.exe
import com.github.sybila.checker.Checker
import com.github.sybila.checker.CheckerStats
import com.github.sybila.checker.SequentialChecker
import com.github.sybila.checker.StateMap
import com.github.sybila.checker.channel.connectWithSharedMemory
import com.github.sybila.checker.partition.asUniformPartitions
import com.github.sybila.checker.solver.SolverStats
import com.github.sybila.huctl.Formula
import com.github.sybila.ode.generator.NodeEncoder
import com.github.sybila.ode.generator.smt.local.Z3OdeFragment
import com.github.sybila.ode.generator.smt.local.Z3Params
import com.github.sybila.ode.generator.smt.remote.bridge.SMT
import com.github.sybila.ode.generator.smt.remote.bridge.readSMT
import com.github.sybila.ode.model.OdeModel
import com.google.gson.Gson
import com.microsoft.z3.Expr
import java.io.PrintStream
import java.util.*
fun z3Main(config: MainConfig, model: OdeModel, properties: Map<String, Formula>, logStream: PrintStream?) {
val resultStream: PrintStream? = config.resultOutput.readStream()
if (config.logLevel >= LogLevel.INFO) {
SolverStats.reset(logStream)
}
if (config.logLevel >= LogLevel.VERBOSE) {
CheckerStats.reset(logStream)
}
if (true) {
val fragment = Z3OdeFragment(model, createSelfLoops = !config.disableSelfLoops)
SequentialChecker(fragment).use { checker ->
fragment.run {
val r = checker.verify(properties)
logStream?.println("Verification finished. Processing results...")
if (config.resultType != ResultType.JSON) {
val encoder = NodeEncoder(model)
for ((property, valid) in r) {
resultStream?.println(property)
for ((s, v) in valid.entries()) {
resultStream?.println("${s.prettyPrint(model, encoder)} -> Params(${v.prettyPrint()})")
}
}
} else {
resultStream?.println(printZ3Results(model, r))
}
}
}
} else {
val m = (0 until config.parallelism).map {
com.github.sybila.ode.generator.smt.remote.Z3OdeFragment(
model, createSelfLoops = !config.disableSelfLoops
)
}
val models = m.asUniformPartitions()
Checker(models.connectWithSharedMemory()).use { checker ->
val r = checker.verify(properties)
logStream?.println("Verification finished. Processing results...")
if (config.resultType != ResultType.JSON) {
val encoder = NodeEncoder(model)
for ((property, valid) in r) {
resultStream?.println(property)
valid.zip(models).forEach {
it.second.run {
it.first.entries().forEach {
resultStream?.println("${it.first.prettyPrint(model, encoder)} -> Params(${it.second.prettyPrint()})")
}
}
}
}
} else {
m.first().run {
resultStream?.println(printSMTResult(model, r))
}
}
}
}
if (config.logLevel >= LogLevel.INFO) {
SolverStats.printGlobal()
}
if (config.logLevel >= LogLevel.VERBOSE) {
CheckerStats.printGlobal()
}
logStream?.close()
resultStream?.close()
}
internal class SMTResult(
val smtlib2Formula: String,
val Rexpression: String
)
internal fun Expr.toR(): String {
return when {
//boolean
this.isAnd -> "(" + this.args.map(Expr::toR).joinToString(separator = " & ") + ")"
this.isOr -> "(" + this.args.map(Expr::toR).joinToString(separator = " | ") + ")"
this.isAdd -> "("+ this.args.map(Expr::toR).joinToString(separator = " + ")+")"
this.isSub -> "("+ this.args.map(Expr::toR).joinToString(separator = " - ")+")"
this.isMul -> "("+ this.args.map(Expr::toR).joinToString(separator = " * ")+")"
this.isDiv -> "("+ this.args.map(Expr::toR).joinToString(separator = " / ")+")"
this.isGT -> "(${this.args[0].toR()} > ${this.args[1].toR()})"
this.isGE -> "(${this.args[0].toR()} >= ${this.args[1].toR()})"
this.isLT -> "(${this.args[0].toR()} < ${this.args[1].toR()})"
this.isLE -> "(${this.args[0].toR()} <= ${this.args[1].toR()})"
this.isNot -> "(!${this.args[0].toR()})"
this.isTrue -> "TRUE"
this.isFalse -> "FALSE"
this.isConst -> "ip\$$this"
this.isInt || this.isReal -> this.toString()
else -> throw IllegalStateException("Unsupported formula: $this")
}
}
private fun Z3OdeFragment.printZ3Results(model: OdeModel, result: Map<String, StateMap<Z3Params>>): String {
val statesIndexMapping = HashMap<Int, Int>()
val states = ArrayList<Int>()
val paramsIndexMapping = HashMap<Z3Params, Int>()
val params = ArrayList<Z3Params>()
val map = ArrayList<Result>()
for ((f, r) in result) {
val rMap = ArrayList<List<Int>>()
for ((s, p) in r.entries()) {
val stateIndex = statesIndexMapping.computeIfAbsent(s) {
states.add(s)
states.size -1
}
val paramIndex = paramsIndexMapping.computeIfAbsent(p) {
params.add(p)
params.size - 1
}
rMap.add(listOf(stateIndex, paramIndex))
}
map.add(Result(f, rMap))
}
val coder = NodeEncoder(model)
val r = ResultSet(
variables = model.variables.map { it.name },
parameters = model.parameters.map { it.name },
thresholds = model.variables.map { it.thresholds },
states = states.map { it.expand(model, coder) },
type = "smt",
results = map,
parameterValues = params.map {
it.minimize()
SMTResult(
smtlib2Formula = it.formula.toString(),
Rexpression = it.formula.toR()
)
},
parameterBounds = model.parameters.map { listOf(it.range.first, it.range.second) }
)
val printer = Gson()
return printer.toJson(r)
}
private fun com.github.sybila.ode.generator.smt.remote.Z3OdeFragment.printSMTResult(
model: OdeModel, result: Map<String, List<StateMap<com.github.sybila.ode.generator.smt.remote.Z3Params>>>
): String {
val statesIndexMapping = HashMap<Int, Int>()
val states = ArrayList<Int>()
val paramsIndexMapping = HashMap<com.github.sybila.ode.generator.smt.remote.Z3Params, Int>()
val params = ArrayList<com.github.sybila.ode.generator.smt.remote.Z3Params>()
val map = ArrayList<Result>()
for ((f, r) in result) {
val rMap = ArrayList<List<Int>>()
for (partitionResult in r) {
for ((s, p) in partitionResult.entries()) {
val stateIndex = statesIndexMapping.computeIfAbsent(s) {
states.add(s)
states.size -1
}
val paramIndex = paramsIndexMapping.computeIfAbsent(p) {
params.add(p)
params.size - 1
}
rMap.add(listOf(stateIndex, paramIndex))
}
}
map.add(Result(f, rMap))
}
val coder = NodeEncoder(model)
val r = ResultSet(
variables = model.variables.map { it.name },
parameters = model.parameters.map { it.name },
thresholds = model.variables.map { it.thresholds },
states = states.map { it.expand(model, coder) },
type = "smt",
results = map,
parameterValues = params.map {
it.minimize(true)
SMTResult(
smtlib2Formula = it.formula,
Rexpression = it.formula.readSMT().toR(model)
)
},
parameterBounds = model.parameters.map { listOf(it.range.first, it.range.second) }
)
val printer = Gson()
return printer.toJson(r)
}
internal fun SMT.toR(model: OdeModel): String {
val paramNames = model.parameters.map { it.name }
return when(this) {
is SMT.Terminal -> when(this.data) {
"true" -> "TRUE"
"false" -> "FALSE"
in paramNames -> "ip\$${this.data}"
else -> this.data
}
is SMT.Expression -> when (this.funName) {
"and" -> "(" + this.funArgs.map { it.toR(model) }.joinToString(separator = " & ") + ")"
"or" -> "(" + this.funArgs.map { it.toR(model) }.joinToString(separator = " | ") + ")"
"+" -> "(" + this.funArgs.map { it.toR(model) }.joinToString(separator = " + ") + ")"
"-" -> "(" + this.funArgs.map { it.toR(model) }.joinToString(separator = " - ") + ")"
"*" -> "(" + this.funArgs.map { it.toR(model) }.joinToString(separator = " * ") + ")"
"/" -> "(" + this.funArgs.map { it.toR(model) }.joinToString(separator = " / ") + ")"
">" -> "(${this.funArgs[0].toR(model)} > ${this.funArgs[1].toR(model)})"
">=" -> "(${this.funArgs[0].toR(model)} >= ${this.funArgs[1].toR(model)})"
"<" -> "(${this.funArgs[0].toR(model)} < ${this.funArgs[1].toR(model)})"
"<=" -> "(${this.funArgs[0].toR(model)} <= ${this.funArgs[1].toR(model)})"
"not" -> "(!${this.funArgs[0].toR(model)})"
else -> throw IllegalStateException("Unsupported formula: $this")
}
}
}
|
gpl-3.0
|
836780156fe8759381f9e03f8eb7cd82
| 39.564315 | 134 | 0.552225 | 4.02429 | false | false | false | false |
apoi/quickbeer-android
|
app/src/main/java/quickbeer/android/data/room/Database.kt
|
2
|
1215
|
package quickbeer.android.data.room
import androidx.room.Database
import androidx.room.RoomDatabase
import quickbeer.android.domain.beer.store.BeerDao
import quickbeer.android.domain.beer.store.BeerEntity
import quickbeer.android.domain.brewer.store.BrewerDao
import quickbeer.android.domain.brewer.store.BrewerEntity
import quickbeer.android.domain.idlist.store.IdListDao
import quickbeer.android.domain.idlist.store.IdListEntity
import quickbeer.android.domain.review.store.ReviewDao
import quickbeer.android.domain.review.store.ReviewEntity
import quickbeer.android.domain.style.store.StyleDao
import quickbeer.android.domain.style.store.StyleEntity
const val DATABASE_NAME = "quickbeer.db"
const val BATCH_SIZE = 999
private const val CURRENT_VERSION = 1
@Database(
entities = [
IdListEntity::class,
BeerEntity::class,
BrewerEntity::class,
ReviewEntity::class,
StyleEntity::class
],
version = CURRENT_VERSION
)
abstract class Database : RoomDatabase() {
abstract fun idListDao(): IdListDao
abstract fun beerDao(): BeerDao
abstract fun brewerDao(): BrewerDao
abstract fun reviewDao(): ReviewDao
abstract fun styleDao(): StyleDao
}
|
gpl-3.0
|
74190893c518d6a2f7e76c4057387f09
| 27.928571 | 57 | 0.775309 | 4.090909 | false | false | false | false |
SpryServers/sprycloud-android
|
src/main/java/com/nextcloud/client/logger/FileLogHandler.kt
|
3
|
4036
|
/*
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* Copyright (C) 2019 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.logger
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
import java.nio.charset.Charset
/**
* Very simple log writer with file rotations.
*
* Files are rotated when writing entry causes log file to exceed it's maximum size.
* Last entry is not truncated and final log file can exceed max file size, but
* no further entries will be written to it.
*/
internal class FileLogHandler(private val logDir: File, private val logFilename: String, private val maxSize: Long) {
data class RawLogs(val lines: List<String>, val logSize: Long)
companion object {
const val ROTATED_LOGS_COUNT = 3
}
private var writer: FileOutputStream? = null
private var size: Long = 0
private val rotationList = listOf(
"$logFilename.2",
"$logFilename.1",
"$logFilename.0",
logFilename
)
val logFile: File
get() {
return File(logDir, logFilename)
}
val isOpened: Boolean
get() {
return writer != null
}
val maxLogFilesCount get() = rotationList.size
fun open() {
try {
writer = FileOutputStream(logFile, true)
size = logFile.length()
} catch (ex: FileNotFoundException) {
logFile.parentFile.mkdirs()
writer = FileOutputStream(logFile, true)
size = logFile.length()
}
}
fun write(logEntry: String) {
val rawLogEntry = logEntry.toByteArray(Charset.forName("UTF-8"))
writer?.write(rawLogEntry)
size += rawLogEntry.size
if (size > maxSize) {
rotateLogs()
}
}
fun close() {
writer?.close()
writer = null
size = 0L
}
fun deleteAll() {
rotationList
.map { File(logDir, it) }
.forEach { it.delete() }
}
fun rotateLogs() {
val rotatatingOpenedLog = isOpened
if (rotatatingOpenedLog) {
close()
}
val existingLogFiles = logDir.listFiles().associate { it.name to it }
existingLogFiles[rotationList.first()]?.delete()
for (i in 0 until rotationList.size - 1) {
val nextFile = File(logDir, rotationList[i])
val previousFile = existingLogFiles[rotationList[i + 1]]
previousFile?.renameTo(nextFile)
}
if (rotatatingOpenedLog) {
open()
}
}
fun loadLogFiles(rotated: Int = ROTATED_LOGS_COUNT): RawLogs {
if (rotated < 0) {
throw IllegalArgumentException("Negative index")
}
val allLines = mutableListOf<String>()
var size = 0L
for (i in 0..Math.min(rotated, rotationList.size - 1)) {
val file = File(logDir, rotationList[i])
if (!file.exists()) continue
try {
val lines = file.readLines(Charsets.UTF_8)
allLines.addAll(lines)
size += file.length()
} catch (ex: IOException) {
// ignore failing file
}
}
return RawLogs(lines = allLines, logSize = size)
}
}
|
gpl-2.0
|
5b64172cc8eb0adce7aeb484129f8c99
| 28.896296 | 117 | 0.611249 | 4.406114 | false | false | false | false |
youkai-app/Youkai
|
app/src/main/kotlin/app/youkai/ui/feature/media/characters/CharactersActivity.kt
|
1
|
3414
|
package app.youkai.ui.feature.media.characters
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Spinner
import app.youkai.R
import app.youkai.data.models.ext.MediaType
import app.youkai.ui.common.app.FragmentContainerActivity
class CharactersActivity : FragmentContainerActivity<CharactersActivityView, CharactersActivityPresenter>(), CharactersActivityView {
override fun createPresenter(): CharactersActivityPresenter = CharactersActivityPresenter()
private var fragment: CharactersFragment? = null
private var spinner: Spinner? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
presenter.load(intent)
}
override fun newFragment(): Fragment {
val extras = intent.extras
val id = extras.getString(ARG_MEDIA_ID)
val type = extras.getString(ARG_MEDIA_TYPE)
val title = extras.getString(ARG_MEDIA_TITLE)
fragment = CharactersFragment.new(id, MediaType.fromString(type), title)
return fragment!!
}
@SuppressLint("RtlHardcoded")
override fun setUpLanguageSelector(languages: List<String>) {
val adapter = ArrayAdapter<String>(this, R.layout.item_spinner_language, languages)
adapter.setDropDownViewResource(R.layout.item_spinner_language_dropdown)
spinner = layoutInflater.inflate(
R.layout.view_spinner_toolbar,
getToolbar(),
false
) as Spinner
spinner?.adapter = adapter
spinner?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
var currentLanguage: String = ""
override fun onNothingSelected(parent: AdapterView<*>?) {
/* do nothing */
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
val selectedLanguage = adapter.getItem(position)
if (currentLanguage != selectedLanguage) {
presenter.onLanguageSelected(selectedLanguage)
currentLanguage = selectedLanguage
}
}
}
getToolbar().addView(spinner)
presenter.onLanguageSpinnerSetUp(languages)
}
override fun setLanguage(index: Int) {
spinner?.setSelection(index)
}
override fun passErrorToFragment(e: Throwable) {
fragment?.errorListener?.invoke(e)
}
override fun passLanguageToFragment(language: String) {
fragment?.languageChangedListener?.invoke(language)
}
companion object {
const val ARG_MEDIA_ID = "media_id"
const val ARG_MEDIA_TYPE = "media_type"
const val ARG_MEDIA_TITLE = "media_title"
fun getLaunchIntent(context: Context, mediaId: String, mediaType: MediaType,
mediaTitle: String): Intent {
val intent = Intent(context, CharactersActivity::class.java)
intent.putExtra(ARG_MEDIA_ID, mediaId)
intent.putExtra(ARG_MEDIA_TYPE, mediaType.value)
intent.putExtra(ARG_MEDIA_TITLE, mediaTitle)
return intent
}
}
}
|
gpl-3.0
|
4e67ef11d9b6777786e2c4aad83ab949
| 34.195876 | 133 | 0.673404 | 4.947826 | false | false | false | false |
gilbertguevara/free-we-code-challenge
|
mainProject/src/main/kotlin/main.kt
|
1
|
1645
|
import org.example.datepicker.DatePicker
import org.example.datepicker.datePickerModel
import org.example.timepicker.TimePicker
import org.example.toShortString
import org.w3c.dom.HTMLElement
import org.w3c.dom.HTMLInputElement
import kotlin.browser.document
/**
* Main function
*/
fun main(args: Array<String>) {
val inputDatePicker = document.getElementById("datepickerinput") as HTMLInputElement
val inputTimePicker = document.getElementById("timepickerinput") as HTMLInputElement
val timePicker = TimePicker(inputTimePicker)
val params = datePickerModel(inputDatePicker, showFilters = true, onSelect = { date ->
timePicker.changeDate(date)
})
val datePicker = DatePicker(params)
val saveButton = document.getElementById("save") as HTMLElement
saveButton.onclick = {
buildMessage(datePicker, timePicker)
}
val cancelButton = document.getElementById("cancel") as HTMLElement
cancelButton.onclick = {
cancel(datePicker, timePicker)
}
}
/**
* Clear out the form resetting all the values to the default ones
*/
private fun cancel(datePicker: DatePicker, timePicker: TimePicker) {
datePicker.clear()
timePicker.reset()
val message = document.getElementById("message") as HTMLElement
message.innerText = ""
}
/**
* Build the message to be shown when saving the
*/
private fun buildMessage(datePicker: DatePicker, timePicker: TimePicker) {
val message = document.getElementById("message") as HTMLElement
message.innerText = "Good! Your appointment is set for ${datePicker.getDate().toShortString()} at ${timePicker.selectedTime}. Thanks."
}
|
mit
|
5ef194c259930e3084cfb321ca3f6954
| 32.571429 | 138 | 0.744681 | 4.68661 | false | false | false | false |
fossasia/open-event-android
|
app/src/main/java/org/fossasia/openevent/general/attendees/AttendeeViewHolder.kt
|
1
|
14019
|
package org.fossasia.openevent.general.attendees
import android.text.Editable
import android.text.SpannableStringBuilder
import android.text.TextWatcher
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.textfield.TextInputEditText
import com.google.android.material.textfield.TextInputLayout
import kotlinx.android.synthetic.main.item_attendee.view.address
import kotlinx.android.synthetic.main.item_attendee.view.addressLayout
import kotlinx.android.synthetic.main.item_attendee.view.attendeeBillingAddress
import kotlinx.android.synthetic.main.item_attendee.view.attendeeBillingAddressLayout
import kotlinx.android.synthetic.main.item_attendee.view.blog
import kotlinx.android.synthetic.main.item_attendee.view.blogLayout
import kotlinx.android.synthetic.main.item_attendee.view.city
import kotlinx.android.synthetic.main.item_attendee.view.cityLayout
import kotlinx.android.synthetic.main.item_attendee.view.company
import kotlinx.android.synthetic.main.item_attendee.view.companyLayout
import kotlinx.android.synthetic.main.item_attendee.view.country
import kotlinx.android.synthetic.main.item_attendee.view.countryLayout
import kotlinx.android.synthetic.main.item_attendee.view.email
import kotlinx.android.synthetic.main.item_attendee.view.emailLayout
import kotlinx.android.synthetic.main.item_attendee.view.facebook
import kotlinx.android.synthetic.main.item_attendee.view.facebookLayout
import kotlinx.android.synthetic.main.item_attendee.view.firstName
import kotlinx.android.synthetic.main.item_attendee.view.firstNameLayout
import kotlinx.android.synthetic.main.item_attendee.view.genderLayout
import kotlinx.android.synthetic.main.item_attendee.view.genderSpinner
import kotlinx.android.synthetic.main.item_attendee.view.genderText
import kotlinx.android.synthetic.main.item_attendee.view.github
import kotlinx.android.synthetic.main.item_attendee.view.githubLayout
import kotlinx.android.synthetic.main.item_attendee.view.homeAddress
import kotlinx.android.synthetic.main.item_attendee.view.homeAddressLayout
import kotlinx.android.synthetic.main.item_attendee.view.jobTitle
import kotlinx.android.synthetic.main.item_attendee.view.jobTitleLayout
import kotlinx.android.synthetic.main.item_attendee.view.lastName
import kotlinx.android.synthetic.main.item_attendee.view.lastNameLayout
import kotlinx.android.synthetic.main.item_attendee.view.phone
import kotlinx.android.synthetic.main.item_attendee.view.phoneLayout
import kotlinx.android.synthetic.main.item_attendee.view.shippingAddress
import kotlinx.android.synthetic.main.item_attendee.view.shippingAddressLayout
import kotlinx.android.synthetic.main.item_attendee.view.state
import kotlinx.android.synthetic.main.item_attendee.view.stateLayout
import kotlinx.android.synthetic.main.item_attendee.view.taxBusinessInfo
import kotlinx.android.synthetic.main.item_attendee.view.taxBusinessInfoLayout
import kotlinx.android.synthetic.main.item_attendee.view.twitter
import kotlinx.android.synthetic.main.item_attendee.view.twitterLayout
import kotlinx.android.synthetic.main.item_attendee.view.website
import kotlinx.android.synthetic.main.item_attendee.view.websiteLayout
import kotlinx.android.synthetic.main.item_attendee.view.workAddress
import kotlinx.android.synthetic.main.item_attendee.view.workAddressLayout
import kotlinx.android.synthetic.main.item_attendee.view.workPhone
import kotlinx.android.synthetic.main.item_attendee.view.workPhoneLayout
import org.fossasia.openevent.general.R
import org.fossasia.openevent.general.attendees.forms.CustomForm
import org.fossasia.openevent.general.attendees.forms.FormIdentifier
import org.fossasia.openevent.general.data.Resource
import org.fossasia.openevent.general.databinding.ItemAttendeeBinding
import org.fossasia.openevent.general.event.EventId
import org.fossasia.openevent.general.ticket.Ticket
import org.fossasia.openevent.general.ticket.TicketId
import org.fossasia.openevent.general.utils.checkEmpty
import org.fossasia.openevent.general.utils.checkValidEmail
import org.fossasia.openevent.general.utils.checkValidURI
import org.fossasia.openevent.general.utils.emptyToNull
import org.fossasia.openevent.general.utils.nullToEmpty
import org.fossasia.openevent.general.utils.setRequired
class AttendeeViewHolder(private val binding: ItemAttendeeBinding) : RecyclerView.ViewHolder(binding.root) {
private val resource = Resource()
private val requiredList = mutableListOf<Pair<TextInputEditText, TextInputLayout>>()
var onAttendeeDetailChanged: AttendeeDetailChangeListener? = null
fun bind(
attendee: Attendee,
ticket: Ticket,
customForm: List<CustomForm>,
position: Int,
eventId: Long,
firstAttendee: Attendee?
) {
with(binding) {
this.attendee = attendee
this.ticket = ticket
}
if (position == 0) {
if (firstAttendee != null) {
itemView.firstName.text = SpannableStringBuilder(firstAttendee.firstname.nullToEmpty())
itemView.lastName.text = SpannableStringBuilder(firstAttendee.lastname.nullToEmpty())
itemView.email.text = SpannableStringBuilder(firstAttendee.email.nullToEmpty())
setFieldEditable(false)
} else {
itemView.firstName.text = SpannableStringBuilder("")
itemView.lastName.text = SpannableStringBuilder("")
itemView.email.text = SpannableStringBuilder("")
setFieldEditable(true)
}
} else {
itemView.firstName.setText(attendee.firstname)
itemView.lastName.setText(attendee.lastname)
itemView.email.setText(attendee.email)
}
val textWatcher = object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
val newAttendee = getAttendeeInformation(attendee.id, ticket, eventId)
onAttendeeDetailChanged?.onAttendeeDetailChanged(newAttendee, position)
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { /*Do nothing*/ }
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { /*Do nothing*/ }
}
requiredList.clear()
setupGendersSpinner(attendee, ticket, eventId, position)
customForm.forEach { form ->
setupCustomFormWithFields(form, textWatcher)
}
}
private fun setupCustomFormWithFields(form: CustomForm, textWatcher: TextWatcher) {
when (form.fieldIdentifier) {
FormIdentifier.FIRST_NAME ->
setupField(itemView.firstNameLayout, itemView.firstName, form.isRequired, textWatcher)
FormIdentifier.LAST_NAME ->
setupField(itemView.lastNameLayout, itemView.lastName, form.isRequired, textWatcher)
FormIdentifier.EMAIL ->
setupField(itemView.emailLayout, itemView.email, form.isRequired, textWatcher)
FormIdentifier.ADDRESS ->
setupField(itemView.addressLayout, itemView.address, form.isRequired, textWatcher)
FormIdentifier.CITY ->
setupField(itemView.cityLayout, itemView.city, form.isRequired, textWatcher)
FormIdentifier.STATE ->
setupField(itemView.stateLayout, itemView.state, form.isRequired, textWatcher)
FormIdentifier.COUNTRY ->
setupField(itemView.countryLayout, itemView.country, form.isRequired, textWatcher)
FormIdentifier.JOB_TITLE ->
setupField(itemView.jobTitleLayout, itemView.jobTitle, form.isRequired, textWatcher)
FormIdentifier.PHONE ->
setupField(itemView.phoneLayout, itemView.phone, form.isRequired, textWatcher)
FormIdentifier.TAX_INFO ->
setupField(itemView.taxBusinessInfoLayout, itemView.taxBusinessInfo, form.isRequired, textWatcher)
FormIdentifier.BILLING_ADDRESS ->
setupField(itemView.attendeeBillingAddressLayout, itemView.attendeeBillingAddress, form.isRequired,
textWatcher)
FormIdentifier.HOME_ADDRESS ->
setupField(itemView.homeAddressLayout, itemView.homeAddress, form.isRequired, textWatcher)
FormIdentifier.SHIPPING_ADDRESS ->
setupField(itemView.shippingAddressLayout, itemView.shippingAddress, form.isRequired, textWatcher)
FormIdentifier.WORK_ADDRESS ->
setupField(itemView.workAddressLayout, itemView.workAddress, form.isRequired, textWatcher)
FormIdentifier.WORK_PHONE ->
setupField(itemView.workPhoneLayout, itemView.workPhone, form.isRequired, textWatcher)
FormIdentifier.WEBSITE ->
setupField(itemView.websiteLayout, itemView.website, form.isRequired, textWatcher)
FormIdentifier.BLOG ->
setupField(itemView.blogLayout, itemView.blog, form.isRequired, textWatcher)
FormIdentifier.TWITTER ->
setupField(itemView.twitterLayout, itemView.twitter, form.isRequired, textWatcher)
FormIdentifier.FACEBOOK ->
setupField(itemView.facebookLayout, itemView.facebook, form.isRequired, textWatcher)
FormIdentifier.COMPANY ->
setupField(itemView.companyLayout, itemView.company, form.isRequired, textWatcher)
FormIdentifier.GITHUB ->
setupField(itemView.githubLayout, itemView.github, form.isRequired, textWatcher)
FormIdentifier.GENDER -> {
itemView.genderLayout.isVisible = true
if (form.isRequired) {
itemView.genderText.text = "${resource.getString(R.string.gender)}*"
}
}
else -> return
}
}
private fun setupGendersSpinner(attendee: Attendee, ticket: Ticket, eventId: Long, position: Int) {
val genders = mutableListOf(resource.getString(R.string.male),
resource.getString(R.string.female), resource.getString(R.string.others))
itemView.genderSpinner.adapter =
ArrayAdapter(itemView.context, android.R.layout.simple_spinner_dropdown_item, genders)
val genderSelected = genders.indexOf(attendee.gender)
if (genderSelected != -1)
itemView.genderSpinner.setSelection(genderSelected)
itemView.genderSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) { /* Do Nothing */ }
override fun onItemSelected(parent: AdapterView<*>?, view: View?, p: Int, id: Long) {
val newAttendee = getAttendeeInformation(attendee.id, ticket, eventId)
onAttendeeDetailChanged?.onAttendeeDetailChanged(newAttendee, position)
}
}
}
private fun setupField(
layout: TextInputLayout,
editText: TextInputEditText,
isRequired: Boolean,
textWatcher: TextWatcher
) {
layout.isVisible = true
editText.addTextChangedListener(textWatcher)
if (isRequired) {
layout.setRequired()
requiredList.add(Pair(editText, layout))
}
}
private fun setFieldEditable(editable: Boolean) {
itemView.firstName.isEnabled = editable
itemView.lastName.isEnabled = editable
itemView.email.isEnabled = editable
}
fun checkValidFields(): Boolean {
var valid = true
requiredList.forEach {
valid = it.first.checkEmpty(it.second) &&
when (it.second) {
itemView.emailLayout -> it.first.checkValidEmail(it.second)
itemView.websiteLayout,
itemView.facebookLayout,
itemView.twitterLayout,
itemView.facebookLayout -> it.first.checkValidURI(it.second)
else -> true
}
}
return valid
}
private fun getAttendeeInformation(id: Long, ticket: Ticket, eventId: Long): Attendee {
return Attendee(
id = id,
firstname = itemView.firstName.text.toString(),
lastname = itemView.lastName.text.toString(),
email = itemView.email.text.toString(),
address = itemView.address.text.toString().emptyToNull(),
city = itemView.city.text.toString().emptyToNull(),
state = itemView.state.text.toString().emptyToNull(),
country = itemView.country.text.toString().emptyToNull(),
jobTitle = itemView.jobTitle.text.toString().emptyToNull(),
phone = itemView.phone.text.toString().emptyToNull(),
taxBusinessInfo = itemView.taxBusinessInfo.text.toString().emptyToNull(),
billingAddress = itemView.attendeeBillingAddress.text.toString().emptyToNull(),
homeAddress = itemView.homeAddress.text.toString().emptyToNull(),
shippingAddress = itemView.shippingAddress.text.toString().emptyToNull(),
company = itemView.company.text.toString().emptyToNull(),
workAddress = itemView.workAddress.text.toString().emptyToNull(),
workPhone = itemView.workPhone.text.toString().emptyToNull(),
website = itemView.website.text.toString().emptyToNull(),
blog = itemView.blog.text.toString().emptyToNull(),
twitter = itemView.twitter.text.toString().emptyToNull(),
facebook = itemView.facebook.text.toString().emptyToNull(),
github = itemView.github.text.toString().emptyToNull(),
gender = itemView.genderSpinner.selectedItem.toString(),
ticket = TicketId(ticket.id.toLong()),
event = EventId(eventId))
}
}
|
apache-2.0
|
48d8a1771c3185ae0ecb5714b5835093
| 52.507634 | 115 | 0.711392 | 4.753815 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android
|
plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/utils/WCCurrencyUtils.kt
|
2
|
2815
|
package org.wordpress.android.fluxc.utils
import org.wordpress.android.fluxc.model.WCSettingsModel
import org.wordpress.android.util.AppLog
import org.wordpress.android.util.AppLog.T
import java.text.DecimalFormat
import java.text.DecimalFormatSymbols
import java.util.Currency
import java.util.Locale
object WCCurrencyUtils {
/**
* Formats the given [rawValue] as a decimal based on the site's currency settings as stored in [siteSettings].
*
* Currency symbol and placement are not handled.
*/
fun formatCurrencyForDisplay(rawValue: Double, siteSettings: WCSettingsModel, locale: Locale? = null): String {
return formatCurrencyForDisplay(
rawValue = rawValue,
currencyDecimalNumber = siteSettings.currencyDecimalNumber,
currencyDecimalSeparator = siteSettings.currencyDecimalSeparator,
currencyThousandSeparator = siteSettings.currencyThousandSeparator,
locale = locale
)
}
fun formatCurrencyForDisplay(
rawValue: Double,
currencyDecimalNumber: Int,
currencyDecimalSeparator: String,
currencyThousandSeparator: String,
locale: Locale? = null
): String {
val pattern = if (currencyDecimalNumber > 0) {
"#,##0.${"0".repeat(currencyDecimalNumber)}"
} else {
"#,##0"
}
val decimalFormat = locale?.let { DecimalFormat(pattern, DecimalFormatSymbols(locale)) }
?: DecimalFormat(pattern)
decimalFormat.decimalFormatSymbols = decimalFormat.decimalFormatSymbols.apply {
// If no decimal separator is set, keep whatever the system default is
currencyDecimalSeparator.takeIf { it.isNotEmpty() }?.let {
decimalSeparator = it[0]
}
// If no thousands separator is set, assume it's intentional and clear it in the formatter
currencyThousandSeparator.takeIf { it.isNotEmpty() }?.let {
groupingSeparator = it[0]
} ?: run { decimalFormat.isGroupingUsed = false }
}
return decimalFormat.format(rawValue)
}
/**
* Given a locale and an ISO 4217 currency code (e.g. USD), returns the currency symbol for that currency,
* localized to the locale.
*
* Will return the [currencyCode] if it's found not to be a valid currency code.
*/
fun getLocalizedCurrencySymbolForCode(currencyCode: String, locale: Locale): String {
return try {
Currency.getInstance(currencyCode).getSymbol(locale)
} catch (e: IllegalArgumentException) {
AppLog.e(T.UTILS,
"Error finding valid currency symbol for currency code [$currencyCode] in locale [$locale]", e)
currencyCode
}
}
}
|
gpl-2.0
|
f33f2a5a0db883a6c5853b569edb2e5b
| 38.097222 | 115 | 0.656128 | 5.127505 | false | false | false | false |
LanternPowered/LanternServer
|
src/main/kotlin/org/lanternpowered/server/service/world/DefaultWorldStorageService.kt
|
1
|
8591
|
/*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.service.world
import org.lanternpowered.api.key.NamespacedKey
import org.lanternpowered.api.service.world.WorldStorage
import org.lanternpowered.api.service.world.WorldStorageService
import org.lanternpowered.api.util.collections.toImmutableList
import org.lanternpowered.server.game.Lantern
import org.spongepowered.api.util.file.CopyFileVisitor
import org.spongepowered.api.util.file.DeleteFileVisitor
import java.io.Closeable
import java.nio.file.Files
import java.nio.file.Path
import java.util.Collections
import java.util.UUID
import java.util.concurrent.ConcurrentHashMap
/**
* A world data service that will handle world data similar like a vanilla
* minecraft server. A vanilla world should be able to be pasted in and be
* completely compatible, if the world data is upgraded to the supported
* version.
*
* The directory structure will be the following for example:
* /worlds
* /config.json -- The global configuration related to worlds
* /minecraft -- A directory containing all the default worlds created by "minecraft"
* /overworld
* /config.json -- The configuration of a specific world
* /data -- The world data, compatible with sponge and vanilla worlds
* /region
* /level.dat
* /sponge_level.dat
* /the_end
* /the_nether
* /myplugin -- A directory containing all the worlds created by "myplugin"
* /myworld
*
* @property directory The directory where all the worlds will be stored
*/
class DefaultWorldStorageService(
override val directory: Path
) : WorldStorageService, Closeable {
private val knownStoragesByUniqueId = ConcurrentHashMap<UUID, LanternWorldStorage>()
private val knownStoragesByKey = ConcurrentHashMap<NamespacedKey, LanternWorldStorage>()
private val modifyLock = Any()
override val onDiscover: MutableList<(storage: WorldStorage) -> Unit> = Collections.synchronizedList(mutableListOf())
override val onRemove: MutableCollection<(storage: WorldStorage) -> Unit> = Collections.synchronizedList(mutableListOf())
/**
* Imports the world directory.
*/
fun import(directory: Path) {
// First check all the sub directories
for (subDirectory in Files.walk(directory, 1)) {
if (LanternWorldStorage.isWorld(subDirectory))
this.importWorld(subDirectory)
}
// Import the root world
if (LanternWorldStorage.isWorld(this.directory))
this.importWorld(directory, "DIM0")
}
private fun importWorld(path: Path, oldName: String = path.fileName.toString()): Path {
val newName = when (oldName) {
"DIM-1" -> "the_nether"
"DIM1" -> "the_end"
"DIM0" -> "overworld"
else -> oldName
}
var destination = this.directory.resolve(newName)
if (Files.exists(destination)) {
var number = 1
// Start numbering if the directory is already in use
while (Files.exists(destination))
destination = this.directory.resolve("$newName${++number}")
Lantern.getLogger().info("The directory $newName was already in use, so the imported world " +
"from $oldName will be moved to $destination.")
}
val dataDestination = destination.resolve(LanternWorldStorage.DATA_DIRECTORY_NAME)
Files.walkFileTree(path, CopyFileVisitor(dataDestination))
Files.walkFileTree(path, DeleteFileVisitor.INSTANCE)
// Remove unneeded data
LanternWorldStorage.cleanupWorld(destination)
return destination
}
override val all: Collection<WorldStorage>
get() = this.knownStoragesByUniqueId.values.toImmutableList()
override fun getConfigPath(name: String): Path =
this.directory.resolve(name)
override fun get(uniqueId: UUID): WorldStorage? =
this.knownStoragesByUniqueId[uniqueId]
override fun getByKey(key: NamespacedKey): WorldStorage? =
this.knownStoragesByKey[key]
private fun put(storage: LanternWorldStorage): LanternWorldStorage {
this.knownStoragesByKey[storage.key] = storage
this.knownStoragesByUniqueId[storage.uniqueId] = storage
return storage
}
override fun create(key: NamespacedKey, uniqueId: UUID): WorldStorage {
synchronized(this.modifyLock) {
if (this.knownStoragesByKey.containsKey(key))
error("There already exists a world for the given key: $key")
if (this.knownStoragesByUniqueId.containsKey(uniqueId))
error("There already exists a world for the given unique id: $uniqueId")
val worldDirectory = this.directory.resolve(key.namespace).resolve(key.value)
if (Files.exists(worldDirectory) && Files.list(worldDirectory).count() > 0)
error("There already exists a world directory for the given key: $key")
Files.createDirectories(worldDirectory)
return this.put(LanternWorldStorage(key, uniqueId, worldDirectory))
}
}
override fun copy(sourceKey: NamespacedKey, copyKey: NamespacedKey, uniqueId: UUID): WorldStorage {
synchronized(this.modifyLock) {
if (!this.knownStoragesByKey.containsKey(sourceKey))
error("There doesn't exist a world for the given source key: $sourceKey")
if (this.knownStoragesByKey.containsKey(copyKey))
error("There already exists a world for the given copy key: $copyKey")
if (this.knownStoragesByUniqueId.containsKey(uniqueId))
error("There already exists a world for the given copy unique id: $uniqueId")
val sourceDirectory = this.directory.resolve(sourceKey.namespace).resolve(sourceKey.value)
if (!Files.exists(sourceDirectory) || Files.list(sourceDirectory).count() == 0L)
error("There doesn't exist a world directory for the given source key: $sourceKey")
val copyDirectory = this.directory.resolve(copyKey.namespace).resolve(copyKey.value)
if (Files.exists(copyDirectory) && Files.list(copyDirectory).count() > 0)
error("There already exists a world directory for the given copy key: $copyKey")
Files.walkFileTree(sourceDirectory, CopyFileVisitor(copyDirectory))
return this.put(LanternWorldStorage(copyKey, uniqueId, copyDirectory))
}
}
override fun move(oldKey: NamespacedKey, newKey: NamespacedKey): WorldStorage {
synchronized(this.modifyLock) {
val source = this.knownStoragesByKey[oldKey]
?: error("There doesn't exist a world for the given source key: $oldKey")
if (this.knownStoragesByKey.containsKey(newKey))
error("There already exists a world for the given destination key: $newKey")
val sourceDirectory = this.directory.resolve(oldKey.namespace).resolve(oldKey.value)
if (!Files.exists(sourceDirectory) || Files.list(sourceDirectory).count() == 0L)
error("There doesn't exist a world directory for the given source key: $oldKey")
val destinationDirectory = this.directory.resolve(newKey.namespace).resolve(newKey.value)
if (Files.exists(destinationDirectory) && Files.list(destinationDirectory).count() > 0)
error("There already exists a world directory for the given destination key: $newKey")
Files.walkFileTree(sourceDirectory, CopyFileVisitor(destinationDirectory))
Files.walkFileTree(sourceDirectory, DeleteFileVisitor.INSTANCE)
this.knownStoragesByKey.remove(source.key)
this.knownStoragesByUniqueId.remove(source.uniqueId)
return this.put(LanternWorldStorage(newKey, source.uniqueId, destinationDirectory))
}
}
override fun close() {
synchronized(this.modifyLock) {
for (storage in this.knownStoragesByKey.values)
storage.close()
this.knownStoragesByKey.clear()
this.knownStoragesByUniqueId.clear()
}
}
}
|
mit
|
f931fe3edf244cfe0b87b3d23042e653
| 44.215789 | 125 | 0.675009 | 4.684297 | false | false | false | false |
valsinats42/meditate
|
mobile/src/main/java/me/stanislav_nikolov/meditate/ui/LogFragment.kt
|
1
|
1391
|
package me.stanislav_nikolov.meditate.ui
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import me.stanislav_nikolov.meditate.R
import me.stanislav_nikolov.meditate.adapters.LogAdapter
import me.stanislav_nikolov.meditate.graph
import javax.inject.Inject
class LogFragment : Fragment() {
@Inject lateinit var adapter: LogAdapter
var recyclerView: RecyclerView? = null
companion object {
fun newInstance(): LogFragment = LogFragment()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
graph().inject(this)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_log, container, false)
recyclerView = view!!.findViewById(R.id.recyclerView) as RecyclerView
with(recyclerView!!) {
layoutManager = LinearLayoutManager(activity)
setHasFixedSize(true)
adapter = [email protected]
}
return view
}
override fun onDestroyView() {
super.onDestroyView()
recyclerView = null
}
}
|
mit
|
a2f4be7548990d6a5edd12a4cda9bfcd
| 27.387755 | 116 | 0.718907 | 4.429936 | false | false | false | false |
jhuizy/Flow
|
library/src/main/java/com/jhuizy/flowsamples/Flow.kt
|
1
|
2579
|
package com.jhuizy.flowsamples
import android.util.Log
import io.reactivex.BackpressureStrategy
import io.reactivex.Observable
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
object Flow {
private data class CreateStore<A, S>(val stateHolder: StateHolder<S>, val dispatcher: Dispatcher<A>, val changes: Observable<S>) : Store<A, S> {
override fun dispatch(action: A) {
dispatcher.dispatch(action)
}
override fun getState(): S {
return stateHolder.state
}
override fun changes(): Observable<S> {
return changes
}
}
fun <A, S> middlewares(middlewares: List<Middleware<A, S>>): StoreCreator<A, S> {
return StoreCreator { initialState, reducer ->
val store = DefaultStoreCreator<A, S>().create(initialState, reducer)
val dispatcher = middlewares.reversed()
.map { middleware -> { stateHolder: StateHolder<S> -> { next: Dispatcher<A> -> middleware.apply(stateHolder, next) } } }
.map { middelware -> middelware.invoke(store.stateHolder) }
.foldRight(store.dispatcher) { m, dispatcher -> m.invoke(dispatcher) }
store.copy(dispatcher = dispatcher)
}
}
fun <A, S> default(): StoreCreator<A, S> = DefaultStoreCreator<A, S>()
private class DefaultStoreCreator<A, S> : StoreCreator<A, S> {
override fun create(initialState: S, reducer: Reducer<A, S>): CreateStore<A, S> {
var state = initialState
val stateHolder = StateHolder { state }
val subject: Subject<A> = PublishSubject.create<A>().toSerialized()
val changes: Observable<S> = subject.toFlowable(BackpressureStrategy.BUFFER)
.toObservable()
.map { action -> reducer.reduce(state, action) }
.doOnNext { nextState -> state = nextState }
val dispatcher = Dispatcher<A> { action -> subject.onNext(action) }
return CreateStore(stateHolder, dispatcher, changes)
}
}
class LoggerMiddleware<A, S> : Middleware<A, S> {
override fun apply(stateHolder: StateHolder<S>, nextDispatcher: Dispatcher<A>): Dispatcher<A> {
return Dispatcher { action ->
val TAG = "LoggerMiddleware"
Log.v(TAG, "redux action --> $action")
nextDispatcher.dispatch(action)
Log.v(TAG, "redux state <-- ${stateHolder.state}")
}
}
}
}
|
gpl-3.0
|
1c0460c7d849ca0fe82be9c9e608f601
| 35.842857 | 148 | 0.599845 | 4.416096 | false | false | false | false |
davidwhitman/changelogs
|
app/src/main/java/com/thunderclouddev/changelogs/ui/comparator/Comparators.kt
|
1
|
1239
|
/*
* Copyright (c) 2017.
* Distributed under the GNU GPLv3 by David Whitman.
* https://www.gnu.org/licenses/gpl-3.0.en.html
*
* This source code is made available to help others learn. Please don't clone my app.
*/
package com.thunderclouddev.changelogs.ui.comparator
import com.thunderclouddev.changelogs.ui.home.AppInfoRecycler
import java.util.*
/**
* Created by David Whitman on 4/22/2015.
* @author David Whitman
*/
object Comparators {
val Default = Sorting.ByRecentlyUpdated
// private val alphabeticalByTitleComparator = AlphabeticalByTitleComparator()
private val recentlyUpdatedComparator = RecentlyUpdatedComparator()
// private val hasUpdateComparator = HasUpdateComparator()
// private val sizeComparator = SizeComparator()
operator fun get(comparatorType: Sorting = Default): Comparator<AppInfoRecycler.AppInfoViewModel> {
when (comparatorType) {
// Sorting.ByTitle -> return alphabeticalByTitleComparator
// Sorting.ByHasUpdate -> return hasUpdateComparator
Sorting.ByRecentlyUpdated -> return recentlyUpdatedComparator
// Sorting.BySize -> return sizeComparator
else -> return recentlyUpdatedComparator
}
}
}
|
gpl-3.0
|
ee7656a362797d1b94d1b632ff3d5499
| 32.486486 | 103 | 0.725585 | 4.472924 | false | false | false | false |
FHannes/intellij-community
|
platform/script-debugger/protocol/schema-reader-generator/src/ProtocolMetaModel.kt
|
16
|
2392
|
package org.jetbrains.jsonProtocol
import org.jetbrains.io.JsonReaderEx
val STRING_TYPE: String = "string"
val INTEGER_TYPE: String = "integer"
val NUMBER_TYPE: String = "number"
val BOOLEAN_TYPE: String = "boolean"
public val OBJECT_TYPE: String = "object"
val ARRAY_TYPE: String = "array"
val UNKNOWN_TYPE: String = "unknown"
val ANY_TYPE: String = "any"
interface ItemDescriptor {
val description: String?
val type: String?
val enum: List<String>?
val items: ProtocolMetaModel.ArrayItemType?
interface Named : Referenceable {
fun name(): String
val shortName: String?
val optional: Boolean
}
interface Referenceable : ItemDescriptor {
@ProtocolName("\$ref")
val ref: String?
}
interface Type : ItemDescriptor {
val properties: List<ProtocolMetaModel.ObjectProperty>?
}
}
interface ProtocolSchemaReader {
@JsonParseMethod
fun parseRoot(reader: JsonReaderEx): ProtocolMetaModel.Root
}
/**
* Defines schema of WIP metamodel defined in http://svn.webkit.org/repository/webkit/trunk/Source/WebCore/inspector/Inspector.json
*/
interface ProtocolMetaModel {
@JsonType
interface Root {
val version: Version?
fun domains(): List<Domain>
}
interface Version {
fun major(): String
fun minor(): String
}
interface Domain {
fun domain(): String
val types: List<StandaloneType>?
fun commands(): List<Command>
val events: List<Event>?
val description: String?
val hidden: Boolean
val experimental: Boolean
}
interface Command {
fun name(): String
val parameters: List<Parameter>?
val returns: List<Parameter>?
val description: String?
val hidden: Boolean
val async: Boolean
}
interface Parameter : ItemDescriptor.Named {
val hidden: Boolean
@JsonField(allowAnyPrimitiveValue = true)
val default: String?
}
interface Event {
fun name(): String
val parameters: List<Parameter>?
val description: String?
val hidden: Boolean
val optionalData: Boolean
}
@JsonType
interface StandaloneType : ItemDescriptor.Type {
fun id(): String
val hidden: Boolean
}
interface ArrayItemType : ItemDescriptor.Type, ItemDescriptor.Referenceable {
val optional: Boolean
}
interface ObjectProperty : ItemDescriptor.Named {
override fun name(): String
val hidden: Boolean
}
}
|
apache-2.0
|
4f9e7b12ca2e340ddcfb44ee028ae725
| 17.84252 | 131 | 0.694398 | 4.413284 | false | false | false | false |
lfkdsk/JustDB
|
src/sql/token/SqlToken.kt
|
1
|
2077
|
package sql.token
import utils.parsertools.ast.Token
/**
* Created by liufengkai on 2017/4/27.
*/
open class SqlToken(override val lineNumber: Int,
override var tag: Int,
override var text: String) : Token {
companion object default {
val EOF = SqlToken(-1, SqlToken.EOF_TAG, "End of File")
/**
* End of line
*/
val EOL = "\\n"
val AND = 256
val BASIC = 257
val BREAK = 258
val DO = 259
val ELSE = 260
val EQ = 261
val FALSE = 262
val GE = 263
val ID = 264
val IF = 265
val INDEX = 266
val LE = 267
val MINUS = 268
val NE = 269
val NUM = 270
val OR = 271
val REAL = 272
val TEMP = 273
val TRUE = 274
val WHILE = 275
val STRING = 276
val LIST = 277
val BLOCK = 278
val BINARY = 279
val FUNCTION = 280
val NEGATIVE = 281
val NULL = 282
val PARALIST = 283
val POSTFIX = 284
val PRIMARY = 285
val FOR = 286
val CLOSURE = 287
val CLASS_TOKEN = 288
val CLASS_BODY_TOKEN = 289
val ARRAY = 290
val CREATE_ARRAY = 291
val OPTION = 292
val IMPORT = 293
val BOOL = 294
val VAR = 295
val INT = 296
val FLOAT = 297
val TYPE = 298
val NEGATIVEBOOL = 295
val RETURN = 296
val CONSTANT_LIST = 297
val FIELD = 298
val FIELD_LIST = 299
val FIELD_DEF = 300
val FIELD_DEF_LIST = 301
val CREATE_TABLE = 302
val CREATE_VIEW = 303
val CREATE_INDEX = 304
val INSERT = 305
val QUERY = 306
val DELETE = 307
val UPDATE = 308
val TERM = 309
val PREDICATE = 310
val TABLE_LIST = 311
val SELECT_LIST = 312
val EOF_TAG = -1
val EOL_TAG = -2
val EMPTY = -100
}
constructor(lineNumber: Int, tag: Int)
: this(lineNumber, tag, "")
override fun isIdentifier(): Boolean {
TODO("not implemented")
}
override fun isNumber(): Boolean {
TODO("not implemented")
}
override fun isString(): Boolean {
TODO("not implemented")
}
override fun isNull(): Boolean {
TODO("not implemented")
}
override fun isType(): Boolean {
TODO("not implemented")
}
override fun isBool(): Boolean {
TODO("not implemented")
}
}
|
apache-2.0
|
c9aceeb9d6a8890b15a3ceb89672b83e
| 17.380531 | 57 | 0.626866 | 3.1 | false | false | false | false |
die-tageszeitung/tazapp-android
|
tazapp/src/main/java/de/thecode/android/tazreader/utils/Connection.kt
|
1
|
1975
|
package de.thecode.android.tazreader.utils
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import com.github.ajalt.timberkt.i
import de.thecode.android.tazreader.app
class Connection {
companion object {
private val systemReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
val info = getConnectionInfo()
listeners.forEach {
it.onNetworkConnectionChanged(info)
}
}
}
val listeners = arrayListOf<ConnectionChangeListener>()
fun getConnectionInfo(): ConnectionInfo {
val manager = app.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val info = manager.activeNetworkInfo
val result = if (info != null) ConnectionInfo(info.isConnectedOrConnecting, manager.isActiveNetworkMetered, info.isRoaming)
else ConnectionInfo(metered = false, connected = false, roaming = false)
i { "ConnectionInfo: $result" }
return result
}
fun addListener(listener: ConnectionChangeListener) {
listeners.add(listener)
if (listeners.size > 0) {
app.registerReceiver(systemReceiver, IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION))
}
}
fun removeListener(listener: ConnectionChangeListener) {
listeners.remove(listener)
if (listeners.size == 0) {
app.unregisterReceiver(systemReceiver)
}
}
}
interface ConnectionChangeListener {
fun onNetworkConnectionChanged(info: ConnectionInfo)
}
}
data class ConnectionInfo(val connected: Boolean = false, val metered: Boolean = false, val roaming: Boolean = false)
|
agpl-3.0
|
1dd19ca9e82ecc95a30ad80089cf8bfa
| 33.649123 | 135 | 0.652658 | 5.280749 | false | false | false | false |
neyb/swak
|
core/src/main/kotlin/swak/interceptor/before/RequestUpdaters.kt
|
1
|
785
|
package swak.interceptor.before
import io.reactivex.Single
import swak.http.request.UpdatableRequest
import java.util.*
internal class RequestUpdaters<T>(
private val interceptors: List<RequestUpdater<T>>
) : RequestUpdater<T> {
override fun updateRequest(request: UpdatableRequest<T>): Single<UpdatableRequest<T>> {
var result = Single.just(request)
for (interceptor in interceptors)
result = result.flatMap { interceptor.updateRequest(it) }
return result
}
class Builder<T> {
val interceptors: MutableList<RequestUpdater<T>> = ArrayList()
fun hasBehaviour() = !interceptors.isEmpty()
fun build() = RequestUpdaters(interceptors.toList())
}
override fun toString() = interceptors.toString()
}
|
apache-2.0
|
00c269e2cb228cc2d0578cb6741be99c
| 30.44 | 91 | 0.695541 | 4.460227 | false | false | false | false |
thm-projects/arsnova-backend
|
authz/src/main/kotlin/de/thm/arsnova/service/authservice/config/RabbitConfig.kt
|
1
|
6805
|
package de.thm.arsnova.service.authservice.config
import de.thm.arsnova.service.authservice.model.event.RoomAccessSyncEvent
import de.thm.arsnova.service.authservice.model.event.RoomAccessSyncRequest
import org.springframework.amqp.core.BindingBuilder.bind
import org.springframework.amqp.core.Declarables
import org.springframework.amqp.core.DirectExchange
import org.springframework.amqp.core.FanoutExchange
import org.springframework.amqp.core.Queue
import org.springframework.amqp.rabbit.annotation.RabbitListenerConfigurer
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory
import org.springframework.amqp.rabbit.connection.ConnectionFactory
import org.springframework.amqp.rabbit.core.RabbitAdmin
import org.springframework.amqp.rabbit.core.RabbitTemplate
import org.springframework.amqp.rabbit.listener.RabbitListenerEndpointRegistrar
import org.springframework.amqp.support.converter.ClassMapper
import org.springframework.amqp.support.converter.DefaultClassMapper
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter
import org.springframework.amqp.support.converter.MessageConverter
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.core.task.TaskExecutor
import org.springframework.messaging.converter.MappingJackson2MessageConverter
import org.springframework.messaging.handler.annotation.support.DefaultMessageHandlerMethodFactory
import java.util.HashMap
@Configuration
@EnableConfigurationProperties(AuthServiceProperties::class)
class RabbitConfig(
private var authServiceProperties: AuthServiceProperties
) : RabbitListenerConfigurer {
companion object {
const val roomAccessSyncResponseQueueName: String = "backend.event.room.access.sync.response"
const val roomAccessSyncRequestQueueName: String = "backend.event.room.access.sync.request"
const val roomCreatedExchangeName: String = "backend.event.room.aftercreation"
const val roomDeletedExchangeName: String = "backend.event.room.afterdeletion"
const val roomCreatedQueueName: String = "backend.event.room.aftercreation.consumer.auth-service"
const val roomDeletedQueueName: String = "backend.event.room.afterdeletion.consumer.auth-service"
const val participantAccessMigrationQueueName: String = "backend.event.migration.access.participant"
}
@Bean
@Autowired
fun connectionFactory(
@TaskExecutorConfig.RabbitConnectionExecutor executor: TaskExecutor?
): ConnectionFactory? {
val connectionFactory = CachingConnectionFactory(
authServiceProperties.rabbitmq.host,
authServiceProperties.rabbitmq.port
)
connectionFactory.username = authServiceProperties.rabbitmq.username
connectionFactory.setPassword(authServiceProperties.rabbitmq.password)
connectionFactory.virtualHost = authServiceProperties.rabbitmq.virtualHost
connectionFactory.setExecutor(executor!!)
return connectionFactory
}
@Bean
@Autowired
fun rabbitTemplate(connectionFactory: ConnectionFactory?): RabbitTemplate? {
val rabbitTemplate = RabbitTemplate(connectionFactory!!)
rabbitTemplate.messageConverter = jsonMessageConverter()
return rabbitTemplate
}
@Bean
@Autowired
fun rabbitAdmin(connectionFactory: ConnectionFactory?): RabbitAdmin? {
return RabbitAdmin(connectionFactory!!)
}
@Bean
fun declarables(): Declarables {
val roomCreatedFanoutExchange = FanoutExchange(roomCreatedExchangeName)
val roomDeletedFanoutExchange = FanoutExchange(roomDeletedExchangeName)
val participantAccessMigrationDlq = Queue("$participantAccessMigrationQueueName.dlq")
val participantAccessMigrationQueue = Queue(
participantAccessMigrationQueueName,
true,
false,
false,
mapOf(
"x-dead-letter-exchange" to "",
"x-dead-letter-routing-key" to "$participantAccessMigrationQueueName.dlq"
)
)
val roomCreatedQueue = Queue(
roomCreatedQueueName,
true,
true,
false,
mapOf(
"x-dead-letter-exchange" to "",
"x-dead-letter-routing-key" to "$roomCreatedQueueName.dlq"
)
)
val roomDeletedQueue = Queue(
roomDeletedQueueName,
true,
true,
false,
mapOf(
"x-dead-letter-exchange" to "",
"x-dead-letter-routing-key" to "$roomDeletedQueueName.dlq"
)
)
val roomCreatedDlq = Queue("$roomCreatedQueueName.dlq")
val roomDeletedDlq = Queue("$roomDeletedQueueName.dlq")
val roomAccessSyncResponseQueue = Queue(
roomAccessSyncResponseQueueName,
true,
false,
false,
mapOf(
"x-dead-letter-exchange" to "",
"x-dead-letter-routing-key" to "$roomAccessSyncResponseQueueName.dlq"
)
)
val roomAccessSyncResponseDlq = Queue("$roomAccessSyncResponseQueueName.dlq")
val roomAccessSyncRequestExchange = DirectExchange(roomAccessSyncRequestQueueName)
return Declarables(
listOf(
roomCreatedFanoutExchange,
roomDeletedFanoutExchange,
participantAccessMigrationQueue,
participantAccessMigrationDlq,
roomCreatedQueue,
roomCreatedDlq,
roomDeletedQueue,
roomDeletedDlq,
bind(roomCreatedQueue).to(roomCreatedFanoutExchange),
bind(roomDeletedQueue).to(roomDeletedFanoutExchange),
roomAccessSyncResponseQueue,
roomAccessSyncResponseDlq,
roomAccessSyncRequestExchange
)
)
}
@Bean
fun jsonMessageConverter(): MessageConverter {
val converter = Jackson2JsonMessageConverter()
return converter
}
@Bean
fun classMapper(): ClassMapper {
val classMapper = DefaultClassMapper()
val idClassMapping: MutableMap<String, Class<*>> = HashMap()
// Because of not having shared models we need this mapping to backend models for jackson
idClassMapping["de.thm.arsnova.event.RoomAccessSyncRequest"] = RoomAccessSyncRequest::class.java
idClassMapping["de.thm.arsnova.event.RoomAccessSyncEvent"] = RoomAccessSyncEvent::class.java
classMapper.setIdClassMapping(idClassMapping)
return classMapper
}
@Bean
fun jackson2Converter(): MappingJackson2MessageConverter? {
return MappingJackson2MessageConverter()
}
@Bean
fun myHandlerMethodFactory(): DefaultMessageHandlerMethodFactory? {
val factory = DefaultMessageHandlerMethodFactory()
factory.setMessageConverter(jackson2Converter()!!)
return factory
}
override fun configureRabbitListeners(registrar: RabbitListenerEndpointRegistrar) {
registrar.messageHandlerMethodFactory = myHandlerMethodFactory()!!
}
}
|
gpl-3.0
|
4d7daa70862be694eee5549121a49783
| 37.664773 | 104 | 0.776047 | 4.676976 | false | true | false | false |
tomhenne/Jerusalem
|
src/test/java/utils/FileBasedHashMapTest.kt
|
1
|
2890
|
package utils
import de.esymetric.jerusalem.utils.FileBasedHashMap
import de.esymetric.jerusalem.utils.FileBasedHashMapForLongKeys
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import java.io.File
class FileBasedHashMapTest {
@Test
fun testFileBasedHashMap() {
File("testData/fileBasedHashMapTest.data").delete()
val fbhm = FileBasedHashMap()
fbhm.open("testData/fileBasedHashMapTest.data", false)
run {
var id = 1000000
while (id > 0) {
val value = (Math.random() * 788823548).toInt()
fbhm.put(id, value)
assertTrue(fbhm[id] == value)
id -= 111
}
}
run {
var id = 1000001
while (id < 1286746) {
val value = (Math.random() * 788823548).toInt()
fbhm.put(id, value)
if (fbhm[id] != value) {
fbhm.put(id, value)
assertTrue(fbhm[id] == value)
}
assertTrue(fbhm[id] == value)
id += 263
}
}
var id = 2000001
while (id < 3000000) {
val key = id
val value = (Math.random() * 788823548).toInt()
fbhm.put(key, value)
assertTrue(fbhm[key] == value)
id += 555
}
fbhm.close()
File("testData/fileBasedHashMapTest.data").delete()
}
@Test
@Throws(Exception::class)
fun testFileBasedHashMapForLongKeys() {
File("testData/fileBasedHashMapTestForLongKeys.data").delete()
val fbhm = FileBasedHashMapForLongKeys()
fbhm.open("testData/fileBasedHashMapTestForLongKeys.data", false)
run {
var id = 1000000
while (id > 0) {
val value = (Math.random() * 788823548).toInt()
fbhm.put(id.toLong(), value)
assertTrue(fbhm[id.toLong()] == value)
id -= 111
}
}
run {
var id = 1000001
while (id < 1286746) {
val value = (Math.random() * 788823548).toInt()
fbhm.put(id.toLong(), value)
if (fbhm[id.toLong()] != value) {
fbhm.put(id.toLong(), value)
assertTrue(fbhm[id.toLong()] == value)
}
assertTrue(fbhm[id.toLong()] == value)
id += 263
}
}
var id = 3000000000L
while (id < 3300000000L) {
val key = id
val value = (Math.random() * 788823548).toInt()
fbhm.put(key, value)
assertTrue(fbhm[key] == value)
id += 23555L
}
fbhm.close()
File("testData/fileBasedHashMapTestForLongKeys.data").delete()
}
}
|
apache-2.0
|
931241b7796ffd1e88ff49f0ab790b7c
| 31.852273 | 73 | 0.497578 | 4.116809 | false | true | false | false |
dafi/photoshelf
|
core/src/main/java/com/ternaryop/photoshelf/repository/tumblr/TumblrRepository.kt
|
1
|
1693
|
package com.ternaryop.photoshelf.repository.tumblr
import android.app.Application
import android.net.Uri
import com.ternaryop.photoshelf.lifecycle.CommandMutableLiveData
import com.ternaryop.tumblr.Blog
import com.ternaryop.tumblr.Tumblr
import com.ternaryop.tumblr.android.TumblrManager
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class TumblrRepository @Inject constructor(private val application: Application) {
// user should be not logged when the manager is created so we create it lazily
val tumblr: Tumblr by lazy { TumblrManager.getInstance(application) }
private val _draftCount = CommandMutableLiveData<Int>()
private val _scheduledCount = CommandMutableLiveData<Int>()
val draftCount = _draftCount.asLiveData()
val scheduledCount = _scheduledCount.asLiveData()
private val _authenticate = CommandMutableLiveData<Boolean>()
val authenticate = _authenticate.asLiveData()
var blogs = emptyList<Blog>()
private set
fun updateDraftCount(count: Int) = _draftCount.setLastValue(count, true)
fun updateScheduledCount(count: Int) = _scheduledCount.setLastValue(count, true)
suspend fun handleCallbackUri(uri: Uri?) {
if (TumblrManager.isLogged(application)) {
return
}
_authenticate.post(false) { TumblrManager.handleOpenURI(application, uri) }
}
fun clearCount() {
_draftCount.setLastValue(null, false)
_scheduledCount.setLastValue(null, false)
}
fun fetchBlogs(): List<Blog> {
blogs = tumblr.blogList
return blogs
}
fun blogByName(blogName: String): Blog = blogs.first { it.name.equals(blogName, true) }
}
|
mit
|
feb7503dc16a669fd32e916532c3e2bc
| 33.55102 | 91 | 0.731246 | 4.264484 | false | false | false | false |
daugeldauge/NeePlayer
|
compose/src/main/java/com/neeplayer/compose/db/Database.kt
|
1
|
3406
|
package com.neeplayer.compose.db
import android.annotation.SuppressLint
import android.content.ContentResolver
import android.database.Cursor
import android.net.Uri
import android.provider.BaseColumns
import android.provider.MediaStore.Audio.Artists
import android.provider.MediaStore.Audio.Artists.Albums
import android.provider.MediaStore.Audio.Media
import com.neeplayer.compose.Album
import com.neeplayer.compose.Artist
import com.neeplayer.compose.Song
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class Database(private val contentResolver: ContentResolver) {
suspend fun artists(): List<Artist> {
return query(
uri = Artists.EXTERNAL_CONTENT_URI,
projection = arrayOf(Artists._ID, Artists.ARTIST, Artists.NUMBER_OF_TRACKS, Artists.NUMBER_OF_ALBUMS)
) {
val artist = Artist(
id = id(),
name = string(Artists.ARTIST) ?: "Unknown",
numberOfSongs = int(Artists.NUMBER_OF_TRACKS),
numberOfAlbums = int(Artists.NUMBER_OF_ALBUMS),
imageUrl = "https://cdns-images.dzcdn.net/images/artist/3a27ec1beff8cae3a0196f32a6361195/250x250-000000-80-0-0.jpg"
)
artist
}
}
suspend fun albums(artist: Artist): List<Album> {
return query(
uri = Albums.getContentUri("external", artist.id),
projection = arrayOf(Albums.ALBUM_ID, Albums.ALBUM, Albums.FIRST_YEAR),
sortOrder = Albums.FIRST_YEAR
) {
val id = long(Albums.ALBUM_ID)
Album(
id = id,
title = string(Albums.ALBUM),
year = int(Albums.FIRST_YEAR),
art = "neeplayer://album/$id",
)
}
}
suspend fun songs(album: Album): List<Song> {
return query(
uri = Media.EXTERNAL_CONTENT_URI,
projection = arrayOf(Media._ID, Media.TITLE, MEDIA_DURATION, Media.TRACK),
selection = "${Media.ALBUM_ID}=${album.id}",
sortOrder = Media.TRACK
) {
Song(
id = id(),
title = string(Media.TITLE),
duration = long(MEDIA_DURATION),
track = int(Media.TRACK)
)
}
}
private suspend fun <T> query(
uri: Uri,
projection: Array<String>? = null,
selection: String? = null,
selectionArgs: Array<String>? = null,
sortOrder: String? = null,
mapper: Cursor.() -> T,
): List<T> {
return withContext(Dispatchers.IO) {
contentResolver.query(uri, projection, selection, selectionArgs, sortOrder)
?.use { cursor ->
val items = ArrayList<T>(cursor.count)
while (cursor.moveToNext()) {
items.add(mapper(cursor))
}
items
}.orEmpty()
}
}
}
private fun Cursor.id(): Long = long(BaseColumns._ID)
private fun Cursor.int(column: String): Int = getInt(getColumnIndexOrThrow(column))
private fun Cursor.long(column: String): Long = getLong(getColumnIndexOrThrow(column))
private fun Cursor.string(column: String): String? = getString(getColumnIndexOrThrow(column))
@SuppressLint("InlinedApi")
private const val MEDIA_DURATION = Media.DURATION
|
mit
|
077e941697e9016f334544ba9aa611f7
| 34.113402 | 131 | 0.597769 | 4.429129 | false | false | false | false |
apollo-rsps/apollo
|
game/src/main/kotlin/org/apollo/game/plugin/kotlin/KotlinPluginScript.kt
|
1
|
3790
|
package org.apollo.game.plugin.kotlin
import org.apollo.game.command.CommandListener
import org.apollo.game.message.handler.MessageHandler
import org.apollo.game.message.impl.ButtonMessage
import org.apollo.game.model.World
import org.apollo.game.model.entity.setting.PrivilegeLevel
import org.apollo.game.model.event.Event
import org.apollo.game.model.event.EventListener
import org.apollo.game.model.event.PlayerEvent
import org.apollo.game.plugin.PluginContext
import org.apollo.net.message.Message
import kotlin.reflect.KClass
import kotlin.script.experimental.annotations.KotlinScript
@KotlinScript("Apollo Plugin Script", fileExtension = "plugin.kts")
abstract class KotlinPluginScript(var world: World, val context: PluginContext) {
private var startListener: (World) -> Unit = { _ -> }
private var stopListener: (World) -> Unit = { _ -> }
fun <T : Any, C : ListenableContext, I : PredicateContext> on(
listenable: Listenable<T, C, I>,
callback: C.() -> Unit
) {
registerListener(listenable, null, callback)
}
internal fun <T : Any, C : ListenableContext, I : PredicateContext> registerListener(
listenable: Listenable<T, C, I>,
predicateContext: I?,
callback: C.() -> Unit
) {
// Smart-casting/type-inference is completely broken in this function in intelliJ, so assign to otherwise
// pointless `l` values for now.
return when (listenable) {
is MessageListenable -> {
@Suppress("UNCHECKED_CAST")
val l = listenable as MessageListenable<Message, C, I>
val handler = l.createHandler(world, predicateContext, callback)
context.addMessageHandler(l.type.java, handler)
}
is EventListenable -> {
@Suppress("UNCHECKED_CAST")
val l = listenable as EventListenable<Event, C, I>
val handler = l.createHandler(world, predicateContext, callback)
world.listenFor(l.type.java, handler)
}
}
}
/**
* Create a [CommandListener] for the given [command] name, which only players with a [PrivilegeLevel]
* of [privileges] and above can use.
*/
fun on_command(command: String, privileges: PrivilegeLevel): KotlinCommandHandler { // TODO what to do with this?
return KotlinCommandHandler(world, command, privileges)
}
/**
* Creates a [MessageHandler].
*/
@Deprecated("Use new on(Type) listener")
fun <T : Message> on(type: () -> KClass<T>): OldKotlinMessageHandler<T> {
return OldKotlinMessageHandler(world, context, type())
}
/**
* Create an [EventListener] for a [PlayerEvent].
*/
@Deprecated("Use new on(Type) listener")
fun <T : PlayerEvent> on_player_event(type: () -> KClass<T>): OldKotlinPlayerEventHandler<T> {
return OldKotlinPlayerEventHandler(world, type())
}
/**
* Create an [EventListener] for an [Event].
*/
@Deprecated("Use new on(Type) listener")
fun <T : Event> on_event(type: () -> KClass<T>): OldKotlinEventHandler<T> {
return OldKotlinEventHandler(world, type())
}
/**
* Create a [ButtonMessage] [MessageHandler] for the given [id].
*/
@Deprecated("Use new on(Type) listener")
fun on_button(id: Int): KotlinPlayerHandlerProxyTrait<ButtonMessage> {
return on { ButtonMessage::class }.where { widgetId == id }
}
fun start(callback: (World) -> Unit) {
startListener = callback
}
fun stop(callback: (World) -> Unit) {
stopListener = callback
}
fun doStart(world: World) {
startListener(world)
}
fun doStop(world: World) {
stopListener(world)
}
}
|
isc
|
bc46a084f53d1adde9ff231027c0f25f
| 32.848214 | 117 | 0.642744 | 4.106176 | false | false | false | false |
adrcotfas/Goodtime
|
app/src/main/java/com/apps/adrcotfas/goodtime/database/Migrations.kt
|
1
|
4609
|
/*
* Copyright 2016-2021 Adrian Cotfas
*
* 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.apps.adrcotfas.goodtime.database
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
val MIGRATION_1_2: Migration = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL(
"CREATE TABLE labels_new (title TEXT NOT NULL, colorId INTEGER NOT NULL, 'order' INTEGER NOT NULL DEFAULT 0, archived INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(title, archived))"
)
database.execSQL(
"INSERT INTO labels_new (title, colorId) SELECT label, color FROM LabelAndColor"
)
database.execSQL("DROP TABLE LabelAndColor")
database.execSQL("ALTER TABLE labels_new RENAME TO Label")
database.execSQL(
"CREATE TABLE sessions_new (id INTEGER NOT NULL, timestamp INTEGER NOT NULL, duration INTEGER NOT NULL, label TEXT, archived INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(id), FOREIGN KEY(label, archived) REFERENCES Label(title, archived) ON UPDATE CASCADE ON DELETE SET DEFAULT)"
)
database.execSQL(
"INSERT INTO sessions_new (timestamp, duration, label) SELECT endTime, totalTime, label FROM Session"
)
database.execSQL("DROP TABLE Session")
database.execSQL("ALTER TABLE sessions_new RENAME TO Session")
}
}
val MIGRATION_2_3: Migration = object : Migration(2, 3) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL(
"CREATE TABLE Profile (name TEXT NOT NULL, durationWork INTEGER NOT NULL" +
", durationBreak INTEGER NOT NULL" +
", enableLongBreak INTEGER NOT NULL" +
", durationLongBreak INTEGER NOT NULL" +
", sessionsBeforeLongBreak INTEGER NOT NULL" +
", PRIMARY KEY(name))"
)
}
}
val MIGRATION_3_4: Migration = object : Migration(3, 4) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL(
"CREATE TABLE sessions_new (id INTEGER NOT NULL, timestamp INTEGER NOT NULL, duration INTEGER NOT NULL, label TEXT, archived INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(id), FOREIGN KEY(label, archived) REFERENCES Label(title, archived) ON UPDATE CASCADE ON DELETE SET DEFAULT)"
)
database.execSQL(
"INSERT INTO sessions_new (id, timestamp, duration, label, archived) SELECT id, timestamp, duration, label, archived FROM Session"
)
database.execSQL("DROP TABLE Session")
database.execSQL("ALTER TABLE sessions_new RENAME TO Session")
}
}
val MIGRATION_4_5: Migration = object : Migration(4, 5) {
override fun migrate(database: SupportSQLiteDatabase) {
// do nothing here; it seems to be needed by the switch to kapt room compiler
}
}
val MIGRATION_5_6: Migration = object : Migration(5, 6) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL(
"CREATE TABLE SessionTmp (id INTEGER NOT NULL, timestamp INTEGER NOT NULL, duration INTEGER NOT NULL, label TEXT, archived INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(id), FOREIGN KEY(label, archived) REFERENCES Label(title, archived) ON UPDATE CASCADE ON DELETE SET DEFAULT)")
database.execSQL(
"INSERT INTO SessionTmp (timestamp, duration, label) SELECT timestamp, duration, label FROM Session")
database.execSQL("DROP TABLE Session")
database.execSQL("ALTER TABLE SessionTmp RENAME TO Session")
database.execSQL(
"CREATE TABLE LabelTmp (title TEXT NOT NULL DEFAULT '', colorId INTEGER NOT NULL DEFAULT 0, 'order' INTEGER NOT NULL DEFAULT 0, archived INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(title, archived))")
database.execSQL(
"INSERT INTO LabelTmp (title, colorId, 'order', archived) SELECT title, colorId, 'order', archived FROM Label")
database.execSQL("DROP TABLE Label")
database.execSQL("ALTER TABLE LabelTmp RENAME TO Label")
}
}
|
apache-2.0
|
6b5b44aca937b6b426a9a4056244e445
| 50.797753 | 286 | 0.68887 | 4.655556 | false | false | false | false |
nemerosa/ontrack
|
ontrack-extension-delivery-metrics/src/main/java/net/nemerosa/ontrack/extension/dm/export/EndToEndPromotionMetricsExportJob.kt
|
1
|
1745
|
package net.nemerosa.ontrack.extension.dm.export
import net.nemerosa.ontrack.common.Time
import net.nemerosa.ontrack.extension.dm.model.DeliveryMetricsJobs
import net.nemerosa.ontrack.job.*
import net.nemerosa.ontrack.model.settings.CachedSettingsService
import net.nemerosa.ontrack.model.support.JobProvider
import org.springframework.stereotype.Component
@Component
class EndToEndPromotionMetricsExportJob(
private val endPromotionMetricsExportService: EndToEndPromotionMetricsExportService,
private val cachedSettingsService: CachedSettingsService,
) : JobProvider {
override fun getStartingJobs() = listOf(
JobRegistration(
createJob(),
Schedule.EVERY_HOUR,
)
)
private fun createJob() = object : Job {
override fun getKey(): JobKey =
DeliveryMetricsJobs.DM_JOB_CATEGORY
.getType("end-to-end-promotion-metrics")
.withName("End to end promotion metrics")
.getKey("export")
override fun getTask() = JobRun {
val settings = cachedSettingsService.getCachedSettings(EndToEndPromotionMetricsExportSettings::class.java)
if (settings.enabled) {
val now = Time.now()
endPromotionMetricsExportService.exportMetrics(
settings.branches,
now.minusDays(settings.pastDays.toLong()),
now,
)
}
}
override fun getDescription(): String =
"Export of end-to-end promotion metrics"
override fun isDisabled(): Boolean =
!cachedSettingsService.getCachedSettings(EndToEndPromotionMetricsExportSettings::class.java).enabled
}
}
|
mit
|
75c637a202d665189b370246e346e18f
| 34.632653 | 118 | 0.66533 | 5.057971 | false | false | false | false |
nemerosa/ontrack
|
ontrack-extension-scm/src/main/java/net/nemerosa/ontrack/extension/scm/catalog/search/SCMCatalogSearchIndexer.kt
|
1
|
4114
|
package net.nemerosa.ontrack.extension.scm.catalog.search
import com.fasterxml.jackson.databind.JsonNode
import net.nemerosa.ontrack.common.asMap
import net.nemerosa.ontrack.extension.scm.SCMExtensionFeature
import net.nemerosa.ontrack.extension.scm.catalog.CatalogLinkService
import net.nemerosa.ontrack.extension.scm.catalog.SCMCatalog
import net.nemerosa.ontrack.extension.scm.catalog.SCMCatalogEntry
import net.nemerosa.ontrack.extension.scm.catalog.ui.SCMCatalogController
import net.nemerosa.ontrack.job.Schedule
import net.nemerosa.ontrack.model.structure.*
import net.nemerosa.ontrack.ui.controller.EntityURIBuilder
import org.springframework.stereotype.Component
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder
import java.net.URI
@Component
class SCMCatalogSearchIndexer(
extensionFeature: SCMExtensionFeature,
private val scmCatalog: SCMCatalog,
private val catalogLinkService: CatalogLinkService,
private val uriBuilder: EntityURIBuilder
) : SearchIndexer<SCMCatalogSearchItem> {
override val indexerName: String = "SCM Catalog"
override val indexName: String = "scm-catalog"
override val searchResultType = SearchResultType(
feature = extensionFeature.featureDescription,
id = "scm-catalog",
name = "SCM Catalog",
description = "Indexed SCM repository, which might be associated or not with an Ontrack project"
)
override fun indexAll(processor: (SCMCatalogSearchItem) -> Unit) {
scmCatalog.catalogEntries.forEach { entry ->
val item = SCMCatalogSearchItem(entry)
processor(item)
}
}
override fun toSearchResult(id: String, score: Double, source: JsonNode): SearchResult? {
// Gets the associated entry
val entry = scmCatalog.getCatalogEntry(id)
// Returns the result
return entry?.let {
// Gets the associated project
val project = catalogLinkService.getLinkedProject(entry)
// Title and description
val title: String
val description: String
val uri: URI
val page: URI
if (project != null) {
title = "${project.name} (${entry.repository})"
description = "Project ${project.name} associated with SCM ${entry.repository} (${entry.scm} @ ${entry.config})"
uri = uriBuilder.getEntityURI(project)
page = uriBuilder.getEntityPage(project)
} else {
title = entry.repository
description = "SCM ${entry.repository} (${entry.scm} @ ${entry.config}) not associated with any project"
uri = uriBuilder.build(MvcUriComponentsBuilder.on(SCMCatalogController::class.java).entries())
page = uriBuilder.page("extension/scm/scm-catalog")
}
// Result
SearchResult(
title = title,
description = description,
uri = uri,
page = page,
accuracy = score,
type = searchResultType
)
}
}
override val isIndexationDisabled: Boolean = false
override val indexerSchedule: Schedule = Schedule.EVERY_WEEK
override val indexMapping: SearchIndexMapping = indexMappings<SCMCatalogSearchItem> {
+SCMCatalogSearchItem::scm to keyword()
+SCMCatalogSearchItem::config to keyword()
+SCMCatalogSearchItem::repository to keyword { scoreBoost = 3.0 } to text()
}
}
data class SCMCatalogSearchItem(
override val id: String,
val scm: String,
val config: String,
val repository: String
) : SearchItem {
constructor(entry: SCMCatalogEntry) : this(
id = entry.key,
scm = entry.scm,
config = entry.config,
repository = entry.repository
)
override val fields: Map<String, Any?> = asMap(
this::scm,
this::config,
this::repository
)
}
|
mit
|
6bf6391154b7ae52713db71c91a24946
| 36.743119 | 128 | 0.6456 | 4.932854 | false | true | false | false |
FFlorien/AmpachePlayer
|
app/src/main/java/be/florien/anyflow/AnyFlowApp.kt
|
1
|
3831
|
package be.florien.anyflow
import android.annotation.SuppressLint
import android.app.NotificationChannel
import android.app.NotificationManager
import android.os.Build
import androidx.multidex.MultiDexApplication
import be.florien.anyflow.data.UpdateService
import be.florien.anyflow.data.server.AmpacheApi
import be.florien.anyflow.data.server.AmpacheConnection
import be.florien.anyflow.data.user.UserComponent
import be.florien.anyflow.extension.eLog
import be.florien.anyflow.injection.ApplicationComponent
import be.florien.anyflow.injection.DaggerApplicationComponent
import be.florien.anyflow.player.PlayerService
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.jackson.JacksonConverterFactory
import timber.log.Timber
import javax.inject.Inject
/**
* Application class used for initialization of many libraries
*/
@SuppressLint("Registered")
open class AnyFlowApp : MultiDexApplication(), UserComponentContainer {
lateinit var applicationComponent: ApplicationComponent
protected set
override var userComponent: UserComponent? = null
@Inject
lateinit var ampacheConnection: AmpacheConnection
@Inject
lateinit var okHttpClient: OkHttpClient
override fun onCreate() {
super.onCreate()
Timber.plant(CrashReportingTree())
initApplicationComponent()
ampacheConnection.ensureConnection()
createNotificationChannels()
Thread.setDefaultUncaughtExceptionHandler { _, e ->
[email protected](e, "Unexpected error")
}
}
protected open fun initApplicationComponent() {
applicationComponent = DaggerApplicationComponent
.builder()
.application(this)
.build()
applicationComponent.inject(this)
}
override fun createUserScopeForServer(serverUrl: String): AmpacheApi {
val ampacheApi = Retrofit
.Builder()
.baseUrl(serverUrl)
.client(okHttpClient)
.addConverterFactory(JacksonConverterFactory.create())
.build()
.create(AmpacheApi::class.java)
userComponent = applicationComponent
.userComponentBuilder()
.ampacheApi(ampacheApi)
.build()
return ampacheApi
}
private fun createNotificationChannels() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val playerChannel = getPlayerChannel()
val updateChannel = getUpdateChannel()
val notificationManager = getSystemService(NotificationManager::class.java)
notificationManager?.createNotificationChannel(playerChannel)
notificationManager?.createNotificationChannel(updateChannel)
}
}
private fun getPlayerChannel(): NotificationChannel {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(PlayerService.MEDIA_SESSION_NAME, "Music", NotificationManager.IMPORTANCE_LOW)
channel.description = "It play music"
channel.vibrationPattern = null
channel.enableVibration(false)
return channel
} else {
throw UnsupportedOperationException("This method shouldn't be called from this api")
}
}
private fun getUpdateChannel(): NotificationChannel {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(UpdateService.UPDATE_SESSION_NAME, "Update", NotificationManager.IMPORTANCE_DEFAULT)
channel.description = "It update your music database"
return channel
} else {
throw UnsupportedOperationException("This method shouldn't be called from this api")
}
}
}
|
gpl-3.0
|
3aed12c440af9fb6aeba2f2c6d586d38
| 36.203883 | 130 | 0.694336 | 5.552174 | false | false | false | false |
FFlorien/AmpachePlayer
|
app/src/main/java/be/florien/anyflow/data/DataRepository.kt
|
1
|
17177
|
package be.florien.anyflow.data
import android.content.SharedPreferences
import androidx.lifecycle.LiveData
import androidx.lifecycle.map
import androidx.paging.*
import be.florien.anyflow.data.local.LibraryDatabase
import be.florien.anyflow.data.local.model.*
import be.florien.anyflow.data.server.AmpacheConnection
import be.florien.anyflow.data.view.*
import be.florien.anyflow.extension.applyPutLong
import com.google.android.exoplayer2.offline.DownloadManager
import com.google.firebase.crashlytics.FirebaseCrashlytics
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.lang.Exception
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
/**
* Update the local data with the one from the server
*/
@Singleton
class DataRepository
@Inject constructor(
private val libraryDatabase: LibraryDatabase,
private val ampacheConnection: AmpacheConnection,
private val sharedPreferences: SharedPreferences,
private val downloadManager: DownloadManager
) {
private fun lastAcceptableUpdate() = TimeOperations.getCurrentDatePlus(Calendar.HOUR, -1)
/**
* Getter with server updates
*/
suspend fun updateAll() = withContext(Dispatchers.IO) {
updateArtistsAsync()
updateAlbumsAsync()
updateSongsAsync()
updatePlaylistAsync()
}
suspend fun getSongAtPosition(position: Int) =
withContext(Dispatchers.IO) {
libraryDatabase.getSongAtPosition(position)?.toViewSongInfo()
}
suspend fun getPositionForSong(songId: Long) =
withContext(Dispatchers.IO) { libraryDatabase.getPositionForSong(songId) }
suspend fun getSongById(songId: Long) =
withContext(Dispatchers.IO) { libraryDatabase.getSongById(songId)?.toViewSongInfo() }
fun getSongsInQueueOrder() =
convertToPagingLiveData(libraryDatabase.getSongsInQueueOrder().map { it.toViewSong() })
fun getIdsInQueueOrder() = libraryDatabase.getIdsInQueueOrder()
fun searchSongs(filter: String) = libraryDatabase.searchSongs("%$filter%")
suspend fun getQueueSize(): Int? =
withContext(Dispatchers.IO) { libraryDatabase.getQueueSize() }
fun <T : Any> getAlbums(mapping: (DbAlbumDisplay) -> T): LiveData<PagingData<T>> =
convertToPagingLiveData(libraryDatabase.getAlbums().map { mapping(it) })
fun <T : Any> getAlbumArtists(mapping: (DbArtistDisplay) -> T): LiveData<PagingData<T>> =
convertToPagingLiveData(libraryDatabase.getAlbumArtists().map { mapping(it) })
fun <T : Any> getGenres(mapping: (String) -> T): LiveData<PagingData<T>> =
convertToPagingLiveData(libraryDatabase.getGenres().map { mapping(it) })
fun <T : Any> getSongs(mapping: (DbSongDisplay) -> T): LiveData<PagingData<T>> =
convertToPagingLiveData(libraryDatabase.getSongsInAlphabeticalOrder().map { mapping(it) })
fun <T : Any> getPlaylists(mapping: (DbPlaylist) -> T): LiveData<PagingData<T>> =
convertToPagingLiveData(libraryDatabase.getPlaylists().map { mapping(it) })
/**
* Filtered lists
*/
fun <T : Any> getAlbumsFiltered(
filter: String,
mapping: (DbAlbumDisplay) -> T
): LiveData<PagingData<T>> =
convertToPagingLiveData(libraryDatabase.getAlbumsFiltered("%$filter%").map { mapping(it) })
suspend fun <T : Any> getAlbumsFilteredList(
filter: String,
mapping: (DbAlbumDisplay) -> T
): List<T> =
libraryDatabase.getAlbumsFilteredList("%$filter%").map { item -> (mapping(item)) }
fun <T : Any> getAlbumArtistsFiltered(
filter: String,
mapping: (DbArtistDisplay) -> T
): LiveData<PagingData<T>> =
convertToPagingLiveData(
libraryDatabase.getAlbumArtistsFiltered("%$filter%").map { mapping(it) })
suspend fun <T : Any> getAlbumArtistsFilteredList(
filter: String,
mapping: (DbArtistDisplay) -> T
): List<T> =
libraryDatabase.getAlbumArtistsFilteredList("%$filter%").map { item -> (mapping(item)) }
fun <T : Any> getGenresFiltered(
filter: String,
mapping: (String) -> T
): LiveData<PagingData<T>> =
convertToPagingLiveData(libraryDatabase.getGenresFiltered("%$filter%").map { mapping(it) })
suspend fun <T : Any> getGenresFilteredList(
filter: String,
mapping: (String) -> T
): List<T> =
libraryDatabase.getGenresFilteredList("%$filter%").map { item -> (mapping(item)) }
fun <T : Any> getSongsFiltered(
filter: String,
mapping: (DbSongDisplay) -> T
): LiveData<PagingData<T>> =
convertToPagingLiveData(libraryDatabase.getSongsFiltered("%$filter%").map { mapping(it) })
suspend fun <T : Any> getSongsFilteredList(
filter: String,
mapping: (DbSongDisplay) -> T
): List<T> =
libraryDatabase.getSongsFilteredList("%$filter%").map { item -> (mapping(item)) }
fun <T : Any> getPlaylistsFiltered(
filter: String,
mapping: (DbPlaylist) -> T
): LiveData<PagingData<T>> =
convertToPagingLiveData(
libraryDatabase.getPlaylistsFiltered("%$filter%").map { mapping(it) })
suspend fun <T : Any> getPlaylistsFilteredList(
filter: String,
mapping: (DbPlaylist) -> T
): List<T> =
libraryDatabase.getPlaylistsFilteredList("%$filter%").map { item -> (mapping(item)) }
suspend fun updateSongLocalUri(songId: Long, uri: String) {
libraryDatabase.updateSongLocalUri(songId, uri)
}
/**
* Playlists modification
*/
suspend fun createPlaylist(name: String) {
ampacheConnection.createPlaylist(name)
updatePlaylistAsync()
}
suspend fun addSongToPlaylist(songId: Long, playlistId: Long) {
ampacheConnection.addSongToPlaylist(songId, playlistId)
libraryDatabase.addPlaylistSongs(listOf(DbPlaylistSongs(songId, playlistId)))
}
/**
* Orders
*/
fun getOrders() =
libraryDatabase.getOrders().map { list -> list.map { item -> item.toViewOrder() } }
suspend fun getOrderlessQueue(filterList: List<Filter<*>>, orderList: List<Order>): List<Long> =
withContext(Dispatchers.IO) {
libraryDatabase.getSongsFromQuery(
getQueryForSongs(
filterList.map { it.toDbFilter(DbFilterGroup.CURRENT_FILTER_GROUP_ID) },
orderList
)
)
}
suspend fun setOrders(orders: List<Order>) =
withContext(Dispatchers.IO) {
libraryDatabase.setOrders(orders.map { it.toDbOrder() })
}
suspend fun saveQueueOrder(listToSave: MutableList<Long>) {
libraryDatabase.saveQueueOrder(listToSave)
}
/**
* Alarms
*/
suspend fun addAlarm(alarm: Alarm) = libraryDatabase.addAlarm(alarm.toDbAlarm())
fun getAlarms(): LiveData<List<Alarm>> =
libraryDatabase.getAlarms().map { list -> list.map { it.toViewAlarm() } }
suspend fun getAlarmList(): List<Alarm> =
libraryDatabase.getAlarmList().map { it.toViewAlarm() }
suspend fun activateAlarm(alarm: Alarm) {
val newAlarm = alarm.copy(active = true)
libraryDatabase.updateAlarm(newAlarm.toDbAlarm())
}
suspend fun deactivateAlarm(alarm: Alarm) {
val newAlarm = alarm.copy(active = false)
libraryDatabase.updateAlarm(newAlarm.toDbAlarm())
}
suspend fun editAlarm(alarm: Alarm) {
libraryDatabase.updateAlarm(alarm.toDbAlarm())
}
suspend fun deleteAlarm(alarm: Alarm) {
libraryDatabase.deleteAlarm(alarm.toDbAlarm())
}
/**
* Filter groups
*/
suspend fun createFilterGroup(filterList: List<Filter<*>>, name: String) =
withContext(Dispatchers.IO) {
libraryDatabase.createFilterGroup(filterList.map {
it.toDbFilter(-1)
}, name)
}
fun getFilterGroups() = libraryDatabase.getFilterGroups()
.map { groupList -> groupList.map { it.toViewFilterGroup() } }
suspend fun setSavedGroupAsCurrentFilters(filterGroup: FilterGroup) =
withContext(Dispatchers.IO) { libraryDatabase.setSavedGroupAsCurrentFilters(filterGroup.toDbFilterGroup()) }
fun getCurrentFilters(): LiveData<List<Filter<*>>> = libraryDatabase.getCurrentFilters()
.map { filterList -> filterList.map { it.toViewFilter() } }
suspend fun setCurrentFilters(filterList: List<Filter<*>>) = withContext(Dispatchers.IO) {
libraryDatabase.setCurrentFilters(filterList.map {
it.toDbFilter(1)
})
}
/**
* Download status
*/
fun hasDownloaded(song: SongInfo): Boolean =
downloadManager.downloadIndex.getDownload(song.url) != null
/**
* Private Method
*/
private suspend fun updateSongsAsync() = updateListAsync(
LAST_SONG_UPDATE,
AmpacheConnection::getSongs,
) { ampacheSongList ->
if (ampacheSongList != null) {
val songs = ampacheSongList.map { it.toDbSong() }
libraryDatabase.addSongs(songs)
libraryDatabase.correctAlbumArtist(songs)
}
}
private suspend fun updateArtistsAsync() = updateListAsync(
LAST_ARTIST_UPDATE,
AmpacheConnection::getArtists,
) { ampacheArtistList ->
if (ampacheArtistList != null) {
libraryDatabase.addArtists(ampacheArtistList.map { it.toDbArtist() })
}
}
private suspend fun updateAlbumsAsync() = updateListAsync(
LAST_ALBUM_UPDATE,
AmpacheConnection::getAlbums,
) { ampacheAlbumList ->
if (ampacheAlbumList != null) {
libraryDatabase.addAlbums(ampacheAlbumList.map { it.toDbAlbum() })
}
}
private suspend fun <SERVER_TYPE> updateListAsync(
updatePreferenceName: String,
getListOnServer: suspend AmpacheConnection.(Calendar) -> List<SERVER_TYPE>?,
saveToDatabase: suspend (List<SERVER_TYPE>?) -> Unit
) {
val nowDate = TimeOperations.getCurrentDate()
val lastUpdate =
TimeOperations.getDateFromMillis(sharedPreferences.getLong(updatePreferenceName, 0))
val lastAcceptableUpdate = lastAcceptableUpdate()
if (lastUpdate.before(lastAcceptableUpdate)) {
var listOnServer = ampacheConnection.getListOnServer(lastUpdate)
while (listOnServer != null) {
// listOnServer = if (listOnServer.getError().code == 401) {
// songServerConnection.reconnect { songServerConnection.getListOnServer(lastUpdate) }
// } else {
// listOnServer
// }
saveToDatabase(listOnServer)
listOnServer = ampacheConnection.getListOnServer(lastUpdate)
}
sharedPreferences.applyPutLong(updatePreferenceName, nowDate.timeInMillis)
}
}
private suspend fun updatePlaylistAsync() {
val nowDate = TimeOperations.getCurrentDate()
val lastUpdate =
TimeOperations.getDateFromMillis(sharedPreferences.getLong(LAST_PLAYLIST_UPDATE, 0))
val lastAcceptableUpdate = lastAcceptableUpdate()
if (lastUpdate.before(lastAcceptableUpdate)) {
var listOnServer = ampacheConnection.getPlaylists()
while (listOnServer != null) {
libraryDatabase.addPlayLists(listOnServer.map { it.toDbPlaylist() })
for (playlist in listOnServer) {
updatePlaylistSongListAsync(playlist.id)
}
listOnServer = ampacheConnection.getPlaylists()
}
sharedPreferences.applyPutLong(LAST_PLAYLIST_UPDATE, nowDate.timeInMillis)
}
}
private suspend fun updatePlaylistSongListAsync(playlistId: Long) {
val nowDate = TimeOperations.getCurrentDate()
val lastUpdate = TimeOperations.getDateFromMillis(
sharedPreferences.getLong(
"$LAST_PLAYLIST_SONGS_UPDATE$playlistId",
0
)
)
val lastAcceptableUpdate = lastAcceptableUpdate()
if (lastUpdate.before(lastAcceptableUpdate)) {
var listOnServer = ampacheConnection.getPlaylistsSongs(playlistId)
while (listOnServer != null) {
libraryDatabase.addPlaylistSongs(listOnServer.map {
DbPlaylistSongs(
it.id,
playlistId
)
})
listOnServer = ampacheConnection.getPlaylistsSongs(playlistId)
}
sharedPreferences.applyPutLong(
"$LAST_PLAYLIST_SONGS_UPDATE$playlistId",
nowDate.timeInMillis
)
}
}
private fun <T : Any> convertToPagingLiveData(dataSourceFactory: DataSource.Factory<Int, T>): LiveData<PagingData<T>> =
Pager(PagingConfig(100), 0, dataSourceFactory.asPagingSourceFactory(Dispatchers.IO)).liveData
private fun getQueryForSongs(dbFilters: List<DbFilter>, orderList: List<Order>): String {
fun constructOrderStatement(): String {
val filteredOrderedList =
orderList.filter { it.orderingType != Order.Ordering.PRECISE_POSITION }
val isSorted =
filteredOrderedList.isNotEmpty() && filteredOrderedList.all { it.orderingType != Order.Ordering.RANDOM }
var orderStatement = if (isSorted) {
" ORDER BY"
} else {
""
}
if (isSorted) {
filteredOrderedList.forEachIndexed { index, order ->
orderStatement += when (order.orderingSubject) {
Order.Subject.ALL -> " song.id"
Order.Subject.ARTIST -> " song.artistName"
Order.Subject.ALBUM_ARTIST -> " song.albumArtistName"
Order.Subject.ALBUM -> " song.albumName"
Order.Subject.ALBUM_ID -> " song.albumId"
Order.Subject.YEAR -> " song.year"
Order.Subject.GENRE -> " song.genre"
Order.Subject.TRACK -> " song.track"
Order.Subject.TITLE -> " song.title"
}
orderStatement += when (order.orderingType) {
Order.Ordering.ASCENDING -> " ASC"
Order.Ordering.DESCENDING -> " DESC"
else -> ""
}
if (index < filteredOrderedList.size - 1 && orderStatement.last() != ',') {
orderStatement += ","
}
}
}
if (orderList.isEmpty() || (orderList.size == 1 && orderList[0].orderingType != Order.Ordering.RANDOM) || orderList.any { it.orderingSubject == Order.Subject.ALL }) {
FirebaseCrashlytics.getInstance()
.recordException(Exception("This is not the order you looking for (orderStatement: $orderStatement)"))
}
return orderStatement
}
return "SELECT id FROM song" + constructJoinStatement(dbFilters) + constructWhereStatement(
dbFilters
) + constructOrderStatement()
}
private fun constructJoinStatement(filterList: List<DbFilter>): String = filterList
.filter { !it.joinClause.isNullOrBlank() }
.distinctBy { it.joinClause }
.joinToString(separator = " ", prefix = " ", postfix = " ") { it.joinClause!! }
private fun constructWhereStatement(filterList: List<DbFilter>): String {
var whereStatement = if (filterList.isNotEmpty()) {
" WHERE"
} else {
""
}
filterList.forEachIndexed { index, filter ->
whereStatement += when (filter.clause) {
DbFilter.SONG_ID,
DbFilter.ARTIST_ID,
DbFilter.ALBUM_ARTIST_ID,
DbFilter.PLAYLIST_ID,
DbFilter.ALBUM_ID -> " ${filter.clause} ${filter.argument}"
DbFilter.DOWNLOADED -> " ${DbFilter.DOWNLOADED}"
DbFilter.NOT_DOWNLOADED -> " ${DbFilter.NOT_DOWNLOADED}"
else -> " ${filter.clause} \"${filter.argument}\""
}
if (index < filterList.size - 1) {
whereStatement += " OR"
}
}
return whereStatement
}
suspend fun isPlaylistContainingSong(playlistId: Long, songId: Long): Boolean =
libraryDatabase.isPlaylistContainingSong(playlistId, songId)
companion object {
private const val LAST_SONG_UPDATE = "LAST_SONG_UPDATE"
// updated because the art was added , see LibraryDatabase migration 1->2
private const val LAST_ARTIST_UPDATE = "LAST_ARTIST_UPDATE_v1"
private const val LAST_ALBUM_UPDATE = "LAST_ALBUM_UPDATE"
private const val LAST_PLAYLIST_UPDATE = "LAST_PLAYLIST_UPDATE"
private const val LAST_PLAYLIST_SONGS_UPDATE = "LAST_PLAYLIST_SONGS_UPDATE_"
}
}
|
gpl-3.0
|
cf7fa0f4a1fbe8cb91764464186c1d9c
| 36.021552 | 178 | 0.624905 | 4.722849 | false | false | false | false |
nickbutcher/plaid
|
core/src/test/java/io/plaidapp/core/designernews/data/stories/StoriesRemoteDataSourceTest.kt
|
1
|
6028
|
/*
* Copyright 2018 Google LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.plaidapp.core.designernews.data.stories
import com.nhaarman.mockitokotlin2.doAnswer
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import io.plaidapp.core.data.Result
import io.plaidapp.core.designernews.data.api.DesignerNewsService
import io.plaidapp.core.designernews.data.stories.model.StoryResponse
import io.plaidapp.core.designernews.errorResponseBody
import io.plaidapp.core.designernews.storyLinks
import java.net.UnknownHostException
import java.util.Date
import java.util.GregorianCalendar
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import retrofit2.Response
/**
* Test for [StoriesRemoteDataSource] mocking all dependencies.
*/
class StoriesRemoteDataSourceTest {
private val createdDate: Date = GregorianCalendar(2018, 1, 13).time
private val story = StoryResponse(
id = 45L,
title = "Plaid 2.0 was released",
created_at = createdDate,
links = storyLinks
)
private val storySequel = StoryResponse(
id = 876L,
title = "Plaid 2.0 is bug free",
created_at = createdDate,
links = storyLinks
)
private val stories = listOf(story, storySequel)
private val query = "Plaid 2.0"
private val service: DesignerNewsService = mock()
private val dataSource = StoriesRemoteDataSource(service)
@Test
fun loadStories_withSuccess() = runBlocking {
// Given that the service responds with success
withStoriesSuccess(2, stories)
// When requesting stories
val result = dataSource.loadStories(2)
// Then there's one request to the service
verify(service).getStories(2)
// Then the correct list of stories is returned
assertEquals(Result.Success(stories), result)
}
@Test
fun loadStories_withError() = runBlocking {
// Given that the service responds with error
withStoriesError(1)
// When requesting stories
val result = dataSource.loadStories(1)
// Then error is returned
assertTrue(result is Result.Error)
}
@Test
fun loadStories_withException() = runBlocking {
// Given that the service throws an exception
doAnswer { throw UnknownHostException() }
.whenever(service).getStories(1)
// When requesting stories
val result = dataSource.loadStories(1)
// Then error is returned
assertTrue(result is Result.Error)
}
@Test
fun search_withSuccess() = runBlocking {
// Given that the service responds with success
val storyIds = stories.map { it.id.toString() }
whenever(service.search(query, 2)).thenReturn(Response.success(storyIds))
val commaSeparatedIds = storyIds.joinToString(",")
whenever(service.getStories(commaSeparatedIds)).thenReturn(Response.success(stories))
// When searching for stories
val result = dataSource.search(query, 2)
// Then the correct list of stories is returned
assertEquals(Result.Success(stories), result)
}
@Test
fun search_withErrorScrapingResults() = runBlocking {
// Given that the service responds with error
val error = Response.error<List<String>>(400, errorResponseBody)
whenever(service.search(query, 1)).thenReturn(error)
// When searching for stories
val result = dataSource.search(query, 1)
// Then error is returned
assertTrue(result is Result.Error)
}
@Test
fun search_withExceptionScrapingResults() = runBlocking {
// Given that the service throws an exception
doAnswer { throw UnknownHostException() }
.whenever(service).search(query, 1)
// When searching for stories
val result = dataSource.search(query, 1)
// Then error is returned
assertTrue(result is Result.Error)
}
@Test
fun search_withErrorFetchingStories() = runBlocking {
// Given that the service responds with error
val storyIds = stories.joinToString(",") { it.id.toString() }
val error = Response.error<List<StoryResponse>>(400, errorResponseBody)
whenever(service.getStories(storyIds)).thenReturn(error)
// When searching for stories
val result = dataSource.search(query, 1)
// Then error is returned
assertTrue(result is Result.Error)
}
@Test
fun search_withExceptionFetchingStories() = runBlocking {
// Given that the service throws an exception
doAnswer { throw UnknownHostException() }
.whenever(service).getStories(stories.joinToString(",") { it.id.toString() })
// When searching for stories
val result = dataSource.search(query, 1)
// Then error is returned
assertTrue(result is Result.Error)
}
private suspend fun withStoriesSuccess(page: Int, stories: List<StoryResponse>) {
val result = Response.success(stories)
whenever(service.getStories(page)).thenReturn(result)
}
private suspend fun withStoriesError(page: Int) {
val result = Response.error<List<StoryResponse>>(
400,
errorResponseBody
)
whenever(service.getStories(page)).thenReturn(result)
}
}
|
apache-2.0
|
214bc0ce83b0ccdf5d318be2c05c4ac5
| 32.488889 | 93 | 0.683145 | 4.612089 | false | true | false | false |
deadpixelsociety/twodee
|
src/main/kotlin/com/thedeadpixelsociety/twodee/assets/namespace.kt
|
1
|
1693
|
package com.thedeadpixelsociety.twodee.assets
import com.badlogic.gdx.assets.AssetLoaderParameters
import com.badlogic.gdx.assets.loaders.ShaderProgramLoader
import com.badlogic.gdx.graphics.glutils.ShaderProgram
import com.thedeadpixelsociety.twodee.Action
/**
* Loads an asset from the asset manager.
* @param T The asset type.
* @param filename The asset filename.
* @param parameters Optional asset loader parameters.
* @param init An optional initialization function with the realized asset.
* @return A delegate used to load the asset.
* @see AssetDelegate<T>
*/
inline fun <reified T> asset(
filename: String,
parameters: AssetLoaderParameters<T>? = null,
noinline init: Action<T>? = null) = AssetDelegate(
filename,
T::class.java,
parameters,
init
)
/**
* Loads and initializes a ShaderProgram from the asset manager. This function will exit the program if the shader
* fails to compile.
* @param vertFileName The vertex shader filename. Should end with a 'vert' extension.
* @param fragFileName The fragment sahder filename. Should end with a 'frag' extension. If left empty this will
* default to the vertex filename.
* versa.
* @return The created shader program.
* @see ShaderProgram
*/
fun shader(vertFileName: String, fragFileName: String? = null) = asset<ShaderProgram>(
vertFileName,
ShaderProgramLoader.ShaderProgramParameter().apply {
this.vertexFile = vertFileName
this.fragmentFile = fragFileName
}
) {
if (!it.isCompiled) {
error("Shader not compilted: ${it.log}")
}
if (it.log.isNotEmpty()) println("Shader log: ${it.log}")
}
|
mit
|
32e8a3f3888c92ee4aaf4a61302b579d
| 33.55102 | 114 | 0.70762 | 4.253769 | false | false | false | false |
Ztiany/Repository
|
Kotlin/Kotlin-Android/app/src/main/java/com/ztiany/kotlin/extension/ExtensionSampleFragment.kt
|
4
|
1961
|
package com.ztiany.kotlin.extension
import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.ztiany.kotlin.R
import kotlinx.android.extensions.CacheImplementation
import kotlinx.android.extensions.ContainerOptions
import kotlinx.android.synthetic.main.fragment_extension_sample.*
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.info
/**
*@author Ztiany
* Email: [email protected]
* Date : 2017-08-27 17:34
*/
@ContainerOptions(CacheImplementation.SPARSE_ARRAY) //指定缓存view的实现
class ExtensionSampleFragment : Fragment(), AnkoLogger {
companion object {
fun newInstance(user: User): Fragment {
val fragment = ExtensionSampleFragment()
val bundle = Bundle()
bundle.putParcelable("User", user)
fragment.arguments = bundle
return fragment
}
}
override fun onAttach(context: Context?) {
super.onAttach(context)
val user = arguments?.getParcelable<User>("User")
info(user)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater.inflate(R.layout.fragment_extension_sample, container, false)
@SuppressLint("SetTextI18n")
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
extension_tv_name.text = "extension 演示"
extension_rv_list.layoutManager = LinearLayoutManager(context)
extension_rv_list.addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL))
extension_rv_list.adapter = SampleAdapter()
}
}
|
apache-2.0
|
ee5fb83ceb8edb5a790ea0339188ac54
| 33.714286 | 116 | 0.737005 | 4.561033 | false | false | false | false |
donald-w/Anki-Android
|
AnkiDroid/src/main/java/com/ichi2/anki/dialogs/DeckPickerContextMenu.kt
|
1
|
9872
|
/****************************************************************************************
* Copyright (c) 2015 Timothy Rae <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.anki.dialogs
import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.annotation.IntDef
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.MaterialDialog.ListCallback
import com.ichi2.anim.ActivityTransitionAnimation
import com.ichi2.anki.*
import com.ichi2.anki.StudyOptionsFragment.StudyOptionsListener
import com.ichi2.anki.analytics.AnalyticsDialogFragment
import com.ichi2.anki.dialogs.customstudy.CustomStudyDialog
import com.ichi2.utils.FragmentFactoryUtils
import com.ichi2.utils.HashUtil.HashMapInit
import timber.log.Timber
import java.util.*
class DeckPickerContextMenu : AnalyticsDialogFragment() {
@kotlin.annotation.Retention(AnnotationRetention.SOURCE)
@IntDef(CONTEXT_MENU_RENAME_DECK, CONTEXT_MENU_DECK_OPTIONS, CONTEXT_MENU_CUSTOM_STUDY, CONTEXT_MENU_DELETE_DECK, CONTEXT_MENU_EXPORT_DECK, CONTEXT_MENU_UNBURY, CONTEXT_MENU_CUSTOM_STUDY_REBUILD, CONTEXT_MENU_CUSTOM_STUDY_EMPTY, CONTEXT_MENU_CREATE_SUBDECK, CONTEXT_MENU_CREATE_SHORTCUT, CONTEXT_MENU_BROWSE_CARDS)
annotation class DECK_PICKER_CONTEXT_MENU
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
super.onCreate(savedInstanceState)
val did = requireArguments().getLong("did")
val title = CollectionHelper.getInstance().getCol(context).decks.name(did)
val itemIds = listIds
return MaterialDialog.Builder(requireActivity())
.title(title)
.cancelable(true)
.autoDismiss(false)
.itemsIds(itemIds)
.items(*ContextMenuHelper.getValuesFromKeys(keyValueMap, itemIds))
.itemsCallback(mContextMenuListener)
.build()
}
private val keyValueMap: HashMap<Int, String>
get() {
val res = resources
val keyValueMap = HashMapInit<Int, String>(9)
keyValueMap[CONTEXT_MENU_RENAME_DECK] = res.getString(R.string.rename_deck)
keyValueMap[CONTEXT_MENU_DECK_OPTIONS] = res.getString(R.string.menu__deck_options)
keyValueMap[CONTEXT_MENU_CUSTOM_STUDY] = res.getString(R.string.custom_study)
keyValueMap[CONTEXT_MENU_DELETE_DECK] = res.getString(R.string.contextmenu_deckpicker_delete_deck)
keyValueMap[CONTEXT_MENU_EXPORT_DECK] = res.getString(R.string.export_deck)
keyValueMap[CONTEXT_MENU_UNBURY] = res.getString(R.string.unbury)
keyValueMap[CONTEXT_MENU_CUSTOM_STUDY_REBUILD] = res.getString(R.string.rebuild_cram_label)
keyValueMap[CONTEXT_MENU_CUSTOM_STUDY_EMPTY] = res.getString(R.string.empty_cram_label)
keyValueMap[CONTEXT_MENU_CREATE_SUBDECK] = res.getString(R.string.create_subdeck)
keyValueMap[CONTEXT_MENU_CREATE_SHORTCUT] = res.getString(R.string.create_shortcut)
keyValueMap[CONTEXT_MENU_BROWSE_CARDS] = res.getString(R.string.browse_cards)
return keyValueMap
} // init with our fixed list size for performance
/**
* Retrieve the list of ids to put in the context menu list
* @return the ids of which values to show
*/
@get:DECK_PICKER_CONTEXT_MENU
private val listIds: IntArray
get() {
val col = CollectionHelper.getInstance().getCol(context)
val did = requireArguments().getLong("did")
val dyn = col.decks.isDyn(did)
val itemIds = ArrayList<Int>(10) // init with our fixed list size for performance
itemIds.add(CONTEXT_MENU_BROWSE_CARDS)
if (dyn) {
itemIds.add(CONTEXT_MENU_CUSTOM_STUDY_REBUILD)
itemIds.add(CONTEXT_MENU_CUSTOM_STUDY_EMPTY)
}
itemIds.add(CONTEXT_MENU_RENAME_DECK)
if (!dyn) {
itemIds.add(CONTEXT_MENU_CREATE_SUBDECK)
}
itemIds.add(CONTEXT_MENU_DECK_OPTIONS)
if (!dyn) {
itemIds.add(CONTEXT_MENU_CUSTOM_STUDY)
}
itemIds.add(CONTEXT_MENU_DELETE_DECK)
itemIds.add(CONTEXT_MENU_EXPORT_DECK)
if (col.sched.haveBuried(did)) {
itemIds.add(CONTEXT_MENU_UNBURY)
}
itemIds.add(CONTEXT_MENU_CREATE_SHORTCUT)
return ContextMenuHelper.integerListToArray(itemIds)
}
// Handle item selection on context menu which is shown when the user long-clicks on a deck
private val mContextMenuListener = ListCallback { _: MaterialDialog?, view: View, _: Int, _: CharSequence? ->
when (view.id) {
CONTEXT_MENU_DELETE_DECK -> {
Timber.i("Delete deck selected")
(activity as DeckPicker?)!!.confirmDeckDeletion()
}
CONTEXT_MENU_DECK_OPTIONS -> {
Timber.i("Open deck options selected")
(activity as DeckPicker?)!!.showContextMenuDeckOptions()
(activity as AnkiActivity?)!!.dismissAllDialogFragments()
}
CONTEXT_MENU_CUSTOM_STUDY -> {
Timber.i("Custom study option selected")
val did = requireArguments().getLong("did")
val ankiActivity = requireActivity() as AnkiActivity
val d = FragmentFactoryUtils.instantiate(ankiActivity, CustomStudyDialog::class.java)
d.withArguments(CustomStudyDialog.CONTEXT_MENU_STANDARD, did)
ankiActivity.showDialogFragment(d)
}
CONTEXT_MENU_CREATE_SHORTCUT -> {
Timber.i("Create icon for a deck")
(activity as DeckPicker?)!!.createIcon(context)
}
CONTEXT_MENU_RENAME_DECK -> {
Timber.i("Rename deck selected")
(activity as DeckPicker?)!!.renameDeckDialog()
}
CONTEXT_MENU_EXPORT_DECK -> {
Timber.i("Export deck selected")
(activity as DeckPicker?)!!.showContextMenuExportDialog()
}
CONTEXT_MENU_UNBURY -> {
Timber.i("Unbury deck selected")
val col = CollectionHelper.getInstance().getCol(context)
col.sched.unburyCardsForDeck(requireArguments().getLong("did"))
(activity as StudyOptionsListener?)!!.onRequireDeckListUpdate()
(activity as AnkiActivity?)!!.dismissAllDialogFragments()
}
CONTEXT_MENU_CUSTOM_STUDY_REBUILD -> {
Timber.i("Empty deck selected")
(activity as DeckPicker?)!!.rebuildFiltered()
(activity as AnkiActivity?)!!.dismissAllDialogFragments()
}
CONTEXT_MENU_CUSTOM_STUDY_EMPTY -> {
Timber.i("Empty deck selected")
(activity as DeckPicker?)!!.emptyFiltered()
(activity as AnkiActivity?)!!.dismissAllDialogFragments()
}
CONTEXT_MENU_CREATE_SUBDECK -> {
Timber.i("Create Subdeck selected")
(activity as DeckPicker?)!!.createSubdeckDialog()
}
CONTEXT_MENU_BROWSE_CARDS -> {
val did = requireArguments().getLong("did")
(activity as DeckPicker?)!!.col?.decks?.select(did)
val intent = Intent(activity, CardBrowser::class.java)
(activity as DeckPicker?)!!.startActivityForResultWithAnimation(intent, NavigationDrawerActivity.REQUEST_BROWSE_CARDS, ActivityTransitionAnimation.Direction.START)
}
}
}
companion object {
/**
* Context Menus
*/
private const val CONTEXT_MENU_RENAME_DECK = 0
private const val CONTEXT_MENU_DECK_OPTIONS = 1
private const val CONTEXT_MENU_CUSTOM_STUDY = 2
private const val CONTEXT_MENU_DELETE_DECK = 3
private const val CONTEXT_MENU_EXPORT_DECK = 4
private const val CONTEXT_MENU_UNBURY = 5
private const val CONTEXT_MENU_CUSTOM_STUDY_REBUILD = 6
private const val CONTEXT_MENU_CUSTOM_STUDY_EMPTY = 7
private const val CONTEXT_MENU_CREATE_SUBDECK = 8
private const val CONTEXT_MENU_CREATE_SHORTCUT = 9
private const val CONTEXT_MENU_BROWSE_CARDS = 10
@JvmStatic
fun newInstance(did: Long): DeckPickerContextMenu {
val f = DeckPickerContextMenu()
val args = Bundle()
args.putLong("did", did)
f.arguments = args
return f
}
}
}
|
gpl-3.0
|
69f2ac83446bb6e4bed07fe6776af3de
| 50.416667 | 318 | 0.599068 | 4.863054 | false | false | false | false |
apixandru/intellij-community
|
platform/testGuiFramework/src/com/intellij/testGuiFramework/generators/GlobalContextCodeGenerator.kt
|
9
|
1354
|
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.generators
import java.awt.Component
import javax.swing.JComponent
/**
* An abstract class for global context such as WelcomeFrame, Dialog, IdeFrame. The main different from
*
* @author Sergey Karashevich
*/
abstract class GlobalContextCodeGenerator<C : Component> : ContextCodeGenerator<C>{
override fun priority(): Int = 0 // prioritize component code generators 0 - for common, (n) - for the most specific
fun generateCode(cmp: Component): String {
return generate(typeSafeCast(cmp))
}
override fun buildContext(component: Component) = Context(originalGenerator = this, component = (component as JComponent).rootPane.parent, code = generate(
typeSafeCast(component.rootPane.parent)))
}
|
apache-2.0
|
fb7f12e04e61a150c9dfcabd21da15ae
| 35.594595 | 157 | 0.753323 | 4.353698 | false | false | false | false |
panpf/sketch
|
sketch/src/androidTest/java/com/github/panpf/sketch/test/utils/LoadListenerSupervisor.kt
|
1
|
2103
|
/*
* Copyright (C) 2022 panpf <[email protected]>
*
* 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.github.panpf.sketch.test.utils
import android.os.Looper
import com.github.panpf.sketch.request.Listener
import com.github.panpf.sketch.request.LoadRequest
import com.github.panpf.sketch.request.LoadResult.Error
import com.github.panpf.sketch.request.LoadResult.Success
class LoadListenerSupervisor constructor(
private val name: String? = null,
private val callbackOnStart: (() -> Unit)? = null
) : Listener<LoadRequest, Success, Error> {
val callbackActionList = mutableListOf<String>()
override fun onStart(request: LoadRequest) {
super.onStart(request)
check(Looper.getMainLooper() === Looper.myLooper())
callbackActionList.add("onStart" + (name?.let { ":$it" } ?: ""))
callbackOnStart?.invoke()
}
override fun onCancel(request: LoadRequest) {
super.onCancel(request)
check(Looper.getMainLooper() === Looper.myLooper())
callbackActionList.add("onCancel" + (name?.let { ":$it" } ?: ""))
}
override fun onError(request: LoadRequest, result: Error) {
super.onError(request, result)
check(Looper.getMainLooper() === Looper.myLooper())
callbackActionList.add("onError" + (name?.let { ":$it" } ?: ""))
}
override fun onSuccess(request: LoadRequest, result: Success) {
super.onSuccess(request, result)
check(Looper.getMainLooper() === Looper.myLooper())
callbackActionList.add("onSuccess" + (name?.let { ":$it" } ?: ""))
}
}
|
apache-2.0
|
a351d055fde4193e2d5d343d12725267
| 37.254545 | 75 | 0.688065 | 4.214429 | false | false | false | false |
wendigo/chrome-reactive-kotlin
|
src/main/kotlin/pl/wendigo/chrome/api/console/Domain.kt
|
1
|
3041
|
package pl.wendigo.chrome.api.console
/**
* This domain is deprecated - use Runtime or Log instead.
*
* @link Protocol [Console](https://chromedevtools.github.io/devtools-protocol/tot/Console) domain documentation.
*/
@Deprecated(level = DeprecationLevel.WARNING, message = "This domain is deprecated - use Runtime or Log instead.")
class ConsoleDomain internal constructor(connection: pl.wendigo.chrome.protocol.ProtocolConnection) :
pl.wendigo.chrome.protocol.Domain("Console", """This domain is deprecated - use Runtime or Log instead.""", connection) {
/**
* Does nothing.
*
* @link Protocol [Console#clearMessages](https://chromedevtools.github.io/devtools-protocol/tot/Console#method-clearMessages) method documentation.
*/
fun clearMessages(): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Console.clearMessages", null, pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Disables console domain, prevents further console messages from being reported to the client.
*
* @link Protocol [Console#disable](https://chromedevtools.github.io/devtools-protocol/tot/Console#method-disable) method documentation.
*/
fun disable(): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Console.disable", null, pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Enables console domain, sends the messages collected so far to the client by means of the
`messageAdded` notification.
*
* @link Protocol [Console#enable](https://chromedevtools.github.io/devtools-protocol/tot/Console#method-enable) method documentation.
*/
fun enable(): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Console.enable", null, pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Issued when new console message is added.
*/
fun messageAdded(): io.reactivex.rxjava3.core.Flowable<MessageAddedEvent> = connection.events("Console.messageAdded", MessageAddedEvent.serializer())
/**
* Returns list of dependant domains that should be enabled prior to enabling this domain.
*/
override fun getDependencies(): List<pl.wendigo.chrome.protocol.Domain> {
return arrayListOf(
pl.wendigo.chrome.api.runtime.RuntimeDomain(connection),
)
}
}
/**
* Issued when new console message is added.
*
* @link [Console#messageAdded](https://chromedevtools.github.io/devtools-protocol/tot/Console#event-messageAdded) event documentation.
*/
@kotlinx.serialization.Serializable
data class MessageAddedEvent(
/**
* Console message that has been added.
*/
val message: ConsoleMessage
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Console"
override fun eventName() = "messageAdded"
}
|
apache-2.0
|
66f52ae0c02148d6d9ab549f853cd3e9
| 45.075758 | 240 | 0.73364 | 4.432945 | false | false | false | false |
AndroidX/androidx
|
tv/tv-foundation/src/main/java/androidx/tv/foundation/lazy/LazyListPinningModifier.kt
|
3
|
3129
|
/*
* Copyright 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 androidx.tv.foundation.lazy
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.lazy.layout.ModifierLocalPinnableParent
import androidx.compose.foundation.lazy.layout.PinnableParent
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.modifier.ModifierLocalConsumer
import androidx.compose.ui.modifier.ModifierLocalProvider
import androidx.compose.ui.modifier.ModifierLocalReadScope
import androidx.compose.ui.modifier.ProvidableModifierLocal
import androidx.tv.foundation.lazy.list.TvLazyListState
/**
* This is a temporary placeholder implementation of pinning until we implement b/195049010.
*/
@Suppress("ComposableModifierFactory")
@Composable
internal fun Modifier.lazyListPinningModifier(
state: TvLazyListState,
beyondBoundsInfo: LazyListBeyondBoundsInfo
): Modifier {
return this then remember(state, beyondBoundsInfo) {
LazyListPinningModifier(state, beyondBoundsInfo)
}
}
@OptIn(ExperimentalFoundationApi::class)
private class LazyListPinningModifier(
private val state: TvLazyListState,
private val beyondBoundsInfo: LazyListBeyondBoundsInfo,
) : ModifierLocalProvider<PinnableParent?>, ModifierLocalConsumer, PinnableParent {
var pinnableGrandParent: PinnableParent? = null
override val key: ProvidableModifierLocal<PinnableParent?>
get() = ModifierLocalPinnableParent
override val value: PinnableParent
get() = this
override fun onModifierLocalsUpdated(scope: ModifierLocalReadScope) {
pinnableGrandParent = with(scope) { ModifierLocalPinnableParent.current }
}
override fun pinItems(): PinnableParent.PinnedItemsHandle = with(beyondBoundsInfo) {
if (hasIntervals()) {
object : PinnableParent.PinnedItemsHandle {
val parentPinnedItemsHandle = pinnableGrandParent?.pinItems()
val interval = addInterval(start, end)
override fun unpin() {
removeInterval(interval)
parentPinnedItemsHandle?.unpin()
state.remeasurement?.forceRemeasure()
}
}
} else {
pinnableGrandParent?.pinItems() ?: EmptyPinnedItemsHandle
}
}
companion object {
private val EmptyPinnedItemsHandle = object : PinnableParent.PinnedItemsHandle {
override fun unpin() {}
}
}
}
|
apache-2.0
|
0e6e7801834b48f3559460f437d92682
| 36.698795 | 92 | 0.736018 | 4.843653 | false | false | false | false |
pyamsoft/padlock
|
padlock/src/main/java/com/pyamsoft/padlock/list/LockListFragment.kt
|
1
|
9666
|
/*
* Copyright 2019 Peter Kenji Yamanaka
*
* 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.pyamsoft.padlock.list
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.pyamsoft.padlock.Injector
import com.pyamsoft.padlock.PadLockComponent
import com.pyamsoft.padlock.R
import com.pyamsoft.padlock.api.service.LockServiceInteractor.ServiceState
import com.pyamsoft.padlock.api.service.LockServiceInteractor.ServiceState.DISABLED
import com.pyamsoft.padlock.api.service.LockServiceInteractor.ServiceState.ENABLED
import com.pyamsoft.padlock.api.service.LockServiceInteractor.ServiceState.PAUSED
import com.pyamsoft.padlock.api.service.LockServiceInteractor.ServiceState.PERMISSION
import com.pyamsoft.padlock.api.service.ServiceManager
import com.pyamsoft.padlock.list.info.LockInfoDialog
import com.pyamsoft.padlock.model.list.AppEntry
import com.pyamsoft.padlock.model.list.ListDiffProvider
import com.pyamsoft.padlock.pin.ClearPinPresenter
import com.pyamsoft.padlock.pin.ConfirmPinPresenter
import com.pyamsoft.padlock.pin.CreatePinPresenter
import com.pyamsoft.padlock.pin.confirm.PinConfirmDialog
import com.pyamsoft.padlock.pin.create.PinCreateDialog
import com.pyamsoft.padlock.service.device.UsagePermissionChecker
import com.pyamsoft.pydroid.core.singleDisposable
import com.pyamsoft.pydroid.core.tryDispose
import com.pyamsoft.pydroid.ui.app.requireToolbarActivity
import com.pyamsoft.pydroid.ui.app.toolbarActivity
import com.pyamsoft.pydroid.ui.util.setUpEnabled
import com.pyamsoft.pydroid.ui.util.show
import timber.log.Timber
import javax.inject.Inject
class LockListFragment : Fragment(),
CreatePinPresenter.Callback,
ConfirmPinPresenter.Callback,
ClearPinPresenter.Callback {
@field:Inject internal lateinit var viewModel: LockListViewModel
@field:Inject internal lateinit var serviceManager: ServiceManager
@field:Inject internal lateinit var lockView: LockListView
@field:Inject internal lateinit var createPinPresenter: CreatePinPresenter
@field:Inject internal lateinit var confirmPinPresenter: ConfirmPinPresenter
@field:Inject internal lateinit var clearPinPresenter: ClearPinPresenter
private var visibilityDisposable by singleDisposable()
private var databaseChangeDisposable by singleDisposable()
private var lockEventDisposable by singleDisposable()
private var fabStateChangeDisposable by singleDisposable()
private var fabStateCheckDisposable by singleDisposable()
private var populateDisposable by singleDisposable()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
Injector.obtain<PadLockComponent>(requireContext().applicationContext)
.plusLockListComponent()
.activity(requireActivity())
.toolbarActivity(requireToolbarActivity())
.listStateTag(TAG)
.owner(viewLifecycleOwner)
.inflater(inflater)
.container(container)
.savedInstanceState(savedInstanceState)
.diffProvider(object : ListDiffProvider<AppEntry> {
override fun data(): List<AppEntry> = lockView.getListData()
})
.build()
.inject(this)
lockView.create()
return lockView.root()
}
override fun onViewCreated(
view: View,
savedInstanceState: Bundle?
) {
super.onViewCreated(view, savedInstanceState)
lockView.onSwipeRefresh { populateList(true) }
lockView.onFabClicked { checkFabState(true) }
lockView.onToolbarMenuItemClicked {
if (it.itemId == R.id.menu_is_system) {
viewModel.setSystemVisibility(!it.isChecked)
populateList(true)
}
}
lockView.onListItemClicked { displayLockInfoFragment(it) }
lockView.onRefreshed { checkFabState(false) }
visibilityDisposable = viewModel.onSystemVisibilityChanged {
lockView.onSystemVisibilityChanged(it)
}
lockEventDisposable = viewModel.onLockEvent(
onWhitelist = { populateList(true) },
onError = { lockView.onModifyEntryError { populateList(true) } }
)
databaseChangeDisposable = viewModel.onDatabaseChangeEvent(
onChange = { lockView.onDatabaseChangeReceived(it.index, it.entry) },
onError = { ErrorDialog().show(requireActivity(), "db_change_error") }
)
fabStateChangeDisposable = viewModel.onFabStateChange {
onFabStateChanged(it, false)
}
val intent = requireActivity().intent
if (intent.hasExtra(ServiceManager.FORCE_REFRESH_ON_OPEN)) {
intent.removeExtra(ServiceManager.FORCE_REFRESH_ON_OPEN)
Timber.d("Launched from notification, force list refresh")
populateList(true)
}
clearPinPresenter.bind(this)
createPinPresenter.bind(this)
confirmPinPresenter.bind(this)
}
private fun onFabStateChanged(
state: ServiceState,
fromClick: Boolean
) {
when (state) {
ENABLED -> onFabIconLocked(fromClick)
DISABLED -> onFabIconUnlocked(fromClick)
PERMISSION -> onFabIconPermissionDenied(fromClick)
PAUSED -> onFabIconPaused(fromClick)
}
}
private fun populateList(forced: Boolean) {
populateDisposable = viewModel.populateList(forced,
onPopulateBegin = { lockView.onListPopulateBegin() },
onPopulateSuccess = { lockView.onListLoaded(it) },
onPopulateError = { lockView.onListPopulateError { populateList(true) } },
onPopulateComplete = { lockView.onListPopulated() }
)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
lockView.commitListState(outState)
}
override fun onStart() {
super.onStart()
populateList(false)
checkFabState(false)
}
override fun onResume() {
super.onResume()
requireToolbarActivity().withToolbar {
it.setTitle(R.string.app_name)
it.setUpEnabled(false)
}
}
override fun onPause() {
super.onPause()
lockView.commitListState(null)
if (isRemoving) {
toolbarActivity?.withToolbar {
it.menu.apply {
removeGroup(R.id.menu_group_list_system)
removeGroup(R.id.menu_group_list_search)
}
it.setOnMenuItemClickListener(null)
}
}
}
override fun onDestroyView() {
super.onDestroyView()
fabStateCheckDisposable.tryDispose()
populateDisposable.tryDispose()
fabStateChangeDisposable.tryDispose()
databaseChangeDisposable.tryDispose()
lockEventDisposable.tryDispose()
visibilityDisposable.tryDispose()
clearPinPresenter.unbind()
createPinPresenter.unbind()
confirmPinPresenter.unbind()
}
private fun checkFabState(fromClick: Boolean) {
fabStateCheckDisposable = viewModel.checkFabState {
onFabStateChanged(it, fromClick)
}
}
private fun displayLockInfoFragment(entry: AppEntry) {
LockInfoDialog.newInstance(entry)
.show(requireActivity(), LockInfoDialog.TAG)
}
private fun onFabIconLocked(fromClick: Boolean) {
lockView.onFabIconLocked()
if (fromClick) {
if (UsagePermissionChecker.hasPermission(requireContext())) {
PinConfirmDialog.newInstance(finishOnDismiss = false)
.show(requireActivity(), PinConfirmDialog.TAG)
}
}
}
private fun onFabIconUnlocked(fromClick: Boolean) {
lockView.onFabIconUnlocked()
if (fromClick) {
if (UsagePermissionChecker.hasPermission(requireContext())) {
PinCreateDialog.newInstance()
.show(requireActivity(), PinCreateDialog.TAG)
}
}
}
private fun onFabIconPermissionDenied(fromClick: Boolean) {
lockView.onFabIconPermissionDenied()
if (fromClick) {
UsageAccessRequestDialog().show(requireActivity(), "usage_access")
}
}
private fun onFabIconPaused(fromClick: Boolean) {
lockView.onFabIconPaused()
if (fromClick) {
serviceManager.startService(true)
}
}
override fun onConfirmPinBegin() {
}
override fun onConfirmPinSuccess(
attempt: String,
checkOnly: Boolean
) {
if (!checkOnly) {
Timber.d("Pin confirm success")
clearPinPresenter.clear(attempt)
}
}
override fun onConfirmPinFailure(
attempt: String,
checkOnly: Boolean
) {
if (!checkOnly) {
Timber.d("Pin confirm failed")
lockView.onMasterPinClearFailure()
}
}
override fun onConfirmPinComplete() {
}
override fun onCreatePinBegin() {
}
override fun onCreatePinSuccess() {
Timber.d("Pin create success")
lockView.onMasterPinCreateSuccess()
// Attempt start service
serviceManager.startService(false)
}
override fun onCreatePinFailure() {
Timber.d("Pin create failure")
lockView.onMasterPinCreateFailure()
}
override fun onCreatePinComplete() {
}
override fun onPinClearSuccess() {
Timber.d("Pin clear success")
lockView.onMasterPinClearSuccess()
}
override fun onPinClearFailed() {
Timber.d("Pin clear failure")
lockView.onMasterPinClearFailure()
}
companion object {
const val TAG = "LockListFragment"
}
}
|
apache-2.0
|
c280fc7b60db31786d6db4d8d4a8b5b1
| 28.650307 | 85 | 0.732361 | 4.427852 | false | false | false | false |
evanjpw/rotlin
|
src/main/kotlin/us/cornus/rotlin/Extensions.kt
|
1
|
2342
|
package us.cornus.rotlin
/**
* Created by ejw on 5/28/17.
*/
fun randomIndex(size: Int) = Math.floor(RNG.getUniform() * size).toInt()
fun <T> Array<T>.random(): T? = if (this.isEmpty()) {
null
} else {
this[randomIndex(this.size)]
}
inline fun <reified T> Array<T>.randomize(): Array<T> {
if (this.isEmpty()) return this
val result = ArrayList<T>()
val indices = ArrayList<Int>(this.size)
indices += IntRange(0, this.size)
while (indices.isNotEmpty()) {
val index = indices[randomIndex(indices.size)]
result.add(this[index])
indices.remove(index)
}
return result.toTypedArray()
}
inline fun <reified T> ArrayList<T>.randomize(): ArrayList<T> {
if (this.isEmpty()) return this
val result = ArrayList<T>()
val indices = ArrayList<Int>(this.size)
indices += this.indices
while (indices.isNotEmpty()) {
val index = indices[randomIndex(indices.size)]
result.add(this[index])
indices.remove(index)
}
return result
}
fun Byte.rotmod(n: Number) = ((this.rem(n.toByte())) + n.toByte()) % n.toByte()
fun Short.rotmod(n: Number) = ((this.rem(n.toShort())) + n.toShort()) % n.toShort()
fun Int.rotmod(n: Number) = ((this.rem(n.toInt())) + n.toInt()) % n.toInt()
fun Long.rotmod(n: Number) = ((this.rem(n.toLong())) + n.toLong()) % n.toLong()
fun Double.rotmod(n: Number) = ((this.rem(n.toDouble())) + n.toDouble()) % n.toDouble()
fun CharSequence.rpad(character: Char = '0', count: Int = 2) = this.padEnd(length = count, padChar = character).toString()
fun CharSequence.lpad(character: Char = '0', count: Int = 2) = this.padStart(length = count, padChar = character).toString()
fun <T> MutableList<T>.pop(): T? = if (this.isEmpty()) null else this.removeAt(this.size - 1)
fun <T> MutableList<T>.push(vararg elements: T): Int {
this.addAll(elements)
return this.size
}
fun <T> MutableList<T>.shift(): T? = if (this.isEmpty()) null else this.removeAt(0)
fun <T> MutableList<T>.unshift(vararg elements: T): Int {
this.addAll(0, elements.toList())
return this.size
}
fun String.jsMatch(re: Regex, global: Boolean = false): Array<String> {
return if (global) {
re.findAll(this).map { it.value }.toList().toTypedArray()
} else {
re.find(this)?.groupValues?.toTypedArray() ?: emptyArray()
}
}
|
bsd-3-clause
|
c22f7fc38c66c5c6e8d697283a4a2d26
| 32.956522 | 124 | 0.638343 | 3.230345 | false | false | false | false |
hannesa2/owncloud-android
|
owncloudApp/src/main/java/com/owncloud/android/utils/AvatarUtils.kt
|
2
|
3828
|
/**
* ownCloud Android client application
*
* @author Abel García de Prada
* Copyright (C) 2020 ownCloud GmbH.
* <p>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
* <p>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p>
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.owncloud.android.utils
import android.accounts.Account
import android.view.MenuItem
import android.widget.ImageView
import com.owncloud.android.R
import com.owncloud.android.presentation.manager.AvatarManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
class AvatarUtils : KoinComponent {
private val avatarManager: AvatarManager by inject()
/**
* Show the avatar corresponding to the received account in an {@ImageView}.
* <p>
* The avatar is shown if available locally in {@link ThumbnailsCacheManager}. The avatar is not
* fetched from the server if not available.
* <p>
* If there is no avatar stored, a colored icon is generated with the first letter of the account username.
* <p>
* If this is not possible either, a predefined user icon is shown instead.
*
* @param account OC account which avatar will be shown.
* @param displayRadius The radius of the circle where the avatar will be clipped into.
* @param fetchIfNotCached When 'true', if there is no avatar stored in the cache, it's fetched from
* the server. When 'false', server is not accessed, the fallback avatar is
* generated instead.
*/
fun loadAvatarForAccount(
imageView: ImageView,
account: Account,
fetchIfNotCached: Boolean = false,
displayRadius: Float
) {
//TODO: Tech debt: Move this to a viewModel and use its viewModelScope instead
CoroutineScope(Dispatchers.IO).launch {
val drawable = avatarManager.getAvatarForAccount(
account = account,
fetchIfNotCached = fetchIfNotCached,
displayRadius = displayRadius
)
withContext(Dispatchers.Main) {
// Not just accessibility support, used to know what account is bound to each imageView
imageView.contentDescription = account.name
if (drawable != null) {
imageView.setImageDrawable(drawable)
} else {
imageView.setImageResource(R.drawable.ic_account_circle)
}
}
}
}
fun loadAvatarForAccount(
menuItem: MenuItem,
account: Account,
fetchIfNotCached: Boolean = false,
displayRadius: Float
) {
CoroutineScope(Dispatchers.IO).launch {
val drawable = avatarManager.getAvatarForAccount(
account = account,
fetchIfNotCached = fetchIfNotCached,
displayRadius = displayRadius
)
withContext(Dispatchers.Main) {
if (drawable != null) {
menuItem.icon = drawable
} else {
menuItem.setIcon(R.drawable.ic_account_circle)
}
}
}
}
}
|
gpl-2.0
|
7e746852ccc12d197d92c3bd89941209
| 37.27 | 111 | 0.643324 | 4.900128 | false | false | false | false |
deeplearning4j/deeplearning4j
|
nd4j/samediff-import/samediff-import-api/src/main/kotlin/org/nd4j/samediff/frameworkimport/rule/attribute/NDArraySizeAtRule.kt
|
1
|
3749
|
/*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * 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.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.nd4j.samediff.frameworkimport.rule.attribute
import org.nd4j.ir.OpNamespace
import org.nd4j.samediff.frameworkimport.ArgDescriptor
import org.nd4j.samediff.frameworkimport.context.MappingContext
import org.nd4j.samediff.frameworkimport.lookupIndexForArgDescriptor
import org.nd4j.shade.protobuf.GeneratedMessageV3
import org.nd4j.shade.protobuf.ProtocolMessageEnum
/**
* Need to implement tensor size extraction value at index
*/
abstract class NDArraySizeAtRule<
GRAPH_DEF: GeneratedMessageV3,
OP_DEF_TYPE: GeneratedMessageV3,
NODE_TYPE: GeneratedMessageV3,
ATTR_DEF : GeneratedMessageV3,
ATTR_VALUE_TYPE : GeneratedMessageV3,
TENSOR_TYPE : GeneratedMessageV3, DATA_TYPE>(mappingNamesToPerform: Map<String, String>,
transformerArgs: Map<String, List<OpNamespace.ArgDescriptor>>):
BaseAttributeExtractionRule<GRAPH_DEF, OP_DEF_TYPE, NODE_TYPE, ATTR_DEF, ATTR_VALUE_TYPE, TENSOR_TYPE, DATA_TYPE>
(name = "ndarraysizeat", mappingNamesToPerform = mappingNamesToPerform, transformerArgs = transformerArgs)
where DATA_TYPE: ProtocolMessageEnum {
override fun acceptsInputType(argDescriptorType: AttributeValueType): Boolean {
return argDescriptorType == AttributeValueType.TENSOR
}
override fun outputsType(argDescriptorType: List<OpNamespace.ArgDescriptor.ArgType>): Boolean {
return argDescriptorType.contains(OpNamespace.ArgDescriptor.ArgType.INT64)
}
override fun convertAttributes(mappingCtx: MappingContext<GRAPH_DEF, NODE_TYPE, OP_DEF_TYPE, TENSOR_TYPE, ATTR_DEF, ATTR_VALUE_TYPE, DATA_TYPE>): List<OpNamespace.ArgDescriptor> {
val ret = ArrayList<OpNamespace.ArgDescriptor>()
mappingNamesToPerform().forEach { (k, v) ->
val transformArgsForAttribute = transformerArgs[k]
//note that this finds a value for a named tensor within either the graph or the node
//some frameworks may have a value node with a value attribute
//others may have the actual tensor value
val inputArr = mappingCtx.tensorInputFor(v)
val sizeIndex = transformArgsForAttribute!![0].int64Value.toInt()
val sizeAt = if(inputArr.shape().isEmpty()) -1 else inputArr.shape()[sizeIndex]
val argDescriptor = ArgDescriptor {
name = v
argType = OpNamespace.ArgDescriptor.ArgType.INT64
int64Value = sizeAt
argIndex = lookupIndexForArgDescriptor(
argDescriptorName = k,
opDescriptorName = mappingCtx.nd4jOpName(),
argDescriptorType = OpNamespace.ArgDescriptor.ArgType.INT64
)
}
ret.add(argDescriptor)
}
return ret
}
}
|
apache-2.0
|
8a113fa526890532a575a9f5236643d9
| 46.468354 | 183 | 0.660976 | 4.763659 | false | false | false | false |
mvarnagiris/expensius
|
app/src/main/kotlin/com/mvcoding/expensius/feature/transaction/TransactionsOverviewView.kt
|
1
|
2366
|
/*
* Copyright (C) 2017 Mantas Varnagiris.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package com.mvcoding.expensius.feature.transaction
import android.content.Context
import android.support.v7.widget.LinearLayoutManager
import android.util.AttributeSet
import android.view.MotionEvent
import android.widget.LinearLayout
import com.mvcoding.expensius.extension.doNotInEditMode
import com.mvcoding.expensius.extension.setGone
import com.mvcoding.expensius.extension.setVisible
import com.mvcoding.expensius.model.Transaction
import kotlinx.android.synthetic.main.view_transactions_overview.view.*
class TransactionsOverviewView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
LinearLayout(context, attrs, defStyleAttr), TransactionsOverviewPresenter.View {
private val presenter by lazy { provideTransactionsOverviewPresenter() }
private val adapter by lazy { TransactionsAdapter(isClickable = false) }
override fun onFinishInflate() {
super.onFinishInflate()
recyclerView.layoutManager = LinearLayoutManager(context)
recyclerView.adapter = adapter
}
override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean = true
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED))
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
doNotInEditMode { presenter.attach(this) }
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
presenter.detach(this)
}
override fun showTransactions(transactions: List<Transaction>): Unit = adapter.setItems(transactions)
override fun showEmptyView(): Unit = emptyTextView.setVisible()
override fun hideEmptyView(): Unit = emptyTextView.setGone()
}
|
gpl-3.0
|
33abd47ffeaf1af0628fcc402f8217c1
| 39.118644 | 128 | 0.766272 | 4.970588 | false | false | false | false |
elect86/oglDevTutorials
|
src/main/kotlin/ogl_dev/tut02/hello-dot.kt
|
1
|
2489
|
package ogl_dev.tut02
import glm.vec._2.Vec2i
import glm.vec._3.Vec3
import ogl_dev.GlfwWindow
import ogl_dev.glfw
import org.lwjgl.opengl.GL
import org.lwjgl.opengl.GL11.*
import org.lwjgl.opengl.GL15.*
import org.lwjgl.opengl.GL20.*
import uno.buffer.floatBufferBig
import uno.buffer.intBufferBig
import uno.glf.semantic
import uno.gln.glBindBuffer
import uno.gln.glDrawArrays
import kotlin.properties.Delegates
/**
* Created by elect on 22/04/17.
*/
private var window by Delegates.notNull<GlfwWindow>()
fun main(args: Array<String>) {
with(glfw) {
// Initialize GLFW. Most GLFW functions will not work before doing this.
// It also setups an error callback. The default implementation will print the error message in System.err.
init()
windowHint { doubleBuffer = true } // Configure GLFW
}
window = GlfwWindow(300, "Tutorial 2") // Create the window
with(window) {
pos = Vec2i(100) // Set the window position
makeContextCurrent() // Make the OpenGL context current
show() // Make the window visible
}
/* This line is critical for LWJGL's interoperation with GLFW's OpenGL context, or any context that is managed
externally. LWJGL detects the context that is current in the current thread, creates the GLCapabilities instance and
makes the OpenGL bindings available for use. */
GL.createCapabilities()
glClearColor(0.0f, 0.0f, 0.0f, 0.0f)
createVertexBuffer()
// Run the rendering loop until the user has attempted to close the window or has pressed the ESCAPE key.
while (!window.shouldClose) {
renderScene()
glfw.pollEvents() // Poll for window events. The key callback above will only be invoked during this call.
}
window.dispose()
glfw.terminate() // Terminate GLFW and free the error callback
}
val vbo = intBufferBig(1)
fun createVertexBuffer(){
val vertices = floatBufferBig(Vec3.SIZE)
Vec3(0.0f, 0.0f, 0.0f) to vertices
glGenBuffers(vbo)
glBindBuffer(GL_ARRAY_BUFFER, vbo)
glBufferData(GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW)
}
fun renderScene() {
glClear(GL_COLOR_BUFFER_BIT)
glEnableVertexAttribArray(semantic.attr.POSITION)
glBindBuffer(GL_ARRAY_BUFFER, vbo)
glVertexAttribPointer(semantic.attr.POSITION, Vec3.length, GL_FLOAT, false, Vec3.SIZE, 0)
glDrawArrays(GL_POINTS, 1)
glDisableVertexAttribArray(semantic.attr.POSITION)
window.swapBuffers()
}
|
mit
|
17e90787475167e2a84959a0bf20a524
| 27.295455 | 120 | 0.711531 | 3.944532 | false | false | false | false |
pokk/SSFM
|
app/src/main/kotlin/taiwan/no1/app/ssfm/models/data/IDataStore.kt
|
1
|
5342
|
package taiwan.no1.app.ssfm.models.data
import io.reactivex.Observable
import taiwan.no1.app.ssfm.misc.constants.Constant
import taiwan.no1.app.ssfm.models.entities.DetailMusicEntity
import taiwan.no1.app.ssfm.models.entities.KeywordEntity
import taiwan.no1.app.ssfm.models.entities.PlaylistEntity
import taiwan.no1.app.ssfm.models.entities.PlaylistItemEntity
import taiwan.no1.app.ssfm.models.entities.SearchMusicEntity
import taiwan.no1.app.ssfm.models.entities.lastfm.AlbumEntity
import taiwan.no1.app.ssfm.models.entities.lastfm.ArtistEntity
import taiwan.no1.app.ssfm.models.entities.lastfm.ArtistSimilarEntity
import taiwan.no1.app.ssfm.models.entities.lastfm.ArtistTopAlbumEntity
import taiwan.no1.app.ssfm.models.entities.lastfm.ArtistTopTrackEntity
import taiwan.no1.app.ssfm.models.entities.lastfm.TagEntity
import taiwan.no1.app.ssfm.models.entities.lastfm.TagTopArtistEntity
import taiwan.no1.app.ssfm.models.entities.lastfm.TopAlbumEntity
import taiwan.no1.app.ssfm.models.entities.lastfm.TopArtistEntity
import taiwan.no1.app.ssfm.models.entities.lastfm.TopTagEntity
import taiwan.no1.app.ssfm.models.entities.lastfm.TopTrackEntity
import taiwan.no1.app.ssfm.models.entities.lastfm.TrackSimilarEntity
import taiwan.no1.app.ssfm.models.entities.v2.HotPlaylistEntity
import taiwan.no1.app.ssfm.models.entities.v2.MusicEntity
import taiwan.no1.app.ssfm.models.entities.v2.MusicRankEntity
import taiwan.no1.app.ssfm.models.entities.v2.RankChartEntity
import taiwan.no1.app.ssfm.models.entities.v2.SongListEntity
/**
* Interface that represents a data store from where data is retrieved.
*
* @author jieyi
* @since 5/10/17
*/
interface IDataStore {
//region V1
/**
* Retrieve the musics or the artists information by the keyword.
*
* @param keyword keyword of the music or the artist.
* @return the result of [SearchMusicEntity]
*/
@Deprecated("There is a better api for searching a music, please check v2")
fun getSearchMusicRes(keyword: String,
page: Int = 1,
pageSize: Int = Constant.QUERY_PAGE_SIZE): Observable<SearchMusicEntity>
/**
* Retrieve the detail of a music information.
*
* @param hash the hash code of a music.
* @return the result of [DetailMusicEntity]
*/
@Deprecated("There is a better api for searching a music, please check v2")
fun getDetailMusicRes(hash: String): Observable<DetailMusicEntity>
//endregion
//region V2
fun searchMusic(keyword: String, page: Int = 0, lang: String = ""): Observable<MusicEntity>
fun fetchRankMusic(rankType: Int = 0): Observable<MusicRankEntity>
fun fetchHotPlaylist(page: Int = 0): Observable<HotPlaylistEntity>
fun fetchPlaylistDetail(id: String = ""): Observable<SongListEntity>
//endregion
//region Chart
fun getChartTopArtist(page: Int = 1, limit: Int = 20): Observable<TopArtistEntity>
fun getChartTopTracks(page: Int = 1, limit: Int = 20): Observable<TopTrackEntity>
fun getChartTopTags(page: Int = 1, limit: Int = 30): Observable<TopTagEntity>
fun getChartTop(): Observable<List<RankChartEntity>>
fun addRankChart(entity: RankChartEntity): Observable<Boolean>
fun editRankChart(entity: RankChartEntity): Observable<Boolean>
//endregion
//region Artist
fun getArtistInfo(mbid: String = "", artist: String = ""): Observable<ArtistEntity>
fun getSimilarArtist(artist: String): Observable<ArtistSimilarEntity>
fun getArtistTopAlbum(artist: String): Observable<ArtistTopAlbumEntity>
fun getArtistTopTrack(artist: String): Observable<ArtistTopTrackEntity>
fun getArtistTags(artist: String, session: Any): Observable<Collection<String>>
fun getSimilarTracks(artist: String, track: String): Observable<TrackSimilarEntity>
//endregion
//region Album
fun getAlbumInfo(artist: String, albumOrMbid: String): Observable<AlbumEntity>
//endregion
//region Tag
fun getTagTopAlbums(tag: String = "",
page: Int = 1,
limit: Int = 20): Observable<TopAlbumEntity>
fun getTagTopArtists(tag: String = "",
page: Int = 1,
limit: Int = 20): Observable<TagTopArtistEntity>
fun getTagTopTracks(tag: String = "",
page: Int = 1,
limit: Int = 20): Observable<TopTrackEntity>
fun getTagInfo(tag: String = ""): Observable<TagEntity>
//endregion
//region Playlist
fun getPlaylists(id: Long = -1): Observable<List<PlaylistEntity>>
fun addPlaylist(entity: PlaylistEntity): Observable<PlaylistEntity>
fun editPlaylist(entity: PlaylistEntity): Observable<Boolean>
fun removePlaylist(entity: PlaylistEntity): Observable<Boolean>
fun getPlaylistItems(playlistId: Long = -1): Observable<List<PlaylistItemEntity>>
fun addPlaylistItem(entity: PlaylistItemEntity): Observable<Boolean>
fun removePlaylistItem(entity: PlaylistItemEntity): Observable<Boolean>
//endregion
//region Search History
fun insertKeyword(keyword: String): Observable<Boolean>
fun getKeywords(quantity: Int = -1): Observable<List<KeywordEntity>>
fun removeKeywords(keyword: String? = null): Observable<Boolean>
//endregion
}
|
apache-2.0
|
0050b12ed60926c32306d7546575d390
| 37.717391 | 98 | 0.725571 | 4.062357 | false | false | false | false |
DUBULEE/spring-kotlin-sample
|
src/main/java/testkotlin/rest/HumanControler.kt
|
1
|
584
|
package humantalks.rest
import org.springframework.stereotype.Controller
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*
import humantalks.domain.*
Controller
public class HumanController() {
Autowired var humanRepo:HumanRepo? = null
val MAX_AGE = 150
RequestMapping(value=array("/humans"))
ResponseBody
fun listHumans(RequestParam(required=false) ageMax:Int?)=
humanRepo!!
.listHumans()
.filter { it.age == null || it.age!! < ageMax ?: MAX_AGE}
}
|
apache-2.0
|
e20dd3e1ae1660a7b947af88c7c4d2e6
| 25.590909 | 77 | 0.693493 | 3.945946 | false | false | false | false |
noemus/kotlin-eclipse
|
kotlin-bundled-compiler/src/com/intellij/formatting/KotlinLanguageCodeStyleSettingsProvider.kt
|
1
|
1174
|
package com.intellij.formatting
import org.jetbrains.kotlin.idea.KotlinLanguage
import com.intellij.application.options.IndentOptionsEditor
import com.intellij.lang.Language
import com.intellij.psi.codeStyle.CodeStyleSettingsCustomizable
import com.intellij.psi.codeStyle.CommonCodeStyleSettings
import com.intellij.psi.codeStyle.LanguageCodeStyleSettingsProvider
import org.jetbrains.kotlin.idea.formatter.KotlinCommonCodeStyleSettings
class KotlinLanguageCodeStyleSettingsProvider : LanguageCodeStyleSettingsProvider() {
override fun getLanguage(): Language = KotlinLanguage.INSTANCE
override fun getCodeSample(settingsType: SettingsType): String = ""
override fun getLanguageName(): String = KotlinLanguage.NAME
override fun customizeSettings(consumer:CodeStyleSettingsCustomizable, settingsType:SettingsType) {
}
override fun getIndentOptionsEditor(): IndentOptionsEditor? = null
override fun getDefaultCommonSettings(): CommonCodeStyleSettings {
val commonCodeStyleSettings = KotlinCommonCodeStyleSettings()
commonCodeStyleSettings.initIndentOptions()
return commonCodeStyleSettings
}
}
|
apache-2.0
|
e1537e4e2a728cfaf83d4066f7dbbea4
| 40.964286 | 103 | 0.810051 | 6.051546 | false | false | false | false |
minecraft-dev/MinecraftDev
|
src/main/kotlin/platform/mcp/vanillagradle/VanillaGradleProjectResolverExtension.kt
|
1
|
1501
|
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mcp.vanillagradle
import com.demonwav.mcdev.platform.mcp.gradle.tooling.vanillagradle.VanillaGradleModel
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.project.ModuleData
import org.gradle.tooling.model.idea.IdeaModule
import org.jetbrains.plugins.gradle.service.project.AbstractProjectResolverExtension
class VanillaGradleProjectResolverExtension : AbstractProjectResolverExtension() {
override fun getExtraProjectModelClasses(): Set<Class<out Any>> =
setOf(VanillaGradleModel::class.java)
override fun getToolingExtensionsClasses() = extraProjectModelClasses
override fun populateModuleExtraModels(gradleModule: IdeaModule, ideModule: DataNode<ModuleData>) {
val vgData = resolverCtx.getExtraProject(gradleModule, VanillaGradleModel::class.java)
if (vgData != null && vgData.hasVanillaGradle()) {
val gradleProjectPath = gradleModule.gradleProject.projectIdentifier.projectPath
val suffix = if (gradleProjectPath.endsWith(':')) "" else ":"
val decompileTaskName = gradleProjectPath + suffix + "decompile"
ideModule.createChild(VanillaGradleData.KEY, VanillaGradleData(ideModule.data, decompileTaskName))
}
super.populateModuleExtraModels(gradleModule, ideModule)
}
}
|
mit
|
5901ac2f6ad9a45bcb51a934114ed79d
| 39.567568 | 110 | 0.764823 | 4.953795 | false | false | false | false |
veyndan/reddit-client
|
app/src/main/java/com/veyndan/paper/reddit/api/reddit/network/RedditService.kt
|
2
|
2139
|
package com.veyndan.paper.reddit.api.reddit.network
import com.veyndan.paper.reddit.api.reddit.model.Listing
import com.veyndan.paper.reddit.api.reddit.model.Thing
import io.reactivex.Single
import retrofit2.Response
import retrofit2.http.*
interface RedditService {
// ================================
// Links & Comments
// ================================
@FormUrlEncoded
@POST("api/hide")
fun hide(
@Field("id") ids: String): Single<Response<Void>>
@FormUrlEncoded
@POST("api/save")
fun save(
@Field("category") category: String,
@Field("id") id: String): Single<Response<Void>>
@FormUrlEncoded
@POST("api/unsave")
fun unsave(
@Field("id") id: String): Single<Response<Void>>
@FormUrlEncoded
@POST("api/vote")
fun vote(
@Field("dir") voteDirection: VoteDirection,
@Field("id") id: String): Single<Response<Void>>
// ================================
// Listings
// ================================
@GET("r/{subreddit}/comments/{article}")
fun subredditComments(
@Path("subreddit") subreddit: String,
@Path("article") article: String): Single<Response<List<Thing<Listing>>>>
@GET("r/{subreddit}/{where}")
fun subreddit(
@Path("subreddit") subreddit: String,
@Path("where") sort: Sort,
@QueryMap queries: Map<String, String>): Single<Response<Thing<Listing>>>
// ================================
// Search
// ================================
@GET("r/{subreddit}/search")
fun search(
@Path("subreddit") subreddit: String,
@QueryMap queries: Map<String, String>): Single<Response<Thing<Listing>>>
// ================================
// Users
// ================================
@GET("user/{username}/{where}")
fun user(
@Path("username") username: String,
@Path("where") where: User,
@QueryMap queries: Map<String, String>): Single<Response<Thing<Listing>>>
}
|
mit
|
53e6db07f4ba0d74446c9b5c2da2ff7f
| 29.557143 | 85 | 0.506311 | 4.551064 | false | false | false | false |
Tvede-dk/CommonsenseAndroidKotlin
|
widgets/src/main/kotlin/com/commonsense/android/kotlin/views/features/SimpleDateDialog.kt
|
1
|
1168
|
@file:Suppress("unused", "NOTHING_TO_INLINE", "MemberVisibilityCanBePrivate")
package com.commonsense.android.kotlin.views.features
import android.app.*
import android.content.*
import android.support.annotation.*
import android.support.annotation.IntRange
import android.widget.*
import java.util.*
/**
* Created by kasper on 11/07/2017.
*/
fun Context.showDatePickerDialog(
@IntRange(from = 0) startYear: Int,
@IntRange(from = 0) monthOfYear: Int,
@IntRange(from = 0) dayOfMonth: Int,
minDate: Date?,
maxDate: Date?,
onDateSelected: (year: Int, month: Int, day: Int) -> Unit,
@StringRes otherAction: Int,
onOtherAction: () -> Unit) {
val dialog = DatePickerDialog(this, { _: DatePicker, year: Int, month: Int, day: Int ->
onDateSelected(year, month, day)
}, startYear, monthOfYear, dayOfMonth)
dialog.setButton(DatePickerDialog.BUTTON_NEUTRAL, this.getString(otherAction)) { _, _ ->
onOtherAction()
}
minDate?.let {
dialog.datePicker.minDate = it.time
}
maxDate?.let {
dialog.datePicker.maxDate = it.time
}
dialog.show()
}
|
mit
|
3314d118c3612f865a0c2ad35522d336
| 25.568182 | 92 | 0.65411 | 3.93266 | false | false | false | false |
MakinGiants/caty
|
app/src/test/java/com/makingiants/caty/model/notifications/NotificationHandlerTest.kt
|
2
|
5267
|
package com.makingiants.caty.model.notifications
import com.makingiants.caty.model.DeviceStatusChecker
import com.makingiants.caty.model.TextReader
import com.makingiants.caty.model.cache.Settings
import com.makingiants.caty.model.notifications.MockNotification.messageNotification
import com.makingiants.caty.model.notifications.MockNotification.notification
import net.paslavsky.kotlin.mockito.spy
import net.paslavsky.kotlin.mockito.verifyNoMoreInteractions
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.Mockito.times
import org.mockito.Mockito.verify
import org.mockito.MockitoAnnotations
class NotificationHandlerTest {
@Mock lateinit var mockedTextReader: TextReader
@Mock lateinit var mockedSettings: Settings
@Mock lateinit var mockedDeviceStatusChecker: DeviceStatusChecker
lateinit var notificationHandler: NotificationHandler
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
notificationHandler = NotificationHandler(mockedSettings, mockedTextReader, mockedDeviceStatusChecker)
Mockito.`when`(mockedSettings.readNotificationEnabled).thenReturn(true)
Mockito.`when`(mockedSettings.readJustMessages).thenReturn(false)
}
@Test
fun test_handle_checkJustWithHeadphonesSettings_ifPlayJustWithHeadphones_ifNoHeadphones_dontRead() {
val notification = notification()
Mockito.`when`(mockedSettings.playJustWithHeadphones).thenReturn(true)
Mockito.`when`(mockedDeviceStatusChecker.headphonesConnected).thenReturn(false)
notificationHandler.handle(notification)
verify(mockedTextReader, times(0)).read(notification.text)
}
@Test
fun test_handle_checkJustWithHeadphonesSettings_ifPlayJustWithHeadphones_ifHeadphones_read() {
val notification = notification()
val spiedNotificationHandler = spy(notificationHandler)
Mockito.`when`(mockedSettings.playJustWithHeadphones).thenReturn(true)
Mockito.`when`(mockedDeviceStatusChecker.headphonesConnected).thenReturn(true)
spiedNotificationHandler.handle(notification)
verify(spiedNotificationHandler).parseWithDelay(notification)
}
@Test
fun test_handle_checkJustWithHeadphonesSettings_ifDontPlayJustWithHeadphones_readAlways() {
val notification = notification()
val spiedNotificationHandler = spy(notificationHandler)
Mockito.`when`(mockedSettings.playJustWithHeadphones).thenReturn(false)
spiedNotificationHandler.handle(notification)
verify(spiedNotificationHandler).parseWithDelay(notification)
}
@Test
fun test_handle_checkReadNotifications_ifFalse_DoNothing() {
val notification = notification()
Mockito.`when`(mockedSettings.readNotificationEnabled).thenReturn(false)
notificationHandler.handle(notification)
verify(mockedTextReader, times(0)).read(notification.text)
}
@Test
fun test_handle_ifNotificationDontHaveSound_doNothing() {
val notification = notification(haveSound = false)
Mockito.`when`(mockedSettings.readNotificationEnabled).thenReturn(true)
notificationHandler.handle(notification)
verifyNoMoreInteractions(mockedTextReader)
}
@Test
fun test_handle_checkReadNotifications_ifTrue_work() {
val notification = notification()
val spiedNotificationHandler = spy(notificationHandler)
Mockito.`when`(mockedSettings.readNotificationEnabled).thenReturn(true)
spiedNotificationHandler.handle(notification)
verify(spiedNotificationHandler).parseWithDelay(notification)
}
@Test
fun test_handle_multipleMessagesFaster_joinMessages() {
val notification = messageNotification("James", "text 1")
val notification2 = messageNotification("James", "text 2")
Mockito.`when`(mockedSettings.readNotificationEnabled).thenReturn(true)
notificationHandler.parseWithDelay(notification)
val pair = notificationHandler.parseWithDelay(notification2).toBlocking().first().first()
assertThat(pair.first).isEqualTo("James")
assertThat(pair.second).isEqualTo("text 1 text 2")
}
fun test_handle_check(readJustMessages: Boolean, notification: Notification) {
val spiedNotificationHandler = spy(notificationHandler)
val notification = messageNotification("James", "text 1")
Mockito.`when`(mockedSettings.readJustMessages).thenReturn(true)
spiedNotificationHandler.parseWithDelay(notification)
verify(spiedNotificationHandler).parseWithDelay(notification)
}
@Test
fun test_handle_checkReadJustMessage_ifIsMessage_work() {
val spiedNotificationHandler = spy(notificationHandler)
val notification = messageNotification("James", "text 1")
Mockito.`when`(mockedSettings.readJustMessages).thenReturn(true)
spiedNotificationHandler.parseWithDelay(notification)
verify(spiedNotificationHandler).parseWithDelay(notification)
}
@Test
fun test_handle_checkReadJustMessage_ifIsNotAMessage_doNothing() {
val spiedNotificationHandler = spy(notificationHandler)
val notification = notification(true)
Mockito.`when`(mockedSettings.readJustMessages).thenReturn(true)
spiedNotificationHandler.handle(notification)
verify(spiedNotificationHandler, times(0)).parseWithDelay(notification)
}
}
|
mit
|
7b09e4240b5a049489d55f34cfe070ab
| 32.987097 | 106 | 0.799127 | 4.673469 | false | true | false | false |
tasomaniac/OpenLinkWith
|
app/src/main/java/com/tasomaniac/openwith/resolver/IntentResolver.kt
|
1
|
3106
|
package com.tasomaniac.openwith.resolver
import android.content.ComponentName
import android.content.Intent
import android.content.pm.PackageManager
import android.content.pm.ResolveInfo
import android.os.Build.VERSION.SDK_INT
import android.os.Build.VERSION_CODES.M
import com.tasomaniac.openwith.BuildConfig
import com.tasomaniac.openwith.extensions.isHttp
import com.tasomaniac.openwith.rx.SchedulingStrategy
import io.reactivex.Observable
import io.reactivex.disposables.Disposable
import io.reactivex.disposables.Disposables
import java.util.ArrayList
import javax.inject.Inject
internal class IntentResolver @Inject constructor(
private val packageManager: PackageManager,
private val schedulingStrategy: SchedulingStrategy,
private val callerPackage: CallerPackage,
private val resolveListGrouper: ResolveListGrouper,
private val browserHandlerFactory: BrowserHandler.Factory,
val sourceIntent: Intent
) {
private var result: IntentResolverResult? = null
private var listener = Listener.NO_OP
private var disposable: Disposable = Disposables.empty()
var lastChosenComponent: ComponentName? = null
fun bind(listener: Listener) {
this.listener = listener
if (result == null) {
resolve()
} else {
listener.onIntentResolved(result!!)
}
}
fun unbind() {
this.listener = Listener.NO_OP
}
fun resolve() {
disposable = Observable
.fromCallable { doResolve() }
.compose(schedulingStrategy.forObservable())
.subscribe { data ->
result = data
listener.onIntentResolved(data)
}
}
fun release() {
disposable.dispose()
}
private fun doResolve(): IntentResolverResult {
val flag = if (SDK_INT >= M) PackageManager.MATCH_ALL else PackageManager.MATCH_DEFAULT_ONLY
val currentResolveList = ArrayList(packageManager.queryIntentActivities(sourceIntent, flag))
currentResolveList.removeAll {
it.activityInfo.packageName == BuildConfig.APPLICATION_ID
}
if (sourceIntent.isHttp()) {
browserHandlerFactory.create(currentResolveList).handleBrowsers()
}
callerPackage.removeFrom(currentResolveList)
val resolved = groupResolveList(currentResolveList)
return IntentResolverResult(
resolved,
resolveListGrouper.filteredItem,
resolveListGrouper.showExtended
)
}
private fun groupResolveList(currentResolveList: List<ResolveInfo>): List<DisplayActivityInfo> {
return if (currentResolveList.isEmpty()) {
emptyList()
} else {
resolveListGrouper.groupResolveList(currentResolveList, lastChosenComponent)
}
}
interface Listener {
fun onIntentResolved(result: IntentResolverResult)
companion object {
val NO_OP = object : Listener {
override fun onIntentResolved(result: IntentResolverResult) = Unit
}
}
}
}
|
apache-2.0
|
1fcc290aab496e13d461794670c18f6e
| 30.06 | 100 | 0.683516 | 4.899054 | false | false | false | false |
PassionateWsj/YH-Android
|
app/src/main/java/com/intfocus/template/dashboard/adapter/DashboardFragmentAdapter.kt
|
1
|
1044
|
package com.intfocus.template.dashboard.adapter
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentStatePagerAdapter
import android.support.v4.view.PagerAdapter
import android.view.ViewGroup
import com.intfocus.template.BuildConfig
import com.intfocus.template.dashboard.workbox.WorkBoxFragment
/**
* Created by liuruilin on 2017/3/23.
*/
class DashboardFragmentAdapter(fragmentManager: FragmentManager, val data: ArrayList<Fragment>) : FragmentStatePagerAdapter(fragmentManager) {
override fun getCount(): Int = data.size
override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
super.destroyItem(container, position, `object`)
}
override fun getItem(position: Int): Fragment = data[position]
override fun getItemPosition(`object`: Any): Int = if (`object` is WorkBoxFragment && "baozhentv" == BuildConfig.FLAVOR) {
PagerAdapter.POSITION_NONE
} else {
super.getItemPosition(`object`)
}
}
|
gpl-3.0
|
c82eb1bcc9f43308c6ed8c089352891b
| 33.8 | 142 | 0.758621 | 4.226721 | false | true | false | false |
sybila/ode-generator
|
src/main/java/com/github/sybila/ode/generator/smt/local/Z3Solver.kt
|
1
|
5861
|
package com.github.sybila.ode.generator.smt.local
import com.github.sybila.checker.Solver
import com.github.sybila.checker.solver.SolverStats
import com.microsoft.z3.ArithExpr
import com.microsoft.z3.BoolExpr
import com.microsoft.z3.Context
import com.microsoft.z3.Status
import java.nio.ByteBuffer
class Z3Solver(bounds: List<Pair<Double, Double>>, names: List<String> = bounds.indices.map { "p$it" })
: Solver<Z3Params>, Z3SolverBase {
override val z3 = Context()
private val simplifyTactic = z3.repeat(z3.mkTactic("ctx-solver-simplify"), Int.MAX_VALUE)
private val goal = z3.mkGoal(false, false, false)
private val solver = z3.mkSolver(z3.mkTactic("qflra"))
override val ff: Z3Params = Z3Params(z3.mkFalse(), false, true)
override val tt: Z3Params = Z3Params(z3.mkTrue(), true, true)
override val params: List<ArithExpr> = names.map { it.toZ3() }
val paramSymbols = bounds.indices.map { z3.mkSymbol("p$it") }.toTypedArray()
val paramSorts = bounds.indices.map { z3.mkRealSort() }.toTypedArray()
val bounds: BoolExpr = z3.mkAnd(*bounds.mapIndexed { i, pair ->
val (low, high) = pair
listOf(params[i] gt low.toZ3(), params[i] lt high.toZ3())
}.flatMap { it }.toTypedArray())
override fun Z3Params.isSat(): Boolean {
SolverStats.solverCall()
if (Math.random() > 0.8) minimize()
return this.sat ?: run {
solver.add(bounds)
solver.add(formula)
val status = solver.check()
solver.reset()
if (status == Status.UNKNOWN) throw IllegalStateException("Unknown solver result")
val sat = status == Status.SATISFIABLE
this.sat = sat
sat
}
}
override fun Z3Params.minimize() {
if (!minimal) {
goal.add(bounds)
goal.add(formula)
val simplified = simplifyTactic.apply(goal)
goal.reset()
if (simplified.numSubgoals != 1) throw IllegalStateException("Unexpected simplification result")
formula = simplified.subgoals[0].AsBoolExpr()
sat = !formula.isFalse
minimal = true
}
}
override fun Z3Params.andNot(other: Z3Params): Boolean {
solver.add(bounds)
solver.add(formula)
solver.add(z3.mkNot(other.formula))
val status = solver.check()
solver.reset()
return status == Status.SATISFIABLE
}
override fun Z3Params.and(other: Z3Params): Z3Params {
return if (this.formula.isFalse || this.sat == false) ff
else if (this.formula.isTrue) other
else if (other.formula.isFalse || other.sat == false) ff
else if (other.formula.isTrue) this
else {
return Z3Params(this.formula and other.formula, null)
}
}
override fun Z3Params.not(): Z3Params {
return if (this.formula.isTrue) ff
else if (this.sat == false || this.formula.isFalse) tt
else {
return Z3Params(z3.mkNot(this.formula), null)
}
}
override fun Z3Params.or(other: Z3Params): Z3Params {
return if (this.formula.isTrue || other.formula.isTrue) tt
else if (this.formula.isFalse || this.sat == false) other
else if (other.formula.isFalse || other.sat == false) this
else {
return Z3Params(this.formula or other.formula, if (this.sat == true || other.sat == true) true else null)
}
}
override fun Z3Params.prettyPrint(): String {
//this.minimize()
return "{$sat: $formula}"
}
override fun Z3Params.byteSize(): Int = ensureBytes().size + 4 + 1
override fun ByteBuffer.putColors(colors: Z3Params): ByteBuffer {
val bytes = colors.ensureBytes()
this.putInt(bytes.size)
bytes.forEach { this.put(it) }
colors.asString = null //release bytes - chance we will be sending the same data again is very small
when (colors.sat) {
null -> put((-1).toByte())
true -> put(1.toByte())
false -> put(0.toByte())
}
return this
}
override fun ByteBuffer.getColors(): Z3Params {
val size = this.int
val array = ByteArray(size)
(0 until size).forEach { array[it] = this.get() }
val string = String(array)
return Z3Params(
z3.parseSMTLIB2String(string, paramSymbols, paramSorts, null, null),
when (this.get().toInt()) {
1 -> true
0 -> false
else -> null
}
)
}
private fun Z3Params.ensureBytes(): ByteArray {
return asString ?: formula.toString().toByteArray().apply { asString = this }
}
override fun Z3Params.transferTo(solver: Solver<Z3Params>): Z3Params {
solver as Z3Solver
val f = this.formula.translate(solver.z3) as BoolExpr
return Z3Params(f, this.sat, this.minimal)
}
}
interface Z3SolverBase {
val z3: Context
val params: List<ArithExpr>
fun String.toZ3() = z3.mkRealConst(this)!!
fun Double.toZ3() = z3.mkReal(this.toString())!!
fun Int.toZ3() = z3.mkReal(this)!!
infix fun BoolExpr.and(other: BoolExpr) = z3.mkAnd(this, other)!!
infix fun BoolExpr.or(other: BoolExpr) = z3.mkOr(this, other)!!
infix fun ArithExpr.gt(other: ArithExpr) = z3.mkGt(this, other)!!
infix fun ArithExpr.ge(other: ArithExpr) = z3.mkGe(this, other)!!
infix fun ArithExpr.lt(other: ArithExpr) = z3.mkLt(this, other)!!
infix fun ArithExpr.le(other: ArithExpr) = z3.mkLe(this, other)!!
infix fun ArithExpr.plus(other: ArithExpr) = z3.mkAdd(this, other)!!
infix fun ArithExpr.times(other: ArithExpr) = z3.mkMul(this, other)!!
infix fun ArithExpr.div(other: ArithExpr) = z3.mkDiv(this, other)!!
}
|
gpl-3.0
|
001e51b9007a5c740aa9ab208f9d405e
| 34.743902 | 117 | 0.613888 | 3.582518 | false | false | false | false |
YinChangSheng/wx-event-broadcast
|
src/main/kotlin/com/yingtaohuo/wxevent/App.kt
|
1
|
6914
|
package com.yingtaohuo.wxevent
import com.qq.weixin.wx3rd.WXComponentApi
import com.qq.weixin.wx3rd.WXComponentClient
import com.qq.weixin.wx3rd.WorkModeProd
import com.rabbitmq.client.Channel
import com.rabbitmq.client.Connection
import com.thoughtworks.xstream.io.xml.StaxDriver
import com.thoughtworks.xstream.security.NoTypePermission
import com.thoughtworks.xstream.security.NullPermission
import com.thoughtworks.xstream.security.PrimitiveTypePermission
import com.yingtaohuo.wxevent.Config.Port
import com.yingtaohuo.wxevent.entrypt.SHA1
import com.yingtaohuo.wxevent.entrypt.WXBizMsgCrypt
import org.apache.commons.pool2.impl.GenericObjectPoolConfig
import org.slf4j.LoggerFactory
import org.springframework.oxm.xstream.XStreamMarshaller
import org.xml.sax.InputSource
import redis.clients.jedis.JedisPool
import spark.Spark.*
import spark.Spark.initExceptionHandler
import java.io.StringReader
import java.net.URI
import javax.xml.parsers.DocumentBuilder
import javax.xml.parsers.DocumentBuilderFactory
/**
* 作者: [email protected]
* 创建于: 2017/9/12
* 微信: yin80871901
* // https://github.com/perwendel/spark-debug-tools
*/
object AppHelper {
private val db: DocumentBuilder
// val xStream : XStreamMarshaller
val wxCrypt = WXBizMsgCrypt(Config.WX3rdAppToken, Config.WX3rdEncodingAesKey, Config.WX3rdAppId)
init {
val dbf = DocumentBuilderFactory.newInstance()
db = dbf.newDocumentBuilder()
}
inline fun <reified T> fromXml(xml: String) : T {
val xStream = XStreamMarshaller()
xStream.setAutodetectAnnotations(true)
xStream.setStreamDriver(StaxDriver())
xStream.setAliases(mapOf("xml" to T::class.java))
xStream.xStream.addPermission(NoTypePermission.NONE)
xStream.xStream.addPermission(NullPermission.NULL)
xStream.xStream.addPermission(PrimitiveTypePermission.PRIMITIVES)
xStream.xStream.allowTypes(arrayOf(T::class.java))
return xStream.unmarshalInputStream(xml.byteInputStream()) as T
}
inline fun <reified T: Any> decrypt(encryptText: String) : T {
val xmlData = wxCrypt.decrypt(encryptText)
return fromXml(xmlData)
}
fun decryptRaw(encryptText: String) = wxCrypt.decrypt(encryptText)
fun getInfoTypeFromEncrypt(encrypt: String) = getInfoType(decryptRaw(encrypt))
fun getInfoType(xmlText: String) : String {
val sr = StringReader(xmlText)
val isa = InputSource(sr)
val document = db.parse(isa)
val root = document.documentElement
return root.getElementsByTagName("InfoType").item(0).textContent
}
}
object App {
private val logger = LoggerFactory.getLogger(App::class.java)
private val channel: Channel?
private val connection: Connection?
private val componentApi : WXComponentApi
private val redis: JedisPool?
private val eventHandler : EventHandler
init {
// redis
val poolConfig = GenericObjectPoolConfig()
poolConfig.maxIdle = 5
poolConfig.minIdle = 3
poolConfig.maxTotal = 10
redis = JedisPool(poolConfig, URI(Config.redisHost), 1000)
// api
componentApi = WXComponentClient().build(WorkModeProd)
// rabbitmq channel create
connection = createRabbitConn()
channel = connection.createChannel()
val queueGroup1 = arrayListOf(
"sys_order",
"sys_order_test"
).map { queueName -> Pair(queueName, "component_token") }
val queueGroup2 = arrayListOf(
EventHandler.WXAuthorize,
EventHandler.WXUnauthorize,
EventHandler.WXUpdateAuthorize,
EventHandler.WXComponentVerifyTicket
)
// 微信令牌
rabbitMQExchangeQueueBind(connection, "wxtoken", queueGroup1)
// 微信第三方平台授权的事件
rabbitMQExchangeQueueBind(connection, "wxauthorize", queueGroup2)
// 该消息暂无人接受,自动处理掉
dumpConsume("wx_component_verify_ticket")
eventHandler = EventHandler(redis, channel, componentApi)
}
fun destroy() {
channel?.close()
connection?.close()
redis?.destroy()
}
fun start() {
/**
* http://wx3rd.menuxx.com/wx/3rd/notify
signature=b1f01f792773a0c2a68a9bd2a09b1061dc1ba49c×tamp=1505444079&nonce=236382074&encrypt_type=aes&msg_signature=2dc385ea7e474497c81dec14ab198ca828934b2b
<xml>
<AppId><![CDATA[wxb3d033d520d15fe7]]></AppId>
<Encrypt><![CDATA[KMmjrgC+G45ZqQ6gW0aDANzf7x5KhhW47JqBJtf7N2uAgX6/SlZ0wcIFSkDDiTMkWBXqYOVJ/lI4u0ewaoxm9Sy11D4+S5StLGshUa8Jdef2pbqRNCgx+4dO0rCiuxfk1RwZlcu2kAKNLERRffhzK9RRglSGxEu7B1ooch+AE5HZ+hKvgBXxfL910/xrApJJdnXYEVxh1rp59j5hThPkL/DOittr4Ze9R4M5ELG1gGN+zG7tG1FI6wO1mafu1UBvDLNXMix9Sk49G1ymPNUEOjJeULHQlrBMTRvqbomy/dNDa0QQs/bwbB6MkbNwOsSRukZl3k/RqMlakgkj7hWjTA==]]></Encrypt>
</xml>
*/
// post("/wx/3rd/notify", { req, resp ->
post("/wx3rd/authorize", "application/xml", { req, resp ->
resp.type("application/json;charset=UTF-8")
logger.debug(" route /wx3rd/authorize -> url: " + req.url())
logger.debug(" route /wx3rd/authorize -> queryString: " + req.queryString())
logger.debug(" route /wx3rd/authorize -> body: " + req.body())
val (_, encrypt) = AppHelper.fromXml<EncryptMsg1>(req.body())
val timestamp = req.queryMap().get("timestamp").value()
val nonce = req.queryMap().get("nonce").value()
val msgSignature = req.queryMap().get("msg_signature").value()
val signature = SHA1.getSHA1(Config.WX3rdAppToken, timestamp, nonce, encrypt)
if (signature == msgSignature) {
val infoType = AppHelper.getInfoTypeFromEncrypt(encrypt)
logger.info("InfoType: $infoType")
when (infoType) {
"component_verify_ticket" -> eventHandler.handleComponentToken(AppHelper.decrypt(encrypt))
"authorized" -> eventHandler.handleAuthorized(AppHelper.decrypt(encrypt))
"updateauthorized" -> eventHandler.handleUpdateAuthorized(AppHelper.decrypt(encrypt))
"unauthorized" -> eventHandler.handleUnAuthorize(AppHelper.decrypt(encrypt))
}
"success"
} else {
"fail"
}
})
// A wx3rd 120.132.29.90
}
}
fun main(args: Array<String>) {
threadPool(10)
port(Port)
initExceptionHandler { e ->
e.printStackTrace()
}
App.start()
init()
// 关闭的时候释放资源
Runtime.getRuntime().addShutdownHook(object : Thread() {
override fun run() {
super.run()
App.destroy()
}
})
}
|
apache-2.0
|
ef28074b1e8927e17a1f8ca78ab41d51
| 31.961353 | 383 | 0.67253 | 3.665771 | false | true | false | false |
westnordost/StreetComplete
|
app/src/main/java/de/westnordost/streetcomplete/util/GeoUri.kt
|
1
|
1206
|
package de.westnordost.streetcomplete.util
import android.net.Uri
import androidx.core.net.toUri
import java.util.*
fun parseGeoUri(uri: Uri): GeoLocation? {
if (uri.scheme != "geo") return null
val geoUriRegex = Regex("(-?[0-9]*\\.?[0-9]+),(-?[0-9]*\\.?[0-9]+).*?(?:\\?z=([0-9]*\\.?[0-9]+))?")
val match = geoUriRegex.matchEntire(uri.schemeSpecificPart) ?: return null
val latitude = match.groupValues[1].toDoubleOrNull() ?: return null
if (latitude < -90 || latitude > +90) return null
val longitude = match.groupValues[2].toDoubleOrNull() ?: return null
if (longitude < -180 && longitude > +180) return null
// zoom is optional. If it is invalid, we treat it the same as if it is not there
val zoom = match.groupValues[3].toFloatOrNull()
return GeoLocation(latitude, longitude, zoom)
}
fun buildGeoUri(latitude: Double, longitude: Double, zoom: Float? = null): Uri {
val zoomStr = if (zoom != null) "?z=$zoom" else ""
val geoUri = Formatter(Locale.US).format("geo:%.5f,%.5f%s", latitude, longitude, zoomStr).toString()
return geoUri.toUri()
}
data class GeoLocation(
val latitude: Double,
val longitude: Double,
val zoom: Float?
)
|
gpl-3.0
|
4bbfa2c47dad8bf129619d2ea0652182
| 34.470588 | 104 | 0.660033 | 3.536657 | false | false | false | false |
dhleong/ideavim
|
src/com/maddyhome/idea/vim/helper/UserDataManager.kt
|
1
|
7487
|
/*
* IdeaVim - Vim emulator for IDEs based on the IntelliJ platform
* Copyright (C) 2003-2019 The IdeaVim authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
@file:JvmName("UserDataManager")
@file:Suppress("ObjectPropertyName")
package com.maddyhome.idea.vim.helper
import com.intellij.openapi.editor.Caret
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.RangeMarker
import com.intellij.openapi.editor.markup.RangeHighlighter
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.UserDataHolder
import com.maddyhome.idea.vim.command.CommandState
import com.maddyhome.idea.vim.command.SelectionType
import com.maddyhome.idea.vim.ex.ExOutputModel
import com.maddyhome.idea.vim.group.visual.VisualChange
import com.maddyhome.idea.vim.group.visual.vimLeadSelectionOffset
import com.maddyhome.idea.vim.ui.ExOutputPanel
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
/**
* @author Alex Plate
*/
//region Vim selection start ----------------------------------------------------
/**
* Caret's offset when entering visual mode
*/
var Caret.vimSelectionStart: Int
get() {
val selectionStart = _vimSelectionStart
if (selectionStart == null) {
vimSelectionStart = vimLeadSelectionOffset
return vimLeadSelectionOffset
}
return selectionStart
}
set(value) {
_vimSelectionStart = value
}
fun Caret.vimSelectionStartClear() {
this._vimSelectionStart = null
}
private var Caret._vimSelectionStart: Int? by userDataCaretToEditor()
//endregion ----------------------------------------------------
var Caret.vimLastColumn: Int by userDataCaretToEditorOr { (this as Caret).visualPosition.column }
var Caret.vimLastVisualOperatorRange: VisualChange? by userDataCaretToEditor()
var Caret.vimInsertStart: RangeMarker by userDataOr { (this as Caret).editor.document.createRangeMarker(this.offset, this.offset) }
//------------------ Editor
fun unInitializeEditor(editor: Editor) {
editor.vimLastSelectionType = null
editor.vimCommandState = null
editor.vimMorePanel = null
editor.vimExOutput = null
editor.vimLastHighlighters = null
}
var Editor.vimLastSearch: String? by userData()
var Editor.vimLastHighlighters: Collection<RangeHighlighter>? by userData()
/***
* @see :help visualmode()
*/
var Editor.vimLastSelectionType: SelectionType? by userData()
var Editor.vimCommandState: CommandState? by userData()
var Editor.vimChangeGroup: Boolean by userDataOr { false }
var Editor.vimMotionGroup: Boolean by userDataOr { false }
var Editor.vimEditorGroup: Boolean by userDataOr { false }
var Editor.vimLineNumbersShown: Boolean by userDataOr { false }
var Editor.vimMorePanel: ExOutputPanel? by userData()
var Editor.vimExOutput: ExOutputModel? by userData()
var Editor.vimTestInputModel: TestInputModel? by userData()
/**
* Checks whether a keeping visual mode visual operator action is performed on editor.
*/
var Editor.vimKeepingVisualOperatorAction: Boolean by userDataOr { false }
var Editor.vimChangeActionSwitchMode: CommandState.Mode? by userData()
/**
* Function for delegated properties.
* The property will be delegated to UserData and has nullable type.
*/
private fun <T> userData(): ReadWriteProperty<UserDataHolder, T?> = object : UserDataReadWriteProperty<UserDataHolder, T?>() {
override fun getValue(thisRef: UserDataHolder, property: KProperty<*>): T? {
return thisRef.getUserData(getKey(property))
}
override fun setValue(thisRef: UserDataHolder, property: KProperty<*>, value: T?) {
thisRef.putUserData(getKey(property), value)
}
}
/**
* Function for delegated properties.
* The property will be saved to caret if this caret is not primary
* and to caret and editor otherwise.
* In case of primary caret getter uses value stored in caret. If it's null, then the value from editor
* Has nullable type.
*/
private fun <T> userDataCaretToEditor(): ReadWriteProperty<Caret, T?> = object : UserDataReadWriteProperty<Caret, T?>() {
override fun getValue(thisRef: Caret, property: KProperty<*>): T? {
return if (thisRef == thisRef.editor.caretModel.primaryCaret) {
thisRef.getUserData(getKey(property)) ?: thisRef.editor.getUserData(getKey(property))
} else {
thisRef.getUserData(getKey(property))
}
}
override fun setValue(thisRef: Caret, property: KProperty<*>, value: T?) {
if (thisRef == thisRef.editor.caretModel.primaryCaret) {
thisRef.editor.putUserData(getKey(property), value)
}
thisRef.putUserData(getKey(property), value)
}
}
/**
* Function for delegated properties.
* The property will be saved to caret if this caret is not primary
* and to caret and editor otherwise.
* In case of primary caret getter uses value stored in caret. If it's null, then the value from editor
* Has not nullable type.
*/
private fun <T> userDataCaretToEditorOr(default: UserDataHolder.() -> T): ReadWriteProperty<Caret, T> = object : UserDataReadWriteProperty<Caret, T>() {
override fun getValue(thisRef: Caret, property: KProperty<*>): T {
val res = if (thisRef == thisRef.editor.caretModel.primaryCaret) {
thisRef.getUserData(getKey(property)) ?: thisRef.editor.getUserData(getKey(property))
} else {
thisRef.getUserData(getKey(property))
}
if (res == null) {
val defaultValue = thisRef.default()
setValue(thisRef, property, defaultValue)
return defaultValue
}
return res
}
override fun setValue(thisRef: Caret, property: KProperty<*>, value: T) {
if (thisRef == thisRef.editor.caretModel.primaryCaret) {
thisRef.editor.putUserData(getKey(property), value)
}
thisRef.putUserData(getKey(property), value)
}
}
/**
* Function for delegated properties.
* The property will be delegated to UserData and has non-nullable type.
* [default] action will be executed if UserData doesn't have this property now.
* The result of [default] will be put to user data and returned.
*/
private fun <T> userDataOr(default: UserDataHolder.() -> T): ReadWriteProperty<UserDataHolder, T> = object : UserDataReadWriteProperty<UserDataHolder, T>() {
override fun getValue(thisRef: UserDataHolder, property: KProperty<*>): T {
return thisRef.getUserData(getKey(property)) ?: run<ReadWriteProperty<UserDataHolder, T>, T> {
val defaultValue = thisRef.default()
thisRef.putUserData(getKey(property), defaultValue)
defaultValue
}
}
override fun setValue(thisRef: UserDataHolder, property: KProperty<*>, value: T) {
thisRef.putUserData(getKey(property), value)
}
}
private abstract class UserDataReadWriteProperty<in R, T> : ReadWriteProperty<R, T> {
private var key: Key<T>? = null
protected fun getKey(property: KProperty<*>): Key<T> {
if (key == null) {
key = Key.create(property.name + " by userData()")
}
return key as Key<T>
}
}
|
gpl-2.0
|
8a22e0aaef6f1b8fdac34a8af97331b3
| 36.628141 | 157 | 0.731935 | 4.315274 | false | false | false | false |
StepicOrg/stepic-android
|
app/src/main/java/org/stepik/android/view/step_quiz_choice/ui/adapter/ChoicesAdapterDelegate.kt
|
2
|
4489
|
package org.stepik.android.view.step_quiz_choice.ui.adapter
import android.graphics.PorterDuff
import android.graphics.drawable.LayerDrawable
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.DrawableCompat
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import kotlinx.android.synthetic.main.item_step_quiz_choice.view.*
import org.stepic.droid.R
import org.stepik.android.view.latex.ui.widget.ProgressableWebViewClient
import org.stepik.android.view.step_quiz_choice.model.Choice
import org.stepik.android.view.step_quiz_choice.ui.delegate.LayerListDrawableDelegate
import ru.nobird.android.ui.adapterdelegates.AdapterDelegate
import ru.nobird.android.ui.adapterdelegates.DelegateViewHolder
import ru.nobird.android.ui.adapters.selection.SelectionHelper
class ChoicesAdapterDelegate(
private val selectionHelper: SelectionHelper,
private val onClick: (Choice) -> Unit
) : AdapterDelegate<Choice, DelegateViewHolder<Choice>>() {
override fun isForViewType(position: Int, data: Choice): Boolean =
true
override fun onCreateViewHolder(parent: ViewGroup): DelegateViewHolder<Choice> =
ViewHolder(createView(parent, R.layout.item_step_quiz_choice))
inner class ViewHolder(
root: View
) : DelegateViewHolder<Choice>(root) {
private val itemChoiceContainer = root.itemChoiceContainer
private val itemChoiceCheckmark = root.itemChoiceCheckmark
private val itemChoiceLatex = root.itemChoiceLatex
private val itemChoiceLatexProgress = root.itemChoiceLatexProgress
private val itemChoiceFeedback = root.itemChoiceFeedback
private val layerListDrawableDelegate: LayerListDrawableDelegate
init {
root.itemChoiceContainer.setOnClickListener {
if (it.isEnabled) {
onClick(itemData as Choice)
}
}
layerListDrawableDelegate = LayerListDrawableDelegate(
listOf(
R.id.not_checked_layer,
R.id.not_checked_layer_with_hint,
R.id.checked_layer,
R.id.correct_layer,
R.id.incorrect_layer,
R.id.incorrect_layer_with_hint
),
itemChoiceContainer.background.mutate() as LayerDrawable
)
itemChoiceLatex.webViewClient = ProgressableWebViewClient(itemChoiceLatexProgress, itemChoiceLatex.webView)
itemChoiceFeedback.background = AppCompatResources
.getDrawable(context, R.drawable.bg_shape_rounded_bottom)
?.mutate()
?.let { DrawableCompat.wrap(it) }
?.also {
DrawableCompat.setTint(it, ContextCompat.getColor(context, R.color.color_elevation_overlay_1dp))
DrawableCompat.setTintMode(it, PorterDuff.Mode.SRC_IN)
}
}
override fun onBind(data: Choice) {
itemView.itemChoiceContainer.isEnabled = data.isEnabled
itemView.isSelected = selectionHelper.isSelected(adapterPosition)
itemChoiceCheckmark.isInvisible = data.correct != true
itemChoiceLatex.setText(data.option)
layerListDrawableDelegate.showLayer(getItemBackgroundLayer(data))
bindHint(data)
}
private fun bindHint(data: Choice) {
itemChoiceFeedback.isVisible = !data.feedback.isNullOrEmpty()
itemChoiceFeedback.setText(data.feedback)
}
private fun getItemBackgroundLayer(data: Choice): Int =
if (itemView.isSelected) {
when (data.correct) {
true ->
R.id.correct_layer
false ->
if (data.feedback.isNullOrEmpty()) {
R.id.incorrect_layer
} else {
R.id.incorrect_layer_with_hint
}
else ->
R.id.checked_layer
}
} else {
if (data.feedback.isNullOrEmpty()) {
R.id.not_checked_layer
} else {
R.id.not_checked_layer_with_hint
}
}
}
}
|
apache-2.0
|
4108e724d4de4cc3c5d38fb6d9867af3
| 40.192661 | 119 | 0.628202 | 4.976718 | false | false | false | false |
marius-m/racer_test
|
core/src/main/java/lt/markmerkk/app/CameraHelper.kt
|
1
|
1907
|
package lt.markmerkk.app
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.OrthographicCamera
import com.badlogic.gdx.math.Matrix4
import org.slf4j.LoggerFactory
/**
* @author mariusmerkevicius
* @since 2016-06-04
*
* Responsible for moving user camera
*/
class CameraHelper(
private val virtualWidth : Int,
private val virtualHeight : Int
) {
var viewportWidth: Int = 0
var viewportHeight: Int = 0
val combine: Matrix4
get() = camera.combined
private val screenWidth: Int
private val screenHeight: Int
private val aspect: Float
private val camera: OrthographicCamera
init {
camera = OrthographicCamera()
screenWidth = Gdx.graphics.width
screenHeight = Gdx.graphics.height
aspect = (virtualWidth / virtualHeight).toFloat()
if (screenWidth / screenHeight >= aspect) {
viewportHeight = virtualHeight
viewportWidth = viewportHeight * screenWidth / screenHeight
} else {
viewportWidth = virtualWidth
viewportHeight = viewportWidth * screenHeight / screenWidth
}
camera.setToOrtho(false, viewportWidth.toFloat(), viewportHeight.toFloat())
logger.debug(String.format(
"Screen: virtualWidth: %d x %d",
virtualWidth,
virtualHeight
))
logger.debug(String.format(
"Screen: screen: %d x %d",
screenWidth,
screenHeight
))
logger.debug(String.format(
"Screen: view port: %d x %d",
viewportWidth,
viewportHeight
))
}
fun update(x : Float, y : Float) {
// camera.position.set(x, y, 0f)
// camera.update()
}
companion object {
val logger = LoggerFactory.getLogger(CameraHelper::class.java)
}
}
|
apache-2.0
|
6728e9db39be4baee24033396a8c5faf
| 25.5 | 83 | 0.603041 | 4.779449 | false | false | false | false |
afollestad/drag-select-recyclerview
|
sample/src/main/java/com/afollestad/dragselectrecyclerviewsample/MainActivity.kt
|
1
|
7074
|
/**
* Designed and developed by Aidan Follestad (@afollestad)
*
* 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.afollestad.dragselectrecyclerviewsample
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.afollestad.dragselectrecyclerview.DragSelectTouchListener
import com.afollestad.dragselectrecyclerview.Mode
import com.afollestad.dragselectrecyclerview.Mode.PATH
import com.afollestad.dragselectrecyclerview.Mode.RANGE
import com.afollestad.materialcab.attached.AttachedCab
import com.afollestad.materialcab.attached.destroy
import com.afollestad.materialcab.attached.isActive
import com.afollestad.materialcab.createCab
import com.afollestad.recyclical.datasource.emptySelectableDataSource
import com.afollestad.recyclical.setup
import com.afollestad.recyclical.viewholder.isSelected
import com.afollestad.recyclical.withItem
import com.afollestad.rxkprefs.Pref
import com.afollestad.rxkprefs.rxjava.observe
import com.afollestad.rxkprefs.rxkPrefs
import io.reactivex.disposables.SerialDisposable
/** @author Aidan Follestad (afollestad) */
class MainActivity : AppCompatActivity() {
private val list by lazy { findViewById<RecyclerView>(R.id.list) }
private val dataSource = emptySelectableDataSource().apply {
onSelectionChange { invalidateCab() }
}
private val selectionModePref: Pref<Mode> by lazy {
rxkPrefs(this).enum(
KEY_SELECTION_MODE,
RANGE,
{ Mode.valueOf(it) },
{ it.name }
)
}
private lateinit var touchListener: DragSelectTouchListener
private var activeCab: AttachedCab? = null
private var selectionModeDisposable = SerialDisposable()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(findViewById<Toolbar>(R.id.main_toolbar))
// Setup adapter and touch listener
touchListener = DragSelectTouchListener.create(
this,
dataSource.asDragSelectReceiver()
) {
this.mode = selectionModePref.get()
}
selectionModeDisposable.set(
selectionModePref.observe()
.filter { it != touchListener.mode }
.subscribe {
touchListener.mode = it
invalidateOptionsMenu()
}
)
dataSource.set(
ALPHABET
.dropLastWhile { it.isEmpty() }
.map(::MainItem)
)
list.setup {
withLayoutManager(GridLayoutManager(this@MainActivity, integer(R.integer.grid_width)))
withDataSource(dataSource)
withItem<MainItem, MainViewHolder>(R.layout.griditem_main) {
onBind(::MainViewHolder) { index, item ->
label.text = item.letter
colorSquare.setBackgroundColor(COLORS[index])
val context = itemView.context
var foreground: Drawable? = null
if (isSelected()) {
foreground = ColorDrawable(context.color(R.color.grid_foreground_selected))
label.setTextColor(context.color(R.color.grid_label_text_selected))
} else {
label.setTextColor(context.color(R.color.grid_label_text_normal))
}
colorSquare.foreground = foreground
}
onClick { toggleSelection() }
onLongClick { touchListener.setIsActive(true, it) }
}
}
list.addOnItemTouchListener(touchListener)
setLightNavBarCompat()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.main, menu)
when (selectionModePref.get()) {
RANGE -> menu.findItem(R.id.range_selection)
.isChecked = true
PATH -> menu.findItem(R.id.path_selection)
.isChecked = true
}
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.range_selection -> selectionModePref.set(RANGE)
R.id.path_selection -> selectionModePref.set(PATH)
}
return super.onOptionsItemSelected(item)
}
override fun onBackPressed() {
if (!activeCab.destroy()) {
super.onBackPressed()
}
}
override fun onDestroy() {
selectionModeDisposable.dispose()
super.onDestroy()
}
private fun invalidateCab() {
if (dataSource.hasSelection()) {
val count = dataSource.getSelectionCount()
if (activeCab.isActive()) {
activeCab?.title(literal = getString(R.string.cab_title_x, count))
} else {
activeCab = createCab(R.id.cab_stub) {
menu(R.menu.cab)
closeDrawable(R.drawable.ic_close)
titleColor(literal = Color.BLACK)
title(literal = getString(R.string.cab_title_x, count))
onSelection {
if (it.itemId == R.id.done) {
val selectionString = (0 until dataSource.size())
.filter { index -> dataSource.isSelectedAt(index) }
.joinToString()
toast("Selected letters: $selectionString")
dataSource.deselectAll()
true
} else {
false
}
}
onDestroy {
dataSource.deselectAll()
true
}
}
}
} else {
activeCab.destroy()
}
}
}
const val KEY_SELECTION_MODE = "selection-mode"
val ALPHABET = "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z"
.split(" ")
val COLORS = intArrayOf(
Color.parseColor("#F44336"), Color.parseColor("#E91E63"),
Color.parseColor("#9C27B0"), Color.parseColor("#673AB7"),
Color.parseColor("#3F51B5"), Color.parseColor("#2196F3"),
Color.parseColor("#03A9F4"), Color.parseColor("#00BCD4"),
Color.parseColor("#009688"), Color.parseColor("#4CAF50"),
Color.parseColor("#8BC34A"), Color.parseColor("#CDDC39"),
Color.parseColor("#FFEB3B"), Color.parseColor("#FFC107"),
Color.parseColor("#FF9800"), Color.parseColor("#FF5722"),
Color.parseColor("#795548"), Color.parseColor("#9E9E9E"),
Color.parseColor("#607D8B"), Color.parseColor("#F44336"),
Color.parseColor("#E91E63"), Color.parseColor("#9C27B0"),
Color.parseColor("#673AB7"), Color.parseColor("#3F51B5"),
Color.parseColor("#2196F3"), Color.parseColor("#03A9F4")
)
|
apache-2.0
|
16b11826e7d62c54756698ef606934db
| 33.339806 | 92 | 0.681368 | 4.25888 | false | false | false | false |
santoslucas/guarda-filme-android
|
app/src/main/java/com/guardafilme/ui/welcome/WelcomeActivity.kt
|
1
|
5120
|
package com.guardafilme.ui.welcome
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.view.Menu
import android.view.MenuItem
import android.view.View
import com.guardafilme.ui.main.MainActivity
import com.guardafilme.R
import com.guardafilme.data.AuthProvider
import com.guardafilme.model.WatchedMovie
import com.guardafilme.ui.UiUtils
import com.guardafilme.ui.searchmovie.SearchMovieActivity
import dagger.android.AndroidInjection
import kotlinx.android.synthetic.main.activity_welcome.*
import kotlinx.android.synthetic.main.activity_welcome.view.*
import javax.inject.Inject
/**
* Created by lucassantos on 05/08/17.
*/
class WelcomeActivity: AppCompatActivity(), WelcomeContract.View {
companion object {
val ADD_MOVIE_REQUEST = 435
fun createIntent(context: Context): Intent {
val intent = Intent(context, WelcomeActivity::class.java)
return intent
}
}
private lateinit var mAdapter: WatchedMoviesAdapter
@Inject
lateinit var presenter: WelcomeContract.Presenter
@Inject
lateinit var authProvider: AuthProvider
override fun onCreate(savedInstanceState: Bundle?) {
AndroidInjection.inject(this)
super.onCreate(savedInstanceState)
presenter.attach(this)
// Setup view
setContentView(R.layout.activity_welcome)
supportActionBar?.title = getString(R.string.title_watched_movies)
fab.setOnClickListener {
presenter.addMovie()
}
// Setup RecyclerView
val layoutManager = GridLayoutManager(this, 2)
layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
override fun getSpanSize(position: Int): Int {
if (position == 4) {
return 2
}
return 1
}
}
val moviesRecyclerView = watched_movies_recycler_view
moviesRecyclerView.layoutManager = layoutManager
mAdapter = WatchedMoviesAdapter(this, object : WatchedMoviesAdapter.WatchedMovieCallback {
override fun editClicked(watchedMovie: WatchedMovie) {
editWatchedMovie(watchedMovie)
}
override fun removeClicked(watchedMovie: WatchedMovie) {
presenter.deleteMovie(watchedMovie)
}
})
moviesRecyclerView.adapter = mAdapter
presenter.load()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.logout_item) {
authProvider.logoutUser(this, {
startActivity(Intent(this, MainActivity::class.java))
finish()
})
} else if (item.itemId == R.id.privacy_policy_item) {
val openURL = Intent(android.content.Intent.ACTION_VIEW)
openURL.data = Uri.parse("http://santoslucas.github.io/guardafilme.html")
startActivity(openURL)
}
return super.onOptionsItemSelected(item)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == ADD_MOVIE_REQUEST && resultCode == Activity.RESULT_OK) {
presenter.load()
}
}
override fun addWatchedMovies(watchedMovies: List<WatchedMovie>?) {
mAdapter.setItems(watchedMovies)
}
override fun showLoading() {
main_layout.visibility = View.GONE
loading_view.visibility = View.VISIBLE
}
override fun hideLoading() {
loading_view.visibility = View.GONE
main_layout.visibility = View.VISIBLE
}
override fun showMoviesList() {
watched_movies_recycler_view.visibility = View.VISIBLE
}
override fun hideMoviesList() {
watched_movies_recycler_view.visibility = View.GONE
}
override fun showTooltip() {
main_layout.tooltip_view.visibility = View.VISIBLE
}
override fun hideTooltip() {
main_layout.tooltip_view.visibility = View.GONE
}
override fun showAddMovie() {
val intent = SearchMovieActivity.createIntent(this)
startActivityForResult(intent, ADD_MOVIE_REQUEST)
}
override fun scrollToTop() {
watched_movies_recycler_view.scrollToPosition(0)
}
private fun editWatchedMovie(watchedMovie: WatchedMovie) {
UiUtils.showDatePickerDialog(this, { date ->
UiUtils.showRateDialog(this, { rate ->
presenter.editMovie(watchedMovie, date, rate)
}, {
presenter.editMovie(watchedMovie, date)
}, watchedMovie.rate)
}, watchedMovie.getWatchedDateAsCalendar())
}
}
|
gpl-3.0
|
bbd761116eaf271c79d15b3eb5b43080
| 30.611111 | 98 | 0.666016 | 4.745134 | false | false | false | false |
xiprox/Tensuu
|
app/src/main/java/tr/xip/scd/tensuu/ui/admin/user/AddUserDialog.kt
|
1
|
3349
|
package tr.xip.scd.tensuu.ui.admin.user
import android.annotation.SuppressLint
import android.content.Context
import android.support.v7.app.AlertDialog
import android.view.View
import io.realm.Realm
import kotlinx.android.synthetic.main.dialog_add_user.view.*
import tr.xip.scd.tensuu.App
import tr.xip.scd.tensuu.R
import tr.xip.scd.tensuu.realm.model.User
import tr.xip.scd.tensuu.common.ext.getLayoutInflater
object AddUserDialog {
fun new(realm: Realm, context: Context): AlertDialog? {
@SuppressLint("InflateParams")
val v = context.getLayoutInflater().inflate(R.layout.dialog_add_user, null, false)
val dialog = AlertDialog.Builder(context)
.setView(v)
.setTitle(R.string.title_add_user)
.setPositiveButton(R.string.action_add, null)
.setNegativeButton(R.string.action_cancel, null)
.create()
dialog.setOnShowListener {
val positive = dialog.getButton(AlertDialog.BUTTON_POSITIVE)
positive.setOnClickListener {
val email = v.email.text.toString()
val password = v.password.text.toString()
val passwordConfirm = v.passwordConfirm.text.toString()
val name = v.name.text.toString()
val admin = v.adminSwitch.isChecked
val modify = v.modifySwitch.isChecked
if (validateFields(v, email, password, passwordConfirm, name)) {
val user = User()
user.email = email
user.password = password
user.name = name
user.isAdmin = admin
user.canModify = modify
realm.executeTransaction {
it.copyToRealm(user)
}
dialog.dismiss()
}
}
}
return dialog
}
private fun validateFields(
v: View,
email: String?,
password: String?,
passwordConfirm: String?,
name: String?
): Boolean {
/* Email */
if (email == null || !email.trim().matches("^\\S+@\\S+\\.\\S+$".toRegex())) {
v.emailLayout.error = App.context.getString(R.string.error_invalid_email)
return false
} else {
v.emailLayout.error = null
}
/* Password */
if (password == null || password.trim().isEmpty()) {
v.passwordLayout.error = App.context.getString(R.string.error_invalid_password)
return false
} else {
v.passwordLayout.error = null
}
/* Password Confirm */
if (passwordConfirm == null || passwordConfirm.trim().isEmpty() || passwordConfirm != password) {
v.passwordConfirmLayout.error = App.context.getString(R.string.error_invalid_password_not_matched)
return false
} else {
v.passwordConfirmLayout.error = null
}
/* Name */
if (name == null || name.trim().isEmpty()) {
v.nameLayout.error = App.context.getString(R.string.error_invalid_name)
return false
} else {
v.nameLayout.error = null
}
/* All iz wel */
return true
}
}
|
gpl-3.0
|
4d3885b54c08517b3723357039ce683e
| 32.5 | 110 | 0.557778 | 4.56267 | false | false | false | false |
DiUS/pact-jvm
|
core/model/src/main/kotlin/au/com/dius/pact/core/model/OptionalBody.kt
|
1
|
5573
|
package au.com.dius.pact.core.model
import au.com.dius.pact.core.model.ContentType.Companion.HTMLREGEXP
import au.com.dius.pact.core.model.ContentType.Companion.JSONREGEXP
import au.com.dius.pact.core.model.ContentType.Companion.XMLREGEXP
import au.com.dius.pact.core.model.ContentType.Companion.XMLREGEXP2
import mu.KLogging
import org.apache.commons.codec.binary.Hex
import org.apache.tika.config.TikaConfig
import org.apache.tika.io.TikaInputStream
import org.apache.tika.metadata.Metadata
import java.util.Base64
/**
* Class to represent missing, empty, null and present bodies
*/
data class OptionalBody(
val state: State,
val value: ByteArray? = null,
var contentType: ContentType = ContentType.UNKNOWN
) {
init {
if (contentType == ContentType.UNKNOWN) {
val detectedContentType = detectContentType()
if (detectedContentType != null) {
this.contentType = detectedContentType
}
}
}
enum class State {
MISSING, EMPTY, NULL, PRESENT
}
fun isMissing(): Boolean {
return state == State.MISSING
}
fun isEmpty(): Boolean {
return state == State.EMPTY
}
fun isNull(): Boolean {
return state == State.NULL
}
fun isPresent(): Boolean {
return state == State.PRESENT
}
fun isNotPresent(): Boolean {
return state != State.PRESENT
}
fun orElse(defaultValue: ByteArray): ByteArray {
return if (state == State.EMPTY || state == State.PRESENT) {
this.value!!
} else {
defaultValue
}
}
fun orEmpty() = orElse(ByteArray(0))
fun unwrap(): ByteArray {
if (isPresent() || isEmpty()) {
return value!!
} else {
throw UnwrapMissingBodyException("Failed to unwrap value from a $state body")
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as OptionalBody
if (state != other.state) return false
if (value != null) {
if (other.value == null) return false
if (!value.contentEquals(other.value)) return false
} else if (other.value != null) return false
return true
}
override fun hashCode(): Int {
var result = state.hashCode()
result = 31 * result + (value?.contentHashCode() ?: 0)
return result
}
override fun toString(): String {
return when (state) {
State.PRESENT -> if (contentType.isBinaryType()) {
"PRESENT(${value!!.size} bytes starting with ${Hex.encodeHexString(slice(16))}...)"
} else {
"PRESENT(${value!!.toString(contentType.asCharset())})"
}
State.EMPTY -> "EMPTY"
State.NULL -> "NULL"
State.MISSING -> "MISSING"
}
}
fun valueAsString(): String {
return when (state) {
State.PRESENT -> value!!.toString(contentType.asCharset())
else -> ""
}
}
fun detectContentType(): ContentType? = when {
this.isPresent() -> {
val metadata = Metadata()
val mimetype = tika.detector.detect(TikaInputStream.get(value!!), metadata)
if (mimetype.baseType.type == "text") {
detectStandardTextContentType() ?: ContentType(mimetype)
} else {
ContentType(mimetype)
}
}
else -> null
}
private fun detectStandardTextContentType(): ContentType? = when {
isPresent() -> {
val newLine = '\n'.toByte()
val cReturn = '\r'.toByte()
val s = value!!.take(32).map {
if (it == newLine || it == cReturn) ' ' else it.toChar()
}.joinToString("")
when {
s.matches(XMLREGEXP) -> ContentType.XML
s.toUpperCase().matches(HTMLREGEXP) -> ContentType.HTML
s.matches(JSONREGEXP) -> ContentType.JSON
s.matches(XMLREGEXP2) -> ContentType.XML
else -> null
}
}
else -> null
}
fun valueAsBase64(): String {
return when (state) {
State.PRESENT -> Base64.getEncoder().encodeToString(value!!)
else -> ""
}
}
fun slice(size: Int): ByteArray {
return when (state) {
State.PRESENT -> if (value!!.size > size) {
value.copyOf(size)
} else {
value
}
else -> ByteArray(0)
}
}
companion object : KLogging() {
@JvmStatic fun missing(): OptionalBody {
return OptionalBody(State.MISSING)
}
@JvmStatic fun empty(): OptionalBody {
return OptionalBody(State.EMPTY, ByteArray(0))
}
@JvmStatic fun nullBody(): OptionalBody {
return OptionalBody(State.NULL)
}
@JvmStatic
@JvmOverloads
fun body(body: ByteArray?, contentType: ContentType = ContentType.UNKNOWN): OptionalBody {
return when {
body == null -> nullBody()
body.isEmpty() -> empty()
else -> OptionalBody(State.PRESENT, body, contentType)
}
}
private val tika = TikaConfig()
}
}
fun OptionalBody?.isMissing() = this == null || this.isMissing()
fun OptionalBody?.isEmpty() = this != null && this.isEmpty()
fun OptionalBody?.isNull() = this == null || this.isNull()
fun OptionalBody?.isPresent() = this != null && this.isPresent()
fun OptionalBody?.isNotPresent() = this == null || this.isNotPresent()
fun OptionalBody?.orElse(defaultValue: ByteArray) = this?.orElse(defaultValue) ?: defaultValue
fun OptionalBody?.orEmpty() = this?.orElse(ByteArray(0))
fun OptionalBody?.valueAsString() = this?.valueAsString() ?: ""
fun OptionalBody?.isNullOrEmpty() = this == null || this.isEmpty() || this.isNull()
fun OptionalBody?.unwrap() = this?.unwrap() ?: throw UnwrapMissingBodyException(
"Failed to unwrap value from a null body")
|
apache-2.0
|
cb70eb5b17815df4ed4318ac76c64872
| 25.412322 | 94 | 0.637179 | 4.100809 | false | false | false | false |
wordpress-mobile/WordPress-Android
|
WordPress/src/main/java/org/wordpress/android/util/experiments/ExPlat.kt
|
1
|
4545
|
package org.wordpress.android.util.experiments
import dagger.Lazy
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import org.wordpress.android.BuildConfig
import org.wordpress.android.fluxc.model.experiments.Assignments
import org.wordpress.android.fluxc.model.experiments.Variation
import org.wordpress.android.fluxc.model.experiments.Variation.Control
import org.wordpress.android.fluxc.store.AccountStore
import org.wordpress.android.fluxc.store.ExperimentStore
import org.wordpress.android.fluxc.store.ExperimentStore.Platform
import org.wordpress.android.fluxc.utils.AppLogWrapper
import org.wordpress.android.modules.APPLICATION_SCOPE
import org.wordpress.android.util.AppLog.T
import org.wordpress.android.util.analytics.AnalyticsTrackerWrapper
import org.wordpress.android.util.experiments.ExPlat.RefreshStrategy.ALWAYS
import org.wordpress.android.util.experiments.ExPlat.RefreshStrategy.IF_STALE
import org.wordpress.android.util.experiments.ExPlat.RefreshStrategy.NEVER
import javax.inject.Inject
import javax.inject.Named
import javax.inject.Singleton
@Singleton
class ExPlat
@Inject constructor(
private val experiments: Lazy<Set<Experiment>>,
private val experimentStore: ExperimentStore,
private val appLog: AppLogWrapper,
private val accountStore: AccountStore,
private val analyticsTracker: AnalyticsTrackerWrapper,
@Named(APPLICATION_SCOPE) private val coroutineScope: CoroutineScope
) {
private val platform = Platform.WORDPRESS_ANDROID
private val activeVariations = mutableMapOf<String, Variation>()
private val experimentNames by lazy { experiments.get().map { it.name } }
fun refreshIfNeeded() {
refresh(refreshStrategy = IF_STALE)
}
fun forceRefresh() {
refresh(refreshStrategy = ALWAYS)
}
fun clear() {
appLog.d(T.API, "ExPlat: clearing cached assignments and active variations")
activeVariations.clear()
experimentStore.clearCachedAssignments()
}
/**
* This returns the current active [Variation] for the provided [Experiment].
*
* If no active [Variation] is found, we can assume this is the first time this method is being
* called for the provided [Experiment] during the current session. In this case, the [Variation]
* is returned from the cached [Assignments] and then set as active. If the cached [Assignments]
* is stale and [shouldRefreshIfStale] is `true`, then new [Assignments] are fetched and their
* variations are going to be returned by this method on the next session.
*
* If the provided [Experiment] was not included in [ExPlat.start], then [Control] is returned.
* If [BuildConfig.DEBUG] is `true`, an [IllegalArgumentException] is thrown instead.
*/
internal fun getVariation(experiment: Experiment, shouldRefreshIfStale: Boolean): Variation {
if (!experimentNames.contains(experiment.name)) {
val message = "ExPlat: experiment not found: \"${experiment.name}\"! " +
"Make sure to include it in the set provided via constructor."
appLog.e(T.API, message)
if (BuildConfig.DEBUG) throw IllegalArgumentException(message) else return Control
}
return activeVariations.getOrPut(experiment.name) {
getAssignments(if (shouldRefreshIfStale) IF_STALE else NEVER).getVariationForExperiment(experiment.name)
}
}
private fun refresh(refreshStrategy: RefreshStrategy) {
if (experimentNames.isNotEmpty() && (accountStore.hasAccessToken() || analyticsTracker.getAnonID() != null)) {
getAssignments(refreshStrategy)
}
}
private fun getAssignments(refreshStrategy: RefreshStrategy): Assignments {
val cachedAssignments = experimentStore.getCachedAssignments() ?: Assignments()
if (refreshStrategy == ALWAYS || (refreshStrategy == IF_STALE && cachedAssignments.isStale())) {
coroutineScope.launch { fetchAssignments() }
}
return cachedAssignments
}
private suspend fun fetchAssignments() =
experimentStore.fetchAssignments(platform, experimentNames, analyticsTracker.getAnonID()).also {
if (it.isError) {
appLog.d(T.API, "ExPlat: fetching assignments failed with result: ${it.error}")
} else {
appLog.d(T.API, "ExPlat: fetching assignments successful with result: ${it.assignments}")
}
}
private enum class RefreshStrategy { ALWAYS, IF_STALE, NEVER }
}
|
gpl-2.0
|
7402e687b34b9c92acb5494e7399302c
| 44.45 | 118 | 0.729593 | 4.642492 | false | false | false | false |
JetBrains/teamcity-nuget-support
|
nuget-tests/src/jetbrains/buildServer/nuget/tests/server/feed/server/NuGetBuildFeedsProviderTest.kt
|
1
|
10990
|
package jetbrains.buildServer.nuget.tests.server.feed.server
import jetbrains.buildServer.nuget.feed.server.index.NuGetFeedData
import jetbrains.buildServer.nuget.feed.server.index.impl.NuGetBuildFeedsProviderImpl
import jetbrains.buildServer.nuget.feed.server.packages.NuGetRepository
import jetbrains.buildServer.serverSide.ProjectManager
import jetbrains.buildServer.serverSide.SBuild
import jetbrains.buildServer.serverSide.SBuildFeatureDescriptor
import jetbrains.buildServer.serverSide.SProject
import jetbrains.buildServer.serverSide.packages.Repository
import jetbrains.buildServer.serverSide.packages.RepositoryType
import jetbrains.buildServer.serverSide.packages.impl.RepositoryManager
import org.hamcrest.Description
import org.jmock.Expectations
import org.jmock.Mockery
import org.jmock.api.Action
import org.jmock.api.Invocation
import org.testng.Assert
import org.testng.annotations.Test
import org.jmock.lib.legacy.ClassImposteriser
@Test
class NuGetBuildFeedsProviderTest {
fun getEmptyListIfProjectNotFound() {
val m = Mockery()
val projectManager = m.mock(ProjectManager::class.java)
val repositoryManager = m.mock(RepositoryManager::class.java)
val build = m.mock(SBuild::class.java)
val feedsProvider = NuGetBuildFeedsProviderImpl(projectManager, repositoryManager)
m.checking(object : Expectations() {
init {
oneOf(build).projectId
will(returnValue("_Root"))
oneOf(projectManager).findProjectById("_Root")
will(returnValue(null))
oneOf(build).getBuildFeaturesOfType("NuGetPackagesIndexer")
will(returnValue(emptyList<SBuildFeatureDescriptor>()))
}
})
val feeds = feedsProvider.getFeeds(build)
Assert.assertTrue(feeds.isEmpty())
m.assertIsSatisfied()
}
fun getEmptyListIfProjectsDoesNotHaveRepositories() {
val m = Mockery()
val projectManager = m.mock(ProjectManager::class.java)
val repositoryManager = m.mock(RepositoryManager::class.java)
val build = m.mock(SBuild::class.java)
val project = m.mock(SProject::class.java)
val feedsProvider = NuGetBuildFeedsProviderImpl(projectManager, repositoryManager)
m.checking(object : Expectations() {
init {
oneOf(build).projectId
will(returnValue("_Root"))
oneOf(projectManager).findProjectById("_Root")
will(returnValue(project))
oneOf(repositoryManager).getRepositories(project, true)
will(returnValue(emptyList<Repository>()))
oneOf(build).getBuildFeaturesOfType("NuGetPackagesIndexer")
will(returnValue(emptyList<SBuildFeatureDescriptor>()))
}
})
val feeds = feedsProvider.getFeeds(build)
Assert.assertTrue(feeds.isEmpty())
m.assertIsSatisfied()
}
fun getEmptyListIfProjectsDoesNotHaveNuGetFeeds() {
val m = object : Mockery() {
init {
setImposteriser(ClassImposteriser.INSTANCE)
}
}
val projectManager = m.mock(ProjectManager::class.java)
val repositoryManager = m.mock(RepositoryManager::class.java)
val build = m.mock(SBuild::class.java)
val project = m.mock(SProject::class.java)
val repository = m.mock(Repository::class.java)
val feedsProvider = NuGetBuildFeedsProviderImpl(projectManager, repositoryManager)
m.checking(object : Expectations() {
init {
oneOf(build).projectId
will(returnValue("_Root"))
oneOf(projectManager).findProjectById("_Root")
will(returnValue(project))
oneOf(repositoryManager).getRepositories(project, true)
will(returnValue(listOf(repository)))
oneOf(build).getBuildFeaturesOfType("NuGetPackagesIndexer")
will(returnValue(emptyList<SBuildFeatureDescriptor>()))
}
})
val feeds = feedsProvider.getFeeds(build)
Assert.assertTrue(feeds.isEmpty())
m.assertIsSatisfied()
}
fun getEmptyListIfProjectFeedDoesNotHaveIndexing() {
val m = object : Mockery() {
init {
setImposteriser(ClassImposteriser.INSTANCE)
}
}
val projectManager = m.mock(ProjectManager::class.java)
val repositoryManager = m.mock(RepositoryManager::class.java)
val build = m.mock(SBuild::class.java)
val project = m.mock(SProject::class.java)
val repositoryType = m.mock(RepositoryType::class.java)
val feedsProvider = NuGetBuildFeedsProviderImpl(projectManager, repositoryManager)
m.checking(object : Expectations() {
init {
one(build).projectId
will(returnValue("_Root"))
oneOf(projectManager).findProjectById("_Root")
will(returnValue(project))
allowing(project).projectId
will(returnValue("_Root"))
oneOf(repositoryManager).getRepositories(project, true)
will(object: Action {
override fun describeTo(description: Description?) = Unit
override fun invoke(invocation: Invocation?): Any {
return listOf(NuGetRepository(repositoryType, project, mapOf("name" to "default")))
}
})
oneOf(build).getBuildFeaturesOfType("NuGetPackagesIndexer")
will(returnValue(emptyList<SBuildFeatureDescriptor>()))
}
})
val feeds = feedsProvider.getFeeds(build)
Assert.assertTrue(feeds.isEmpty())
m.assertIsSatisfied()
}
fun getFeedsFromProjectWithIndexing() {
val m = object : Mockery() {
init {
setImposteriser(ClassImposteriser.INSTANCE)
}
}
val projectManager = m.mock(ProjectManager::class.java)
val repositoryManager = m.mock(RepositoryManager::class.java)
val build = m.mock(SBuild::class.java)
val project = m.mock(SProject::class.java)
val repositoryType = m.mock(RepositoryType::class.java)
val feedsProvider = NuGetBuildFeedsProviderImpl(projectManager, repositoryManager)
m.checking(object : Expectations() {
init {
one(build).projectId
will(returnValue("_Root"))
oneOf(projectManager).findProjectById("_Root")
will(returnValue(project))
allowing(project).projectId
will(returnValue("_Root"))
oneOf(repositoryManager).getRepositories(project, true)
will(object: Action {
override fun describeTo(description: Description?) = Unit
override fun invoke(invocation: Invocation?): Any {
return listOf(NuGetRepository(repositoryType, project, mapOf(
"name" to "default",
"indexPackages" to "true"
)))
}
})
oneOf(build).getBuildFeaturesOfType("NuGetPackagesIndexer")
will(returnValue(emptyList<SBuildFeatureDescriptor>()))
}
})
val feeds = feedsProvider.getFeeds(build)
Assert.assertEquals(feeds.size, 1)
Assert.assertEquals(feeds.first(), NuGetFeedData.DEFAULT)
m.assertIsSatisfied()
}
fun getFeedsFromNuGetIndexerFeature() {
val m = Mockery()
val projectManager = m.mock(ProjectManager::class.java)
val repositoryManager = m.mock(RepositoryManager::class.java)
val build = m.mock(SBuild::class.java)
val project = m.mock(SProject::class.java)
val feature = m.mock(SBuildFeatureDescriptor::class.java)
val feedsProvider = NuGetBuildFeedsProviderImpl(projectManager, repositoryManager)
m.checking(object : Expectations() {
init {
one(build).projectId
will(returnValue("_Root"))
oneOf(projectManager).findProjectById("_Root")
will(returnValue(project))
allowing(project).projectId
will(returnValue("_Root"))
oneOf(repositoryManager).getRepositories(project, true)
will(returnValue(emptyList<Repository>()))
oneOf(build).getBuildFeaturesOfType("NuGetPackagesIndexer")
will(returnValue(listOf(feature)))
oneOf(feature).parameters
will(returnValue(mapOf("feed" to "_Root/default")))
oneOf(projectManager).findProjectByExternalId("_Root")
will(returnValue(project))
oneOf(repositoryManager).hasRepository(project, "nuget", "default")
will(returnValue(true))
}
})
val feeds = feedsProvider.getFeeds(build)
Assert.assertEquals(feeds.size, 1)
Assert.assertEquals(feeds.first(), NuGetFeedData.DEFAULT)
m.assertIsSatisfied()
}
fun getDistinctFeedsFromNuGetIndexerFeature() {
val m = Mockery()
val projectManager = m.mock(ProjectManager::class.java)
val repositoryManager = m.mock(RepositoryManager::class.java)
val build = m.mock(SBuild::class.java)
val project = m.mock(SProject::class.java)
val feature = m.mock(SBuildFeatureDescriptor::class.java)
val feedsProvider = NuGetBuildFeedsProviderImpl(projectManager, repositoryManager)
m.checking(object : Expectations() {
init {
one(build).projectId
will(returnValue("_Root"))
oneOf(projectManager).findProjectById("_Root")
will(returnValue(project))
allowing(project).projectId
will(returnValue("_Root"))
oneOf(repositoryManager).getRepositories(project, true)
will(returnValue(emptyList<Repository>()))
oneOf(build).getBuildFeaturesOfType("NuGetPackagesIndexer")
will(returnValue(listOf(feature, feature)))
allowing(feature).parameters
will(returnValue(mapOf("feed" to "_Root/default")))
allowing(projectManager).findProjectByExternalId("_Root")
will(returnValue(project))
allowing(repositoryManager).hasRepository(project, "nuget", "default")
will(returnValue(true))
}
})
val feeds = feedsProvider.getFeeds(build)
Assert.assertEquals(feeds.size, 1)
Assert.assertEquals(feeds.first(), NuGetFeedData.DEFAULT)
m.assertIsSatisfied()
}
}
|
apache-2.0
|
99683f6b8ddf8d4d06582b5d0febf016
| 36.254237 | 107 | 0.619017 | 5.062183 | false | false | false | false |
iPoli/iPoli-android
|
app/src/main/java/io/ipoli/android/quest/schedule/agenda/usecase/CreateAgendaPreviewItemsUseCase.kt
|
1
|
6827
|
package io.ipoli.android.quest.schedule.agenda.usecase
import io.ipoli.android.common.UseCase
import io.ipoli.android.common.datetime.Time
import io.ipoli.android.common.datetime.datesBetween
import io.ipoli.android.event.Event
import io.ipoli.android.quest.Color
import io.ipoli.android.quest.Quest
import org.threeten.bp.LocalDate
/**
* Created by Polina Zhelyazkova <[email protected]>
* on 10/26/18.
*/
class CreateAgendaPreviewItemsUseCase :
UseCase<CreateAgendaPreviewItemsUseCase.Params, List<CreateAgendaPreviewItemsUseCase.PreviewItem>> {
override fun execute(parameters: Params): List<CreateAgendaPreviewItemsUseCase.PreviewItem> {
val dayQuests = mapQuestsToDays(parameters.quests)
val dayEvents = mapEventsToDays(parameters.events)
return parameters.startDate.datesBetween(parameters.endDate).map {
PreviewItem(
date = it,
weekIndicators = createWeekIndicators(it, dayQuests, dayEvents),
monthIndicators = createMonthIndicators(it, dayQuests, dayEvents)
)
}
}
private fun mapEventsToDays(events: List<Event>): Map<LocalDate, List<Event>> {
val dayEvents = mutableMapOf<LocalDate, List<Event>>()
events.forEach {
val date = it.startDate
val list =
if (!dayEvents.containsKey(date)) listOf()
else dayEvents[date]!!
dayEvents[date] = list + it
}
return dayEvents
}
private fun mapQuestsToDays(quests: List<Quest>): Map<LocalDate, List<Quest>> {
val dayQuests = mutableMapOf<LocalDate, List<Quest>>()
quests.forEach {
val date = it.scheduledDate!!
val list =
if (!dayQuests.containsKey(date)) listOf()
else dayQuests[date]!!
dayQuests[date] = list + it
}
return dayQuests
}
private fun createMonthIndicators(
date: LocalDate,
quests: Map<LocalDate, List<Quest>>,
events: Map<LocalDate, List<Event>>
): List<PreviewItem.MonthIndicator> {
val indicators = mutableListOf<PreviewItem.MonthIndicator>()
events[date]?.forEach { e ->
val d = if (e.isAllDay) Time.MINUTES_IN_A_DAY else e.duration.intValue
indicators.add(PreviewItem.MonthIndicator.Event(d, e.color))
}
quests[date]?.forEach { q ->
indicators.add(PreviewItem.MonthIndicator.Quest(q.duration, q.color))
}
return indicators.sortedByDescending { i -> i.duration }
}
private fun createWeekIndicators(
date: LocalDate,
quests: Map<LocalDate, List<Quest>>,
events: Map<LocalDate, List<Event>>
): List<PreviewItem.WeekIndicator> {
val indicators = mutableListOf<PreviewItem.WeekIndicator>()
quests[date]?.forEach { q ->
val startTime: Time? = q.startTime
if (startTime == null) {
indicators.add(
PreviewItem.WeekIndicator.Quest(
startMinute = 0,
duration = MIN_TIME.minutesTo(MAX_TIME),
color = q.color
)
)
} else if (!(startTime < MIN_TIME && q.endTime!! < MIN_TIME)) {
val (startMinute, duration) =
when {
startTime < MIN_TIME -> Pair(
MIN_TIME.toMinuteOfDay(),
MIN_TIME.minutesTo(q.endTime!!)
)
q.endTime!! < MIN_TIME -> Pair(
startTime.toMinuteOfDay(),
startTime.minutesTo(MAX_TIME)
)
else -> Pair(startTime.toMinuteOfDay(), q.duration)
}
indicators.add(
PreviewItem.WeekIndicator.Quest(
startMinute = startMinute - MINUTES_OFFSET,
duration = duration,
color = q.color
)
)
}
}
events[date]?.forEach { e ->
val startTime: Time = e.startTime
if (!(startTime < MIN_TIME && e.endTime < MIN_TIME)) {
val (startMinute, duration) =
when {
e.isAllDay -> Pair(
MIN_TIME.toMinuteOfDay(),
MIN_TIME.minutesTo(MAX_TIME)
)
startTime < MIN_TIME -> Pair(
MIN_TIME.toMinuteOfDay(),
MIN_TIME.minutesTo(e.endTime)
)
e.endTime < MIN_TIME -> Pair(
startTime.toMinuteOfDay(),
startTime.minutesTo(MAX_TIME)
)
else -> Pair(startTime.toMinuteOfDay(), e.duration.intValue)
}
indicators.add(
PreviewItem.WeekIndicator.Event(
startMinute = startMinute - MINUTES_OFFSET,
duration = duration,
color = e.color
)
)
}
}
return indicators.sortedWith(
compareBy<PreviewItem.WeekIndicator> { i -> i.startMinute }
.thenByDescending { i -> i.duration }
)
}
companion object {
const val MINUTES_OFFSET = 8 * 60
val MIN_TIME = Time.atHours(8)
val MAX_TIME = Time.at(23, 59)
}
data class PreviewItem(
val date: LocalDate,
val weekIndicators: List<WeekIndicator>,
val monthIndicators: List<MonthIndicator>
) {
sealed class WeekIndicator {
abstract val duration: Int
abstract val startMinute: Int
data class Quest(
val color: Color,
override val duration: Int,
override val startMinute: Int
) : WeekIndicator()
data class Event(
val color: Int,
override val duration: Int,
override val startMinute: Int
) : WeekIndicator()
}
sealed class MonthIndicator {
abstract val duration: Int
data class Quest(override val duration: Int, val color: Color) : MonthIndicator()
data class Event(override val duration: Int, val color: Int) : MonthIndicator()
}
}
data class Params(
val startDate: LocalDate,
val endDate: LocalDate,
val quests: List<Quest>,
val events: List<Event>
)
}
|
gpl-3.0
|
0fd0c733a534354e3b116ec6c4d0c7e4
| 34.378238 | 104 | 0.52351 | 4.965091 | false | false | false | false |
iMeiji/Daily
|
app/src/main/java/com/meiji/daily/binder/PostsListViewBinder.kt
|
1
|
2774
|
package com.meiji.daily.binder
import android.support.v7.widget.CardView
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.meiji.daily.GlideApp
import com.meiji.daily.R
import com.meiji.daily.bean.PostsListBean
import com.meiji.daily.module.postscontent.PostsContentActivity
import kotlinx.android.synthetic.main.item_postlist.view.*
import me.drakeet.multitype.ItemViewBinder
/**
* Created by Meiji on 2017/6/6.
*/
internal class PostsListViewBinder : ItemViewBinder<PostsListBean, PostsListViewBinder.ViewHolder>() {
override fun onCreateViewHolder(inflater: LayoutInflater, parent: ViewGroup): PostsListViewBinder.ViewHolder {
val view = inflater.inflate(R.layout.item_postlist, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: PostsListViewBinder.ViewHolder, item: PostsListBean) {
val context = holder.itemView.context
val publishedTime = item.publishedTime.substring(0, 10)
val likesCount = item.likesCount.toString() + "赞"
val commentsCount = item.commentsCount.toString() + "条评论"
var titleImage = item.titleImage
val title = item.title
if (!TextUtils.isEmpty(titleImage)) {
titleImage = item.titleImage.replace("r.jpg", "b.jpg")
GlideApp.with(context)
.load(titleImage)
.centerCrop()
.error(R.color.viewBackground)
.transition(DrawableTransitionOptions().crossFade())
.into(holder.iv_titleImage)
} else {
holder.iv_titleImage.setImageResource(R.drawable.error_image)
holder.iv_titleImage.scaleType = ImageView.ScaleType.CENTER_CROP
}
holder.tv_publishedTime.text = publishedTime
holder.tv_likesCount.text = likesCount
holder.tv_commentsCount.text = commentsCount
holder.tv_title.text = title
holder.root.setOnClickListener { PostsContentActivity.start(context, item.titleImage, item.title, item.slug.toString()) }
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val root: CardView = itemView.cardview
val tv_publishedTime: TextView = itemView.tv_publishedTime
val tv_likesCount: TextView = itemView.tv_likesCount
val tv_commentsCount: TextView = itemView.tv_commentsCount
val iv_titleImage: ImageView = itemView.iv_titleImage
val tv_title: TextView = itemView.tv_title
}
}
|
apache-2.0
|
678502605ede9637e5aec05fafeb47e3
| 40.283582 | 129 | 0.710051 | 4.301711 | false | false | false | false |
GunoH/intellij-community
|
plugins/gradle/java/src/service/project/wizard/GradleJavaNewProjectWizardData.kt
|
7
|
2344
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.gradle.service.project.wizard
import com.intellij.ide.wizard.NewProjectWizardStep
import com.intellij.openapi.observable.properties.GraphProperty
import com.intellij.openapi.util.Key
interface GradleJavaNewProjectWizardData : GradleNewProjectWizardData {
val addSampleCodeProperty: GraphProperty<Boolean>
var addSampleCode: Boolean
companion object {
@JvmStatic val KEY = Key.create<GradleJavaNewProjectWizardData>(GradleJavaNewProjectWizardData::class.java.name)
@JvmStatic val NewProjectWizardStep.gradleData get() = data.getUserData(KEY)!!
@JvmStatic val NewProjectWizardStep.sdkProperty get() = gradleData.sdkProperty
@JvmStatic val NewProjectWizardStep.useKotlinDslProperty get() = gradleData.useKotlinDslProperty
@JvmStatic val NewProjectWizardStep.parentProperty get() = gradleData.parentProperty
@JvmStatic val NewProjectWizardStep.groupIdProperty get() = gradleData.groupIdProperty
@JvmStatic val NewProjectWizardStep.artifactIdProperty get() = gradleData.artifactIdProperty
@JvmStatic val NewProjectWizardStep.versionProperty get() = gradleData.versionProperty
@JvmStatic val NewProjectWizardStep.addSampleCodeProperty get() = gradleData.addSampleCodeProperty
@JvmStatic var NewProjectWizardStep.sdk get() = gradleData.sdk; set(it) { gradleData.sdk = it }
@JvmStatic var NewProjectWizardStep.useKotlinDsl get() = gradleData.useKotlinDsl; set(it) { gradleData.useKotlinDsl = it }
@JvmStatic var NewProjectWizardStep.parent get() = gradleData.parent; set(it) { gradleData.parent = it }
@JvmStatic var NewProjectWizardStep.parentData get() = gradleData.parentData; set(it) { gradleData.parentData = it }
@JvmStatic var NewProjectWizardStep.groupId get() = gradleData.groupId; set(it) { gradleData.groupId = it }
@JvmStatic var NewProjectWizardStep.artifactId get() = gradleData.artifactId; set(it) { gradleData.artifactId = it }
@JvmStatic var NewProjectWizardStep.version get() = gradleData.version; set(it) { gradleData.version = it }
@JvmStatic var NewProjectWizardStep.addSampleCode get() = gradleData.addSampleCode; set(it) { gradleData.addSampleCode = it }
}
}
|
apache-2.0
|
91561095c69d9171221bb6d6e4c5cd14
| 67.970588 | 158 | 0.793089 | 4.803279 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/jvm-debugger/core-fe10/src/org/jetbrains/kotlin/idea/debugger/stepping/smartStepInto/KotlinSmartStepTargetFilterer.kt
|
4
|
4136
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.debugger.stepping.smartStepInto
import com.intellij.debugger.engine.DebugProcessImpl
import com.intellij.debugger.impl.DebuggerUtilsEx
import com.intellij.psi.PsiMethod
import org.jetbrains.kotlin.asJava.LightClassUtil
import org.jetbrains.kotlin.idea.debugger.core.DebuggerUtils.trimIfMangledInBytecode
import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtPropertyAccessor
import java.util.*
class KotlinSmartStepTargetFilterer(
private val targets: List<KotlinMethodSmartStepTarget>,
private val debugProcess: DebugProcessImpl
) {
private val functionCounter = mutableMapOf<String, Int>()
private val targetWasVisited = BooleanArray(targets.size) { false }
fun visitInlineFunction(function: KtNamedFunction) {
val descriptor = function.descriptor ?: return
val label = KotlinMethodSmartStepTarget.calcLabel(descriptor)
val currentCount = functionCounter.increment(label) - 1
val matchedSteppingTargetIndex = targets.indexOfFirst {
it.getDeclaration() === function && it.ordinal == currentCount
}
if (matchedSteppingTargetIndex < 0) return
targetWasVisited[matchedSteppingTargetIndex] = true
}
fun visitOrdinaryFunction(owner: String, name: String, signature: String) {
val currentCount = functionCounter.increment("$owner.$name$signature") - 1
for ((i, target) in targets.withIndex()) {
if (target.shouldBeVisited(owner, name, signature, currentCount)) {
targetWasVisited[i] = true
break
}
}
}
private fun KotlinMethodSmartStepTarget.shouldBeVisited(owner: String, name: String, signature: String, currentCount: Int): Boolean {
val actualName = name.trimIfMangledInBytecode(methodInfo.isNameMangledInBytecode)
if (methodInfo.isInlineClassMember) {
return matches(
owner,
actualName,
// Inline class constructor argument is injected as the first
// argument in inline class' functions. This doesn't correspond
// with the PSI, so we delete the first argument from the signature
signature.getSignatureWithoutFirstArgument(),
currentCount
)
}
return matches(owner, actualName, signature, currentCount)
}
private fun KotlinMethodSmartStepTarget.matches(owner: String, name: String, signature: String, currentCount: Int): Boolean {
if (methodInfo.name == name && ordinal == currentCount) {
val lightClassMethod = getDeclaration()?.getLightClassMethod() ?: return false
return lightClassMethod.matches(owner, name, signature, debugProcess)
}
return false
}
fun getUnvisitedTargets(): List<KotlinMethodSmartStepTarget> =
targets.filterIndexed { i, _ ->
!targetWasVisited[i]
}
fun reset() {
Arrays.fill(targetWasVisited, false)
functionCounter.clear()
}
}
private fun String.getSignatureWithoutFirstArgument() =
removeRange(indexOf('(') + 1..indexOf(';'))
private fun KtDeclaration.getLightClassMethod(): PsiMethod? =
when (this) {
is KtNamedFunction -> LightClassUtil.getLightClassMethod(this)
is KtPropertyAccessor -> LightClassUtil.getLightClassPropertyMethods(property).getter
else -> null
}
private fun PsiMethod.matches(className: String, methodName: String, signature: String, debugProcess: DebugProcessImpl): Boolean =
DebuggerUtilsEx.methodMatches(
this,
className.replace("/", "."),
methodName,
signature,
debugProcess
)
private fun MutableMap<String, Int>.increment(key: String): Int {
val newValue = (get(key) ?: 0) + 1
put(key, newValue)
return newValue
}
|
apache-2.0
|
5cf072b54b7ced2a41ad84f7acb019a8
| 39.950495 | 137 | 0.691973 | 5.050061 | false | false | false | false |
jk1/intellij-community
|
platform/testGuiFramework/src/com/intellij/testGuiFramework/fixtures/TreeTableFixture.kt
|
2
|
1470
|
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.testGuiFramework.fixtures
import com.intellij.testGuiFramework.driver.ExtendedJTreeDriver
import com.intellij.testGuiFramework.driver.ExtendedJTreePathFinder
import com.intellij.ui.treeStructure.treetable.TreeTable
import org.fest.swing.core.MouseButton
import org.fest.swing.core.Robot
import org.fest.swing.driver.ComponentPreconditions
import org.fest.swing.driver.JTreeLocation
import java.awt.Dimension
import java.awt.Point
import java.awt.Rectangle
class TreeTableFixture(val robot: Robot, val target: TreeTable) :
ComponentFixture<TreeTableFixture, TreeTable>(TreeTableFixture::class.java, robot, target) {
@Suppress("unused")
fun clickColumn(column: Int, vararg pathStrings: String) {
ComponentPreconditions.checkEnabledAndShowing(target)
val tree = target.tree
val path = ExtendedJTreePathFinder(tree).findMatchingPath(*pathStrings)
var x = target.location.x + (0 until column).sumBy { target.columnModel.getColumn(it).width }
x += target.columnModel.getColumn(column).width / 3
val y = JTreeLocation().pathBoundsAndCoordinates(tree, path).second.y
val visibleHeight = target.visibleRect.height
target.scrollRectToVisible(Rectangle(Point(0, y + visibleHeight / 2), Dimension(0, 0)))
robot.click(target, Point(x, y), MouseButton.LEFT_BUTTON, 1)
}
}
|
apache-2.0
|
1a18de6426bc820706ef9def47052cff
| 42.264706 | 140 | 0.786395 | 4.027397 | false | true | false | false |
Doctoror/ParticleConstellationsLiveWallpaper
|
app/src/main/java/com/doctoror/particleswallpaper/framework/file/BackgroundImageManagerImpl.kt
|
1
|
3463
|
/*
* Copyright (C) 2017 Yaroslav Mytkalyk
*
* 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.doctoror.particleswallpaper.framework.file
import android.content.Context
import android.net.Uri
import android.util.Log
import java.io.File
import java.io.IOException
import java.util.regex.Pattern
/**
* The background image manager
*/
class BackgroundImageManagerImpl(
private val context: Context,
private val fileSaver: FileSaver,
private val fileUriResolver: FileUriResolver
) : BackgroundImageManager {
private val backgroundsDirectory = "backgrounds"
private val fileNamePrefix = "bg"
private val tag = "BackgroundImageManager"
private val fileNamePattern = Pattern.compile("$fileNamePrefix([0-9])+")!!
override fun copyBackgroundToFile(source: Uri): Uri {
val filesDir = context.filesDir ?: throw IOException("getFilesDir() returned null")
val backgroundsDir = File(filesDir, backgroundsDirectory)
if (!backgroundsDir.exists()) {
if (!backgroundsDir.mkdir()) {
throw IOException("Failed to create backgrounds directory")
}
}
val largestIndex = deletePreviousFilesAndGetLargestFileIndex(backgroundsDir)
val file = File(backgroundsDir, fileNamePrefix + largestIndex)
fileSaver.saveToPrivateFile(source, file)
if (!file.exists()) {
throw IOException("The created file does not exist")
}
return fileUriResolver.getUriForFile(file)
?: throw IOException("FileProvider returned null Uri for saved file")
}
private fun deletePreviousFilesAndGetLargestFileIndex(filesDir: File): Int {
var largestIndex = 0
val files = filesDir.listFiles()
files?.forEach {
try {
val matcher = fileNamePattern.matcher(it.name)
if (matcher.matches()) {
if (!it.delete()) {
Log.w(tag, "Failed to delete previous background image file named $it")
}
val number = matcher.group(1).toInt()
if (largestIndex < number) {
largestIndex = number
}
}
} catch (e: NumberFormatException) {
Log.wtf(tag, e)
}
}
return largestIndex + 1
}
override fun clearBackgroundImage() {
val filesDir = context.filesDir
if (filesDir == null) {
Log.w(tag, "getFilesDir() returned null")
return
}
val backgroundsDir = File(filesDir, backgroundsDirectory)
if (backgroundsDir.exists()) {
val files = backgroundsDir.listFiles()
files?.forEach {
if (!it.delete()) {
Log.w(tag, "Failed to delete background image file: " + it.name)
}
}
}
}
}
|
apache-2.0
|
123b80f61a68e42f7fbe90de148a3770
| 33.63 | 95 | 0.619694 | 4.743836 | false | false | false | false |
KinveyApps/Android-Starter
|
app/src/main/java/com/kinvey/bookshelf/ui/activity/ShelfActivity.kt
|
1
|
13499
|
package com.kinvey.bookshelf.ui.activity
import android.app.ProgressDialog
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.AdapterView
import android.widget.AdapterView.OnItemClickListener
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.facebook.CallbackManager
import com.facebook.CallbackManager.Factory
import com.facebook.FacebookCallback
import com.facebook.FacebookException
import com.facebook.login.LoginManager
import com.facebook.login.LoginResult
import com.kinvey.android.Client
import com.kinvey.android.callback.KinveyPurgeCallback
import com.kinvey.android.callback.KinveyReadCallback
import com.kinvey.android.model.User
import com.kinvey.android.store.DataStore
import com.kinvey.android.store.UserStore
import com.kinvey.android.sync.KinveyPullCallback
import com.kinvey.android.sync.KinveyPushCallback
import com.kinvey.android.sync.KinveyPushResponse
import com.kinvey.android.sync.KinveySyncCallback
import com.kinvey.bookshelf.App
import com.kinvey.bookshelf.ui.adapter.BooksAdapter
import com.kinvey.bookshelf.Constants
import com.kinvey.bookshelf.R
import com.kinvey.bookshelf.entity.Author
import com.kinvey.bookshelf.entity.Book
import com.kinvey.java.AbstractClient
import com.kinvey.java.core.KinveyClientCallback
import com.kinvey.java.dto.BaseUser
import com.kinvey.java.model.KinveyPullResponse
import com.kinvey.java.model.KinveyReadResponse
import com.kinvey.java.store.StoreType
import kotlinx.android.synthetic.main.activity_shelf.*
import kotlinx.android.synthetic.main.content_shelf.*
import timber.log.Timber
import java.io.IOException
import java.util.*
class ShelfActivity : AppCompatActivity(), OnItemClickListener {
private val SAVE_BOOKS_COUNT = 5
private var client: Client<User>? = null
private var adapter: BooksAdapter? = null
private var bookStore: DataStore<Book>? = null
private var progressDialog: ProgressDialog? = null
private var mCallbackManager: CallbackManager? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_shelf)
setSupportActionBar(myToolbar)
client = (application as App).sharedClient
bookStore = DataStore.collection(Constants.COLLECTION_NAME, Book::class.java, StoreType.SYNC, client)
mCallbackManager = Factory.create()
LoginManager.getInstance().registerCallback(mCallbackManager,
object : FacebookCallback<LoginResult?> {
override fun onSuccess(loginResult: LoginResult?) {
Timber.d("Success Login")
kinveyFacebookLogin(loginResult?.accessToken?.token ?: "")
}
override fun onCancel() {
Toast.makeText(this@ShelfActivity, "Login Cancel", Toast.LENGTH_LONG).show()
}
override fun onError(exception: FacebookException) {
Toast.makeText(this@ShelfActivity, exception.message, Toast.LENGTH_LONG).show()
}
})
}
override fun onResume() {
super.onResume()
if (client != null && client?.isUserLoggedIn == true) { data }
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
mCallbackManager?.onActivityResult(requestCode, resultCode, data)
}
override fun onStop() {
dismissProgress()
super.onStop()
}
private fun sync() {
showProgress(resources.getString(R.string.progress_sync))
bookStore?.sync(object : KinveySyncCallback {
override fun onSuccess(kinveyPushResponse: KinveyPushResponse?, kinveyPullResponse: KinveyPullResponse?) {
data
dismissProgress()
Toast.makeText(this@ShelfActivity, R.string.toast_sync_completed, Toast.LENGTH_LONG).show()
}
override fun onPullStarted() {}
override fun onPushStarted() {}
override fun onPullSuccess(kinveyPullResponse: KinveyPullResponse?) {}
override fun onPushSuccess(kinveyPushResponse: KinveyPushResponse?) {}
override fun onFailure(t: Throwable?) {
dismissProgress()
Toast.makeText(this@ShelfActivity, R.string.toast_sync_failed, Toast.LENGTH_LONG).show()
}
})
}
private val data: Unit
private get() {
bookStore?.find(object : KinveyReadCallback<Book> {
override fun onSuccess(result: KinveyReadResponse<Book>?) {
updateBookAdapter(result?.result)
Timber.d("ListCallback: success")
}
override fun onFailure(error: Throwable?) {
Timber.d("ListCallback: failure")
}
})
}
private fun updateBookAdapter(list: List<Book>?) {
val books = list ?: listOf()
shelfList?.onItemClickListener = this@ShelfActivity
adapter = BooksAdapter(books, this@ShelfActivity)
shelfList?.adapter = adapter
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_shelf, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
when (item.itemId) {
R.id.action_new -> {
val i = Intent(this, BookActivity::class.java)
startActivity(i)
return true
}
R.id.action_save_batch -> saveBatch()
R.id.action_sync -> sync()
R.id.action_pull -> pull()
R.id.action_push -> push()
R.id.action_purge -> purge()
R.id.action_login -> login()
R.id.action_facebook_login -> facebookLogin()
R.id.action_logout -> logout()
}
return super.onOptionsItemSelected(item)
}
private fun pull() {
showProgress(resources.getString(R.string.progress_pull))
bookStore?.pull(object : KinveyPullCallback {
override fun onSuccess(result: KinveyPullResponse?) {
dismissProgress()
data
Toast.makeText(this@ShelfActivity, R.string.toast_pull_completed, Toast.LENGTH_LONG).show()
}
override fun onFailure(error: Throwable?) {
dismissProgress()
Toast.makeText(this@ShelfActivity, R.string.toast_pull_failed, Toast.LENGTH_LONG).show()
}
})
}
private fun push() {
showProgress(resources.getString(R.string.progress_push))
bookStore?.push(object : KinveyPushCallback {
override fun onSuccess(result: KinveyPushResponse?) {
dismissProgress()
Toast.makeText(this@ShelfActivity, R.string.toast_push_completed, Toast.LENGTH_SHORT).show()
}
override fun onFailure(error: Throwable?) {
dismissProgress()
Toast.makeText(this@ShelfActivity, R.string.toast_push_failed, Toast.LENGTH_SHORT).show()
}
override fun onProgress(current: Long, all: Long) {}
})
}
private fun saveBatch() {
val list = generateList(SAVE_BOOKS_COUNT)
bookStore?.save(list,
object : KinveyClientCallback<List<Book>> {
override fun onSuccess(result: List<Book>?) {
dismissProgress()
Toast.makeText(application, resources.getString(R.string.toast_batch_items_created), Toast.LENGTH_LONG).show()
}
override fun onFailure(error: Throwable?) {
dismissProgress()
Toast.makeText(application, resources.getString(R.string.toast_save_failed), Toast.LENGTH_LONG).show()
}
})
}
private fun generateList(count: Int): List<Book> {
var book: Book
val booksList = mutableListOf<Book>()
for (i in 0 until count) {
book = Book()
book.name = "Book v5 #$i"
book.author = Author("Author v5 #{\$i}")
booksList.add(book)
}
return booksList
}
private fun login() {
showProgress(resources.getString(R.string.progress_login))
try {
UserStore.login(Constants.USER_NAME, Constants.USER_PASSWORD, client as Client<User>,
object : KinveyClientCallback<User> {
override fun onSuccess(result: User?) {
//successfully logged in
dismissProgress()
Toast.makeText(this@ShelfActivity, R.string.toast_sign_in_completed, Toast.LENGTH_LONG).show()
}
override fun onFailure(error: Throwable?) {
dismissProgress()
Toast.makeText(this@ShelfActivity, R.string.toast_can_not_login, Toast.LENGTH_LONG).show()
signUp()
}
})
} catch (e: IOException) {
Timber.e(e)
dismissProgress()
Toast.makeText(this@ShelfActivity, R.string.toast_unsuccessful, Toast.LENGTH_LONG).show()
}
}
private fun facebookLogin() {
LoginManager.getInstance().logInWithReadPermissions(this, listOf("public_profile", "user_friends"))
}
private fun kinveyFacebookLogin(accessToken: String) {
showProgress(resources.getString(R.string.progress_login))
try {
UserStore.loginFacebook<User>(accessToken, client as Client<User>, object : KinveyClientCallback<User> {
override fun onSuccess(result: User?) {
//successfully logged in
dismissProgress()
Toast.makeText(this@ShelfActivity, R.string.toast_sign_in_completed, Toast.LENGTH_LONG).show()
}
override fun onFailure(error: Throwable?) {
dismissProgress()
Toast.makeText(this@ShelfActivity, R.string.toast_can_not_login, Toast.LENGTH_LONG).show()
signUp()
}
})
} catch (e: IOException) {
Timber.e(e)
dismissProgress()
Toast.makeText(this@ShelfActivity, R.string.toast_unsuccessful, Toast.LENGTH_LONG).show()
}
}
private fun signUp() {
showProgress(resources.getString(R.string.progress_sign_up))
UserStore.signUp(Constants.USER_NAME, Constants.USER_PASSWORD, client as Client<User>, object : KinveyClientCallback<User> {
override fun onSuccess(result: User?) {
dismissProgress()
Toast.makeText(this@ShelfActivity, R.string.toast_sign_up_completed, Toast.LENGTH_LONG).show()
}
override fun onFailure(error: Throwable?) {
dismissProgress()
Toast.makeText(this@ShelfActivity, R.string.toast_can_not_sign_up, Toast.LENGTH_LONG).show()
}
})
}
private fun logout() {
showProgress(resources.getString(R.string.progress_logout))
UserStore.logout(client as AbstractClient<BaseUser>, object : KinveyClientCallback<Void> {
override fun onSuccess(result: Void?) {
updateBookAdapter(ArrayList())
bookStore = DataStore.collection<Book, Client<*>>(Constants.COLLECTION_NAME, Book::class.java, StoreType.SYNC, client)
dismissProgress()
Toast.makeText(this@ShelfActivity, R.string.toast_logout_completed, Toast.LENGTH_LONG).show()
}
override fun onFailure(error: Throwable?) {
dismissProgress()
Toast.makeText(this@ShelfActivity, R.string.toast_logout_failed, Toast.LENGTH_LONG).show()
}
})
}
private fun purge() {
showProgress(resources.getString(R.string.progress_purge))
bookStore?.purge(object : KinveyPurgeCallback {
override fun onSuccess(result: Void?) {
dismissProgress()
Toast.makeText(this@ShelfActivity, R.string.toast_purge_completed, Toast.LENGTH_LONG).show()
}
override fun onFailure(error: Throwable?) {
dismissProgress()
Toast.makeText(this@ShelfActivity, R.string.toast_purge_failed, Toast.LENGTH_LONG).show()
}
})
}
private fun showProgress(message: String) {
if (progressDialog == null) {
progressDialog = ProgressDialog(this)
}
progressDialog?.setMessage(message)
progressDialog?.show()
}
private fun dismissProgress() {
progressDialog?.dismiss()
}
override fun onItemClick(parent: AdapterView<*>?, view: View, position: Int, id: Long) {
val book = adapter?.getItem(position) ?: return
val i = Intent(this, BookActivity::class.java)
i.putExtra(Constants.EXTRA_ID, book[Constants.ID].toString())
startActivity(i)
}
}
|
apache-2.0
|
3b47214e8147ac31c3cba8d16015f93a
| 39.785498 | 134 | 0.627454 | 4.664478 | false | false | false | false |
tomekby/miscellaneous
|
kotlin-game/android/app/src/main/java/pl/vot/tomekby/mathGame/Container.kt
|
1
|
2425
|
package pl.vot.tomekby.mathGame
import kotlin.reflect.KCallable
import kotlin.reflect.KParameter
import kotlin.reflect.jvm.jvmErasure
// Type representing factory for DI definitions
typealias DependencyFactory<T> = () -> T
object Container {
// DTO containing data needed to autowire definition
data class AutoWiredClass<T>(val factory: KCallable<T>, val arguments: Map<KParameter, String>)
val definitions = HashMap<String, Any>()
/**
* Get name of a definition based on a type name
*/
inline fun <reified T> definition(): String = T::class.qualifiedName!!
/**
* Set "singleton" definition for given interface/class
* Instance passed as the argument will be returned on each call
* On each call
*/
inline fun <reified T : Any> setInstance(instance: T) {
definitions[definition<T>()] = instance
}
/**
* Set factory method for given interface/class
* This factory will be called each time definition is fetched
*/
inline fun <reified T> setFactory(noinline factory: DependencyFactory<T>) {
definitions[definition<T>()] = factory
}
/**
* Autowire selected instance
* If singleton is selected, it'll try to autowire on setup
* Else, it will be done at each call
*/
inline fun <reified T> autowire(factory: KCallable<T>, singleton: Boolean = false) {
val arguments = factory.parameters
.groupBy { it }
.mapValues { it.value.first().type.jvmErasure.qualifiedName!! }
// Save autowired definition
definitions[definition<T>()] = AutoWiredClass(factory, arguments)
// If this is supposed to be singleton, call & replace it right away
if (singleton) definitions[definition<T>()] = get(definition<T>())
}
// Get definition by name
fun get(def: String): Any {
val element = definitions[def]!!
return when (element) {
is DependencyFactory<*> -> element()
is AutoWiredClass<*> ->
// Try to recursively autowire arguments
element.factory.callBy(element.arguments.mapValues { get(it.value) })
else -> element
}!!
}
}
// Convenience method for shorter DI definition fetching
inline fun <reified T: Any> di(): T = Container.get(Container.definition<T>()) as T
|
mit
|
1c264dd32d9e2855d0e0d64506aa601d
| 33.691176 | 99 | 0.629691 | 4.584121 | false | false | false | false |
dahlstrom-g/intellij-community
|
platform/build-scripts/groovy/org/jetbrains/intellij/build/impl/BuildHelper.kt
|
1
|
9888
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplacePutWithAssignment")
package org.jetbrains.intellij.build.impl
import com.intellij.diagnostic.telemetry.createTask
import com.intellij.diagnostic.telemetry.useWithScope
import com.intellij.util.JavaModuleOptions
import com.intellij.util.lang.CompoundRuntimeException
import com.intellij.util.system.OS
import com.intellij.util.xml.dom.readXmlAsModel
import io.opentelemetry.api.trace.Span
import io.opentelemetry.api.trace.SpanBuilder
import io.opentelemetry.api.trace.StatusCode
import org.jetbrains.intellij.build.BuildContext
import org.jetbrains.intellij.build.BuildScriptsLoggedError
import org.jetbrains.intellij.build.CompilationContext
import org.jetbrains.intellij.build.OsFamily
import org.jetbrains.intellij.build.TraceManager.spanBuilder
import org.jetbrains.intellij.build.io.copyDir
import org.jetbrains.intellij.build.io.runJava
import java.io.File
import java.nio.file.FileSystems
import java.nio.file.Files
import java.nio.file.NoSuchFileException
import java.nio.file.Path
import java.util.concurrent.ForkJoinTask
import java.util.concurrent.TimeUnit
import java.util.function.Predicate
import kotlin.io.path.copyTo
val DEFAULT_TIMEOUT = TimeUnit.MINUTES.toMillis(10L)
internal fun span(spanBuilder: SpanBuilder, task: Runnable) {
spanBuilder.useWithScope {
task.run()
}
}
inline fun createSkippableTask(spanBuilder: SpanBuilder,
taskId: String,
context: BuildContext,
crossinline task: () -> Unit): ForkJoinTask<*>? {
if (context.options.buildStepsToSkip.contains(taskId)) {
val span = spanBuilder.startSpan()
span.addEvent("skip")
span.end()
return null
}
else {
return createTask(spanBuilder) { task() }
}
}
/**
* Filter is applied only to files, not to directories.
*/
fun copyDirWithFileFilter(fromDir: Path, targetDir: Path, fileFilter: Predicate<Path>) {
copyDir(sourceDir = fromDir, targetDir = targetDir, fileFilter = fileFilter)
}
fun zip(context: CompilationContext, targetFile: Path, dir: Path, compress: Boolean) {
zipWithPrefixes(context, targetFile, mapOf(dir to ""), compress)
}
fun zipWithPrefixes(context: CompilationContext, targetFile: Path, map: Map<Path, String>, compress: Boolean) {
spanBuilder("pack")
.setAttribute("targetFile", context.paths.buildOutputDir.relativize(targetFile).toString())
.useWithScope {
org.jetbrains.intellij.build.io.zip(targetFile = targetFile, dirs = map, compress = compress, addDirEntries = false)
}
}
/**
* Executes a Java class in a forked JVM
*/
@JvmOverloads
fun runJava(context: CompilationContext,
mainClass: String,
args: Iterable<String>,
jvmArgs: Iterable<String>,
classPath: Iterable<String>,
timeoutMillis: Long = DEFAULT_TIMEOUT,
workingDir: Path? = null,
onError: (() -> Unit)? = null) {
runJava(mainClass = mainClass,
args = args,
jvmArgs = getCommandLineArgumentsForOpenPackages(context) + jvmArgs,
classPath = classPath,
javaExe = context.stableJavaExecutable,
logger = context.messages,
timeoutMillis = timeoutMillis,
workingDir = workingDir,
onError = onError)
}
/**
* Forks all tasks in the specified collection, returning when
* `isDone` holds for each task or an (unchecked) exception is encountered, in which case the exception is rethrown.
* If more than one task encounters an exception, then this method throws a compound exception.
* If any task encounters an exception, others will be not cancelled.
*
* It is typically used when you have multiple asynchronous tasks that are not dependent on one another to complete successfully,
* or you'd always like to know the result of each promise.
*
* This way, we can get valid artifacts for one OS if building artifacts for another OS failed.
*/
internal fun invokeAllSettled(tasks: List<ForkJoinTask<*>>) {
for (task in tasks) {
task.fork()
}
joinAllSettled(tasks)
}
private fun joinAllSettled(tasks: List<ForkJoinTask<*>>) {
if (tasks.isEmpty()) {
return
}
val errors = ArrayList<Throwable>()
for (task in tasks.asReversed()) {
try {
task.join()
}
catch (e: Throwable) {
errors.add(e)
}
}
if (!errors.isEmpty()) {
val error = if (errors.size == 1) errors[0] else CompoundRuntimeException(errors)
val span = Span.current()
span.recordException(error)
span.setStatus(StatusCode.ERROR)
throw error
}
}
fun runApplicationStarter(context: BuildContext,
tempDir: Path,
ideClasspath: Set<String>,
arguments: List<String>,
systemProperties: Map<String, Any> = emptyMap(),
vmOptions: List<String> = emptyList(),
timeoutMillis: Long = DEFAULT_TIMEOUT,
classpathCustomizer: ((MutableSet<String>) -> Unit)? = null) {
Files.createDirectories(tempDir)
val jvmArgs = ArrayList<String>()
val systemDir = tempDir.resolve("system")
BuildUtils.addVmProperty(jvmArgs, "idea.home.path", context.paths.projectHome.toString())
BuildUtils.addVmProperty(jvmArgs, "idea.system.path", systemDir.toString())
BuildUtils.addVmProperty(jvmArgs, "idea.config.path", "$tempDir/config")
// reproducible build - avoid touching module outputs, do no write classpath.index
BuildUtils.addVmProperty(jvmArgs, "idea.classpath.index.enabled", "false")
BuildUtils.addVmProperty(jvmArgs, "java.system.class.loader", "com.intellij.util.lang.PathClassLoader")
BuildUtils.addVmProperty(jvmArgs, "idea.platform.prefix", context.productProperties.platformPrefix)
jvmArgs.addAll(BuildUtils.propertiesToJvmArgs(systemProperties))
jvmArgs.addAll(vmOptions.takeIf { it.isNotEmpty() } ?: listOf("-Xmx1024m"))
val debugPort = System.getProperty("intellij.build." + arguments.first() + ".debug.port")
if (debugPort != null) {
jvmArgs.add("-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=*:$debugPort")
}
val effectiveIdeClasspath = LinkedHashSet(ideClasspath)
val additionalPluginPaths = context.productProperties.getAdditionalPluginPaths(context)
val additionalPluginIds = LinkedHashSet<String>()
for (pluginPath in additionalPluginPaths) {
for (jarFile in BuildUtils.getPluginJars(pluginPath)) {
if (effectiveIdeClasspath.add(jarFile.toString())) {
context.messages.debug("$jarFile from plugin $pluginPath")
readPluginId(jarFile)?.let {
additionalPluginIds.add(it)
}
}
}
}
classpathCustomizer?.invoke(effectiveIdeClasspath)
disableCompatibleIgnoredPlugins(context, tempDir.resolve("config"), additionalPluginIds)
runJava(context, "com.intellij.idea.Main", arguments, jvmArgs, effectiveIdeClasspath, timeoutMillis) {
val logFile = systemDir.resolve("log").resolve("idea.log")
val logFileToPublish = File.createTempFile("idea-", ".log")
logFile.copyTo(logFileToPublish.toPath(), true)
context.notifyArtifactBuilt(logFileToPublish.toPath())
try {
context.messages.error("Log file: ${logFileToPublish.canonicalPath} attached to build artifacts")
}
catch (_: BuildScriptsLoggedError) {
// skip exception thrown by logger.error
}
}
}
private fun readPluginId(pluginJar: Path): String? {
if (!pluginJar.toString().endsWith(".jar") || !Files.isRegularFile(pluginJar)) {
return null
}
try {
FileSystems.newFileSystem(pluginJar, null).use {
return readXmlAsModel(Files.newInputStream(it.getPath("META-INF/plugin.xml"))).getChild("id")?.content
}
}
catch (ignore: NoSuchFileException) {
return null
}
}
private fun disableCompatibleIgnoredPlugins(context: BuildContext,
configDir: Path,
explicitlyEnabledPlugins: Set<String?>) {
val toDisable = LinkedHashSet<String>()
for (moduleName in context.productProperties.productLayout.compatiblePluginsToIgnore) {
// TODO: It is temporary solution to avoid exclude Kotlin from searchable options build because Kotlin team
// need to use the same id in fir plugin.
// Remove it when "kotlin.plugin-fir" will removed from compatiblePluginsToIgnore
// see: org/jetbrains/intellij/build/BaseIdeaProperties.groovy:179
if (moduleName == "kotlin.plugin-fir") {
continue
}
val pluginXml = context.findFileInModuleSources(moduleName, "META-INF/plugin.xml")!!
val child = readXmlAsModel(Files.newInputStream(pluginXml)).getChild("id")
val pluginId = child?.content ?: continue
if (!explicitlyEnabledPlugins.contains(pluginId)) {
toDisable.add(pluginId)
context.messages.debug(
"runApplicationStarter: \'$pluginId\' will be disabled, because it\'s mentioned in \'compatiblePluginsToIgnore\'")
}
}
if (!toDisable.isEmpty()) {
Files.createDirectories(configDir)
Files.writeString(configDir.resolve("disabled_plugins.txt"), java.lang.String.join("\n", toDisable))
}
}
/**
* @return a list of JVM args for opened packages (JBR17+) in a format `--add-opens=PACKAGE=ALL-UNNAMED` for a specified or current OS
*/
fun getCommandLineArgumentsForOpenPackages(context: CompilationContext, target: OsFamily? = null): List<String> {
val file = context.paths.communityHomeDir.communityRoot.resolve("plugins/devkit/devkit-core/src/run/OpenedPackages.txt")
val os = when (target) {
OsFamily.WINDOWS -> OS.Windows
OsFamily.MACOS -> OS.macOS
OsFamily.LINUX -> OS.Linux
null -> OS.CURRENT
}
return JavaModuleOptions.readOptions(file, os)
}
|
apache-2.0
|
a912a566ffb8b938ef749bb902ade8be
| 38.870968 | 134 | 0.707423 | 4.334941 | false | false | false | false |
github/codeql
|
java/ql/test/kotlin/library-tests/super-method-calls/test.kt
|
1
|
378
|
open class A {
open fun f(x: String) = x
}
interface B {
fun g(x: String) = x
}
interface C {
fun g(x: String) = x
}
class User : A(), B, C {
override fun f(x: String) = super.f(x)
override fun g(x: String) = super<B>.g(x)
fun source() = "tainted"
fun sink(s: String) { }
fun test() {
sink(this.f(source()))
sink(this.g(source()))
}
}
|
mit
|
852c953b86f84ffa5437d348ab3c47fc
| 9.5 | 43 | 0.534392 | 2.571429 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ
|
src/main/kotlin/com/demonwav/mcdev/translations/lang/formatting/LangBlock.kt
|
1
|
1940
|
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.translations.lang.formatting
import com.demonwav.mcdev.translations.lang.gen.psi.LangTypes
import com.intellij.formatting.Alignment
import com.intellij.formatting.Block
import com.intellij.formatting.Indent
import com.intellij.formatting.SpacingBuilder
import com.intellij.formatting.Wrap
import com.intellij.formatting.WrapType
import com.intellij.lang.ASTNode
import com.intellij.psi.TokenType
import com.intellij.psi.formatter.common.AbstractBlock
import java.util.ArrayList
class LangBlock(node: ASTNode, wrap: Wrap?, alignment: Alignment?, private val spacingBuilder: SpacingBuilder) :
AbstractBlock(node, wrap, alignment) {
override fun buildChildren(): List<Block> {
val blocks = ArrayList<Block>()
var child: ASTNode? = myNode.firstChildNode
var previousChild: ASTNode? = null
while (child != null) {
if (
child.elementType !== TokenType.WHITE_SPACE &&
(
previousChild == null ||
previousChild.elementType !== LangTypes.LINE_ENDING ||
child.elementType !== LangTypes.LINE_ENDING
)
) {
val block = LangBlock(
child,
Wrap.createWrap(WrapType.NONE, false),
Alignment.createAlignment(),
spacingBuilder
)
blocks.add(block)
}
previousChild = child
child = child.treeNext
}
return blocks
}
override fun getIndent() = Indent.getNoneIndent()
override fun getSpacing(child1: Block?, child2: Block) = spacingBuilder.getSpacing(this, child1, child2)
override fun isLeaf() = myNode.firstChildNode == null
}
|
mit
|
e49b3b5244a9f2f8f122842e1089f90e
| 31.881356 | 112 | 0.626804 | 4.720195 | false | false | false | false |
GreyTeardrop/jwt-tool
|
src/main/java/com/github/greyteardrop/jwt/CommandLineParser.kt
|
1
|
2286
|
package com.github.greyteardrop.jwt
/**
* Parses command line parameters and creates [Command] that should be executed.
*/
class CommandLineParser {
private val supportedCommands = setOf("create")
/**
* Parses [args] and creates [Command] that should be executed, if any.
*
* Returns successfully parsed [Command] or `null` if no command was provided.
* @param args command line parameters
* @throws UserException if error/help message has to be displayed to user
*/
fun parseCommandLine(args: Array<String>): Command? {
if (args.isEmpty()) {
return null
}
// TODO: as there's only one command now, we create it from the start
// TODO: to support multiple commands, command has to be instantiated when command line argument is parsed
var command = CreateCommand()
var i = 0
while (i < args.size) {
when (args[i]) {
"--to-clipboard" -> command = command.copy(exportToClipboard = true)
"--payload" -> {
if (i + 2 >= args.size) {
throw UserException(
"--payload requires 2 arguments: <key> and <value>")
}
val key = args[i + 1]
val value = args[i + 2]
command = command.withPayload(key, value)
i += 2
}
"--help" -> displayHelp()
else -> {
val commandName = args[i]
if (!supportedCommands.contains(commandName)) {
throw UserException(
"Unknown command $commandName, supportedCommands: $supportedCommands")
}
}
}
i++
}
return command
}
private fun displayHelp(): Nothing {
// TODO: Help text might be built from list of available options, might be loaded from resource
throw UserException("""|jwt-tool [--help] | <command> [<options>]
| Commands:
| create [--to-clipboard|--payload <key> <value>]""".trimMargin(), 0)
}
}
|
mit
|
47c791c2fdc7ff8a2907433a0cb49477
| 36.47541 | 114 | 0.505687 | 5.068736 | false | false | false | false |
paplorinc/intellij-community
|
platform/lang-api/src/com/intellij/execution/configurations/RunConfigurationMinimalBase.kt
|
16
|
2506
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.configurations
import com.intellij.configurationStore.ComponentSerializationUtil
import com.intellij.openapi.components.BaseState
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtilRt
import com.intellij.util.ReflectionUtil
import com.intellij.util.xmlb.annotations.Transient
import org.jdom.Element
import javax.swing.Icon
// RunConfiguration interface in java, so, we have to use base class (short kotlin property declaration doesn't support java)
abstract class RunConfigurationMinimalBase<T : BaseState>(name: String?,
private val factory: ConfigurationFactory,
private val project: Project) : RunConfiguration, PersistentStateComponent<T> {
private var name: String = name ?: ""
protected var options: T = createOptions()
private set
@Transient
override fun getName(): String {
// a lot of clients not ready that name can be null and in most cases it is not convenient - just add more work to handle null value
// in any case for run configuration empty name it is the same as null, we don't need to bother clients and use null
return StringUtilRt.notNullize(name)
}
override fun setName(value: String) {
name = value
}
override fun getFactory() = factory
override fun getIcon(): Icon = factory.icon
override fun getProject() = project
final override fun readExternal(element: Element) {
throw UnsupportedOperationException("readExternal must be not called")
}
final override fun writeExternal(element: Element) {
// serializeObjectInto(options, element)
throw UnsupportedOperationException("writeExternal must be not called")
}
override fun loadState(state: T) {
options = state
}
private fun createOptions(): T {
return ReflectionUtil.newInstance<T>(getOptionsClass())
}
private fun getOptionsClass(): Class<T> {
val result = factory.optionsClass
@Suppress("UNCHECKED_CAST")
return when {
result != null -> result as Class<T>
else -> {
val instance = this as PersistentStateComponent<*>
ComponentSerializationUtil.getStateClass(instance.javaClass)
}
}
}
}
|
apache-2.0
|
13939b2172ebeebf9e4a70a797235d9e
| 35.867647 | 140 | 0.713887 | 4.972222 | false | true | false | false |
apache/isis
|
incubator/clients/kroviz/src/main/kotlin/org/apache/causeway/client/kroviz/to/bs3/Row.kt
|
2
|
1633
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* 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 CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.causeway.client.kroviz.to.bs3
import org.apache.causeway.client.kroviz.utils.XmlHelper
import org.w3c.dom.Node
class Row(node: Node) {
val colList = mutableListOf<Col>()
var id: String = ""
init {
val dyNode = node.asDynamic()
if (dyNode.hasOwnProperty("id")) {
id = dyNode.getAttribute("id") as String
}
val nodeList = XmlHelper.nonTextChildren(node)
val cl = nodeList.filter { it.nodeName.equals("bs3:col") }
for (n: Node in cl) {
val col = Col(n)
colList.add(col)
}
}
fun getPropertyList(): List<Property> {
val list = mutableListOf<Property>()
colList.forEach { c ->
list.addAll(c.getPropertyList())
}
return list
}
}
|
apache-2.0
|
6b8b8f0a3d64a69a858b2733964e97e1
| 31.66 | 66 | 0.657073 | 3.93494 | false | false | false | false |
JetBrains/intellij-community
|
plugins/git4idea/src/git4idea/ui/branch/GitBranchesTreeModelImpl.kt
|
1
|
10704
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package git4idea.ui.branch
import com.intellij.dvcs.branch.GroupingKey.GROUPING_BY_DIRECTORY
import com.intellij.dvcs.getCommonCurrentBranch
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.psi.codeStyle.MinusculeMatcher
import com.intellij.ui.tree.TreePathUtil
import com.intellij.util.containers.headTail
import com.intellij.util.containers.init
import com.intellij.util.ui.tree.AbstractTreeModel
import com.intellij.vcsUtil.Delegates.equalVetoingObservable
import git4idea.GitBranch
import git4idea.branch.GitBranchType
import git4idea.branch.GitBranchUtil
import git4idea.config.GitVcsSettings
import git4idea.repo.GitRepository
import git4idea.ui.branch.GitBranchesTreeModel.TreeRoot
import javax.swing.tree.TreePath
import kotlin.properties.Delegates.observable
private typealias PathAndBranch = Pair<List<String>, GitBranch>
private typealias MatchResult = Pair<Collection<GitBranch>, Pair<GitBranch, Int>?>
class GitBranchesTreeModelImpl(
private val project: Project,
private val repositories: List<GitRepository>,
private val topLevelActions: List<Any> = emptyList()
) : AbstractTreeModel(), GitBranchesTreeModel {
private val branchesSubtreeSeparator = GitBranchesTreePopup.createTreeSeparator()
private val branchManager = project.service<GitBranchManager>()
private val branchComparator = compareBy<GitBranch> {
it.isNotCurrentBranch()
} then compareBy {
it.isNotFavorite()
} then compareBy {
!(isPrefixGrouping && it.name.contains('/'))
} then compareBy { it.name }
private val subTreeComparator = compareBy<Any> {
it is GitBranch && it.isNotCurrentBranch() && it.isNotFavorite()
} then compareBy {
it is GitBranchesTreeModel.BranchesPrefixGroup
}
private fun GitBranch.isNotCurrentBranch() = !repositories.any { repo -> repo.currentBranch == this }
private fun GitBranch.isNotFavorite() = !repositories.all { repo -> branchManager.isFavorite(GitBranchType.of(this), repo, name) }
private lateinit var localBranchesTree: LazyBranchesSubtreeHolder
private lateinit var remoteBranchesTree: LazyBranchesSubtreeHolder
private val branchesTreeCache = mutableMapOf<Any, List<Any>>()
private var branchTypeFilter: GitBranchType? = null
private var branchNameMatcher: MinusculeMatcher? by observable(null) { _, _, matcher -> rebuild(matcher) }
override var isPrefixGrouping: Boolean by equalVetoingObservable(branchManager.isGroupingEnabled(GROUPING_BY_DIRECTORY)) {
branchNameMatcher = null // rebuild tree
}
init {
// set trees
branchNameMatcher = null
}
private fun rebuild(matcher: MinusculeMatcher?) {
branchesTreeCache.keys.clear()
val localBranches = repositories.singleOrNull()?.branches?.localBranches ?: GitBranchUtil.getCommonLocalBranches(repositories)
val remoteBranches = repositories.singleOrNull()?.branches?.remoteBranches ?: GitBranchUtil.getCommonRemoteBranches(repositories)
localBranchesTree = LazyBranchesSubtreeHolder(localBranches, branchComparator, matcher)
remoteBranchesTree = LazyBranchesSubtreeHolder(remoteBranches, branchComparator, matcher)
treeStructureChanged(TreePath(arrayOf(root)), null, null)
}
override fun getRoot() = TreeRoot
override fun getChild(parent: Any?, index: Int): Any = getChildren(parent)[index]
override fun getChildCount(parent: Any?): Int = getChildren(parent).size
override fun getIndexOfChild(parent: Any?, child: Any?): Int = getChildren(parent).indexOf(child)
override fun isLeaf(node: Any?): Boolean = node is GitBranch
|| (node === GitBranchType.LOCAL && localBranchesTree.isEmpty())
|| (node === GitBranchType.REMOTE && remoteBranchesTree.isEmpty())
private fun getChildren(parent: Any?): List<Any> {
if (parent == null || !haveFilteredBranches()) return emptyList()
return when (parent) {
TreeRoot -> getTopLevelNodes()
is GitBranchType -> branchesTreeCache.getOrPut(parent) { getBranchTreeNodes(parent, emptyList()) }
is GitBranchesTreeModel.BranchesPrefixGroup -> {
branchesTreeCache.getOrPut(parent) { getBranchTreeNodes(parent.type, parent.prefix).sortedWith(subTreeComparator) }
}
else -> emptyList()
}
}
private fun getTopLevelNodes(): List<Any> {
val repositoriesOrEmpty = if (repositories.size > 1) repositories + branchesSubtreeSeparator else emptyList()
return if (branchTypeFilter != null) topLevelActions + repositoriesOrEmpty + branchTypeFilter!!
else topLevelActions + repositoriesOrEmpty + GitBranchType.LOCAL + GitBranchType.REMOTE
}
private fun getBranchTreeNodes(branchType: GitBranchType, path: List<String>): List<Any> {
val branchesMap: Map<String, Any> = when (branchType) {
GitBranchType.LOCAL -> localBranchesTree.tree
GitBranchType.REMOTE -> remoteBranchesTree.tree
}
if (path.isEmpty()) {
return branchesMap.mapToNodes(branchType, path)
}
else {
var currentLevel = branchesMap
for (prefixPart in path) {
@Suppress("UNCHECKED_CAST")
currentLevel = (currentLevel[prefixPart] as? Map<String, Any>) ?: return emptyList()
}
return currentLevel.mapToNodes(branchType, path)
}
}
private fun Map<String, Any>.mapToNodes(branchType: GitBranchType, path: List<String>): List<Any> {
return entries.map { (name, value) ->
if (value is Map<*, *>) GitBranchesTreeModel.BranchesPrefixGroup(branchType, path + name) else value
}
}
override fun getPreferredSelection(): TreePath? = getPreferredBranch()?.let(::createTreePathFor)
private fun getPreferredBranch(): GitBranch? {
if (branchNameMatcher == null) {
if (branchTypeFilter != GitBranchType.REMOTE) {
if (repositories.size == 1) {
val repository = repositories.single()
val recentBranches = GitVcsSettings.getInstance(project).recentBranchesByRepository
val recentBranch = recentBranches[repository.root.path]?.let { recentBranchName ->
localBranchesTree.branches.find { it.name == recentBranchName }
}
if (recentBranch != null) {
return recentBranch
}
val currentBranch = repository.currentBranch
if (currentBranch != null) {
return currentBranch
}
return null
}
else {
val branch = (GitVcsSettings.getInstance(project).recentCommonBranch ?: repositories.getCommonCurrentBranch())
?.let { recentBranchName ->
localBranchesTree.branches.find { it.name == recentBranchName }
}
return branch
}
}
else {
return null
}
}
val localMatch = if (branchTypeFilter != GitBranchType.REMOTE) localBranchesTree.topMatch else null
val remoteMatch = if (branchTypeFilter != GitBranchType.LOCAL) remoteBranchesTree.topMatch else null
if (localMatch == null && remoteMatch == null) return null
if (localMatch != null && remoteMatch == null) return localMatch.first
if (localMatch == null && remoteMatch != null) return remoteMatch.first
if (localMatch!!.second >= remoteMatch!!.second) {
return localMatch.first
}
else {
return remoteMatch.first
}
}
override fun createTreePathFor(value: Any): TreePath? {
val repository = value as? GitRepository
if (repository != null) {
return TreePathUtil.convertCollectionToTreePath(listOf(root, repository))
}
val branch = value as? GitBranch ?: return null
val branchType = GitBranchType.of(branch)
val path = mutableListOf<Any>().apply {
add(root)
add(branchType)
}
val nameParts = if (isPrefixGrouping) branch.name.split('/') else listOf(branch.name)
val currentPrefix = mutableListOf<String>()
for (prefixPart in nameParts.init()) {
currentPrefix.add(prefixPart)
path.add(GitBranchesTreeModel.BranchesPrefixGroup(branchType, currentPrefix.toList()))
}
path.add(branch)
return TreePathUtil.convertCollectionToTreePath(path)
}
override fun filterBranches(type: GitBranchType?, matcher: MinusculeMatcher?) {
branchTypeFilter = type
branchNameMatcher = matcher
}
private fun haveFilteredBranches(): Boolean = !localBranchesTree.isEmpty() || !remoteBranchesTree.isEmpty()
private inner class LazyBranchesSubtreeHolder(
unsortedBranches: Collection<GitBranch>,
comparator: Comparator<GitBranch>,
private val matcher: MinusculeMatcher? = null
) {
val branches by lazy { unsortedBranches.sortedWith(comparator) }
fun isEmpty() = matchingResult.first.isEmpty()
private val matchingResult: MatchResult by lazy {
match(branches)
}
val tree: Map<String, Any> by lazy {
val branchesList = matchingResult.first
buildSubTree(branchesList.map { (if (isPrefixGrouping) it.name.split('/') else listOf(it.name)) to it })
}
val topMatch: Pair<GitBranch, Int>?
get() = matchingResult.second
private fun buildSubTree(prevLevel: List<PathAndBranch>): Map<String, Any> {
val result = LinkedHashMap<String, Any>()
val groups = LinkedHashMap<String, List<PathAndBranch>>()
for ((pathParts, branch) in prevLevel) {
val (firstPathPart, restOfThePath) = pathParts.headTail()
if (restOfThePath.isEmpty()) {
result[firstPathPart] = branch
}
else {
groups.compute(firstPathPart) { _, currentList ->
(currentList ?: mutableListOf()) + (restOfThePath to branch)
}?.let { group -> result[firstPathPart] = group }
}
}
for ((prefix, branchesWithPaths) in groups) {
result[prefix] = buildSubTree(branchesWithPaths)
}
return result
}
private fun match(branches: Collection<GitBranch>): MatchResult {
if (branches.isEmpty() || matcher == null) return MatchResult(branches, null)
val result = mutableListOf<GitBranch>()
var topMatch: Pair<GitBranch, Int>? = null
for (branch in branches) {
val matchingFragments = matcher.matchingFragments(branch.name)
if (matchingFragments == null) continue
result.add(branch)
val matchingDegree = matcher.matchingDegree(branch.name, false, matchingFragments)
if (topMatch == null || topMatch.second < matchingDegree) {
topMatch = branch to matchingDegree
}
}
return MatchResult(result, topMatch)
}
}
}
|
apache-2.0
|
ac2ec64bc7332774c1a1c4f70df95063
| 37.365591 | 133 | 0.704596 | 4.711268 | false | false | false | false |
JetBrains/intellij-community
|
plugins/kotlin/base/code-insight/src/org/jetbrains/kotlin/idea/base/codeInsight/EnumValuesSoftDeprecate.kt
|
1
|
1590
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.base.codeInsight
import com.intellij.psi.PsiElement
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtClassKind
import org.jetbrains.kotlin.analysis.api.symbols.KtClassOrObjectSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtSymbolOrigin
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.name.Name
@ApiStatus.Internal
val ENUM_VALUES_METHOD_NAME = Name.identifier("values")
@ApiStatus.Internal
fun KtAnalysisSession.isEnumValuesMethod(symbol: KtCallableSymbol): Boolean {
return KtClassKind.ENUM_CLASS == (symbol.getContainingSymbol() as? KtClassOrObjectSymbol)?.classKind &&
ENUM_VALUES_METHOD_NAME == symbol.callableIdIfNonLocal?.callableName &&
// Don't touch user-declared methods with the name "values"
symbol.origin == KtSymbolOrigin.SOURCE_MEMBER_GENERATED
}
@ApiStatus.Internal
fun PsiElement.isEnumValuesSoftDeprecateEnabled(): Boolean = languageVersionSettings.isEnumValuesSoftDeprecateEnabled()
@ApiStatus.Internal
fun LanguageVersionSettings.isEnumValuesSoftDeprecateEnabled(): Boolean = supportsFeature(LanguageFeature.EnumEntries)
|
apache-2.0
|
d41dc9081318df4d7adfcd18acf3ca67
| 50.290323 | 120 | 0.825157 | 4.582133 | false | true | false | false |
scenerygraphics/scenery
|
src/main/kotlin/graphics/scenery/utils/extensions/VectorMath.kt
|
1
|
4440
|
@file:JvmName("VectorMath")
package graphics.scenery.utils.extensions
import org.joml.*
import java.lang.Math
/* Vector2f */
operator fun Vector2f.plus(other: Vector2fc): Vector2f {
return Vector2f(this).add(other)
}
operator fun Vector2f.times(other: Vector2fc): Vector2f {
return Vector2f(this).mul(other)
}
operator fun Vector2f.times(other: Float): Vector2f {
return Vector2f(this).mul(other)
}
operator fun Vector2f.minus(other: Vector2fc): Vector2f {
return Vector2f(this).minus(other)
}
operator fun Vector2f.plusAssign(other: Vector2fc): Unit {
this.add(other)
}
operator fun Vector2f.minusAssign(other: Vector2fc): Unit {
this.sub(other)
}
operator fun Vector2f.timesAssign(other: Float): Unit {
this.mul(other)
}
operator fun Vector2f.divAssign(other: Float): Unit {
this.mul(1.0f / other)
}
operator fun Float.times(other: Vector2fc): Vector2f {
return Vector2f(other).times(this)
}
fun Vector2fc.xyz(): Vector3f {
return Vector3f().set(x(), y(), 0.0f)
}
fun Vector2fc.xyzw(): Vector4f {
return Vector4f().set(x(), y(), 0.0f, 1.0f)
}
fun Vector2fc.max(): Float {
val component = this.maxComponent()
return this[component]
}
fun Vector2f.toFloatArray(): FloatArray {
return floatArrayOf(this.x, this.y)
}
/* Vector3f */
operator fun Vector3f.plus(other: Vector3fc): Vector3f {
return Vector3f(this).add(other)
}
operator fun Vector3f.times(other: Vector3fc): Vector3f {
return Vector3f(this).mul(other)
}
operator fun Vector3f.times(other: Float): Vector3f {
return Vector3f(this).mul(other)
}
operator fun Vector3f.minus(other: Vector3fc): Vector3f {
return Vector3f(this).sub(other)
}
operator fun Vector3f.plusAssign(other: Vector3fc): Unit {
this.add(other)
}
operator fun Vector3f.minusAssign(other: Vector3fc): Unit {
this.sub(other)
}
operator fun Vector3f.timesAssign(other: Float): Unit {
this.mul(other)
}
operator fun Vector3f.divAssign(other: Float): Unit {
this.set(this.mul(1.0f / other))
}
operator fun Float.times(other: Vector3fc): Vector3f {
return Vector3f(other).times(this)
}
fun Vector3fc.xy(): Vector2f {
return Vector2f().set(this.x(), this.y())
}
fun Vector3fc.xyzw(): Vector4f {
return Vector4f().set(this, 1.0f)
}
fun Vector3fc.max(): Float {
val component = this.maxComponent()
return this[component]
}
fun Vector3f.toFloatArray(): FloatArray {
return floatArrayOf(this.x, this.y, this.z)
}
/* Vector4f */
operator fun Vector4f.plus(other: Vector4fc): Vector4f {
return Vector4f(this).add(other)
}
operator fun Vector4f.times(other: Vector4fc): Vector4f {
return Vector4f(this).mul(other)
}
operator fun Vector4f.times(other: Float): Vector4f {
return Vector4f(this).mul(other)
}
operator fun Vector4f.minus(other: Vector4fc): Vector4f {
return Vector4f(this).sub(other)
}
operator fun Vector4f.plusAssign(other: Vector4fc): Unit {
this.add(other)
}
operator fun Vector4f.minusAssign(other: Vector4fc): Unit {
this.sub(other)
}
operator fun Vector4f.timesAssign(other: Float): Unit {
this.mul(other)
}
operator fun Vector4f.divAssign(other: Float): Unit {
this.mul(1.0f / other)
}
operator fun Float.times(other: Vector4fc): Vector4f {
return Vector4f(other).times(this)
}
fun Vector4fc.max(): Float {
val component = this.maxComponent()
return this[component]
}
fun Vector4fc.xyz(): Vector3f {
return Vector3f().set(x(), y(), z())
}
fun Vector4f.toFloatArray(): FloatArray {
return floatArrayOf(this.x, this.y, this.z, this.w)
}
operator fun Quaternionf.times(other: Quaternionf): Quaternionf {
return this.mul(other)
}
infix operator fun Matrix4f.times(rhs: Matrix4f): Matrix4f {
val m = Matrix4f(this)
m.mul(rhs)
return m
}
fun Matrix4f.compare(right: Matrix4fc, explainDiff: Boolean): Boolean {
val EPSILON = 0.00001f
val left = this
for (r in 0 .. 3) {
for (c in 0..3) {
val delta = Math.abs(left.get(c, r) - right.get(c, r))
if (delta > EPSILON) {
if (explainDiff) {
System.err.println(
"Matrices differ at least in position row=$r, col=$c, |delta|=$delta")
System.err.println("LHS: $left")
System.err.println("RHS: $right")
}
return false
}
}
}
return true
}
|
lgpl-3.0
|
500b133afb1be6aa9d0275f557145d11
| 20.871921 | 94 | 0.666216 | 3.072664 | false | false | false | false |
FlashLight13/poliwhirl
|
app/src/main/java/org/example/poliwhirl/MainActivity.kt
|
1
|
4402
|
package org.example.poliwhirl
import android.graphics.Bitmap
import android.graphics.Color
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import com.antonpotapov.Poliwhirl
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.ImageViewTarget
import kotlinx.android.synthetic.main.activity_main.*
import java.util.concurrent.Executors
class MainActivity : AppCompatActivity() {
val poliwhirl = Poliwhirl()
var bitmap: Bitmap? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
imageUrl.adapter = ArrayAdapter(this, R.layout.v_text, arrayOf(
ImageData("Instagram", "https://instagram-brand.com/wp-content/uploads/2016/11/app-icon2.png"),
ImageData("Habrahabr", "https://pbs.twimg.com/profile_images/583482649924218881/HbQGtx57.jpg"),
ImageData("Netflix", "https://cdn.vox-cdn.com/thumbor/PgkEvDUnSUA_85lvxA3Hu4dxrs8=/800x0/filters:no_upscale()/cdn.vox-cdn.com/uploads/chorus_asset/file/6678919/10478570_10152214521608870_2744465531652776073_n.0.png"),
ImageData("Google Maps", "https://vignette.wikia.nocookie.net/logopedia/images/e/e1/Googlemapslogo2014.png/revision/latest?cb=20150309221525"))
)
imageUrl.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
Glide.with(this@MainActivity)
.asBitmap()
.load((parent!!.adapter.getItem(position) as ImageData).url)
.into(object : ImageViewTarget<Bitmap>(picture) {
override fun setResource(resource: Bitmap?) {
[email protected] = resource
this.view.setImageBitmap(resource)
}
})
}
}
borderSizeDivMul.setText(poliwhirl.verticalBorderSizeMul.toString())
borderSizeDivMul.addTextChangedListener(object : TextWatcherAdapter() {
override fun afterTextChanged(s: Editable?) {
poliwhirl.setBorderSizeDivideMultiplier(Math.max(1, parse(s.toString())))
}
})
accuracy.setText(poliwhirl.accuracy.toString())
accuracy.addTextChangedListener(object : TextWatcherAdapter() {
override fun afterTextChanged(s: Editable?) {
poliwhirl.setAccuracy(Math.max(1, parse(s.toString())))
}
})
minAvailableDistance.setText(poliwhirl.minAvailableDistance.toString())
minAvailableDistance.addTextChangedListener(object : TextWatcherAdapter() {
override fun afterTextChanged(s: Editable?) {
poliwhirl.setMinAvailableColorDistance(Math.max(0, parse(s.toString())))
}
})
calculateColor.setOnClickListener { updatePoliwhirl() }
clearColor.setOnClickListener { pictureBackground.setBackgroundColor(Color.TRANSPARENT) }
}
private fun updatePoliwhirl() {
val bitmap = bitmap
if (bitmap != null) {
poliwhirl.generateOnExecutor(bitmap, object : Poliwhirl.Callback {
override fun foundColor(color: Int) {
pictureBackground.setBackgroundColor(color)
}
}, Executors.newSingleThreadExecutor())
}
}
private fun parse(text: String): Int = try {
Integer.parseInt(text)
} catch (e: NumberFormatException) {
0
}
private open class TextWatcherAdapter : TextWatcher {
override fun afterTextChanged(s: Editable?) {
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
}
private data class ImageData(val name: String, val url: String) {
override fun toString(): String = name
}
}
|
apache-2.0
|
237ab441e7b8029ef42f962c13be778a
| 40.528302 | 233 | 0.646524 | 4.455466 | false | false | false | false |
scenerygraphics/scenery
|
src/main/kotlin/graphics/scenery/controls/behaviours/MouseDragSphere.kt
|
1
|
2607
|
package graphics.scenery.controls.behaviours
import graphics.scenery.BoundingGrid
import graphics.scenery.Camera
import graphics.scenery.Node
import graphics.scenery.utils.LazyLogger
import graphics.scenery.utils.extensions.minus
import graphics.scenery.utils.extensions.plus
import graphics.scenery.utils.extensions.times
import org.joml.Vector3f
import org.scijava.ui.behaviour.DragBehaviour
/**
* Drag nodes roughly along a sphere around the camera by mouse.
* Implements algorithm from https://forum.unity.com/threads/implement-a-drag-and-drop-script-with-c.130515/
*
* @author Jan Tiemann <[email protected]>
*/
open class MouseDragSphere(
protected val name: String,
camera: () -> Camera?,
protected var debugRaycast: Boolean = false,
var filter: (Node) -> Boolean
) : DragBehaviour, WithCameraDelegateBase(camera) {
protected val logger by LazyLogger()
protected var currentNode: Node? = null
protected var currentHit: Vector3f = Vector3f()
protected var distance: Float = 0f
constructor(
name: String,
camera: () -> Camera?,
debugRaycast: Boolean = false,
ignoredObjects: List<Class<*>> = listOf<Class<*>>(BoundingGrid::class.java)
) : this(name, camera, debugRaycast, { n: Node ->
!ignoredObjects.any { it.isAssignableFrom(n.javaClass) }})
override fun init(x: Int, y: Int) {
cam?.let { cam ->
val matches = cam.getNodesForScreenSpacePosition(x, y, filter, debugRaycast)
currentNode = matches.matches.firstOrNull()?.node
distance =
matches.matches.firstOrNull()?.distance ?: 0f//currentNode?.position?.distance(cam.position) ?: 0f
val (rayStart, rayDir) = cam.screenPointToRay(x, y)
rayDir.normalize()
currentHit = rayStart + rayDir * distance
}
}
override fun drag(x: Int, y: Int) {
if (distance <= 0)
return
cam?.let { cam ->
currentNode?.let {
val (rayStart, rayDir) = cam.screenPointToRay(x, y)
rayDir.normalize()
val newHit = rayStart + rayDir * distance
val movement = newHit - currentHit
it.ifSpatial {
val newPos = position + movement / worldScale()
currentNode?.spatialOrNull()?.position = newPos
currentHit = newHit
}
}
}
}
override fun end(x: Int, y: Int) {
// intentionally empty. A new click will overwrite the running variables.
}
}
|
lgpl-3.0
|
acf805c95a19e9d0c67cf5c13fde5e71
| 32 | 114 | 0.627925 | 4.252855 | false | false | false | false |
fobid/webviewer
|
webviewer/src/main/java/com/tfc/webviewer/presenter/WebViewPresenterImpl.kt
|
1
|
10421
|
/*
* Copyright fobidlim. 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.tfc.webviewer.presenter
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.text.TextUtils
import android.util.Log
import android.webkit.URLUtil
import android.webkit.WebView
import android.webkit.WebView.HitTestResult
import android.widget.PopupWindow
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.tfc.webviewer.R
import com.tfc.webviewer.util.UrlUtils
import com.tfc.webviewer.vibrate
import java.io.UnsupportedEncodingException
import java.net.MalformedURLException
import java.net.URLEncoder
/**
* author @fobidlim
*/
class WebViewPresenterImpl(
private val context: Context,
private val view: View
) : IWebViewPresenter {
private fun makeToast(text: CharSequence): Toast =
Toast.makeText(context, text, Toast.LENGTH_LONG)
override fun validateUrl(url: String) =
if (URLUtil.isValidUrl(url)) {
view.loadUrl(url)
} else {
if (!TextUtils.isEmpty(url)) {
var tempUrl = url
if (!URLUtil.isHttpUrl(url) && !URLUtil.isHttpsUrl(url)) {
tempUrl = "http://$url"
}
var host = ""
try {
host = UrlUtils.getHost(tempUrl)
} catch (e: MalformedURLException) {
view.setToolbarUrl(context.getString(R.string.loading))
}
if (URLUtil.isValidUrl(tempUrl)) {
view.loadUrl(tempUrl)
view.setToolbarTitle(host)
} else try {
tempUrl = "http://www.google.com/search?q=" + URLEncoder.encode(url, "UTF-8")
tempUrl = UrlUtils.getHost(tempUrl)
view.loadUrl(tempUrl)
view.setToolbarTitle(tempUrl)
} catch (e: UnsupportedEncodingException) {
e.printStackTrace()
view.showToast(makeToast(context.getString(R.string.message_invalid_url)))
view.close()
} catch (e: MalformedURLException) {
view.setToolbarUrl(context.getString(R.string.loading))
}
} else {
view.showToast(makeToast(context.getString(R.string.message_invalid_url)))
view.close()
}
}
override fun onBackPressed(menu: PopupWindow, webView: WebView) =
when {
menu.isShowing -> view.closeMenu()
webView.canGoBack() -> view.goBack()
else -> view.close()
}
override fun onReceivedTitle(title: String, url: String) {
view.setToolbarTitle(title)
try {
var tempUrl: String? = url
tempUrl = UrlUtils.getHost(tempUrl)
view.setToolbarUrl(tempUrl)
} catch (e: MalformedURLException) {
view.setToolbarUrl(context.getString(R.string.loading))
}
}
override fun onClick(resId: Int, url: String, popupWindow: PopupWindow) {
view.closeMenu()
when (resId) {
R.id.toolbar_btn_close -> view.close()
R.id.toolbar_btn_more -> {
if (popupWindow.isShowing) {
view.closeMenu()
} else {
view.openMenu()
}
}
R.id.popup_menu_btn_back -> view.goBack()
R.id.popup_menu_btn_forward -> view.goForward()
R.id.popup_menu_btn_refresh -> view.onRefresh()
R.id.popup_menu_btn_copy_link -> view.run {
copyLink(url)
showToast(makeToast(context.getString(R.string.message_copy_to_clipboard)))
}
R.id.popup_menu_btn_open_with_other_browser -> view.openBrowser(Uri.parse(url))
R.id.popup_menu_btn_share -> view.openShare(url)
else -> {
}
}
}
override fun setEnabledGoBackAndGoForward(enabledGoBack: Boolean, enabledGoForward: Boolean) {
if (enabledGoBack || enabledGoForward) {
view.setEnabledGoBackAndGoForward()
if (enabledGoBack) {
view.setEnabledGoBack()
} else {
view.setDisabledGoBack()
}
if (enabledGoForward) {
view.setEnabledGoForward()
} else {
view.setDisabledGoForward()
}
} else {
view.setDisabledGoBackAndGoForward()
}
}
override fun onLongClick(result: HitTestResult) {
context.vibrate()
val type = result.type
val extra = result.extra ?: return
when (type) {
HitTestResult.EMAIL_TYPE -> {
val items = arrayOf<CharSequence>(
context.getString(R.string.send_email),
context.getString(R.string.copy_email),
context.getString(R.string.copy_link_text)
)
AlertDialog.Builder(context)
.setTitle(extra)
.setItems(items) { _, which ->
if (which == 0) {
view.openEmail(extra)
} else if (which == 1 || which == 2) {
view.copyLink(extra)
view.showToast(makeToast(context.getString(R.string.message_copy_to_clipboard)))
}
}
.show()
}
HitTestResult.GEO_TYPE -> {
Log.d(TAG, "geo longclicked")
}
HitTestResult.SRC_IMAGE_ANCHOR_TYPE, HitTestResult.IMAGE_TYPE -> {
val items = arrayOf<CharSequence>(
context.getString(R.string.copy_link),
context.getString(R.string.save_link),
context.getString(R.string.save_image),
context.getString(R.string.open_image)
)
AlertDialog.Builder(context)
.setTitle(extra)
.setItems(items) { _, which ->
when (which) {
0 ->
view.run {
copyLink(extra)
showToast(makeToast(context.getString(R.string.message_copy_to_clipboard)))
}
1 -> view.onDownloadStart(extra)
2 -> view.onDownloadStart(extra)
3 -> view.openPopup(extra)
else -> {
}
}
}
.show()
}
HitTestResult.PHONE_TYPE, HitTestResult.SRC_ANCHOR_TYPE -> {
val items = arrayOf<CharSequence>(
context.getString(R.string.copy_link),
context.getString(R.string.copy_link_text),
context.getString(R.string.save_link)
)
AlertDialog.Builder(context)
.setTitle(extra)
.setItems(items) { _, which ->
when (which) {
0 -> view.run {
copyLink(extra)
showToast(makeToast(context.getString(R.string.message_copy_to_clipboard)))
}
1 -> view.run {
copyLink(extra)
showToast(makeToast(context.getString(R.string.message_copy_to_clipboard)))
}
2 -> view.onDownloadStart(extra)
else -> {
}
}
}
.show()
}
}
}
override fun onProgressChanged(swipeRefreshLayout: SwipeRefreshLayout, progress: Int) {
var progress = progress
if (swipeRefreshLayout.isRefreshing && progress == 100) {
swipeRefreshLayout.post { view.setRefreshing(false) }
}
if (!swipeRefreshLayout.isRefreshing && progress != 100) {
swipeRefreshLayout.post { view.setRefreshing(true) }
}
if (progress == 100) {
progress = 0
}
view.setProgressBar(progress)
}
fun startActivity(intent: Intent) =
try {
context.startActivity(intent)
} catch (e: ActivityNotFoundException) {
view.showToast(makeToast(context.getString(R.string.message_activity_not_found)))
}
interface View {
fun loadUrl(url: String)
fun close()
fun closeMenu()
fun openMenu()
fun setEnabledGoBackAndGoForward()
fun setDisabledGoBackAndGoForward()
fun setEnabledGoBack()
fun setDisabledGoBack()
fun setEnabledGoForward()
fun setDisabledGoForward()
fun goBack()
fun goForward()
fun onRefresh()
fun copyLink(url: String)
fun showToast(toast: Toast)
fun openBrowser(uri: Uri)
fun openShare(url: String)
fun setToolbarTitle(title: String)
fun setToolbarUrl(url: String)
fun onDownloadStart(url: String)
fun setProgressBar(progress: Int)
fun setRefreshing(refreshing: Boolean)
fun openEmail(email: String)
fun openPopup(url: String)
}
companion object {
private const val TAG = "WebViewPresenterImpl"
}
}
|
apache-2.0
|
3d7a78e12f2807d8c7a55b2b6094cada
| 36.354839 | 111 | 0.527493 | 4.960019 | false | false | false | false |
zdary/intellij-community
|
platform/lang-impl/src/com/intellij/codeInsight/hints/presentation/InsetPresentation.kt
|
12
|
2043
|
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.hints.presentation
import com.intellij.openapi.editor.markup.TextAttributes
import java.awt.Graphics2D
import java.awt.Point
import java.awt.event.MouseEvent
/**
* Presentation that wraps existing one into rectangle with given insets
* All mouse events that are outside of inner rectangle are not passed to underlying presentation.
*/
class InsetPresentation(
presentation: InlayPresentation,
val left: Int = 0,
val right: Int = 0,
val top: Int = 0,
val down: Int = 0
) : StaticDelegatePresentation(presentation) {
private var isPresentationUnderCursor = false
override val width: Int
get() = presentation.width + left + right
override val height: Int
get() = presentation.height + top + down
override fun paint(g: Graphics2D, attributes: TextAttributes) {
g.withTranslated(left, top) {
presentation.paint(g, attributes)
}
}
private fun handleMouse(
original: Point,
action: (InlayPresentation, Point) -> Unit
) {
val x = original.x
val y = original.y
val cursorIsOutOfBounds = x < left || x >= left + presentation.width || y < top || y >= top + presentation.height
if (cursorIsOutOfBounds) {
if (isPresentationUnderCursor) {
presentation.mouseExited()
isPresentationUnderCursor = false
}
return
}
val translated = original.translateNew(-left, -top)
action(presentation, translated)
}
override fun mouseClicked(event: MouseEvent, translated: Point) {
handleMouse(translated) { presentation, point ->
presentation.mouseClicked(event, point)
}
}
override fun mouseMoved(event: MouseEvent, translated: Point) {
handleMouse(translated) { presentation, point ->
presentation.mouseMoved(event, point)
}
}
override fun mouseExited() {
presentation.mouseExited()
isPresentationUnderCursor = false
}
}
|
apache-2.0
|
a5ff196abf3d478abad89b6188379a80
| 29.507463 | 140 | 0.707783 | 4.319239 | false | false | false | false |
leafclick/intellij-community
|
platform/credential-store/src/keePass/KeePassFileManager.kt
|
1
|
9323
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.credentialStore.keePass
import com.intellij.credentialStore.EncryptionSpec
import com.intellij.credentialStore.LOG
import com.intellij.credentialStore.getTrimmedChars
import com.intellij.credentialStore.kdbx.IncorrectMasterPasswordException
import com.intellij.credentialStore.kdbx.KdbxPassword
import com.intellij.credentialStore.kdbx.KdbxPassword.Companion.createAndClear
import com.intellij.credentialStore.kdbx.KeePassDatabase
import com.intellij.credentialStore.kdbx.loadKdbx
import com.intellij.credentialStore.toByteArrayAndClear
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.ui.components.dialog
import com.intellij.ui.layout.*
import com.intellij.util.SmartList
import com.intellij.util.io.delete
import com.intellij.util.io.exists
import java.awt.Component
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardCopyOption
import java.security.SecureRandom
import javax.swing.JPasswordField
internal open class KeePassFileManager(private val file: Path,
masterKeyFile: Path,
private val masterKeyEncryptionSpec: EncryptionSpec,
private val secureRandom: Lazy<SecureRandom>) {
private val masterKeyFileStorage = MasterKeyFileStorage(masterKeyFile)
fun clear() {
if (!file.exists()) {
return
}
try {
// don't create with preloaded empty db because "clear" action should remove only IntelliJ group from database,
// but don't remove other groups
val masterPassword = masterKeyFileStorage.load()
if (masterPassword != null) {
val db = loadKdbx(file, KdbxPassword.createAndClear(masterPassword))
val store = KeePassCredentialStore(file, masterKeyFileStorage, db)
store.clear()
store.save(masterKeyEncryptionSpec)
return
}
}
catch (e: Exception) {
// ok, just remove file
if (e !is IncorrectMasterPasswordException && ApplicationManager.getApplication()?.isUnitTestMode == false) {
LOG.error(e)
}
}
file.delete()
}
fun import(fromFile: Path, event: AnActionEvent?) {
if (file == fromFile) {
return
}
try {
doImportOrUseExisting(fromFile, event)
}
catch (e: IncorrectMasterPasswordException) {
throw e
}
catch (e: Exception) {
LOG.warn(e)
Messages.showMessageDialog(event?.getData(PlatformDataKeys.CONTEXT_COMPONENT)!!, "Internal error", "Cannot Import", Messages.getErrorIcon())
}
}
// throws IncorrectMasterPasswordException if user cancelled ask master password dialog
@Throws(IncorrectMasterPasswordException::class)
fun useExisting() {
if (file.exists()) {
if (!doImportOrUseExisting(file, event = null)) {
throw IncorrectMasterPasswordException()
}
}
else {
saveDatabase(file, KeePassDatabase(), generateRandomMasterKey(masterKeyEncryptionSpec, secureRandom.value), masterKeyFileStorage, secureRandom.value)
}
}
private fun doImportOrUseExisting(file: Path, event: AnActionEvent?): Boolean {
val contextComponent = event?.getData(PlatformDataKeys.CONTEXT_COMPONENT)
// check master key file in parent dir of imported file
val possibleMasterKeyFile = file.parent.resolve(MASTER_KEY_FILE_NAME)
var masterPassword = MasterKeyFileStorage(possibleMasterKeyFile).load()
if (masterPassword != null) {
try {
loadKdbx(file, KdbxPassword(masterPassword))
}
catch (e: IncorrectMasterPasswordException) {
LOG.warn("On import \"$file\" found existing master key file \"$possibleMasterKeyFile\" but key is not correct")
masterPassword = null
}
}
if (masterPassword == null && !requestMasterPassword("Specify Master Password", contextComponent = contextComponent) {
try {
loadKdbx(file, KdbxPassword(it))
masterPassword = it
null
}
catch (e: IncorrectMasterPasswordException) {
"Master password not correct."
}
}) {
return false
}
if (file !== this.file) {
Files.copy(file, this.file, StandardCopyOption.REPLACE_EXISTING)
}
masterKeyFileStorage.save(createMasterKey(masterPassword!!))
return true
}
fun askAndSetMasterKey(event: AnActionEvent?, topNote: String? = null): Boolean {
val contextComponent = event?.getData(PlatformDataKeys.CONTEXT_COMPONENT)
// to open old database, key can be required, so, to avoid showing 2 dialogs, check it before
val db = try {
if (file.exists()) loadKdbx(file, KdbxPassword(this.masterKeyFileStorage.load() ?: throw IncorrectMasterPasswordException(isFileMissed = true))) else KeePassDatabase()
}
catch (e: IncorrectMasterPasswordException) {
// ok, old key is required
return requestCurrentAndNewKeys(contextComponent)
}
return requestMasterPassword("Set Master Password", topNote = topNote, contextComponent = contextComponent) {
saveDatabase(file, db, createMasterKey(it), masterKeyFileStorage, secureRandom.value)
null
}
}
protected open fun requestCurrentAndNewKeys(contextComponent: Component?): Boolean {
val currentPasswordField = JPasswordField()
val newPasswordField = JPasswordField()
val panel = panel {
row("Current password:") { currentPasswordField().focused() }
row("New password:") { newPasswordField() }
commentRow("If the current password is unknown, clear the KeePass database.")
}
return dialog(title = "Change Master Password", panel = panel, parent = contextComponent) {
val errors = SmartList<ValidationInfo>()
val current = checkIsEmpty(currentPasswordField, errors)
val new = checkIsEmpty(newPasswordField, errors)
if (errors.isEmpty()) {
try {
if (doSetNewMasterPassword(current!!, new!!)) {
return@dialog errors
}
}
catch (e: IncorrectMasterPasswordException) {
errors.add(ValidationInfo("The current password is incorrect.", currentPasswordField))
new?.fill(0.toChar())
}
}
else {
current?.fill(0.toChar())
new?.fill(0.toChar())
}
errors
}.showAndGet()
}
@Suppress("MemberVisibilityCanBePrivate")
protected fun doSetNewMasterPassword(current: CharArray, new: CharArray): Boolean {
val db = loadKdbx(file, createAndClear(current.toByteArrayAndClear()))
saveDatabase(file, db, createMasterKey(new), masterKeyFileStorage, secureRandom.value)
return false
}
private fun createMasterKey(value: CharArray) = createMasterKey(value.toByteArrayAndClear())
private fun createMasterKey(value: ByteArray, isAutoGenerated: Boolean = false) = MasterKey(value, isAutoGenerated, masterKeyEncryptionSpec)
private fun checkIsEmpty(field: JPasswordField, errors: MutableList<ValidationInfo>): CharArray? {
val chars = field.getTrimmedChars()
if (chars == null) {
errors.add(ValidationInfo("Current master password is empty.", field))
}
return chars
}
protected open fun requestMasterPassword(title: String, topNote: String? = null, contextComponent: Component? = null, ok: (value: ByteArray) -> String?): Boolean {
val passwordField = JPasswordField()
val panel = panel {
topNote?.let {
noteRow(it)
}
row("Master password:") { passwordField().focused() }
}
return dialog(title = title, panel = panel, parent = contextComponent) {
val errors = SmartList<ValidationInfo>()
val value = checkIsEmpty(passwordField, errors)
if (errors.isEmpty()) {
val result = value!!.toByteArrayAndClear()
ok(result)?.let {
errors.add(ValidationInfo(it, passwordField))
}
if (!errors.isEmpty()) {
result.fill(0)
}
}
errors
}
.showAndGet()
}
fun saveMasterKeyToApplyNewEncryptionSpec() {
// if null, master key file doesn't exist now, it will be saved later somehow, no need to re-save with a new encryption spec
val existing = masterKeyFileStorage.load() ?: return
// no need to re-save db file because master password is not changed, only master key encryption spec changed
masterKeyFileStorage.save(createMasterKey(existing, isAutoGenerated = masterKeyFileStorage.isAutoGenerated()))
}
fun setCustomMasterPasswordIfNeeded(defaultDbFile: Path) {
// https://youtrack.jetbrains.com/issue/IDEA-174581#focus=streamItem-27-3081868-0-0
// for custom location require to set custom master password to make sure that user will be able to reuse file on another machine
if (file == defaultDbFile) {
return
}
if (!masterKeyFileStorage.isAutoGenerated()) {
return
}
askAndSetMasterKey(null, topNote = "Database in a custom location, therefore\ncustom master password is required.")
}
}
|
apache-2.0
|
6c024df984c8a71db83c1363a3c086fa
| 36.748988 | 173 | 0.699882 | 4.893963 | false | false | false | false |
AndroidX/androidx
|
compose/compiler/compiler-hosted/src/main/java/androidx/compose/compiler/plugins/kotlin/ComposeFqNames.kt
|
3
|
10612
|
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.compiler.plugins.kotlin
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.SourceElement
import org.jetbrains.kotlin.descriptors.annotations.Annotated
import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.descriptors.findClassAcrossModuleDependencies
import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor
import org.jetbrains.kotlin.ir.declarations.IrAnnotationContainer
import org.jetbrains.kotlin.ir.types.IrType
import org.jetbrains.kotlin.ir.util.hasAnnotation
import org.jetbrains.kotlin.name.CallableId
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.constants.ConstantValue
import org.jetbrains.kotlin.resolve.descriptorUtil.annotationClass
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils.NO_EXPECTED_TYPE
import org.jetbrains.kotlin.types.TypeUtils.UNIT_EXPECTED_TYPE
import org.jetbrains.kotlin.types.typeUtil.replaceAnnotations
private const val root = "androidx.compose.runtime"
private const val internalRoot = "$root.internal"
private val rootFqName = FqName(root)
private val internalRootFqName = FqName(internalRoot)
object ComposeClassIds {
private fun classIdFor(cname: String) =
ClassId(rootFqName, Name.identifier(cname))
internal fun internalClassIdFor(cname: String) =
ClassId(internalRootFqName, Name.identifier(cname))
val Composable = classIdFor("Composable")
val ComposableInferredTarget = classIdFor("ComposableInferredTarget")
val ComposableLambda = internalClassIdFor("ComposableLambda")
val ComposableOpenTarget = classIdFor("ComposableOpenTarget")
val ComposableTarget = classIdFor("ComposableTarget")
val ComposeVersion = classIdFor("ComposeVersion")
val Composer = classIdFor("Composer")
val FunctionKeyMetaClass = internalClassIdFor("FunctionKeyMetaClass")
val FunctionKeyMeta = internalClassIdFor("FunctionKeyMeta")
val LiveLiteralFileInfo = internalClassIdFor("LiveLiteralFileInfo")
val LiveLiteralInfo = internalClassIdFor("LiveLiteralInfo")
val NoLiveLiterals = classIdFor("NoLiveLiterals")
val State = classIdFor("State")
val StabilityInferred = internalClassIdFor("StabilityInferred")
}
object ComposeCallableIds {
private fun topLevelCallableId(name: String) =
CallableId(rootFqName, Name.identifier(name))
internal fun internalTopLevelCallableId(name: String) =
CallableId(internalRootFqName, Name.identifier(name))
val cache = topLevelCallableId("cache")
val composableLambda = internalTopLevelCallableId("composableLambda")
val composableLambdaInstance =
internalTopLevelCallableId("composableLambdaInstance")
val composableLambdaN = internalTopLevelCallableId("composableLambdaN")
val composableLambdaNInstance =
internalTopLevelCallableId("composableLambdaNInstance")
val currentComposer = topLevelCallableId("currentComposer")
val isLiveLiteralsEnabled =
internalTopLevelCallableId("isLiveLiteralsEnabled")
val isTraceInProgress =
topLevelCallableId(KtxNameConventions.IS_TRACE_IN_PROGRESS)
val liveLiteral = internalTopLevelCallableId("liveLiteral")
val remember = topLevelCallableId("remember")
val sourceInformation =
topLevelCallableId(KtxNameConventions.SOURCEINFORMATION)
val sourceInformationMarkerEnd =
topLevelCallableId(KtxNameConventions.SOURCEINFORMATIONMARKEREND)
val sourceInformationMarkerStart =
topLevelCallableId(KtxNameConventions.SOURCEINFORMATIONMARKERSTART)
val traceEventEnd = topLevelCallableId(KtxNameConventions.TRACE_EVENT_END)
val traceEventStart = topLevelCallableId(KtxNameConventions.TRACE_EVENT_START)
val updateChangedFlags = topLevelCallableId(KtxNameConventions.UPDATE_CHANGED_FLAGS)
}
object ComposeFqNames {
internal fun fqNameFor(cname: String) = FqName("$root.$cname")
private fun internalFqNameFor(cname: String) = FqName("$internalRoot.$cname")
private fun composablesFqNameFor(cname: String) = fqNameFor("ComposablesKt.$cname")
val Composable = ComposeClassIds.Composable.asSingleFqName()
val ComposableTarget = ComposeClassIds.ComposableTarget.asSingleFqName()
val ComposableTargetMarker = fqNameFor("ComposableTargetMarker")
val ComposableTargetMarkerDescription = "description"
val ComposableTargetApplierArgument = Name.identifier("applier")
val ComposableOpenTarget = ComposeClassIds.ComposableOpenTarget.asSingleFqName()
val ComposableOpenTargetIndexArgument = Name.identifier("index")
val ComposableInferredTarget = ComposeClassIds.ComposableInferredTarget.asSingleFqName()
val ComposableInferredTargetSchemeArgument = Name.identifier("scheme")
val CurrentComposerIntrinsic = fqNameFor("<get-currentComposer>")
val getCurrentComposerFullName = composablesFqNameFor("<get-currentComposer>")
val DisallowComposableCalls = fqNameFor("DisallowComposableCalls")
val ReadOnlyComposable = fqNameFor("ReadOnlyComposable")
val ExplicitGroupsComposable = fqNameFor("ExplicitGroupsComposable")
val NonRestartableComposable = fqNameFor("NonRestartableComposable")
val composableLambdaType = ComposeClassIds.ComposableLambda.asSingleFqName()
val composableLambda = ComposeCallableIds.composableLambda.asSingleFqName()
val composableLambdaFullName =
internalFqNameFor("ComposableLambdaKt.composableLambda")
val remember = ComposeCallableIds.remember.asSingleFqName()
val cache = ComposeCallableIds.cache.asSingleFqName()
val key = fqNameFor("key")
val StableMarker = fqNameFor("StableMarker")
val Stable = fqNameFor("Stable")
val Composer = ComposeClassIds.Composer.asSingleFqName()
val ComposeVersion = fqNameFor("ComposeVersion")
val Package = FqName(root)
val StabilityInferred = ComposeClassIds.StabilityInferred.asSingleFqName()
fun makeComposableAnnotation(module: ModuleDescriptor): AnnotationDescriptor =
object : AnnotationDescriptor {
override val type: KotlinType
get() = module.findClassAcrossModuleDependencies(
ClassId.topLevel(Composable)
)!!.defaultType
override val allValueArguments: Map<Name, ConstantValue<*>> get() = emptyMap()
override val source: SourceElement get() = SourceElement.NO_SOURCE
override fun toString() = "[@Composable]"
}
}
private fun makeComposableAnnotation(module: ModuleDescriptor): AnnotationDescriptor =
object : AnnotationDescriptor {
override val type: KotlinType
get() = module.findClassAcrossModuleDependencies(
ComposeClassIds.Composable
)!!.defaultType
override val allValueArguments: Map<Name, ConstantValue<*>> get() = emptyMap()
override val source: SourceElement get() = SourceElement.NO_SOURCE
override fun toString() = "[@Composable]"
}
fun KotlinType.makeComposable(module: ModuleDescriptor): KotlinType {
if (hasComposableAnnotation()) return this
val annotation = makeComposableAnnotation(module)
return replaceAnnotations(Annotations.create(annotations + annotation))
}
fun AnonymousFunctionDescriptor.annotateAsComposable(module: ModuleDescriptor) =
AnonymousFunctionDescriptor(
containingDeclaration,
Annotations.create(annotations + makeComposableAnnotation(module)),
kind,
source,
isSuspend
)
fun IrType.hasComposableAnnotation(): Boolean =
hasAnnotation(ComposeFqNames.Composable)
fun IrAnnotationContainer.hasComposableAnnotation(): Boolean =
hasAnnotation(ComposeFqNames.Composable)
fun KotlinType.hasComposableAnnotation(): Boolean =
!isSpecialType && annotations.findAnnotation(ComposeFqNames.Composable) != null
fun Annotated.hasComposableAnnotation(): Boolean =
annotations.findAnnotation(ComposeFqNames.Composable) != null
fun Annotated.hasNonRestartableComposableAnnotation(): Boolean =
annotations.findAnnotation(ComposeFqNames.NonRestartableComposable) != null
fun Annotated.hasReadonlyComposableAnnotation(): Boolean =
annotations.findAnnotation(ComposeFqNames.ReadOnlyComposable) != null
fun Annotated.hasExplicitGroupsAnnotation(): Boolean =
annotations.findAnnotation(ComposeFqNames.ExplicitGroupsComposable) != null
fun Annotated.hasDisallowComposableCallsAnnotation(): Boolean =
annotations.findAnnotation(ComposeFqNames.DisallowComposableCalls) != null
fun Annotated.compositionTarget(): String? =
annotations.map { it.compositionTarget() }.firstOrNull { it != null }
fun Annotated.hasCompositionTargetMarker(): Boolean =
annotations.findAnnotation(
ComposeFqNames.ComposableTargetMarker
) != null
fun AnnotationDescriptor.compositionTarget(): String? =
if (fqName == ComposeFqNames.ComposableTarget)
allValueArguments[ComposeFqNames.ComposableTargetApplierArgument]?.value as? String
else if (annotationClass?.hasCompositionTargetMarker() == true) this.fqName.toString() else null
fun Annotated.compositionScheme(): String? =
annotations.findAnnotation(
ComposeFqNames.ComposableInferredTarget
)?.allValueArguments?.let {
it[ComposeFqNames.ComposableInferredTargetSchemeArgument]?.value as? String
}
fun Annotated.compositionOpenTarget(): Int? =
annotations.findAnnotation(
ComposeFqNames.ComposableOpenTarget
)?.allValueArguments?.let {
it[ComposeFqNames.ComposableOpenTargetIndexArgument]?.value as Int
}
internal val KotlinType.isSpecialType: Boolean get() =
this === NO_EXPECTED_TYPE || this === UNIT_EXPECTED_TYPE
val AnnotationDescriptor.isComposableAnnotation: Boolean get() = fqName == ComposeFqNames.Composable
|
apache-2.0
|
aab521ca09fbd157130ba458cc169abb
| 47.678899 | 100 | 0.778741 | 5.151456 | false | false | false | false |
vimeo/vimeo-networking-java
|
models/src/main/java/com/vimeo/networking2/UserSegmentSurveyList.kt
|
1
|
525
|
package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import com.vimeo.networking2.common.Page
/**
* A list of [UserSegmentSurveys][UserSegmentSurvey].
*/
@JsonClass(generateAdapter = true)
data class UserSegmentSurveyList(
@Json(name = "total")
override val total: Int? = null,
@Json(name = "data")
override val data: List<UserSegmentSurvey>? = null,
@Json(name = "filtered_total")
override val filteredTotal: Int? = null
) : Page<UserSegmentSurvey>
|
mit
|
811857afc8b7614ed18f5f90264da077
| 24 | 55 | 0.721905 | 3.571429 | false | false | false | false |
AndroidX/androidx
|
camera/camera-camera2-pipe-integration/src/test/java/androidx/camera/camera2/pipe/integration/impl/EvCompControlTest.kt
|
3
|
5702
|
/*
* 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.camera2.pipe.integration.impl
import android.hardware.camera2.CameraCharacteristics
import android.os.Build
import android.util.Range
import android.util.Rational
import androidx.camera.camera2.pipe.integration.adapter.RobolectricCameraPipeTestRunner
import androidx.camera.camera2.pipe.integration.compat.EvCompImpl
import androidx.camera.camera2.pipe.integration.testing.FakeCameraProperties
import androidx.camera.camera2.pipe.integration.testing.FakeUseCaseCamera
import androidx.camera.camera2.pipe.testing.FakeCameraMetadata
import androidx.camera.core.CameraControl
import androidx.testutils.assertThrows
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Job
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeout
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.annotation.Config
import org.robolectric.annotation.internal.DoNotInstrument
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
@RunWith(RobolectricCameraPipeTestRunner::class)
@DoNotInstrument
@Config(minSdk = Build.VERSION_CODES.LOLLIPOP)
class EvCompControlTest {
private val fakeUseCaseThreads by lazy {
val executor = Executors.newSingleThreadExecutor()
val dispatcher = executor.asCoroutineDispatcher()
val cameraScope = CoroutineScope(Job() + dispatcher)
UseCaseThreads(
cameraScope,
executor,
dispatcher,
)
}
private val metadata = FakeCameraMetadata(
mapOf(
CameraCharacteristics.CONTROL_AE_COMPENSATION_RANGE to Range.create(-4, 4),
CameraCharacteristics.CONTROL_AE_COMPENSATION_STEP to Rational.parseRational("1/2"),
),
)
private val comboRequestListener = ComboRequestListener()
private lateinit var exposureControl: EvCompControl
@Before
fun setUp() {
exposureControl = EvCompControl(
EvCompImpl(
FakeCameraProperties(metadata),
fakeUseCaseThreads,
comboRequestListener
)
)
exposureControl.useCaseCamera = FakeUseCaseCamera()
}
@Test
fun setExposureTwice_theFirstCallShouldBeCancelled(): Unit = runBlocking {
val deferred: Deferred<Int> = exposureControl.updateAsync(1)
val deferred1: Deferred<Int> = exposureControl.updateAsync(2)
// Assert. The second call should keep working.
assertThat(deferred1.isCompleted).isFalse()
// Assert. The first call should be cancelled with a CameraControl.OperationCanceledException.
assertThrows<CameraControl.OperationCanceledException> {
deferred.awaitWithTimeout()
}
}
@Test
fun setExposureCancelled_theCompensationValueShouldKeepInControl() = runBlocking {
// Arrange.
val deferred = exposureControl.updateAsync(1)
// Act.
deferred.cancel()
// Assert. The new value should be set to the exposure control even when the task fails.
assertThat(exposureControl.exposureState.exposureCompensationIndex).isEqualTo(1)
}
@Test
fun exposureControlInactive_setExposureTaskShouldCancel(): Unit = runBlocking {
val deferred = exposureControl.updateAsync(1)
// Act. Simulate control inactive by set useCaseCamera to null & call reset().
exposureControl.useCaseCamera = null
exposureControl.reset()
// Assert. The exposure control has been set to inactive. It should throw an exception.
assertThrows<CameraControl.OperationCanceledException> {
deferred.awaitWithTimeout()
}
}
@Test
fun setExposureNotInRange_shouldCompleteTheTaskWithException(): Unit = runBlocking {
// Assert. The Exposure index 5 is not in the valid range. It should throw an exception.
assertThrows<IllegalArgumentException> {
exposureControl.updateAsync(5).awaitWithTimeout()
}
}
@Test
fun setExposureOnNotSupportedCamera_shouldCompleteTheTaskWithException(): Unit = runBlocking {
// Arrange.
val evCompCompat = EvCompImpl(
// Fake CameraProperties without CONTROL_AE_COMPENSATION related properties.
FakeCameraProperties(),
fakeUseCaseThreads,
comboRequestListener
)
exposureControl = EvCompControl(evCompCompat)
exposureControl.useCaseCamera = FakeUseCaseCamera()
// Act.
val deferred = exposureControl.updateAsync(1)
// Assert. This camera does not support the exposure compensation, the task should fail.
assertThrows<IllegalArgumentException> {
deferred.awaitWithTimeout()
}
}
private suspend fun Deferred<Int>.awaitWithTimeout(
timeMillis: Long = TimeUnit.SECONDS.toMillis(5)
) = withTimeout(timeMillis) {
await()
}
}
|
apache-2.0
|
620d994d78cf1d1d580b7b988edacf7f
| 36.032468 | 102 | 0.719923 | 4.919758 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.