repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 53
values | size
stringlengths 2
6
| content
stringlengths 73
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
977
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bsmr-java/lwjgl3
|
modules/templates/src/main/kotlin/org/lwjgl/opengl/templates/NV_float_buffer.kt
|
1
|
2746
|
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.opengl.templates
import org.lwjgl.generator.*
import org.lwjgl.opengl.*
val NV_float_buffer = "NVFloatBuffer".nativeClassGL("NV_float_buffer", postfix = NV) {
documentation =
"""
Native bindings to the $registryLink extension.
This extension builds upon NV_fragment_program to provide a framebuffer and texture format that allows fragment programs to read and write
unconstrained floating point data.
"""
IntConstant(
"Accepted by the {@code internalformat} parameter of TexImage2D and CopyTexImage2D.",
"FLOAT_R_NV"..0x8880,
"FLOAT_RG_NV"..0x8881,
"FLOAT_RGB_NV"..0x8882,
"FLOAT_RGBA_NV"..0x8883,
"FLOAT_R16_NV"..0x8884,
"FLOAT_R32_NV"..0x8885,
"FLOAT_RG16_NV"..0x8886,
"FLOAT_RG32_NV"..0x8887,
"FLOAT_RGB16_NV"..0x8888,
"FLOAT_RGB32_NV"..0x8889,
"FLOAT_RGBA16_NV"..0x888A,
"FLOAT_RGBA32_NV"..0x888B
)
IntConstant(
"Accepted by the {@code pname} parameter of GetTexLevelParameterfv and GetTexLevelParameteriv.",
"TEXTURE_FLOAT_COMPONENTS_NV"..0x888C
)
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetDoublev.",
"FLOAT_CLEAR_COLOR_VALUE_NV"..0x888D,
"FLOAT_RGBA_MODE_NV"..0x888E
)
}
val WGL_NV_float_buffer = "WGLNVFloatBuffer".nativeClassWGL("WGL_NV_float_buffer", postfix = NV) {
documentation =
"""
Native bindings to the $registryLink extension.
WGL functionality for ${NV_float_buffer.link}.
"""
IntConstant(
"""
Accepted in the {@code piAttributes} array of wglGetPixelFormatAttribivARB and wglGetPixelFormatAttribfvARB and in the {@code piAttribIList} and
{@code pfAttribFList} arrays of wglChoosePixelFormatARB.
""",
"FLOAT_COMPONENTS_NV"..0x20B0,
"BIND_TO_TEXTURE_RECTANGLE_FLOAT_R_NV"..0x20B1,
"BIND_TO_TEXTURE_RECTANGLE_FLOAT_RG_NV"..0x20B2,
"BIND_TO_TEXTURE_RECTANGLE_FLOAT_RGB_NV"..0x20B3,
"BIND_TO_TEXTURE_RECTANGLE_FLOAT_RGBA_NV"..0x20B4
)
IntConstant(
"""
Accepted in the {@code piAttribIList} array of wglCreatePbufferARB and returned in the {@code value} parameter of wglQueryPbufferARB when
{@code iAttribute} is TEXTURE_FORMAT_ARB.
""",
"TEXTURE_FLOAT_R_NV"..0x20B5,
"TEXTURE_FLOAT_RG_NV"..0x20B6,
"TEXTURE_FLOAT_RGB_NV"..0x20B7,
"TEXTURE_FLOAT_RGBA_NV"..0x20B8
)
}
val GLX_NV_float_buffer = "GLXNVFloatBuffer".nativeClassGLX("GLX_NV_float_buffer", postfix = NV) {
documentation =
"""
Native bindings to the $registryLink extension.
GLX functionality for ${NV_float_buffer.link}.
"""
IntConstant(
"Accepted in the {@code value} array of glXGetFBConfigAttrib (and glXGetFBConfigAttribSGIX).",
"FLOAT_COMPONENTS_NV"..0x20B0
)
}
|
bsd-3-clause
|
b7a7746621d48a1bfcc7f0df62b23faa
| 27.319588 | 146 | 0.721413 | 3.034254 | false | false | false | false |
andstatus/andstatus
|
app/src/androidTest/kotlin/org/andstatus/app/note/NoteViewItemTest.kt
|
1
|
4847
|
/*
* Copyright (c) 2016 yvolk (Yuri Volkov), http://yurivolkov.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.andstatus.app.note
import org.andstatus.app.context.TestSuite
import org.andstatus.app.origin.Origin
import org.andstatus.app.timeline.DuplicationLink
import org.andstatus.app.timeline.meta.Timeline
import org.andstatus.app.util.MyHtml
import org.andstatus.app.util.RelativeTime
import org.junit.Assert
import org.junit.Before
import org.junit.Test
/**
* @author [email protected]
*/
class NoteViewItemTest {
@Before
fun setUp() {
TestSuite.initialize(this)
}
@Test
fun testDuplicationLink() {
val item1 = NoteViewItem(false, RelativeTime.DATETIME_MILLIS_NEVER)
setContent(item1, HTML_BODY)
val item2 = NoteViewItem(false, RelativeTime.DATETIME_MILLIS_NEVER)
setContent(item2, "Some other text")
assertDuplicates(item1, DuplicationLink.DUPLICATES, item2)
item2.setNoteId(2)
assertDuplicates(item1, DuplicationLink.NONE, item2)
setContent(item2, "@<a href=\"https://bsdnode.xyz/actor/2\" class=\"h-card mention\">username</a> On duplicated posts, sent by AndStatus, please read <a href=\"https://github.com/andstatus/andstatus/issues/83\" title=\"https://github.com/andstatus/andstatus/issues/83\" class=\"attachment\" rel=\"nofollow\">https://github.com/andstatus/andstatus/issues/83</a><br /> Sorry if I misunderstood your post :-)")
assertDuplicates(item1, DuplicationLink.DUPLICATES, item2)
setContent(item1, ""Interactions" timeline in Twidere is the same or close to existing "Mentions" timeline in AndStatus")
setContent(item2, "\"Interactions\" timeline in Twidere is the same or close to existing \"Mentions\" timeline in AndStatus")
assertDuplicates(item1, DuplicationLink.DUPLICATES, item2)
val content5 = "What is good about Android is that I can use Quitter.se via AndStatus."
setContent(item1, content5)
val content6 = "What is good about Android is that I can use <a href=\"https://quitter.se/\" title=\"https://quitter.se/\" class=\"attachment\" id=\"attachment-1205381\" rel=\"nofollow external\">Quitter.se</a> via AndStatus."
setContent(item2, content6)
assertDuplicates(item1, DuplicationLink.DUPLICATES, item2)
assertDuplicates(item2, DuplicationLink.DUPLICATES, item1)
val item3 = NoteViewItem(false, 1468509659000L)
setContent(item3, content5)
val item4 = NoteViewItem(false, 1468509658000L)
setContent(item4, content6)
item4.setNoteId(item2.getNoteId())
assertDuplicates(item3, DuplicationLink.DUPLICATES, item4)
assertDuplicates(item4, DuplicationLink.IS_DUPLICATED, item3)
val item5 = NoteViewItem(false, item3.updatedDate)
setContent(item5, content6)
item5.setNoteId(item4.getNoteId())
item5.favorited = true
assertDuplicates(item3, DuplicationLink.DUPLICATES, item5)
assertDuplicates(item5, DuplicationLink.IS_DUPLICATED, item3)
item3.reblogged = true
assertDuplicates(item3, DuplicationLink.DUPLICATES, item5)
assertDuplicates(item5, DuplicationLink.IS_DUPLICATED, item3)
item5.favorited = false
assertDuplicates(item5, DuplicationLink.DUPLICATES, item3)
assertDuplicates(item3, DuplicationLink.IS_DUPLICATED, item5)
}
private fun assertDuplicates(item1: NoteViewItem, duplicates: DuplicationLink, item2: NoteViewItem) {
Assert.assertEquals("$item1 vs $item2", duplicates, item1.duplicates(Timeline.EMPTY, Origin.EMPTY, item2))
}
companion object {
private val HTML_BODY: String = """@<a href="https://bsdnode.xyz/user/2" class="h-card mention">username</a> On duplicated posts, sent by AndStatus, please read <a href="https://github.com/andstatus/andstatus/issues/83" title="https://github.com/andstatus/andstatus/issues/83" class="attachment" id="attachment-15180" rel="nofollow external">https://github.com/andstatus/andstatus/issues/83</a><br />
Sorry if I misunderstood your post :-)"""
private fun setContent(item: NoteViewItem, content: String) {
item.setContent(content)
item.contentToSearch = MyHtml.getContentToSearch(content)
}
}
}
|
apache-2.0
|
4087a37ef74c534490adb729c956c9d0
| 51.684783 | 415 | 0.718589 | 4.125106 | false | true | false | false |
ImXico/punk
|
camera/src/main/kotlin/cyberpunk/camera/CameraStyles.kt
|
2
|
3185
|
@file:JvmName("CameraStyles")
package cyberpunk.camera
import com.badlogic.gdx.graphics.Camera
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.math.Vector3
/**
* Centers the [Camera] in the middle of the screen, fiven the world coordinates.
* @param worldWidth width of the world (world coordinates).
* @param worldHeight height of the world (world coordinates).
*/
fun Camera.center(worldWidth: Int, worldHeight: Int) {
val newPosition = Vector3(worldWidth / 2f, worldHeight / 2f, 0f)
this.refresh(newPosition)
}
/**
* The [Camera] will follow the target coordinates rigidly.
* Not suitable for all cases, as it may cause a very rough motion.
* @param targetPosition position of the target, where the camera will be also positioned to.
*/
fun Camera.lockOn(targetPosition: Vector2) {
val newPosition = Vector3(targetPosition.x, targetPosition.y, 0f)
this.refresh(newPosition)
}
/**
* The [Camera] will rigidly follow the [targetPosition] horizontally, but will be
* offset vertically by a [yOffset].
* @param targetPosition position of the target, where the camera will be also positioned to (horizontally).
* @param yOffset camera's Y offset, relatively to the [targetPosition] Y.
*/
fun Camera.lockOnX(targetPosition: Vector2, yOffset: Float) {
val newPosition = Vector3(targetPosition.x, targetPosition.y + yOffset, 0f)
this.refresh(newPosition)
}
/**
* The [Camera] will rigidly follow the [targetPosition] vertically, but will be
* offset horizontally by a [xOffset].
* @param targetPosition position of the target, where the camera will be also positioned to (horizontally).
* @param xOffset camera's X offset, relatively to the [targetPosition] X.
*/
fun Camera.lockOnY(targetPosition: Vector2, xOffset: Float) {
val newPosition = Vector3(targetPosition.x + xOffset, targetPosition.y, 0f)
this.refresh(newPosition)
}
/**
* The [Camera] will follow a [targetPosition] with a smooth linear interpolation, based on a [lerp] amount.
* The lower that interpolation amount, the smoother - and thus slower - the following motion.
* The camera can also be offset by an [xOffset] and [yOffset] amounts, but that's optional.
* @param targetPosition position of the target that the camera will be set on.
* @param lerp defines how smoothly the camera follows; ]0 (slowest), 1 (fastest)].
* @param xOffset camera's X offset, relatively to the [targetPosition] X.
* @param yOffset camera's Y offset, relatively to the [targetPosition] Y.
*/
@JvmOverloads
fun Camera.lerpTo(targetPosition: Vector2, lerp: Float, xOffset: Float = 0f, yOffset: Float = 0f) {
val newX = this.position.x + ((targetPosition.x - position.x) * lerp) + xOffset
val newY = this.position.y + ((targetPosition.y - position.y) * lerp) + yOffset
val newPosition = Vector3(newX, newY, 0f)
this.refresh(newPosition)
}
/**
* Sets the [Camera] position to the given one and updates it.
* Won't be called explicitly anywhere besides this class.
* @param newPosition new [Vector3] position for the camera.
*/
private fun Camera.refresh(newPosition: Vector3) {
this.apply {
position.set(newPosition)
update()
}
}
|
mit
|
3879a4a97d5a5cec7c2639c18e5c481c
| 39.846154 | 108 | 0.733438 | 3.837349 | false | false | false | false |
InfiniteSoul/ProxerAndroid
|
src/main/kotlin/me/proxer/app/ui/view/bbcode/prototype/OrderedListPrototype.kt
|
1
|
2008
|
package me.proxer.app.ui.view.bbcode.prototype
import android.view.Gravity.CENTER
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.widget.LinearLayout
import android.widget.LinearLayout.HORIZONTAL
import android.widget.LinearLayout.VERTICAL
import me.proxer.app.ui.view.bbcode.BBArgs
import me.proxer.app.ui.view.bbcode.BBCodeView
import me.proxer.app.ui.view.bbcode.BBTree
import me.proxer.app.util.extension.dip
/**
* @author Ruben Gees
*/
object OrderedListPrototype : AutoClosingPrototype {
override val startRegex = Regex(" *ol( .*?)?", BBPrototype.REGEX_OPTIONS)
override val endRegex = Regex("/ *ol *", BBPrototype.REGEX_OPTIONS)
override fun makeViews(parent: BBCodeView, children: List<BBTree>, args: BBArgs): List<View> {
val childViews = children.filter { it.prototype == ListItemPrototype }.flatMap { it.makeViews(parent, args) }
return listOf(LinearLayout(parent.context).apply {
val eightDip = dip(8)
layoutParams = ViewGroup.MarginLayoutParams(MATCH_PARENT, WRAP_CONTENT)
orientation = VERTICAL
@Suppress("ExplicitItLambdaParameter") // TODO: False positive. Remove once fixed.
childViews.forEachIndexed { index, it ->
addView(LinearLayout(parent.context).apply {
layoutParams = ViewGroup.MarginLayoutParams(MATCH_PARENT, WRAP_CONTENT)
orientation = HORIZONTAL
addView(TextPrototype.makeView(parent, args + BBArgs(text = "${index + 1}.")).apply {
layoutParams = LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT).apply {
setMargins(0, 0, eightDip, 0)
gravity = CENTER
}
})
addView(it)
})
}
})
}
}
|
gpl-3.0
|
daaee5d9eb15a34d0e9b3f0a0dbbd7a3
| 37.615385 | 117 | 0.64741 | 4.648148 | false | false | false | false |
Etik-Tak/backend
|
src/main/kotlin/dk/etiktak/backend/service/company/StoreService.kt
|
1
|
6484
|
// Copyright (c) 2017, Daniel Andersen ([email protected])
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package dk.etiktak.backend.service.company
import dk.etiktak.backend.model.company.Company
import dk.etiktak.backend.model.company.Store
import dk.etiktak.backend.model.contribution.*
import dk.etiktak.backend.model.user.Client
import dk.etiktak.backend.repository.company.StoreRepository
import dk.etiktak.backend.service.security.ClientVerified
import dk.etiktak.backend.service.trust.ContributionService
import dk.etiktak.backend.util.CryptoUtil
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
@Service
@Transactional
open class StoreService @Autowired constructor(
private val storeRepository: StoreRepository,
private val contributionService: ContributionService) {
private val logger = LoggerFactory.getLogger(StoreService::class.java)
/**
* Finds a store from the given UUID.
*
* @param uuid UUID
* @return Store with given UUID
*/
open fun getStoreByUuid(uuid: String): Store? {
return storeRepository.findByUuid(uuid)
}
/**
* Creates a new store.
*
* @param inClient Client
* @param name Name of store
* @param modifyValues Function called with modified client
* @return Created store
*/
@ClientVerified
open fun createStore(inClient: Client, name: String, modifyValues: (Client) -> Unit = {}): Store {
var client = inClient
// Create store
var store = Store()
store.uuid = CryptoUtil().uuid()
store = storeRepository.save(store)
// Create name contribution
editStoreName(client, store, name, modifyValues = {modifiedClient, modifiedStore -> client = modifiedClient; store = modifiedStore})
modifyValues(client)
return store
}
/**
* Edits a store name.
*
* @param inClient Client
* @param inStore Store
* @param name Name of store
* @param modifyValues Function called with modified client and store
* @return Store name contribution
*/
@ClientVerified
open fun editStoreName(inClient: Client, inStore: Store, name: String, modifyValues: (Client, Store) -> Unit = {client, store -> Unit}): Contribution {
var client = inClient
var store = inStore
// Create contribution
val contribution = contributionService.createTextContribution(Contribution.ContributionType.EditStoreName, client, store.uuid, name, modifyValues = { modifiedClient -> client = modifiedClient})
// Edit name
store.name = name
store = storeRepository.save(store)
modifyValues(client, store)
return contribution
}
/**
* Assigns a company to a store.
*
* @param client Client
* @param store Store
* @param company Company
* @param modifyValues Function called with modified client
* @return Product company contribution
*/
@ClientVerified
open fun assignCompanyToStore(client: Client, store: Store, company: Company, modifyValues: (Client) -> Unit = {}): Contribution {
return contributionService.createReferenceContribution(Contribution.ContributionType.AssignCompanyToStore, client, store.uuid, company.uuid, modifyValues = modifyValues)
}
/**
* Returns the store name contribution which is currently active.
*
* @param store Store
* @return Store name contribution
*/
open fun storeNameContribution(store: Store): TextContribution? {
return contributionService.currentTextContribution(Contribution.ContributionType.EditStoreName, store.uuid)
}
/**
* Returns whether the given client can edit the name of the store.
*
* @param client Client
* @param store Store
* @return Yes,if the given client can edit the name of the store, or else false
*/
open fun canEditStoreName(client: Client, store: Store): Boolean {
return client.verified && contributionService.hasSufficientTrustToEditContribution(client, storeNameContribution(store))
}
/**
* Trust votes store name.
*
* @param client Client
* @param store Store
* @param vote Vote
* @param modifyValues Function called with modified client
* @return Trust vote
*/
open fun trustVoteStoreName(client: Client, store: Store, vote: TrustVote.TrustVoteType, modifyValues: (Client) -> Unit = {}): TrustVote {
val contribution = storeNameContribution(store)!!
return contributionService.trustVoteItem(client, contribution, vote, modifyValues = {client, contribution -> modifyValues(client)})
}
}
|
bsd-3-clause
|
1139e738c2a7c5077099b78d93572541
| 39.279503 | 201 | 0.691857 | 4.897281 | false | false | false | false |
inorichi/tachiyomi-extensions
|
src/en/dynasty/src/eu/kanade/tachiyomi/extension/en/dynasty/DynastyAnthologies.kt
|
1
|
992
|
package eu.kanade.tachiyomi.extension.en.dynasty
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.SManga
import okhttp3.Request
import org.jsoup.nodes.Document
class DynastyAnthologies : DynastyScans() {
override val name = "Dynasty-Anthologies"
override val searchPrefix = "anthologies"
override fun popularMangaInitialUrl() = "$baseUrl/anthologies?view=cover"
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
return GET("$baseUrl/search?q=$query&classes%5B%5D=Anthology&sort=&page=$page", headers)
}
override fun mangaDetailsParse(document: Document): SManga {
val manga = SManga.create()
manga.thumbnail_url = baseUrl + document.select("div.span2 > img").attr("src")
parseHeader(document, manga)
parseGenres(document, manga)
parseDescription(document, manga)
return manga
}
}
|
apache-2.0
|
14a8f0e5eb759e3c205e5827b7f8c360
| 33.206897 | 96 | 0.725806 | 4.04898 | false | false | false | false |
hpedrorodrigues/GZMD
|
app/src/main/kotlin/com/hpedrorodrigues/gzmd/crawler/PreviewCrawler.kt
|
1
|
3139
|
/*
* Copyright 2016 Pedro Rodrigues
*
* 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.hpedrorodrigues.gzmd.crawler
import com.hpedrorodrigues.gzmd.entity.Preview
import org.jsoup.select.Elements
import java.util.*
object PreviewCrawler : AbstractCrawler() {
fun findByPage(baseUrl: String, page: Int): List<Preview> {
var count = 0
return extractElements(baseUrl, page)
.map { element ->
count++
extractPreview(element, count)
}
}
private fun extractElements(baseUrl: String, page: Int): List<Elements> {
val document = JsoupManager.document(baseUrl.replace("%s", page.toString()))
var count = 1
var elements = document.select("#maincontent #loop-chamadas div:nth-child($count)")
val allElements = ArrayList<Elements>()
while (!document.select("#maincontent #loop-chamadas div:nth-child(${count})").html().trim().isEmpty()) {
allElements.add(elements)
count += 1
elements = document.select("#maincontent #loop-chamadas div:nth-child($count)")
}
return allElements
.filter { element -> element.attr("id").startsWith("post-") && element.hasClass("post") }
}
private fun extractPreview(elements: Elements, count: Int): Preview {
val preview = Preview()
preview.title = elements.select(".title-1000 > a").attr("title").trim()
preview.shortBody = elements.select(".chamada-contents .chamada-intro > a").text().trim()
preview.info = elements.select(".chamada-contents .chamada-intro .autor").text().trim()
val imageElem = imageElement(elements, count)
if (imageElem != null) {
preview.imageUrl = imageElem.attr("src").trim()
}
preview.postUrl = elements.select(".title-1000 > a").attr("href").trim()
preview.tagName = elements.select(".chamada-thumb .chamada-cat > a").text().trim()
preview.tagUrl = elements.select(".chamada-thumb .chamada-cat > a").attr("href").trim()
preview.authorName = elements
.select(".chamada-contents .chamada-intro .autor .por > a").text().trim()
preview.postedAt = postedAt(preview.info, preview.authorName)
preview.authorProfileUrl = elements
.select(".chamada-contents .chamada-intro .autor .por > a").attr("href").trim()
preview.commentsCount = commentsCount(elements)
preview.sharesCount = sharesCount(elements)
preview.crawledAt = Date().time
return preview
}
}
|
apache-2.0
|
335a0ccc9d772b6a3eb5e3776abeee01
| 34.681818 | 113 | 0.642243 | 4.365786 | false | false | false | false |
ZieIony/Carbon
|
samples/src/main/java/tk/zielony/carbonsamples/demo/MusicPlayerActivity.kt
|
1
|
1722
|
package tk.zielony.carbonsamples.demo
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import carbon.recycler.RowFactory
import carbon.recycler.RowListAdapter
import kotlinx.android.synthetic.main.activity_musicplayer.*
import tk.zielony.carbonsamples.R
import tk.zielony.carbonsamples.SampleAnnotation
import tk.zielony.carbonsamples.ThemedActivity
import java.io.Serializable
@SampleAnnotation(
layoutId = R.layout.activity_musicplayer,
titleId = R.string.musicPlayerActivity_title,
iconId = R.drawable.ic_play_arrow_black_24dp
)
class MusicPlayerActivity : ThemedActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initToolbar()
val songs = arrayListOf(
SongItem(1, "Code Around the Clock", 213),
SongItem(2, "Compile Yourself", 225),
SongItem(3, "Androidic Dreaming", 167),
SongItem(4, "Carbonite Tonight", 192),
SongItem(5, "Getting Away With Errors", 214),
SongItem(6, "Nine Million XMLs", 202),
SongItem(7, "Last Commit in the Repo", 276),
SongItem(8, "Don't Fix Me Down", 234)
)
recycler.layoutManager = LinearLayoutManager(this)
recycler.adapter = RowListAdapter(songs, RowFactory { SongRow(it) })
}
override fun applyTheme() {
super.applyTheme()
theme.applyStyle(R.style.Translucent, true)
}
}
class SongItem(val id: Int, val name: String, val duration: Int) : Serializable {
fun getDurationString(): String {
return String.format("%d:%02d", duration / 60, duration % 60)
}
}
|
apache-2.0
|
1181dde0b9772a569cf2496aad4d94cc
| 33.46 | 81 | 0.66899 | 4.381679 | false | false | false | false |
neworld/random-decision
|
desktop/src/main/java/lt/neworld/randomdecision2/AppProperties.kt
|
1
|
943
|
package lt.neworld.randomdecision2
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.util.*
/**
* @author neworld
* @since 09/04/16
*/
object AppProperties {
private const val PROP_CATEGORIES_DIR = "categories_dir"
private val file = File(".properties")
private val properties by lazy {
Properties().apply {
if (!file.exists()) {
file.createNewFile()
}
val fin = FileInputStream(file)
load(fin)
fin.close()
}
}
private fun save() {
val fout = FileOutputStream(file)
properties.store(fout, "")
fout.close()
}
var categoriesDir: File
get() = properties.getProperty(PROP_CATEGORIES_DIR).let { File(it ?: ".") }
set(value) {
properties.setProperty(PROP_CATEGORIES_DIR, value.canonicalPath)
save()
}
}
|
apache-2.0
|
b003b7d6dd3b49bbbe8ff0579de917dc
| 22.02439 | 83 | 0.582185 | 4.266968 | false | false | false | false |
CarlosEsco/tachiyomi
|
app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/TrackHolder.kt
|
1
|
6348
|
package eu.kanade.tachiyomi.ui.manga.track
import android.annotation.SuppressLint
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import eu.kanade.domain.ui.UiPreferences
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.databinding.TrackItemBinding
import eu.kanade.tachiyomi.util.view.popupMenu
import uy.kohesive.injekt.injectLazy
import java.text.DateFormat
class TrackHolder(private val binding: TrackItemBinding, adapter: TrackAdapter) : RecyclerView.ViewHolder(binding.root) {
private val preferences: UiPreferences by injectLazy()
private val dateFormat: DateFormat by lazy {
UiPreferences.dateFormat(preferences.dateFormat().get())
}
private val listener = adapter.rowClickListener
init {
binding.trackSet.setOnClickListener { listener.onSetClick(bindingAdapterPosition) }
binding.trackTitle.setOnClickListener { listener.onSetClick(bindingAdapterPosition) }
binding.trackTitle.setOnLongClickListener {
listener.onTitleLongClick(bindingAdapterPosition)
true
}
binding.trackStatus.setOnClickListener { listener.onStatusClick(bindingAdapterPosition) }
binding.trackChapters.setOnClickListener { listener.onChaptersClick(bindingAdapterPosition) }
binding.trackScore.setOnClickListener { listener.onScoreClick(bindingAdapterPosition) }
}
@SuppressLint("SetTextI18n")
fun bind(item: TrackItem) {
val track = item.track
binding.trackLogo.setImageResource(item.service.getLogo())
binding.logoContainer.setCardBackgroundColor(item.service.getLogoColor())
binding.trackSet.isVisible = track == null
binding.trackTitle.isVisible = track != null
binding.more.isVisible = track != null
binding.middleRow.isVisible = track != null
binding.bottomDivider.isVisible = track != null
binding.bottomRow.isVisible = track != null
binding.card.isVisible = track != null
if (track != null) {
val ctx = binding.trackTitle.context
binding.trackLogo.setOnClickListener {
listener.onOpenInBrowserClick(bindingAdapterPosition)
}
binding.trackTitle.text = track.title
binding.trackChapters.text = track.last_chapter_read.toInt().toString()
if (track.total_chapters > 0) {
binding.trackChapters.text = "${binding.trackChapters.text} / ${track.total_chapters}"
}
binding.trackStatus.text = item.service.getStatus(track.status)
val supportsScoring = item.service.getScoreList().isNotEmpty()
if (supportsScoring) {
if (track.score != 0F) {
item.service.getScoreList()
binding.trackScore.text = item.service.displayScore(track)
binding.trackScore.alpha = SET_STATUS_TEXT_ALPHA
} else {
binding.trackScore.text = ctx.getString(R.string.score)
binding.trackScore.alpha = UNSET_STATUS_TEXT_ALPHA
}
}
binding.trackScore.isVisible = supportsScoring
binding.vertDivider2.isVisible = supportsScoring
val supportsReadingDates = item.service.supportsReadingDates
if (supportsReadingDates) {
if (track.started_reading_date != 0L) {
binding.trackStartDate.text = dateFormat.format(track.started_reading_date)
binding.trackStartDate.alpha = SET_STATUS_TEXT_ALPHA
binding.trackStartDate.setOnClickListener {
it.popupMenu(R.menu.track_item_date) {
when (itemId) {
R.id.action_edit -> listener.onStartDateEditClick(bindingAdapterPosition)
R.id.action_remove -> listener.onStartDateRemoveClick(bindingAdapterPosition)
}
}
}
} else {
binding.trackStartDate.text = ctx.getString(R.string.track_started_reading_date)
binding.trackStartDate.alpha = UNSET_STATUS_TEXT_ALPHA
binding.trackStartDate.setOnClickListener {
listener.onStartDateEditClick(bindingAdapterPosition)
}
}
if (track.finished_reading_date != 0L) {
binding.trackFinishDate.text = dateFormat.format(track.finished_reading_date)
binding.trackFinishDate.alpha = SET_STATUS_TEXT_ALPHA
binding.trackFinishDate.setOnClickListener {
it.popupMenu(R.menu.track_item_date) {
when (itemId) {
R.id.action_edit -> listener.onFinishDateEditClick(bindingAdapterPosition)
R.id.action_remove -> listener.onFinishDateRemoveClick(bindingAdapterPosition)
}
}
}
} else {
binding.trackFinishDate.text = ctx.getString(R.string.track_finished_reading_date)
binding.trackFinishDate.alpha = UNSET_STATUS_TEXT_ALPHA
binding.trackFinishDate.setOnClickListener {
listener.onFinishDateEditClick(bindingAdapterPosition)
}
}
}
binding.bottomDivider.isVisible = supportsReadingDates
binding.bottomRow.isVisible = supportsReadingDates
binding.more.setOnClickListener {
it.popupMenu(R.menu.track_item) {
when (itemId) {
R.id.action_open_in_browser -> {
listener.onOpenInBrowserClick(bindingAdapterPosition)
}
R.id.action_remove -> {
listener.onRemoveItemClick(bindingAdapterPosition)
}
}
}
}
}
}
companion object {
private const val SET_STATUS_TEXT_ALPHA = 1F
private const val UNSET_STATUS_TEXT_ALPHA = 0.5F
}
}
|
apache-2.0
|
56b50fae9adf1ceff227530543d3ee77
| 44.669065 | 121 | 0.598141 | 5.425641 | false | false | false | false |
Heiner1/AndroidAPS
|
pump-common/src/main/java/info/nightscout/androidaps/plugins/pump/common/sync/PumpSyncStorage.kt
|
1
|
7788
|
package info.nightscout.androidaps.plugins.pump.common.sync
import com.thoughtworks.xstream.XStream
import com.thoughtworks.xstream.security.AnyTypePermission
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.interfaces.PumpSync
import info.nightscout.shared.logging.AAPSLogger
import info.nightscout.shared.logging.LTag
import info.nightscout.shared.sharedPreferences.SP
import javax.inject.Inject
import javax.inject.Singleton
/**
* This class is intended for Pump Drivers that use temporaryId and need way to pair records
*/
@Singleton
class PumpSyncStorage @Inject constructor(
val pumpSync: PumpSync,
val sp: SP,
val aapsLogger: AAPSLogger
) {
companion object {
const val pumpSyncStorageBolusKey: String = "pump_sync_storage_bolus"
const val pumpSyncStorageTBRKey: String = "pump_sync_storage_tbr"
}
var pumpSyncStorageBolus: MutableList<PumpDbEntryBolus> = mutableListOf()
var pumpSyncStorageTBR: MutableList<PumpDbEntryTBR> = mutableListOf()
private var storageInitialized: Boolean = false
private var xstream: XStream = XStream()
init {
initStorage()
cleanOldStorage()
}
fun initStorage() {
if (storageInitialized)
return
xstream.addPermission(AnyTypePermission.ANY)
if (sp.contains(pumpSyncStorageBolusKey)) {
val jsonData: String = sp.getString(pumpSyncStorageBolusKey, "")
if (jsonData.isNotBlank()) {
@Suppress("UNCHECKED_CAST")
pumpSyncStorageBolus = xstream.fromXML(jsonData, MutableList::class.java) as
MutableList<PumpDbEntryBolus>
aapsLogger.debug(LTag.PUMP, "Loading Pump Sync Storage Bolus: boluses=${pumpSyncStorageBolus.size}")
aapsLogger.debug(LTag.PUMP, "DD: PumpSyncStorageBolus=$pumpSyncStorageBolus")
}
}
if (sp.contains(pumpSyncStorageTBRKey)) {
val jsonData: String = sp.getString(pumpSyncStorageTBRKey, "")
if (jsonData.isNotBlank()) {
@Suppress("UNCHECKED_CAST")
pumpSyncStorageTBR = xstream.fromXML(jsonData, MutableList::class.java) as
MutableList<PumpDbEntryTBR>
aapsLogger.debug(LTag.PUMP, "Loading Pump Sync Storage: tbrs=${pumpSyncStorageTBR.size}.")
aapsLogger.debug(LTag.PUMP, "DD: PumpSyncStorageTBR=$pumpSyncStorageTBR")
}
}
storageInitialized = true
}
fun saveStorageBolus() {
if (!pumpSyncStorageBolus.isEmpty()) {
sp.putString(pumpSyncStorageBolusKey, xstream.toXML(pumpSyncStorageBolus))
aapsLogger.debug(LTag.PUMP, "Saving Pump Sync Storage: boluses=${pumpSyncStorageBolus.size}")
} else {
if (sp.contains(pumpSyncStorageBolusKey))
sp.remove(pumpSyncStorageBolusKey)
}
}
fun saveStorageTBR() {
if (!pumpSyncStorageTBR.isEmpty()) {
sp.putString(pumpSyncStorageTBRKey, xstream.toXML(pumpSyncStorageTBR))
aapsLogger.debug(LTag.PUMP, "Saving Pump Sync Storage: tbr=${pumpSyncStorageTBR.size}")
} else {
if (sp.contains(pumpSyncStorageTBRKey))
sp.remove(pumpSyncStorageTBRKey)
}
}
private fun cleanOldStorage() {
val oldSpKeys = setOf("pump_sync_storage", "pump_sync_storage_xstream", "pump_sync_storage_xstream_v2")
for (oldSpKey in oldSpKeys) {
if (sp.contains(oldSpKey))
sp.remove(oldSpKey)
}
}
fun getBoluses(): MutableList<PumpDbEntryBolus> {
return pumpSyncStorageBolus
}
fun getTBRs(): MutableList<PumpDbEntryTBR> {
return pumpSyncStorageTBR
}
fun addBolusWithTempId(detailedBolusInfo: DetailedBolusInfo, writeToInternalHistory: Boolean, creator: PumpSyncEntriesCreator): Boolean {
val temporaryId = creator.generateTempId(detailedBolusInfo.timestamp)
val result = pumpSync.addBolusWithTempId(
detailedBolusInfo.timestamp,
detailedBolusInfo.insulin,
temporaryId,
detailedBolusInfo.bolusType,
creator.model(),
creator.serialNumber())
aapsLogger.debug(
LTag.PUMP, "addBolusWithTempId [date=${detailedBolusInfo.timestamp}, temporaryId=$temporaryId, " +
"insulin=${detailedBolusInfo.insulin}, type=${detailedBolusInfo.bolusType}, pumpSerial=${creator.serialNumber()}] - " +
"Result: $result")
if (detailedBolusInfo.carbs > 0.0) {
addCarbs(PumpDbEntryCarbs(detailedBolusInfo, creator))
}
if (result && writeToInternalHistory) {
val dbEntry = PumpDbEntryBolus(temporaryId = temporaryId,
date = detailedBolusInfo.timestamp,
pumpType = creator.model(),
serialNumber = creator.serialNumber(),
detailedBolusInfo = detailedBolusInfo)
aapsLogger.debug("PumpDbEntryBolus: $dbEntry")
pumpSyncStorageBolus.add(dbEntry)
saveStorageBolus()
}
return result
}
fun addCarbs(carbsDto: PumpDbEntryCarbs) {
val result = pumpSync.syncCarbsWithTimestamp(
carbsDto.date,
carbsDto.carbs,
null,
carbsDto.pumpType,
carbsDto.serialNumber)
aapsLogger.debug(
LTag.PUMP, "syncCarbsWithTimestamp [date=${carbsDto.date}, " +
"carbs=${carbsDto.carbs}, pumpSerial=${carbsDto.serialNumber}] - Result: $result")
}
fun addTemporaryBasalRateWithTempId(temporaryBasal: PumpDbEntryTBR, writeToInternalHistory: Boolean, creator: PumpSyncEntriesCreator): Boolean {
val timeNow: Long = System.currentTimeMillis()
val temporaryId = creator.generateTempId(timeNow)
val response = pumpSync.addTemporaryBasalWithTempId(
timeNow,
temporaryBasal.rate,
(temporaryBasal.durationInSeconds * 1000L),
temporaryBasal.isAbsolute,
temporaryId,
temporaryBasal.tbrType,
creator.model(),
creator.serialNumber())
if (response && writeToInternalHistory) {
val dbEntry = PumpDbEntryTBR(temporaryId = temporaryId,
date = timeNow,
pumpType = creator.model(),
serialNumber = creator.serialNumber(),
entry = temporaryBasal,
pumpId=null)
aapsLogger.debug("PumpDbEntryTBR: $dbEntry")
pumpSyncStorageTBR.add(dbEntry)
saveStorageTBR()
}
return response
}
fun removeBolusWithTemporaryId(temporaryId: Long) {
var dbEntry: PumpDbEntryBolus? = null
for (pumpDbEntry in pumpSyncStorageBolus) {
if (pumpDbEntry.temporaryId == temporaryId) {
dbEntry = pumpDbEntry
}
}
if (dbEntry != null) {
pumpSyncStorageBolus.remove(dbEntry)
}
saveStorageBolus()
}
fun removeTemporaryBasalWithTemporaryId(temporaryId: Long) {
var dbEntry: PumpDbEntryTBR? = null
for (pumpDbEntry in pumpSyncStorageTBR) {
if (pumpDbEntry.temporaryId == temporaryId) {
dbEntry = pumpDbEntry
}
}
if (dbEntry != null) {
pumpSyncStorageTBR.remove(dbEntry)
}
saveStorageTBR()
}
}
|
agpl-3.0
|
7578667ba509797243f1fc1b8566476f
| 34.404545 | 148 | 0.614792 | 5.515581 | false | false | false | false |
Deanveloper/SlaK
|
src/main/kotlin/com/deanveloper/slak/User.kt
|
1
|
4548
|
package com.deanveloper.slak
import com.deanveloper.slak.util.Cacher
import com.deanveloper.slak.util.ErrorHandler
import com.google.gson.JsonObject
import java.awt.Color
import java.net.URL
import java.util.*
import javax.imageio.ImageIO
/**
* Represents a slack user
*
* @author Dean B
*/
class User private constructor(
id: String,
name: String,
deleted: Boolean,
color: Color,
profile: Profile,
timezone: TimeZone,
isAdmin: Boolean,
isOwner: Boolean,
has2FA: Boolean,
hasFiles: Boolean
) {
val id: String
var name: String
internal set
var deleted: Boolean
internal set
var color: Color
internal set
val profile: Profile
var timezone: TimeZone
internal set
var isAdmin: Boolean
internal set
var isOwner: Boolean
internal set
var has2FA: Boolean
internal set
var hasFiles: Boolean
internal set
init {
this.id = id
this.name = name
this.deleted = deleted
this.color = color
this.profile = profile
this.timezone = timezone
this.isAdmin = isAdmin
this.isOwner = isOwner
this.has2FA = has2FA
this.hasFiles = hasFiles
UserManager.put(if (name.startsWith('@')) name else "@$name", this)
UserManager.put(id, this)
}
constructor(json: JsonObject) : this(
json["id"].asString,
json["name"].asString,
json["deleted"]?.asBoolean ?: false,
Color(Integer.parseInt(json["color"].nullSafe?.asString ?: "0", 16)),
Profile(json["profile"].asJsonObject),
SimpleTimeZone((json["tz_offset"].nullSafe?.asInt ?: 0) * 1000,
json["tz_label"].nullSafe?.asString ?: "null"),
json["is_admin"]?.asBoolean ?: false,
json["is_owner"]?.asBoolean ?: false,
json["has_2fa"]?.asBoolean ?: false,
json["has_files"]?.asBoolean ?: false
)
companion object UserManager : Cacher<User>() {
inline fun start(crossinline cb: () -> Unit): ErrorHandler {
return runMethod("users.list", "token" to TOKEN) {
for (json in it["members"].asJsonArray) {
try {
User(json.asJsonObject)
} catch (e: Exception) {
e.printStackTrace()
}
}
cb()
}
}
protected fun fromJson(json: JsonObject): User {
if (json["is_user"]?.asBoolean ?: false) {
throw IllegalArgumentException("json does not represent a User")
}
return User(
json["id"].asString,
json["name"].asString,
json["deleted"]?.asBoolean ?: false,
Color(Integer.parseInt(json["color"].nullSafe?.asString ?: "0", 16)),
Profile(json["profile"].asJsonObject),
SimpleTimeZone((json["tz_offset"].nullSafe?.asInt ?: 0) * 1000,
json["tz_label"].nullSafe?.asString ?: "null"),
json["is_admin"]?.asBoolean ?: false,
json["is_owner"]?.asBoolean ?: false,
json["has_2fa"]?.asBoolean ?: false,
json["has_files"]?.asBoolean ?: false
)
}
val list: Set<User>
get() = this.values.toSet()
}
data class Profile(val firstName: String?, val lastName: String?, val realName: String?, val email: String?,
val skype: String?, val phone: String?, val imageSmallUrl: String, val imageLargeUrl: String) {
val imageSmall by lazy { ImageIO.read(URL(imageSmallUrl)) }
val imageLarge by lazy { ImageIO.read(URL(imageLargeUrl)) }
constructor(json: JsonObject) : this(json["first_name"].nullSafe?.asString,
json["last_name"].nullSafe?.asString,
json["real_name"].nullSafe?.asString, json["email"].nullSafe?.asString,
json["skype"].nullSafe?.asString, json["phone"].nullSafe?.asString,
json["image_32"].asString, json["image_192"].asString)
}
override fun toString() = "User[$id|@$name]"
override fun hashCode() = id.hashCode()
override fun equals(other: Any?): Boolean {
if (this === other) return true
return id == (other as? User)?.id
}
}
|
mit
|
91d74416c9e84813b6f37022ff1346c8
| 31.956522 | 118 | 0.544415 | 4.621951 | false | false | false | false |
Heiner1/AndroidAPS
|
danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketOptionGetUserOption.kt
|
1
|
3392
|
package info.nightscout.androidaps.danars.comm
import dagger.android.HasAndroidInjector
import info.nightscout.shared.logging.LTag
import info.nightscout.androidaps.dana.DanaPump
import info.nightscout.androidaps.danars.encryption.BleEncryption
import javax.inject.Inject
class DanaRSPacketOptionGetUserOption(
injector: HasAndroidInjector
) : DanaRSPacket(injector) {
@Inject lateinit var danaPump: DanaPump
init {
opCode = BleEncryption.DANAR_PACKET__OPCODE_OPTION__GET_USER_OPTION
aapsLogger.debug(LTag.PUMPCOMM, "Requesting user settings")
}
override fun handleMessage(data: ByteArray) {
danaPump.timeDisplayType24 = intFromBuff(data, 0, 1) == 0
danaPump.buttonScrollOnOff = intFromBuff(data, 1, 1) == 1
danaPump.beepAndAlarm = intFromBuff(data, 2, 1)
danaPump.lcdOnTimeSec = intFromBuff(data, 3, 1)
danaPump.backlightOnTimeSec = intFromBuff(data, 4, 1)
danaPump.selectedLanguage = intFromBuff(data, 5, 1)
danaPump.units = intFromBuff(data, 6, 1)
danaPump.shutdownHour = intFromBuff(data, 7, 1)
danaPump.lowReservoirRate = intFromBuff(data, 8, 1)
danaPump.cannulaVolume = intFromBuff(data, 9, 2)
danaPump.refillAmount = intFromBuff(data, 11, 2)
val selectableLanguage1 = intFromBuff(data, 13, 1)
val selectableLanguage2 = intFromBuff(data, 14, 1)
val selectableLanguage3 = intFromBuff(data, 15, 1)
val selectableLanguage4 = intFromBuff(data, 16, 1)
val selectableLanguage5 = intFromBuff(data, 17, 1)
if (data.size >= 22) // hw 7+
danaPump.target = intFromBuff(data, 18, 2)
// Pump's screen on time can't be less than 5
failed = danaPump.lcdOnTimeSec < 5
aapsLogger.debug(LTag.PUMPCOMM, "timeDisplayType24: " + danaPump.timeDisplayType24)
aapsLogger.debug(LTag.PUMPCOMM, "buttonScrollOnOff: " + danaPump.buttonScrollOnOff)
aapsLogger.debug(LTag.PUMPCOMM, "beepAndAlarm: " + danaPump.beepAndAlarm)
aapsLogger.debug(LTag.PUMPCOMM, "lcdOnTimeSec: " + danaPump.lcdOnTimeSec)
aapsLogger.debug(LTag.PUMPCOMM, "backlightOnTimeSec: " + danaPump.backlightOnTimeSec)
aapsLogger.debug(LTag.PUMPCOMM, "selectedLanguage: " + danaPump.selectedLanguage)
aapsLogger.debug(LTag.PUMPCOMM, "Pump units: " + if (danaPump.units == DanaPump.UNITS_MGDL) "MGDL" else "MMOL")
aapsLogger.debug(LTag.PUMPCOMM, "shutdownHour: " + danaPump.shutdownHour)
aapsLogger.debug(LTag.PUMPCOMM, "lowReservoirRate: " + danaPump.lowReservoirRate)
aapsLogger.debug(LTag.PUMPCOMM, "cannulaVolume: " + danaPump.cannulaVolume)
aapsLogger.debug(LTag.PUMPCOMM, "refillAmount: " + danaPump.refillAmount)
aapsLogger.debug(LTag.PUMPCOMM, "selectableLanguage1: $selectableLanguage1")
aapsLogger.debug(LTag.PUMPCOMM, "selectableLanguage2: $selectableLanguage2")
aapsLogger.debug(LTag.PUMPCOMM, "selectableLanguage3: $selectableLanguage3")
aapsLogger.debug(LTag.PUMPCOMM, "selectableLanguage4: $selectableLanguage4")
aapsLogger.debug(LTag.PUMPCOMM, "selectableLanguage5: $selectableLanguage5")
aapsLogger.debug(LTag.PUMPCOMM, "target: ${if (danaPump.units == DanaPump.UNITS_MGDL) danaPump.target else danaPump.target / 100}")
}
override val friendlyName: String = "OPTION__GET_USER_OPTION"
}
|
agpl-3.0
|
a315262639c1a5b7be762cb475c16ff9
| 54.622951 | 139 | 0.715212 | 4.399481 | false | false | false | false |
maurocchi/chesslave
|
backend/src/main/java/io/chesslave/app/Application.kt
|
2
|
1791
|
package io.chesslave.app
import com.fasterxml.jackson.module.kotlin.KotlinModule
import io.vertx.core.eventbus.DeliveryOptions
import io.vertx.core.json.Json
import io.vertx.ext.web.handler.sockjs.BridgeOptions
import io.vertx.ext.web.handler.sockjs.PermittedOptions
import io.vertx.reactivex.core.Vertx
import io.vertx.reactivex.core.eventbus.EventBus
import io.vertx.reactivex.ext.web.Router
import io.vertx.reactivex.ext.web.handler.sockjs.SockJSHandler
import org.slf4j.LoggerFactory
import io.vertx.core.eventbus.EventBus as VertxEventBus
object log {
private val logger = LoggerFactory.getLogger("main")
internal lateinit var bus: EventBus
fun info(message: String) {
logger.info(message)
publish("INFO", message)
}
fun debug(message: String) {
logger.debug(message)
publish("DEBUG", message)
}
fun error(message: String, throwable: Throwable) {
logger.error(message, throwable)
publish("ERROR", "$message ($throwable)")
}
private fun publish(level: String, message: String) {
bus.publish("log", message, DeliveryOptions().addHeader("level", level))
}
}
fun main(args: Array<String>) {
Json.mapper.registerModule(KotlinModule())
val vertx = Vertx.vertx()
log.bus = vertx.eventBus()
val router = Router.router(vertx)
val bridgeOptions = BridgeOptions()
.addInboundPermitted(PermittedOptions())
.addOutboundPermitted(PermittedOptions())
val eventBusHandler = SockJSHandler.create(vertx).bridge(bridgeOptions)
router.route("/events/*").handler(eventBusHandler)
vertx.createHttpServer().requestHandler(router::accept).listen(8080) {
if (it.succeeded()) log.info("Server started")
}
Chesslave.configure(vertx.eventBus())
}
|
gpl-2.0
|
812ec1527305048052ef95df20a9ab2e
| 32.185185 | 80 | 0.71971 | 4.042889 | false | false | false | false |
Saketme/JRAW
|
lib/src/main/kotlin/net/dean/jraw/oauth/DeferredPersistentTokenStore.kt
|
1
|
5495
|
package net.dean.jraw.oauth
import net.dean.jraw.filterValuesNotNull
import net.dean.jraw.models.OAuthData
import net.dean.jraw.models.PersistedAuthData
/**
* This specific TokenStore abstraction is a way of dealing with the assumption that all `store*` and `fetch*`
* operations happen in insignificant time.
*
* All data is saved in memory until manually told to persist to a data source. This data source may be a file,
* database, or a cloud storage provider. If the time it takes to persist the data is insignificant, you can enable
* [autoPersist].
*
* When first created, it might be necessary to load the persisted data into memory using [load]. Otherwise the
* TokenStore could be missing out on some data.
*/
abstract class DeferredPersistentTokenStore @JvmOverloads constructor(
initialData: Map<String, PersistedAuthData> = mapOf()
) : TokenStore {
private var memoryData: MutableMap<String, PersistedAuthData> = initialData.toMutableMap()
private var lastPersistedData: Map<String, PersistedAuthData>? = null
/** If true, [persist] will automatically be called after the in-memory data is mutated. */
var autoPersist: Boolean = false
/** Fetches any data stored in memory about the given username. Useful for debugging. */
fun inspect(username: String): PersistedAuthData? = memoryData[username]
/** A list of all usernames that have either a refresh token or some OAuthData associated with it */
val usernames: List<String>
get() = memoryData.keys.toList()
/** Returns true if the in-memory copy of the data differs from the last persisted data */
fun hasUnsaved() = lastPersistedData != memoryData
/**
* Persists the in-memory data to somewhere more permanent. Assume this is a blocking operation. Returns this
* instance for chaining.
*/
fun persist() {
// Do less work in the long run
val actualData = memoryData
.mapValues { it.value.simplify() }
.filterValuesNotNull()
val result = doPersist(actualData)
this.lastPersistedData = HashMap(memoryData)
return result
}
/**
* Loads the data from its persistent source. Overwrites any existing data in memory. Assume this is a blocking
* operation. Returns this instance for chaining.
*/
fun load() {
// Don't include insignificant data
this.memoryData = doLoad()
.mapValues { it.value.simplify() }
.filterValuesNotNull()
.toMutableMap()
}
/**
* Clears all data currently being held in memory. Does not affect data already persisted. To clear both in-memory
* data and store data, perform a [clear] follow by a [persist].
*/
fun clear() {
this.memoryData.clear()
}
/** Returns the amount of entries currently being stored in memory. */
fun size() = this.memoryData.size
/**
* Does the actual work for persisting data. The given data may contain null values depending on if the user asked
* to keep insignificant values.
*/
protected abstract fun doPersist(data: Map<String, PersistedAuthData>)
/**
* Does the actual loading of the persisted data. Any insignificant entries returned will automatically be filtered
* out, so unless manually doing this here saves a significant amount of time, you should just load all stored data.
*/
protected abstract fun doLoad(): Map<String, PersistedAuthData>
/** Returns a copy of the data currently in memory. */
fun data(): Map<String, PersistedAuthData> = HashMap(this.memoryData)
override final fun storeLatest(username: String, data: OAuthData) {
if (username == AuthManager.USERNAME_UNKOWN)
throw IllegalArgumentException("Refusing to store data for unknown username")
val stored = this.memoryData[username]
val new = PersistedAuthData.create(data, stored?.refreshToken)
this.memoryData[username] = new
if (autoPersist && this.hasUnsaved())
persist()
}
override final fun storeRefreshToken(username: String, token: String) {
if (username == AuthManager.USERNAME_UNKOWN)
throw IllegalArgumentException("Refusing to store data for unknown username")
val stored = this.memoryData[username]
val new = PersistedAuthData.create(stored?.latest, token)
this.memoryData[username] = new
if (autoPersist && this.hasUnsaved())
persist()
}
override final fun fetchLatest(username: String): OAuthData? {
return memoryData[username]?.latest
}
override final fun fetchRefreshToken(username: String): String? {
return memoryData[username]?.refreshToken
}
override fun deleteLatest(username: String) {
val saved = memoryData[username] ?: return
if (saved.refreshToken == null) {
memoryData.remove(username)
} else {
memoryData[username] = PersistedAuthData.create(null, saved.refreshToken)
}
if (autoPersist && this.hasUnsaved())
persist()
}
override fun deleteRefreshToken(username: String) {
val saved = memoryData[username] ?: return
if (saved.latest == null)
memoryData.remove(username)
else
memoryData[username] = PersistedAuthData.create(saved.latest, null)
if (autoPersist && this.hasUnsaved())
persist()
}
}
|
mit
|
8c0f96f462fb43a567b4dd99168719e1
| 37.159722 | 120 | 0.675705 | 4.893143 | false | false | false | false |
rlac/unitconverter
|
app/src/main/kotlin/au/id/rlac/unitconverter/converter/UnitConverter.kt
|
1
|
4385
|
package au.id.rlac.unitconverter.converter
import android.content.Context
import au.id.rlac.unitconverter.R
import au.id.rlac.util.android.use
import java.math.BigDecimal
import java.util.*
/**
* Converts a numeric value for one [Measure] to the equivalent value for another [Measure].
*
* A [UnitConverter] has a base [Measure] along with a set of [Conversion] objects that can convert
* values to and from the base [Measure] to their own [Measure].
*
* @property base The base [Measure] all [converters] work with.
* @property displayNameResId Display name for the unit converter.
* @property theme The theme associated with this unit converter.
* @param converters Converters that convert to the [base]. Each [Conversion] is adds its [Measure]
* as a supported type to this unit converter.
*/
enum class UnitConverter(private val base: Measure,
val displayNameResId: Int,
val theme: Int,
vararg converters: Conversion) {
TEMPERATURE(
Measure.CELSIUS,
R.string.temperature,
R.style.TemperatureTheme,
Conversion.fahrenheit),
LENGTH(
Measure.METRE,
R.string.length,
R.style.LengthTheme,
Conversion(Measure.CENTIMETRE, BigDecimal(0.01)),
Conversion(Measure.KILOMETRE, BigDecimal(1000.0)),
Conversion(Measure.INCH, BigDecimal(0.0254)),
Conversion(Measure.FEET, BigDecimal(0.3048)),
Conversion(Measure.YARD, BigDecimal(0.9144)),
Conversion(Measure.MILE, BigDecimal(1609.344))),
MASS(
Measure.GRAM,
R.string.mass,
R.style.MassTheme,
Conversion(Measure.OUNCE, BigDecimal(28.3495)),
Conversion(Measure.STONE, BigDecimal(6350.29)),
Conversion(Measure.POUND, BigDecimal(453.592)),
Conversion(Measure.KILOGRAM, BigDecimal(1000.0))),
VOLUME(
Measure.LITRE,
R.string.volume,
R.style.VolumeTheme,
Conversion(Measure.MILLILITRE, BigDecimal(0.001)),
Conversion(Measure.FLUIDOUNCE, BigDecimal(0.0295735)),
Conversion(Measure.CUP, BigDecimal(0.236588)),
Conversion(Measure.PINT, BigDecimal(0.473176)),
Conversion(Measure.GALLON, BigDecimal(3.78541))),
ENERGY(
Measure.KILOJOULE,
R.string.energy,
R.style.EnergyTheme,
Conversion(Measure.KILOCALORIE, BigDecimal(4.184)));
class Theme private constructor(val colorPrimary: Int, val colorPrimaryDark: Int) {
companion object {
operator fun invoke(context: Context, uc: UnitConverter): Theme {
with(context.getResources().newTheme()) {
setTo(context.getTheme())
applyStyle(uc.theme, true)
return obtainStyledAttributes(R.styleable.AppCompatTheme).use {
Theme(it.getColor(R.styleable.AppCompatTheme_colorPrimary, 0),
it.getColor(R.styleable.AppCompatTheme_colorPrimaryDark, 0))
}
}
}
}
}
private val converterMap: Map<Measure, Conversion> = Collections.unmodifiableMap(
with(HashMap<Measure, Conversion>()) {
converters.forEach { c -> put(c.targetMeasurement, c) }
put(base, Conversion(base, BigDecimal.ONE))
this
})
/**
* @param forSystem If set filters the list to measurements for this system only.
* @return the list of units supported by this converter's convert method.
*/
fun supportedUnits(forSystem: MeasurementSystem? = null): List<Measure> =
with(converterMap.map({ it.key }).sortedBy { it.weight }) {
if (forSystem == null) this
else filter { it.system == forSystem }
}
/**
* Convert the value of a unit to its equivalent value as another measure.
*
* @param from The unit type to convert from.
* @param to The unit type to convert to.
* @param value The value of the unit to convert from.
* @return the converted value.
* @throws IllegalArgumentException if the from or to unit is not supported by the converter.
*/
fun convert(from: Measure, to: Measure, value: BigDecimal): BigDecimal {
val fromConverter = converterMap[from]
val toConverter = converterMap[to]
if (fromConverter == null) throw IllegalArgumentException("from unit ${from} not supported.")
if (toConverter == null) throw IllegalArgumentException("to unit ${to} not supported.")
return toConverter.fromBase(fromConverter.toBase(value))
}
}
|
apache-2.0
|
38ccf2bedbf6bbc7850b4fc50c2a96e2
| 36.161017 | 99 | 0.678677 | 4.109653 | false | false | false | false |
PolymerLabs/arcs
|
java/arcs/android/util/AndroidBinderStatsParser.kt
|
1
|
1398
|
/*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.android.util
/**
* Parser for the output of /sys/kernel/debug/binder/stats file.
*/
class AndroidBinderStatsParser {
companion object {
private const val PROCESS_TAG = "proc "
}
/**
* Parses binder stats extracting entries for a given PID.
*/
fun parse(lines: Sequence<String>, pid: Int): Map<String, String> {
val delimiter = PROCESS_TAG + pid
var partitionFlip = false
return lines.partition {
if (it.startsWith(PROCESS_TAG)) {
partitionFlip = it == delimiter
}
partitionFlip
}.first.associate {
// General case where a binder process record is delimited by a colon.
var index = it.lastIndexOf(":")
if (index != -1) {
return@associate it.substring(0, index).trim() to
it.substring(index + 1).trim()
}
// Special case e.g. "ready threads N", "free async space M"
index = it.lastIndexOf(" ")
if (index != -1) {
return@associate it.substring(0, index).trim() to
it.substring(index + 1).trim()
}
it.trim() to ""
}
}
}
|
bsd-3-clause
|
14675a449c1754b9d948d05562a05f08
| 25.884615 | 96 | 0.626609 | 3.883333 | false | false | false | false |
k9mail/k-9
|
app/ui/legacy/src/main/java/com/fsck/k9/ui/messagesource/MessageHeadersFragment.kt
|
2
|
2840
|
package com.fsck.k9.ui.messagesource
import android.graphics.Typeface
import android.os.Bundle
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.style.StyleSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.fsck.k9.controller.MessageReference
import com.fsck.k9.mail.Header
import com.fsck.k9.mail.internet.MimeUtility
import com.fsck.k9.ui.R
import com.fsck.k9.ui.base.loader.observeLoading
import com.fsck.k9.ui.withArguments
import org.koin.androidx.viewmodel.ext.android.viewModel
class MessageHeadersFragment : Fragment() {
private val messageHeadersViewModel: MessageHeadersViewModel by viewModel()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.message_view_headers, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val messageReferenceString = requireArguments().getString(ARG_REFERENCE)
?: error("Missing argument $ARG_REFERENCE")
val messageReference = MessageReference.parse(messageReferenceString)
?: error("Invalid message reference: $messageReferenceString")
val messageHeaderView = view.findViewById<TextView>(R.id.message_source)
messageHeadersViewModel.loadHeaders(messageReference).observeLoading(
owner = this,
loadingView = view.findViewById(R.id.message_headers_loading),
errorView = view.findViewById(R.id.message_headers_error),
dataView = view.findViewById(R.id.message_headers_data)
) { headers ->
populateHeadersList(messageHeaderView, headers)
}
}
private fun populateHeadersList(messageHeaderView: TextView, headers: List<Header>) {
val sb = SpannableStringBuilder()
var first = true
for ((name, value) in headers) {
if (!first) {
sb.append("\n")
} else {
first = false
}
val boldSpan = StyleSpan(Typeface.BOLD)
val label = SpannableString("$name: ")
label.setSpan(boldSpan, 0, label.length, 0)
sb.append(label)
sb.append(MimeUtility.unfoldAndDecode(value))
}
messageHeaderView.text = sb
}
companion object {
private const val ARG_REFERENCE = "reference"
fun newInstance(reference: MessageReference): MessageHeadersFragment {
return MessageHeadersFragment().withArguments(
ARG_REFERENCE to reference.toIdentityString()
)
}
}
}
|
apache-2.0
|
490ff61d8719d5c77347e852f76aba26
| 36.866667 | 116 | 0.691549 | 4.595469 | false | false | false | false |
googlecodelabs/android-accessibility
|
BasicAndroidAccessibility-Kotlin/app/src/main/java/com/example/android/basicandroidaccessibility/ExpandTouchAreaFragment.kt
|
1
|
1975
|
/*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.basicandroidaccessibility
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
class ExpandTouchAreaFragment : Fragment() {
private lateinit var toggleImageButton: ImageButton
private var playing: Boolean = false
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_expand_touch_area, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
toggleImageButton = view.findViewById(R.id.play_pause_toggle_view)
setUI()
toggleImageButton.setOnClickListener {
playing = !playing
setUI()
}
}
private fun setUI() {
if (playing) {
toggleImageButton.setImageResource(R.drawable.ic_cancel)
toggleImageButton.contentDescription = "Cancel"
} else {
toggleImageButton.setImageResource(R.drawable.ic_play_circle_outline)
toggleImageButton.contentDescription = "Refresh"
}
}
}
|
apache-2.0
|
d94cd5500c949ed8be933008727b1869
| 31.916667 | 86 | 0.698734 | 4.805353 | false | false | false | false |
JetBrains/ideavim
|
src/main/java/com/maddyhome/idea/vim/vimscript/model/commands/CmdFilterCommand.kt
|
1
|
4020
|
/*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.vimscript.model.commands
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProcessCanceledException
import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.ex.ExException
import com.maddyhome.idea.vim.ex.ExOutputModel
import com.maddyhome.idea.vim.ex.ranges.Ranges
import com.maddyhome.idea.vim.helper.EditorHelper
import com.maddyhome.idea.vim.helper.MessageHelper
import com.maddyhome.idea.vim.newapi.ij
import com.maddyhome.idea.vim.vimscript.model.ExecutionResult
/**
* see "h :!"
*/
data class CmdFilterCommand(val ranges: Ranges, val argument: String) : Command.SingleExecution(ranges) {
override val argFlags = flags(RangeFlag.RANGE_OPTIONAL, ArgumentFlag.ARGUMENT_OPTIONAL, Access.SELF_SYNCHRONIZED)
override fun processCommand(editor: VimEditor, context: ExecutionContext, operatorArguments: OperatorArguments): ExecutionResult {
logger.debug("execute")
val command = buildString {
var inBackslash = false
argument.forEach { c ->
when {
!inBackslash && c == '!' -> {
val last = VimPlugin.getProcess().lastCommand
if (last.isNullOrEmpty()) {
VimPlugin.showMessage(MessageHelper.message("e_noprev"))
return ExecutionResult.Error
}
append(last)
}
!inBackslash && c == '%' -> {
val virtualFile = EditorHelper.getVirtualFile(editor.ij)
if (virtualFile == null) {
// Note that we use a slightly different error message to Vim, because we don't support alternate files or file
// name modifiers. (I also don't know what the :p:h means)
// (Vim) E499: Empty file name for '%' or '#', only works with ":p:h"
// (IdeaVim) E499: Empty file name for '%'
VimPlugin.showMessage(MessageHelper.message("E499"))
return ExecutionResult.Error
}
append(virtualFile.path)
}
else -> append(c)
}
inBackslash = c == '\\'
}
}
if (command.isEmpty()) {
return ExecutionResult.Error
}
val workingDirectory = editor.ij.project?.basePath
return try {
if (ranges.size() == 0) {
// Show command output in a window
VimPlugin.getProcess().executeCommand(editor, command, null, workingDirectory)?.let {
ExOutputModel.getInstance(editor.ij).output(it)
}
ExecutionResult.Success
} else {
// Filter
val range = this.getTextRange(editor, false)
val input = editor.ij.document.charsSequence.subSequence(range.startOffset, range.endOffset)
VimPlugin.getProcess().executeCommand(editor, command, input, workingDirectory)?.let {
ApplicationManager.getApplication().runWriteAction {
val start = editor.offsetToBufferPosition(range.startOffset)
val end = editor.offsetToBufferPosition(range.endOffset)
editor.ij.document.replaceString(range.startOffset, range.endOffset, it)
val linesFiltered = end.line - start.line
if (linesFiltered > 2) {
VimPlugin.showMessage("$linesFiltered lines filtered")
}
}
}
ExecutionResult.Success
}
} catch (e: ProcessCanceledException) {
throw ExException("Command terminated")
} catch (e: Exception) {
throw ExException(e.message)
}
}
companion object {
private val logger = Logger.getInstance(CmdFilterCommand::class.java.name)
}
}
|
mit
|
fb496aeefcf1ae0cec5509aa9c764a79
| 37.653846 | 132 | 0.664179 | 4.589041 | false | false | false | false |
Turbo87/intellij-rust
|
src/main/kotlin/org/rust/ide/structure/RustFnTreeElement.kt
|
1
|
747
|
package org.rust.ide.structure
import com.intellij.ide.structureView.StructureViewTreeElement
import com.intellij.ide.structureView.impl.common.PsiTreeElementBase
import org.rust.lang.core.psi.RustFnItem
class RustFnTreeElement(element: RustFnItem) : PsiTreeElementBase<RustFnItem>(element) {
override fun getPresentableText(): String? {
var text = element?.name
val params = element?.fnParams?.paramList?.map { it.typeSum.text }?.joinToString()
if (params != null)
text += "($params)"
val retType = element?.retType;
if (retType != null)
text += " ${retType.text}"
return text;
}
override fun getChildrenBase() = arrayListOf<StructureViewTreeElement>()
}
|
mit
|
b81cbca9e579fa303074b97e478a83ea
| 30.125 | 90 | 0.68407 | 4.582822 | false | false | false | false |
ingokegel/intellij-community
|
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/MainEntityListImpl.kt
|
1
|
5848
|
package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class MainEntityListImpl : MainEntityList, WorkspaceEntityBase() {
companion object {
val connections = listOf<ConnectionId>(
)
}
@JvmField
var _x: String? = null
override val x: String
get() = _x!!
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: MainEntityListData?) : ModifiableWorkspaceEntityBase<MainEntityList>(), MainEntityList.Builder {
constructor() : this(MainEntityListData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity MainEntityList is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isXInitialized()) {
error("Field MainEntityList#x should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as MainEntityList
this.entitySource = dataSource.entitySource
this.x = dataSource.x
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var x: String
get() = getEntityData().x
set(value) {
checkModificationAllowed()
getEntityData().x = value
changedProperty.add("x")
}
override fun getEntityData(): MainEntityListData = result ?: super.getEntityData() as MainEntityListData
override fun getEntityClass(): Class<MainEntityList> = MainEntityList::class.java
}
}
class MainEntityListData : WorkspaceEntityData<MainEntityList>() {
lateinit var x: String
fun isXInitialized(): Boolean = ::x.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<MainEntityList> {
val modifiable = MainEntityListImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): MainEntityList {
val entity = MainEntityListImpl()
entity._x = x
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return MainEntityList::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return MainEntityList(x, entitySource) {
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as MainEntityListData
if (this.entitySource != other.entitySource) return false
if (this.x != other.x) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as MainEntityListData
if (this.x != other.x) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + x.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + x.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
|
apache-2.0
|
f2f2676e6ab9c89f138fbc07da491587
| 29.300518 | 124 | 0.721614 | 5.277978 | false | false | false | false |
TonyTangAndroid/storio
|
storio-content-resolver-annotations-processor/src/main/kotlin/com/pushtorefresh/storio3/contentresolver/annotations/processor/StorIOContentResolverProcessor.kt
|
3
|
14103
|
package com.pushtorefresh.storio3.contentresolver.annotations.processor
import com.pushtorefresh.storio3.common.annotations.processor.ProcessingException
import com.pushtorefresh.storio3.common.annotations.processor.SkipNotAnnotatedClassWithAnnotatedParentException
import com.pushtorefresh.storio3.common.annotations.processor.StorIOAnnotationsProcessor
import com.pushtorefresh.storio3.common.annotations.processor.generate.Generator
import com.pushtorefresh.storio3.common.annotations.processor.introspection.JavaType
import com.pushtorefresh.storio3.contentresolver.annotations.StorIOContentResolverColumn
import com.pushtorefresh.storio3.contentresolver.annotations.StorIOContentResolverCreator
import com.pushtorefresh.storio3.contentresolver.annotations.StorIOContentResolverType
import com.pushtorefresh.storio3.contentresolver.annotations.processor.generate.DeleteResolverGenerator
import com.pushtorefresh.storio3.contentresolver.annotations.processor.generate.GetResolverGenerator
import com.pushtorefresh.storio3.contentresolver.annotations.processor.generate.MappingGenerator
import com.pushtorefresh.storio3.contentresolver.annotations.processor.generate.PutResolverGenerator
import com.pushtorefresh.storio3.contentresolver.annotations.processor.introspection.StorIOContentResolverColumnMeta
import com.pushtorefresh.storio3.contentresolver.annotations.processor.introspection.StorIOContentResolverCreatorMeta
import com.pushtorefresh.storio3.contentresolver.annotations.processor.introspection.StorIOContentResolverTypeMeta
import javax.annotation.processing.RoundEnvironment
import javax.lang.model.element.Element
import javax.lang.model.element.ElementKind
import javax.lang.model.element.ExecutableElement
import javax.lang.model.element.Modifier.ABSTRACT
import javax.lang.model.element.TypeElement
import javax.lang.model.util.Elements
import javax.tools.Diagnostic.Kind.WARNING
/**
* Annotation processor for StorIOContentResolver
*
* It'll process annotations to generate StorIOContentResolver Object-Mapping
*
* Addition: Annotation Processor should work fast and be optimized because it's part of compilation
* We don't want to annoy developers, who use StorIO
*/
open class StorIOContentResolverProcessor : StorIOAnnotationsProcessor<StorIOContentResolverTypeMeta, StorIOContentResolverColumnMeta>() {
override fun getSupportedAnnotationTypes() = setOf(
StorIOContentResolverType::class.java.canonicalName,
StorIOContentResolverColumn::class.java.canonicalName,
StorIOContentResolverCreator::class.java.canonicalName
)
/**
* Processes annotated class
*
* @param classElement type element annotated with [StorIOContentResolverType]
*
* @param elementUtils utils for working with elementUtils
*
* @return result of processing as [StorIOContentResolverTypeMeta]
*/
override fun processAnnotatedClass(classElement: TypeElement, elementUtils: Elements): StorIOContentResolverTypeMeta {
val storIOContentResolverType = classElement.getAnnotation(StorIOContentResolverType::class.java)
val commonUri = storIOContentResolverType.uri
val urisForOperations = mapOf(
"insert" to storIOContentResolverType.insertUri,
"update" to storIOContentResolverType.updateUri,
"delete" to storIOContentResolverType.deleteUri
)
validateUris(classElement, commonUri, urisForOperations)
val simpleName = classElement.simpleName.toString()
val packageName = elementUtils.getPackageOf(classElement).qualifiedName.toString()
return StorIOContentResolverTypeMeta(simpleName, packageName, storIOContentResolverType, ABSTRACT in classElement.modifiers, nonNullAnnotationClassName)
}
/**
* Verifies that uris are valid.
*
* @param classElement type element
*
* @param commonUri nullable default uri for all operations
*
* @param operationUriMap non-null map where key - operation name, value - specific uri for this
* * operation
*/
private fun validateUris(classElement: TypeElement, commonUri: String, operationUriMap: Map<String, String>) {
if (!validateUri(commonUri)) {
val operationsWithInvalidUris = mutableListOf<String>()
operationUriMap.forEach { (key, value) ->
if (!validateUri(value)) operationsWithInvalidUris.add(key)
}
if (operationsWithInvalidUris.isNotEmpty()) {
var message = "Uri of ${classElement.simpleName} annotated with ${typeAnnotationClass.simpleName} is empty"
if (operationsWithInvalidUris.size < operationUriMap.size) {
message += " for operation " + operationsWithInvalidUris[0]
}
// Else (there is no any uris) - do not specify operation, because commonUri is default and straightforward way.
throw ProcessingException(classElement, message)
}
// It will be okay if uris for all operations were specified separately.
}
}
private fun validateUri(uri: String) = uri.isNotEmpty()
/**
* Processes fields annotated with [StorIOContentResolverColumn]
*
* @param roundEnvironment current processing environment
*
* @param annotatedClasses map of classes annotated with [StorIOContentResolverType]
*/
override fun processAnnotatedFieldsOrMethods(roundEnvironment: RoundEnvironment, annotatedClasses: Map<TypeElement, StorIOContentResolverTypeMeta>) {
val elementsAnnotatedWithStorIOContentResolverColumn = roundEnvironment.getElementsAnnotatedWith(StorIOContentResolverColumn::class.java)
elementsAnnotatedWithStorIOContentResolverColumn.forEach { element ->
try {
validateAnnotatedFieldOrMethod(element)
val columnMeta = processAnnotatedFieldOrMethod(element)
annotatedClasses[columnMeta.enclosingElement]?.let { typeMeta ->
// If class already contains column with same name - throw an exception.
if (columnMeta.storIOColumn.name in typeMeta.columns.keys) {
throw ProcessingException(element, "Column name already used in this class: ${columnMeta.storIOColumn.name}")
}
// If field annotation applied to both fields and methods in a same class.
if (typeMeta.needsCreator && !columnMeta.needsCreator || !typeMeta.needsCreator && columnMeta.needsCreator && typeMeta.columns.isNotEmpty()) {
throw ProcessingException(element, "Can't apply ${StorIOContentResolverColumn::class.java.simpleName} annotation to both" +
" fields and methods in a same class: ${typeMeta.simpleName}"
)
}
// If column needs creator then enclosing class needs it as well.
if (!typeMeta.needsCreator && columnMeta.needsCreator) typeMeta.needsCreator = true
// Put meta column info.
typeMeta.columns += columnMeta.storIOColumn.name to columnMeta
}
} catch (e: SkipNotAnnotatedClassWithAnnotatedParentException) {
messager.printMessage(WARNING, e.message)
}
}
}
/**
* Processes annotated field and returns result of processing or throws exception
*
* @param annotatedField field that was annotated with [StorIOContentResolverColumn]
*
* @return non-null [StorIOContentResolverColumnMeta] with meta information about field
*/
override fun processAnnotatedFieldOrMethod(annotatedField: Element): StorIOContentResolverColumnMeta {
val javaType: JavaType
try {
javaType = JavaType.from(
if (annotatedField.kind == ElementKind.FIELD)
annotatedField.asType()
else
(annotatedField as ExecutableElement).returnType)
} catch (e: Exception) {
throw ProcessingException(annotatedField, "Unsupported type of field or method for ${StorIOContentResolverColumn::class.java.simpleName} annotation," +
" if you need to serialize/deserialize field of that type -> please write your own resolver: ${e.message}"
)
}
val column = annotatedField.getAnnotation(StorIOContentResolverColumn::class.java)
if (column.ignoreNull && annotatedField.asType().kind.isPrimitive) {
throw ProcessingException(annotatedField, "ignoreNull should not be used for primitive type: ${annotatedField.simpleName}")
}
if (column.name.isEmpty()) {
throw ProcessingException(annotatedField, "Column name is empty: ${annotatedField.simpleName}")
}
val getter = getters[annotatedField]
return StorIOContentResolverColumnMeta(annotatedField.enclosingElement, annotatedField, annotatedField.simpleName.toString(), javaType, column, getter)
}
/**
* Processes factory methods or constructors annotated with [StorIOContentResolverCreator].
*
* @param roundEnvironment current processing environment
*
* @param annotatedClasses map of classes annotated with [StorIOContentResolverType]
*/
override fun processAnnotatedExecutables(roundEnvironment: RoundEnvironment, annotatedClasses: Map<TypeElement, StorIOContentResolverTypeMeta>) {
val elementsAnnotatedWithStorIOContentResolverCreator = roundEnvironment.getElementsAnnotatedWith(StorIOContentResolverCreator::class.java)
elementsAnnotatedWithStorIOContentResolverCreator.forEach { element ->
val executableElement = element as ExecutableElement
validateAnnotatedExecutable(executableElement)
val creatorMeta = StorIOContentResolverCreatorMeta(executableElement.enclosingElement, executableElement,
executableElement.getAnnotation(StorIOContentResolverCreator::class.java))
annotatedClasses[creatorMeta.enclosingElement]?.let { typeMeta ->
// Put meta creator info.
// If class already contains another creator -> throw exception.
if (typeMeta.creator == null) {
typeMeta.creator = executableElement
} else {
throw ProcessingException(executableElement, "Only one creator method or constructor is allowed: ${executableElement.enclosingElement.simpleName}")
}
}
}
}
override fun validateAnnotatedClassesAndColumns(annotatedClasses: Map<TypeElement, StorIOContentResolverTypeMeta>) {
// check that each annotated class has columns with at least one key column
annotatedClasses.forEach { (key, typeMeta) ->
if (typeMeta.columns.isEmpty()) {
throw ProcessingException(key, "Class marked with ${StorIOContentResolverType::class.java.simpleName} annotation should have at least one field or method" +
" marked with ${StorIOContentResolverColumn::class.java.simpleName} annotation: ${typeMeta.simpleName}")
}
val hasAtLeastOneKeyColumn = typeMeta.columns.values.any { it.storIOColumn.key }
if (!hasAtLeastOneKeyColumn) {
throw ProcessingException(key, "Class marked with ${StorIOContentResolverType::class.java.simpleName} annotation should have at least one KEY field or method" +
" marked with ${StorIOContentResolverColumn::class.java.simpleName} annotation: ${typeMeta.simpleName}")
}
if (typeMeta.needsCreator && typeMeta.creator == null) {
throw ProcessingException(key, "Class marked with ${StorIOContentResolverType::class.java.simpleName} annotation needs factory method or constructor" +
" marked with ${StorIOContentResolverCreator::class.java.simpleName} annotation: ${typeMeta.simpleName}")
}
if (typeMeta.needsCreator) {
if (typeMeta.creator == null) {
throw ProcessingException(key, "Class marked with ${StorIOContentResolverType::class.java.simpleName} annotation needs factory method or constructor marked with" +
" ${StorIOContentResolverCreator::class.java.simpleName} annotation: ${typeMeta.simpleName}")
}
val params = typeMeta.creator!!.parameters.map { it.simpleName.toString() }
val resolvesParams = typeMeta.columns.values.all { it.realElementName in params }
if (params.size != typeMeta.columns.size || !resolvesParams) {
throw ProcessingException(key, "Class marked with ${StorIOContentResolverType::class.java.simpleName} annotation needs factory method or constructor marked with" +
" ${StorIOContentResolverCreator::class.java.simpleName} annotation with parameters matching ${typeMeta.simpleName} columns")
}
}
}
}
override val typeAnnotationClass: Class<out Annotation>
get() = StorIOContentResolverType::class.java
override val columnAnnotationClass: Class<out Annotation>
get() = StorIOContentResolverColumn::class.java
override val creatorAnnotationClass: Class<out Annotation>
get() = StorIOContentResolverCreator::class.java
override fun createPutResolver(): Generator<StorIOContentResolverTypeMeta> = PutResolverGenerator
override fun createGetResolver(): Generator<StorIOContentResolverTypeMeta> = GetResolverGenerator
override fun createDeleteResolver(): Generator<StorIOContentResolverTypeMeta> = DeleteResolverGenerator
override fun createMapping(): Generator<StorIOContentResolverTypeMeta> = MappingGenerator
override fun createTableGenerator(): Generator<StorIOContentResolverTypeMeta>? = null
}
|
apache-2.0
|
8d1e5f8088b9e79cd1057adbac558dfc
| 52.424242 | 183 | 0.709991 | 5.983454 | false | false | false | false |
bg1bgst333/Sample
|
kotlin/var/var/src/var/var.kt
|
1
|
196
|
fun main(args: Array<String>){
var a: Int
a = 10
println(a)
var b: Int = 20
println(b)
var c = 30
println(c)
a = 100
b = 200
c = 300
println(a)
println(b)
println(c)
}
|
mit
|
5f931e8050dd27810499de07d7a5fd82
| 12 | 31 | 0.551546 | 2.519481 | false | false | false | false |
ChristopherGittner/OSMBugs
|
app/src/main/java/org/gittner/osmbugs/osmnotes/OsmNotesLoginActivity.kt
|
1
|
2902
|
package org.gittner.osmbugs.osmnotes
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.github.scribejava.core.model.OAuth1RequestToken
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.gittner.osmbugs.R
import org.gittner.osmbugs.statics.Settings
import org.koin.android.ext.android.inject
class OsmNotesLoginActivity : AppCompatActivity(R.layout.activity_osm_notes_login) {
private val mApi: OsmNotesApi by inject()
private val mSettings = Settings.getInstance()
companion object {
private var lastRequestToken: OAuth1RequestToken? = null
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (intent.toUri(0).startsWith(OsmNotesApi.AUTH_CALLBACK_URL, false)) {
authDone(intent)
} else {
login()
}
}
// Called when the Activity is started from within the App to open the Login URL
private fun login() {
GlobalScope.launch(Dispatchers.Main) {
try {
lastRequestToken = mApi.getRequestToken()
val requestUrl = mApi.getRequestUrl(lastRequestToken!!)
startActivity(Intent(Intent.ACTION_VIEW).setData(Uri.parse(requestUrl)))
} catch (err: Exception) {
val msg = getString(R.string.login_failed_msg).format(err.message)
Toast.makeText(this@OsmNotesLoginActivity, msg, Toast.LENGTH_LONG).show()
setResult(Activity.RESULT_CANCELED)
finish()
}
}
}
// Called when the user has granted Access
private fun authDone(intent: Intent) {
GlobalScope.launch(Dispatchers.Main) {
try {
val requestToken = lastRequestToken ?: throw Exception("Request Token not yet set")
val verifier = intent.data?.getQueryParameter(OsmNotesApi.AUTH_VERIFIER_PARAM) ?: throw Exception(getString(R.string.login_failed_no_verifier))
val accessToken = mApi.getAccessToken(requestToken, verifier)
mSettings.OsmNotes.Token = accessToken.token
mSettings.OsmNotes.ConsumerSecret = accessToken.tokenSecret
Toast.makeText(this@OsmNotesLoginActivity, R.string.login_succeed, Toast.LENGTH_LONG).show()
setResult(Activity.RESULT_OK)
finish()
} catch (err: Exception) {
val msg = getString(R.string.login_failed_msg).format(err.message)
Toast.makeText(this@OsmNotesLoginActivity, msg, Toast.LENGTH_LONG).show()
setResult(Activity.RESULT_CANCELED)
finish()
}
}
}
}
|
mit
|
f7e76976c49c1496d2026a89cbd4bf86
| 35.275 | 159 | 0.658167 | 4.718699 | false | false | false | false |
micolous/metrodroid
|
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/chilebip/ChileBipTransitData.kt
|
1
|
7612
|
/*
* ChileBipTransitData.kt
*
* Copyright 2019 Google
*
* 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 au.id.micolous.metrodroid.transit.chilebip
import au.id.micolous.metrodroid.card.CardType
import au.id.micolous.metrodroid.card.classic.ClassicCard
import au.id.micolous.metrodroid.card.classic.ClassicCardTransitFactory
import au.id.micolous.metrodroid.card.classic.ClassicSector
import au.id.micolous.metrodroid.multi.Parcelize
import au.id.micolous.metrodroid.multi.R
import au.id.micolous.metrodroid.time.MetroTimeZone
import au.id.micolous.metrodroid.time.Timestamp
import au.id.micolous.metrodroid.time.TimestampFull
import au.id.micolous.metrodroid.transit.*
import au.id.micolous.metrodroid.ui.ListItem
import au.id.micolous.metrodroid.util.*
import kotlin.experimental.and
private const val NAME = "bip!"
private val CARD_INFO = CardInfo(
name = NAME,
locationId = R.string.location_santiago_chile,
imageId = R.drawable.chilebip,
cardType = CardType.MifareClassic,
region = TransitRegion.CHILE,
keysRequired = true, keyBundle = "chilebip")
private fun formatSerial(serial: Long) = serial.toString()
private fun getSerial(card: ClassicCard) = card[0,1].data.byteArrayToLongReversed(4, 4)
private fun parseTimestamp(raw: ImmutableByteArray): TimestampFull? {
return TimestampFull(MetroTimeZone.SANTIAGO_CHILE,
raw.getBitsFromBufferLeBits(15, 5) + 2000,
raw.getBitsFromBufferLeBits(11, 4) - 1,
raw.getBitsFromBufferLeBits(6, 5),
raw.getBitsFromBufferLeBits(20, 5),
raw.getBitsFromBufferLeBits(25, 6),
raw.getBitsFromBufferLeBits(31, 6)
)
}
@Parcelize
data class ChileBipTrip internal constructor(private val mFare: Int,
override val startTimestamp: TimestampFull?,
private val mType: Int,
private val mA: Int,
private val mB: Int,
private val mD: Int,
private val mE: Int,
private val mHash: Byte): Trip() {
override val mode: Mode
get() = when (mType) {
0x45 -> Mode.METRO
0x46 -> Mode.BUS
else -> Mode.OTHER
}
override val fare: TransitCurrency?
get() = TransitCurrency.CLP(mFare)
override fun getRawFields(level: TransitData.RawLevel): String? = "type=${mType.hexString}/A=${mA.hexString}/B=${mB.hexString}/D=${mD.hexString}/E=${mE.hexString}"
companion object {
fun parse(raw: ImmutableByteArray): ChileBipTrip? {
if (raw.sliceOffLen(1, 14).isAllZero())
return null
return ChileBipTrip(
mType = raw[8].toInt(),
startTimestamp = parseTimestamp(raw),
mA = raw.getBitsFromBufferLeBits(0, 6),
mB = raw.getBitsFromBufferLeBits(37, 27),
mD = raw.getBitsFromBufferLeBits(70, 10),
mE = raw.getBitsFromBufferLeBits(98, 22),
mHash = raw[15],
mFare = raw.getBitsFromBufferLeBits(82, 16))
}
}
}
@Parcelize
data class ChileBipRefill internal constructor(
private val mFare: Int, override val startTimestamp: Timestamp?,
private val mA: Int,
private val mB: Int,
private val mD: Int,
private val mE: Int,
private val mHash: Byte): Trip() {
override val mode: Mode
get() = Mode.TICKET_MACHINE
override val fare: TransitCurrency?
get() = TransitCurrency.CLP(-mFare)
override fun getRawFields(level: TransitData.RawLevel): String? = "A=${mA.hexString}/B=${mB.hexString}/D=${mD.hexString}/E=${mE.hexString}"
companion object {
fun parse (raw: ImmutableByteArray): ChileBipRefill? {
if (raw.sliceOffLen(1, 14).isAllZero())
return null
return ChileBipRefill(mFare = raw.getBitsFromBufferLeBits(74, 16),
mA = raw.getBitsFromBufferLeBits(0, 6),
mB = raw.getBitsFromBufferLeBits(37, 19),
mD = raw.getBitsFromBufferLeBits(56, 18),
mE = raw.getBitsFromBufferLeBits(90, 30),
mHash = raw[15],
startTimestamp = parseTimestamp(raw)
)
}
}
}
@Parcelize
data class ChileBipTransitData(private val mSerial: Long,
private val mBalance: Int,
override val trips: List<Trip>?,
private val mHolderId: Int,
private val mHolderName: String?) : TransitData() {
override val serialNumber get() = formatSerial(mSerial)
override val cardName get() = NAME
override val balance get() = TransitCurrency.CLP(mBalance)
override val info: List<ListItem>?
get() = listOfNotNull(
ListItem(R.string.card_type, if (mHolderId == 0) R.string.card_type_anonymous else R.string.card_type_personal),
(mHolderName != null && !Preferences.hideCardNumbers).ifTrue {
ListItem(R.string.card_holders_name, mHolderName)
},
(mHolderId != 0 && !Preferences.hideCardNumbers).ifTrue {
ListItem(R.string.card_holders_id, mHolderId.toString())
}
)
}
object ChileBipTransitFactory : ClassicCardTransitFactory {
override val allCards get() = listOf(CARD_INFO)
override fun parseTransitIdentity(card: ClassicCard) = TransitIdentity(
NAME, formatSerial(getSerial(card)))
override fun parseTransitData(card: ClassicCard): ChileBipTransitData {
val balanceBlock = card[8,1].data
val balance = balanceBlock.byteArrayToIntReversed(0, 3). let {
if (balanceBlock[3] and 0x7f != 0.toByte())
-it
else
it
}
val nameBlock = card[3, 0].data
val holderName = (nameBlock[14] != 0.toByte()).ifTrue { nameBlock.sliceOffLen(1, 14).reverseBuffer().readASCII() }
return ChileBipTransitData(
mSerial = getSerial(card),
mBalance = balance,
mHolderName = holderName,
mHolderId = card[3, 1].data.byteArrayToIntReversed(3, 4),
trips = (0..2).mapNotNull { ChileBipTrip.parse(card[11, it].data) } +
(0..2).mapNotNull { ChileBipRefill.parse(card[10, it].data) }
)
}
override fun earlyCheck(sectors: List<ClassicSector>) =
HashUtils.checkKeyHash(sectors[0], "chilebip",
"201d3ae5a9e52edd4e8efbfb1e75b42c", "23f0d2cfb56e189553c46af1e2ff3faf") >= 0
override val earlySectors get() = 1
}
|
gpl-3.0
|
d4aaf16ffd8bfb4fbeb5450431e68319
| 40.145946 | 167 | 0.606805 | 4.498818 | false | false | false | false |
li-yu/Huahui-Android
|
app/src/main/java/com/liyu/huahui/utils/Player.kt
|
1
|
1542
|
package com.liyu.huahui.utils
import android.media.MediaPlayer
/**
* Updated by ultranity on 2020/9/20.
* Created by liyu on 2017/3/3.
*/
class Player private constructor() {
companion object {
private val monitor = Any()
private var mediaPlayer: MediaPlayer? = MediaPlayer()
private var player: Player? = null
@JvmStatic
val instance: Player?
get() {
if (player == null) {
synchronized(monitor) { player = Player() }
}
return player
}
}
fun play(url: String?) {
try {
if (mediaPlayer!!.isPlaying) {
stop()
}
mediaPlayer!!.reset()
mediaPlayer!!.setDataSource(url)
mediaPlayer!!.prepare()
mediaPlayer!!.setOnPreparedListener { mediaPlayer -> mediaPlayer.start() }
} catch (e: Exception) {
e.printStackTrace()
}
}
fun pause() {
if (mediaPlayer != null && mediaPlayer!!.isPlaying) {
mediaPlayer!!.pause()
}
}
private fun stop() {
if (mediaPlayer != null) {
mediaPlayer!!.stop()
try {
mediaPlayer!!.prepare()
} catch (e: Exception) {
e.printStackTrace()
}
}
}
fun destroy() {
if (mediaPlayer != null) {
mediaPlayer!!.stop()
mediaPlayer!!.release()
}
player = null
}
}
|
apache-2.0
|
c54a1264f90bbb62e3aa4902c9c4cdb7
| 23.109375 | 86 | 0.48249 | 5.039216 | false | false | false | false |
dakshsrivastava/Loglr
|
Loglr/src/main/java/com/tumblr/loglr/TaskRetrieveAccessToken.kt
|
2
|
5978
|
package com.tumblr.loglr
import android.app.Dialog
import android.content.Context
import android.os.AsyncTask
import android.text.TextUtils
import android.util.Log
import com.tumblr.loglr.Exceptions.LoglrLoginException
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider
import oauth.signpost.exception.OAuthCommunicationException
import oauth.signpost.exception.OAuthExpectationFailedException
import oauth.signpost.exception.OAuthMessageSignerException
import oauth.signpost.exception.OAuthNotAuthorizedException
class TaskRetrieveAccessToken: AsyncTask<Void, RuntimeException, LoginResult?>() {
/**
* The OAuth provider
*/
private var commonsHttpOAuthProvider: CommonsHttpOAuthProvider? = null
/**
* OAuth Consumer
*/
private var commonsHttpOAuthConsumer: CommonsHttpOAuthConsumer? = null
/**
* variables to hold verifier retrieved from Tumblr
*/
private var strOAuthVerifier: String? = null
/**
* Context of the calling activity
*/
private var context: Context? = null
/**
* A loading Dialog to display to user if passed by developer
*/
private var loadingDialog: Dialog? = null
/**
* Set the context to show progressBars and stuff
* @param context
*/
internal fun setContext(context: Context?) {
this.context = context
}
/**
* Accept Loading dialog passed on by the developer. Null in case no Dialog was passed
* @param loadingDialog Loading Dialog to display to user
*/
internal fun setLoadingDialog(loadingDialog: Dialog?) {
this.loadingDialog = loadingDialog
}
/**
* Set the OAuthConsumer
* @param OAuthConsumer TheOAuthConsumer to which tokens will be applied
*/
internal fun setOAuthConsumer(OAuthConsumer: CommonsHttpOAuthConsumer?) {
this.commonsHttpOAuthConsumer = OAuthConsumer
}
/**
* Set the OAuthProvider
* @param OAuthProvider The OAuthProvider which makes the request for tokens
*/
internal fun setOAuthProvider(OAuthProvider: CommonsHttpOAuthProvider?) {
this.commonsHttpOAuthProvider = OAuthProvider
}
/**
* Set the OAuthVerifier
* @param OAuthVerifier The OAuthVerifier token which is used as a param to retrieve access tokens
*/
fun setOAuthVerifier(OAuthVerifier: String) {
this.strOAuthVerifier = OAuthVerifier
}
override fun onPreExecute() {
super.onPreExecute()
//If the developer a loading dialog, show that instead of default.
loadingDialog?.show()
}
override fun doInBackground(vararg params: Void?): LoginResult? {
//Instantiate a new LoginResult object which will store the Consumer key and secret key
//to be returned to the
val loginResult: LoginResult = LoginResult()
try {
//Queries the service provider for access tokens. The method does not return anything.
//It stores the OAuthToken & OAuthToken secret in the commonsHttpOAuthConsumer object.
commonsHttpOAuthProvider?.retrieveAccessToken(commonsHttpOAuthConsumer, strOAuthVerifier)
//Check if tokens were received. If Yes, save them to SharedPreferences for later use.
if(!TextUtils.isEmpty(commonsHttpOAuthConsumer?.token)) {
//Set the consumer key token in the LoginResult object
loginResult.setStrOAuthToken(commonsHttpOAuthConsumer?.token!!)
Log.i(TAG, "OAuthToken : " + loginResult.getOAuthToken())
}
if(!TextUtils.isEmpty(commonsHttpOAuthConsumer?.tokenSecret)) {
//Set the Secret consumer key token in the LoginResult object
loginResult.setStrOAuthTokenSecret(commonsHttpOAuthConsumer?.tokenSecret!!)
Log.i(TAG, "OAuthSecretToken : " + loginResult.strOAuthTokenSecret)
}
//Return the login result with ConsumerKey and ConsumerSecret Key
return loginResult
} catch (e: OAuthCommunicationException) {
e.printStackTrace()
publishProgress(LoglrLoginException(e.responseBody))
return null
} catch (e: OAuthExpectationFailedException) {
e.printStackTrace()
publishProgress(LoglrLoginException(e.message!!))
return null
} catch (e: OAuthNotAuthorizedException) {
e.printStackTrace()
publishProgress(LoglrLoginException(e.responseBody))
return null
} catch (e: OAuthMessageSignerException) {
e.printStackTrace()
publishProgress(LoglrLoginException(e.message!!))
return null
}
}
override fun onProgressUpdate(vararg values: RuntimeException?) {
super.onProgressUpdate(*values)
if(values.isNotEmpty()) {
val exception : RuntimeException = values[0]!!
if(Loglr.exceptionHandler != null)
Loglr.exceptionHandler?.onLoginFailed(exception)
else
finish()
}
}
override fun onPostExecute(result: LoginResult?) {
super.onPostExecute(result)
loadingDialog?.dismiss()
//Check if tokens were retrieved. If yes, Set result as successful and finish activity
//otherwise, set as failed.
if(result != null) {
//Send firebase event for successful login alongwith bundle of method
Loglr.loginListener?.onLoginSuccessful(result)
}
finish()
}
/**
* A method to finish the calling activity
*/
private fun finish() {
val loglrActivity: LoglrActivity = context as LoglrActivity
loglrActivity.finish()
}
companion object {
/**
* Tag for logging
*/
private val TAG: String = TaskRetrieveAccessToken::class.java.simpleName
}
}
|
mit
|
f84eced3cd00d94ebaa0bd7a375a2a13
| 34.802395 | 102 | 0.66728 | 5.424682 | false | false | false | false |
google/accompanist
|
sample/src/main/java/com/google/accompanist/sample/pager/HorizontalPagerTabsSample.kt
|
1
|
4892
|
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.accompanist.sample.pager
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Card
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Scaffold
import androidx.compose.material.ScrollableTabRow
import androidx.compose.material.Surface
import androidx.compose.material.Tab
import androidx.compose.material.TabRowDefaults
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.google.accompanist.pager.ExperimentalPagerApi
import com.google.accompanist.pager.HorizontalPager
import com.google.accompanist.pager.pagerTabIndicatorOffset
import com.google.accompanist.pager.rememberPagerState
import com.google.accompanist.sample.AccompanistSampleTheme
import com.google.accompanist.sample.R
import kotlinx.coroutines.launch
class HorizontalPagerTabsSample : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
AccompanistSampleTheme {
Surface {
Sample()
}
}
}
}
}
@OptIn(ExperimentalPagerApi::class)
@Composable
private fun Sample() {
Scaffold(
topBar = {
TopAppBar(
title = { Text(stringResource(R.string.horiz_pager_title_tabs)) },
backgroundColor = MaterialTheme.colors.surface,
)
},
modifier = Modifier.fillMaxSize()
) { padding ->
val pages = remember {
listOf("Home", "Shows", "Movies", "Books", "Really long movies", "Short audiobooks")
}
Column(Modifier.fillMaxSize().padding(padding)) {
val coroutineScope = rememberCoroutineScope()
// Remember a PagerState
val pagerState = rememberPagerState()
ScrollableTabRow(
// Our selected tab is our current page
selectedTabIndex = pagerState.currentPage,
indicator = { tabPositions ->
TabRowDefaults.Indicator(
Modifier.pagerTabIndicatorOffset(pagerState, tabPositions)
)
}
) {
// Add tabs for all of our pages
pages.forEachIndexed { index, title ->
Tab(
text = { Text(title) },
selected = pagerState.currentPage == index,
onClick = {
// Animate to the selected page when clicked
coroutineScope.launch {
pagerState.animateScrollToPage(index)
}
}
)
}
}
HorizontalPager(
count = pages.size,
state = pagerState,
// Add 16.dp padding to 'center' the pages
contentPadding = PaddingValues(16.dp),
modifier = Modifier
.weight(1f)
.fillMaxWidth()
) { page ->
// Our content for each page
Card {
Box(Modifier.fillMaxSize()) {
Text(
text = "Page: ${pages[page]}",
style = MaterialTheme.typography.h4,
modifier = Modifier.align(Alignment.Center)
)
}
}
}
}
}
}
|
apache-2.0
|
3a69de010d768452d442c8295a36a691
| 35.507463 | 96 | 0.614473 | 5.346448 | false | false | false | false |
carrotengineer/Warren
|
src/main/kotlin/engineer/carrot/warren/warren/ssl/SHA256SignaturesX509TrustManager.kt
|
2
|
2451
|
package engineer.carrot.warren.warren.ssl
import engineer.carrot.warren.warren.loggerFor
import java.math.BigInteger
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.security.cert.CertificateException
import java.security.cert.X509Certificate
import javax.net.ssl.X509TrustManager
internal class SHA256SignaturesX509TrustManager(val fingerprints: Set<String>) : X509TrustManager {
private val LOGGER = loggerFor<SHA256SignaturesX509TrustManager>()
@Throws(CertificateException::class)
override fun checkClientTrusted(x509Certificates: Array<X509Certificate>, s: String) {
throw CertificateException("Forcible Trust Manager is not made to verify client certificates")
}
@Throws(CertificateException::class)
override fun checkServerTrusted(x509Certificates: Array<X509Certificate>, s: String) {
var sha256Digest = try {
MessageDigest.getInstance("SHA-256")
} catch (e: NoSuchAlgorithmException) {
LOGGER.error("Couldn't get SHA256 instance: {}", e)
throw CertificateException("Couldn't check server trust because SHA256 digest instance is missing!")
}
var allTrusted = true
val trustedCertificates = mutableSetOf<String>()
val untrustedCertificates = mutableSetOf<String>()
LOGGER.warn("Checking presented certificates against forcibly trusted: ")
for (certificate in x509Certificates) {
certificate.checkValidity()
sha256Digest.update(certificate.encoded)
val sha256DigestString = String.format("%064x", BigInteger(1, sha256Digest.digest()));
if (this.fingerprints.contains(sha256DigestString)) {
LOGGER.warn(" {} IS trusted", sha256DigestString)
trustedCertificates.add(sha256DigestString)
} else {
LOGGER.warn(" {} IS NOT trusted", sha256DigestString)
untrustedCertificates.add(sha256DigestString)
allTrusted = false
}
}
if (!allTrusted) {
throw CertificateException("Certificates were presented with SHA256 signatures that we DO NOT trust! $untrustedCertificates")
} else {
LOGGER.warn("All presented certificates were forcibly trusted by us")
}
}
override fun getAcceptedIssuers(): Array<X509Certificate> {
return emptyArray()
}
}
|
isc
|
12d2999b0d7ea4f1e63fab9a56955f20
| 38.532258 | 137 | 0.69237 | 5.10625 | false | false | false | false |
inorichi/mangafeed
|
app/src/main/java/eu/kanade/tachiyomi/extension/util/ExtensionInstaller.kt
|
2
|
9567
|
package eu.kanade.tachiyomi.extension.util
import android.app.DownloadManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.Uri
import android.os.Environment
import androidx.core.content.ContextCompat
import androidx.core.content.getSystemService
import androidx.core.net.toUri
import com.jakewharton.rxrelay.PublishRelay
import eu.kanade.tachiyomi.data.preference.PreferenceValues
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.extension.installer.Installer
import eu.kanade.tachiyomi.extension.model.Extension
import eu.kanade.tachiyomi.extension.model.InstallStep
import eu.kanade.tachiyomi.util.storage.getUriCompat
import eu.kanade.tachiyomi.util.system.logcat
import logcat.LogPriority
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import java.io.File
import java.util.concurrent.TimeUnit
/**
* The installer which installs, updates and uninstalls the extensions.
*
* @param context The application context.
*/
internal class ExtensionInstaller(private val context: Context) {
/**
* The system's download manager
*/
private val downloadManager = context.getSystemService<DownloadManager>()!!
/**
* The broadcast receiver which listens to download completion events.
*/
private val downloadReceiver = DownloadCompletionReceiver()
/**
* The currently requested downloads, with the package name (unique id) as key, and the id
* returned by the download manager.
*/
private val activeDownloads = hashMapOf<String, Long>()
/**
* Relay used to notify the installation step of every download.
*/
private val downloadsRelay = PublishRelay.create<Pair<Long, InstallStep>>()
private val installerPref = Injekt.get<PreferencesHelper>().extensionInstaller()
/**
* Adds the given extension to the downloads queue and returns an observable containing its
* step in the installation process.
*
* @param url The url of the apk.
* @param extension The extension to install.
*/
fun downloadAndInstall(url: String, extension: Extension) = Observable.defer {
val pkgName = extension.pkgName
val oldDownload = activeDownloads[pkgName]
if (oldDownload != null) {
deleteDownload(pkgName)
}
// Register the receiver after removing (and unregistering) the previous download
downloadReceiver.register()
val downloadUri = url.toUri()
val request = DownloadManager.Request(downloadUri)
.setTitle(extension.name)
.setMimeType(APK_MIME)
.setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, downloadUri.lastPathSegment)
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
val id = downloadManager.enqueue(request)
activeDownloads[pkgName] = id
downloadsRelay.filter { it.first == id }
.map { it.second }
// Poll download status
.mergeWith(pollStatus(id))
// Stop when the application is installed or errors
.takeUntil { it.isCompleted() }
// Always notify on main thread
.observeOn(AndroidSchedulers.mainThread())
// Always remove the download when unsubscribed
.doOnUnsubscribe { deleteDownload(pkgName) }
}
/**
* Returns an observable that polls the given download id for its status every second, as the
* manager doesn't have any notification system. It'll stop once the download finishes.
*
* @param id The id of the download to poll.
*/
private fun pollStatus(id: Long): Observable<InstallStep> {
val query = DownloadManager.Query().setFilterById(id)
return Observable.interval(0, 1, TimeUnit.SECONDS)
// Get the current download status
.map {
downloadManager.query(query).use { cursor ->
cursor.moveToFirst()
cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS))
}
}
// Ignore duplicate results
.distinctUntilChanged()
// Stop polling when the download fails or finishes
.takeUntil { it == DownloadManager.STATUS_SUCCESSFUL || it == DownloadManager.STATUS_FAILED }
// Map to our model
.flatMap { status ->
when (status) {
DownloadManager.STATUS_PENDING -> Observable.just(InstallStep.Pending)
DownloadManager.STATUS_RUNNING -> Observable.just(InstallStep.Downloading)
else -> Observable.empty()
}
}
}
/**
* Starts an intent to install the extension at the given uri.
*
* @param uri The uri of the extension to install.
*/
fun installApk(downloadId: Long, uri: Uri) {
when (val installer = installerPref.get()) {
PreferenceValues.ExtensionInstaller.LEGACY -> {
val intent = Intent(context, ExtensionInstallActivity::class.java)
.setDataAndType(uri, APK_MIME)
.putExtra(EXTRA_DOWNLOAD_ID, downloadId)
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_GRANT_READ_URI_PERMISSION)
context.startActivity(intent)
}
else -> {
val intent = ExtensionInstallService.getIntent(context, downloadId, uri, installer)
ContextCompat.startForegroundService(context, intent)
}
}
}
/**
* Cancels extension install and remove from download manager and installer.
*/
fun cancelInstall(pkgName: String) {
val downloadId = activeDownloads.remove(pkgName) ?: return
downloadManager.remove(downloadId)
Installer.cancelInstallQueue(context, downloadId)
}
/**
* Starts an intent to uninstall the extension by the given package name.
*
* @param pkgName The package name of the extension to uninstall
*/
fun uninstallApk(pkgName: String) {
val intent = Intent(Intent.ACTION_UNINSTALL_PACKAGE, "package:$pkgName".toUri())
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(intent)
}
/**
* Sets the step of the installation of an extension.
*
* @param downloadId The id of the download.
* @param step New install step.
*/
fun updateInstallStep(downloadId: Long, step: InstallStep) {
downloadsRelay.call(downloadId to step)
}
/**
* Deletes the download for the given package name.
*
* @param pkgName The package name of the download to delete.
*/
private fun deleteDownload(pkgName: String) {
val downloadId = activeDownloads.remove(pkgName)
if (downloadId != null) {
downloadManager.remove(downloadId)
}
if (activeDownloads.isEmpty()) {
downloadReceiver.unregister()
}
}
/**
* Receiver that listens to download status events.
*/
private inner class DownloadCompletionReceiver : BroadcastReceiver() {
/**
* Whether this receiver is currently registered.
*/
private var isRegistered = false
/**
* Registers this receiver if it's not already.
*/
fun register() {
if (isRegistered) return
isRegistered = true
val filter = IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)
context.registerReceiver(this, filter)
}
/**
* Unregisters this receiver if it's not already.
*/
fun unregister() {
if (!isRegistered) return
isRegistered = false
context.unregisterReceiver(this)
}
/**
* Called when a download event is received. It looks for the download in the current active
* downloads and notifies its installation step.
*/
override fun onReceive(context: Context, intent: Intent?) {
val id = intent?.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0) ?: return
// Avoid events for downloads we didn't request
if (id !in activeDownloads.values) return
val uri = downloadManager.getUriForDownloadedFile(id)
// Set next installation step
if (uri == null) {
logcat(LogPriority.ERROR) { "Couldn't locate downloaded APK" }
downloadsRelay.call(id to InstallStep.Error)
return
}
val query = DownloadManager.Query().setFilterById(id)
downloadManager.query(query).use { cursor ->
if (cursor.moveToFirst()) {
val localUri = cursor.getString(
cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_LOCAL_URI)
).removePrefix(FILE_SCHEME)
installApk(id, File(localUri).getUriCompat(context))
}
}
}
}
companion object {
const val APK_MIME = "application/vnd.android.package-archive"
const val EXTRA_DOWNLOAD_ID = "ExtensionInstaller.extra.DOWNLOAD_ID"
const val FILE_SCHEME = "file://"
}
}
|
apache-2.0
|
3a30dbdc20d9b2c9a41d86ee0d6342fc
| 34.966165 | 116 | 0.638758 | 5.138024 | false | false | false | false |
octarine-noise/BetterFoliage
|
src/main/kotlin/mods/octarinecore/client/resource/Utils.kt
|
1
|
5648
|
@file:JvmName("Utils")
package mods.octarinecore.client.resource
import mods.betterfoliage.loader.Refs
import mods.octarinecore.PI2
import mods.octarinecore.client.render.HSB
import mods.octarinecore.metaprog.reflectField
import mods.octarinecore.stripStart
import mods.octarinecore.tryDefault
import net.minecraft.client.Minecraft
import net.minecraft.client.renderer.block.model.ModelBlock
import net.minecraft.client.renderer.texture.TextureAtlasSprite
import net.minecraft.client.renderer.texture.TextureMap
import net.minecraft.client.resources.IResource
import net.minecraft.client.resources.IResourceManager
import net.minecraft.client.resources.SimpleReloadableResourceManager
import net.minecraft.util.ResourceLocation
import net.minecraftforge.client.model.IModel
import java.awt.image.BufferedImage
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.lang.Math.*
import javax.imageio.ImageIO
/** Concise getter for the Minecraft resource manager. */
val resourceManager: SimpleReloadableResourceManager get() =
Minecraft.getMinecraft().resourceManager as SimpleReloadableResourceManager
/** Append a string to the [ResourceLocation]'s path. */
operator fun ResourceLocation.plus(str: String) = ResourceLocation(namespace, path + str)
/** Index operator to get a resource. */
operator fun IResourceManager.get(domain: String, path: String): IResource? = get(ResourceLocation(domain, path))
/** Index operator to get a resource. */
operator fun IResourceManager.get(location: ResourceLocation): IResource? = tryDefault(null) { getResource(location) }
/** Index operator to get a texture sprite. */
operator fun TextureMap.get(name: String): TextureAtlasSprite? = getTextureExtry(ResourceLocation(name).toString())
operator fun TextureMap.get(res: ResourceLocation): TextureAtlasSprite? = getTextureExtry(res.toString())
/** Load an image resource. */
fun IResource.loadImage(): BufferedImage? = ImageIO.read(this.inputStream)
/** Get the lines of a text resource. */
fun IResource.getLines(): List<String> {
val result = arrayListOf<String>()
inputStream.bufferedReader().useLines { it.forEach { result.add(it) } }
return result
}
/** Index operator to get the RGB value of a pixel. */
operator fun BufferedImage.get(x: Int, y: Int) = this.getRGB(x, y)
/** Index operator to set the RGB value of a pixel. */
operator fun BufferedImage.set(x: Int, y: Int, value: Int) = this.setRGB(x, y, value)
/** Get an [InputStream] to an image object in PNG format. */
val BufferedImage.asStream: InputStream get() =
ByteArrayInputStream(ByteArrayOutputStream().let { ImageIO.write(this, "PNG", it); it.toByteArray() })
/**
* Calculate the average color of a texture.
*
* Only non-transparent pixels are considered. Averages are taken in the HSB color space (note: Hue is a circular average),
* and the result transformed back to the RGB color space.
*/
val TextureAtlasSprite.averageColor: Int? get() {
val locationNoDirs = ResourceLocation(iconName).stripStart("blocks/")
val locationWithDirs = ResourceLocation(locationNoDirs.namespace, "textures/blocks/%s.png".format(locationNoDirs.path))
val image = resourceManager[locationWithDirs]?.loadImage() ?: return null
var numOpaque = 0
var sumHueX = 0.0
var sumHueY = 0.0
var sumSaturation = 0.0f
var sumBrightness = 0.0f
for (x in 0..image.width - 1)
for (y in 0..image.height - 1) {
val pixel = image[x, y]
val alpha = (pixel shr 24) and 255
val hsb = HSB.fromColor(pixel)
if (alpha == 255) {
numOpaque++
sumHueX += cos((hsb.hue.toDouble() - 0.5) * PI2)
sumHueY += sin((hsb.hue.toDouble() - 0.5) * PI2)
sumSaturation += hsb.saturation
sumBrightness += hsb.brightness
}
}
// circular average - transform sum vector to polar angle
val avgHue = (atan2(sumHueY.toDouble(), sumHueX.toDouble()) / PI2 + 0.5).toFloat()
return HSB(avgHue, sumSaturation / numOpaque.toFloat(), sumBrightness / numOpaque.toFloat()).asColor
}
/**
* Get the actual location of a texture from the name of its [TextureAtlasSprite].
*/
fun textureLocation(iconName: String) = ResourceLocation(iconName).let {
if (it.path.startsWith("mcpatcher")) it
else ResourceLocation(it.namespace, "textures/${it.path}")
}
@Suppress("UNCHECKED_CAST")
val IModel.modelBlockAndLoc: List<Pair<ModelBlock, ResourceLocation>> get() {
if (Refs.VanillaModelWrapper.isInstance(this))
return listOf(Pair(Refs.model_VMW.get(this) as ModelBlock, Refs.location_VMW.get(this) as ResourceLocation))
else if (Refs.WeightedRandomModel.isInstance(this)) Refs.models_WRM.get(this)?.let {
return (it as List<IModel>).flatMap(IModel::modelBlockAndLoc)
}
else if (Refs.MultipartModel.isInstance(this)) Refs.partModels_MPM.get(this)?.let {
return (it as Map<Any, IModel>).flatMap { it.value.modelBlockAndLoc }
} else {
this::class.java.declaredFields.find { it.type.isInstance(IModel::class.java) }?.let { modelField ->
modelField.isAccessible = true
return (modelField.get(this) as IModel).modelBlockAndLoc
}
}
return listOf()
}
fun Pair<ModelBlock, ResourceLocation>.derivesFrom(targetLocation: ResourceLocation): Boolean {
if (second.stripStart("models/") == targetLocation) return true
if (first.parent != null && first.parentLocation != null)
return Pair(first.parent, first.parentLocation!!).derivesFrom(targetLocation)
return false
}
|
mit
|
25864e00b60a458991ecd65e457dfca1
| 43.472441 | 123 | 0.724858 | 4.063309 | false | false | false | false |
DemonWav/MinecraftDev
|
src/main/kotlin/com/demonwav/mcdev/error/IdeaITNProxy.kt
|
1
|
1627
|
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.error
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.application.ex.ApplicationInfoEx
import com.intellij.openapi.diagnostic.Attachment
import com.intellij.openapi.util.SystemInfo
object IdeaITNProxy {
fun getKeyValuePairs(
error: ErrorBean,
appInfo: ApplicationInfoEx,
namesInfo: ApplicationNamesInfo
): Pair<LinkedHashMap<String, String?>, List<Attachment>> {
val params = LinkedHashMap<String, String?>(21)
params["error.description"] = error.description
params["Plugin Name"] = error.pluginName
params["Plugin Version"] = error.pluginVersion
params["OS Name"] = SystemInfo.OS_NAME
params["Java Version"] = SystemInfo.JAVA_VERSION
params["Java VM Vendor"] = SystemInfo.JAVA_VENDOR
params["App Name"] = namesInfo.productName
params["App Full Name"] = namesInfo.fullProductName
params["App Version Name"] = appInfo.versionName
params["Is EAP"] = appInfo.isEAP.toString()
params["App Build"] = appInfo.build.asString()
params["App Version"] = appInfo.fullVersion
if (error.lastAction.isNullOrBlank()) {
params["Last Action"] = "None"
} else {
params["Last Action"] = error.lastAction
}
params["error.message"] = error.message
params["error.stacktrace"] = error.stackTrace
return params to error.attachments
}
}
|
mit
|
0e2a67ec09a02455bb4fbabcaa025b15
| 29.698113 | 63 | 0.665642 | 4.544693 | false | false | false | false |
jovr/imgui
|
core/src/main/kotlin/imgui/internal/api/focusScope.kt
|
2
|
1092
|
package imgui.internal.api
import imgui.ID
import imgui.api.g
// Focus Scope (WIP)
// This is generally used to identify a selection set (multiple of which may be in the same window), as selection
// patterns generally need to react (e.g. clear selection) when landing on an item of the set.
interface focusScope {
fun pushFocusScope(id: ID) { // TODO dsl
val window = g.currentWindow!!
g.focusScopeStack += window.dc.navFocusScopeIdCurrent
window.dc.navFocusScopeIdCurrent = id
}
fun popFocusScope() {
val window = g.currentWindow!!
assert(g.focusScopeStack.isNotEmpty()) { "Too many PopFocusScope() ?" }
window.dc.navFocusScopeIdCurrent = g.focusScopeStack.last()
g.focusScopeStack.pop()
}
/** Focus scope which is actually active
* ~GetFocusedFocusScope */
val focusedFocusScope: ID
get() = g.navFocusScopeId
/** Focus scope we are outputting into, set by PushFocusScope()
* ~GetFocusScopeID */
val focusScope: ID
get() = g.currentWindow!!.dc.navFocusScopeIdCurrent
}
|
mit
|
84e84caa82da8bcd02e130bd8f2e3ab4
| 32.121212 | 113 | 0.679487 | 4.216216 | false | false | false | false |
dbrant/apps-android-wikipedia
|
app/src/main/java/org/wikipedia/suggestededits/SuggestedEditsCardsItemFragment.kt
|
1
|
15830
|
package org.wikipedia.suggestededits
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.ViewGroup
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.schedulers.Schedulers
import org.wikipedia.R
import org.wikipedia.databinding.FragmentSuggestedEditsCardsItemBinding
import org.wikipedia.dataclient.Service
import org.wikipedia.dataclient.ServiceFactory
import org.wikipedia.dataclient.WikiSite
import org.wikipedia.descriptions.DescriptionEditActivity.Action.*
import org.wikipedia.page.Namespace
import org.wikipedia.page.PageTitle
import org.wikipedia.settings.Prefs
import org.wikipedia.suggestededits.provider.EditingSuggestionsProvider
import org.wikipedia.util.DateUtil
import org.wikipedia.util.FeedbackUtil
import org.wikipedia.util.L10nUtil.setConditionalLayoutDirection
import org.wikipedia.util.StringUtil
import org.wikipedia.util.log.L
import org.wikipedia.views.ImageZoomHelper
class SuggestedEditsCardsItemFragment : SuggestedEditsItemFragment() {
private var _binding: FragmentSuggestedEditsCardsItemBinding? = null
private val binding get() = _binding!!
var sourceSummaryForEdit: PageSummaryForEdit? = null
var targetSummaryForEdit: PageSummaryForEdit? = null
var addedContribution: String = ""
internal set
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
super.onCreateView(inflater, container, savedInstanceState)
_binding = FragmentSuggestedEditsCardsItemBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setConditionalLayoutDirection(binding.viewArticleContainer, parent().langFromCode)
binding.viewArticleImage.setOnClickListener {
if (Prefs.shouldShowImageZoomTooltip()) {
Prefs.setShouldShowImageZoomTooltip(false)
FeedbackUtil.showMessage(requireActivity(), R.string.suggested_edits_image_zoom_tooltip)
}
}
binding.cardItemErrorView.backClickListener = View.OnClickListener { requireActivity().finish() }
binding.cardItemErrorView.retryClickListener = View.OnClickListener {
binding.cardItemProgressBar.visibility = VISIBLE
getArticleWithMissingDescription()
}
updateContents()
if (sourceSummaryForEdit == null) {
getArticleWithMissingDescription()
}
binding.viewArticleContainer.setOnClickListener {
if (sourceSummaryForEdit != null) {
parent().onSelectPage()
}
}
showAddedContributionView(addedContribution)
}
override fun onDestroyView() {
_binding = null
super.onDestroyView()
}
private fun getArticleWithMissingDescription() {
when (parent().action) {
TRANSLATE_DESCRIPTION -> {
disposables.add(EditingSuggestionsProvider.getNextArticleWithMissingDescription(WikiSite.forLanguageCode(parent().langFromCode), parent().langToCode, true)
.map {
if (it.first.description.isNullOrEmpty()) {
throw EditingSuggestionsProvider.ListEmptyException()
}
it
}
.retry { t: Throwable -> t is EditingSuggestionsProvider.ListEmptyException }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ pair ->
val source = pair.first
val target = pair.second
sourceSummaryForEdit = PageSummaryForEdit(
source.apiTitle,
source.lang,
source.getPageTitle(WikiSite.forLanguageCode(parent().langFromCode)),
source.displayTitle,
source.description,
source.thumbnailUrl,
source.extract,
source.extractHtml
)
targetSummaryForEdit = PageSummaryForEdit(
target.apiTitle,
target.lang,
target.getPageTitle(WikiSite.forLanguageCode(parent().langToCode)),
target.displayTitle,
target.description,
target.thumbnailUrl,
target.extract,
target.extractHtml
)
updateContents()
}, { this.setErrorState(it) })!!)
}
ADD_CAPTION -> {
disposables.add(EditingSuggestionsProvider.getNextImageWithMissingCaption(parent().langFromCode)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.flatMap { title ->
ServiceFactory.get(WikiSite(Service.COMMONS_URL)).getImageInfo(title, parent().langFromCode)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
}
.subscribe({ response ->
val page = response.query()!!.pages()!![0]
if (page.imageInfo() != null) {
val imageInfo = page.imageInfo()!!
val title = if (imageInfo.commonsUrl.isEmpty()) page.title() else WikiSite(Service.COMMONS_URL).titleForUri(Uri.parse(imageInfo.commonsUrl)).prefixedText
sourceSummaryForEdit = PageSummaryForEdit(
title,
parent().langFromCode,
PageTitle(
Namespace.FILE.name,
StringUtil.removeNamespace(title),
null,
imageInfo.thumbUrl,
WikiSite.forLanguageCode(parent().langFromCode)
),
StringUtil.removeHTMLTags(title),
imageInfo.metadata!!.imageDescription(),
imageInfo.thumbUrl,
null,
null,
imageInfo.timestamp,
imageInfo.user,
imageInfo.metadata
)
}
updateContents()
}, { this.setErrorState(it) })!!)
}
TRANSLATE_CAPTION -> {
var fileCaption: String? = null
disposables.add(EditingSuggestionsProvider.getNextImageWithMissingCaption(parent().langFromCode, parent().langToCode)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.flatMap { pair ->
fileCaption = pair.first
ServiceFactory.get(WikiSite(Service.COMMONS_URL)).getImageInfo(pair.second, parent().langFromCode)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
}
.subscribe({ response ->
val page = response.query()!!.pages()!![0]
if (page.imageInfo() != null) {
val imageInfo = page.imageInfo()!!
val title = if (imageInfo.commonsUrl.isEmpty()) page.title() else WikiSite(Service.COMMONS_URL).titleForUri(Uri.parse(imageInfo.commonsUrl)).prefixedText
sourceSummaryForEdit = PageSummaryForEdit(
title,
parent().langFromCode,
PageTitle(
Namespace.FILE.name,
StringUtil.removeNamespace(title),
null,
imageInfo.thumbUrl,
WikiSite.forLanguageCode(parent().langFromCode)
),
StringUtil.removeHTMLTags(title),
fileCaption,
imageInfo.thumbUrl,
null,
null,
imageInfo.timestamp,
imageInfo.user,
imageInfo.metadata
)
targetSummaryForEdit = sourceSummaryForEdit!!.copy(
description = null,
lang = parent().langToCode,
pageTitle = PageTitle(
Namespace.FILE.name,
StringUtil.removeNamespace(title),
null,
imageInfo.thumbUrl,
WikiSite.forLanguageCode(parent().langToCode)
)
)
}
updateContents()
}, { this.setErrorState(it) })!!)
}
else -> {
disposables.add(EditingSuggestionsProvider.getNextArticleWithMissingDescription(WikiSite.forLanguageCode(parent().langFromCode))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ pageSummary ->
sourceSummaryForEdit = PageSummaryForEdit(
pageSummary.apiTitle,
parent().langFromCode,
pageSummary.getPageTitle(WikiSite.forLanguageCode(parent().langFromCode)),
pageSummary.displayTitle,
pageSummary.description,
pageSummary.thumbnailUrl,
pageSummary.extract,
pageSummary.extractHtml
)
updateContents()
}, { this.setErrorState(it) }))
}
}
}
fun showAddedContributionView(addedContribution: String?) {
if (!addedContribution.isNullOrEmpty()) {
binding.viewArticleSubtitleContainer.visibility = VISIBLE
binding.viewArticleSubtitle.text = addedContribution
this.addedContribution = addedContribution
}
}
private fun setErrorState(t: Throwable) {
L.e(t)
binding.cardItemErrorView.setError(t)
binding.cardItemErrorView.visibility = VISIBLE
binding.cardItemProgressBar.visibility = GONE
binding.cardItemContainer.visibility = GONE
}
private fun updateContents() {
val sourceAvailable = sourceSummaryForEdit != null
binding.cardItemErrorView.visibility = GONE
binding.cardItemContainer.visibility = if (sourceAvailable) VISIBLE else GONE
binding.cardItemProgressBar.visibility = if (sourceAvailable) GONE else VISIBLE
if (!sourceAvailable) {
return
}
ImageZoomHelper.setViewZoomable(binding.viewArticleImage)
if (parent().action == ADD_DESCRIPTION || parent().action == TRANSLATE_DESCRIPTION) {
updateDescriptionContents()
} else {
updateCaptionContents()
}
}
private fun updateDescriptionContents() {
binding.viewArticleTitle.text = StringUtil.fromHtml(sourceSummaryForEdit!!.displayTitle)
binding.viewArticleTitle.visibility = VISIBLE
if (parent().action == TRANSLATE_DESCRIPTION) {
binding.viewArticleSubtitleContainer.visibility = VISIBLE
binding.viewArticleSubtitle.text = if (addedContribution.isNotEmpty()) addedContribution else sourceSummaryForEdit!!.description
}
binding.viewImageSummaryContainer.visibility = GONE
binding.viewArticleExtract.text = StringUtil.removeHTMLTags(sourceSummaryForEdit!!.extractHtml!!)
if (sourceSummaryForEdit!!.thumbnailUrl.isNullOrBlank()) {
binding.viewArticleImagePlaceholder.visibility = GONE
} else {
binding.viewArticleImagePlaceholder.visibility = VISIBLE
binding.viewArticleImage.loadImage(Uri.parse(sourceSummaryForEdit!!.getPreferredSizeThumbnailUrl()))
}
}
private fun updateCaptionContents() {
binding.viewArticleTitle.visibility = GONE
binding.viewArticleSubtitleContainer.visibility = VISIBLE
val descriptionText = when {
addedContribution.isNotEmpty() -> addedContribution
sourceSummaryForEdit!!.description!!.isNotEmpty() -> sourceSummaryForEdit!!.description!!
else -> getString(R.string.suggested_edits_no_description)
}
binding.viewArticleSubtitle.text = StringUtil.strip(StringUtil.removeHTMLTags(descriptionText))
binding.viewImageFileName.setDetailText(StringUtil.removeNamespace(sourceSummaryForEdit!!.displayTitle!!))
if (!sourceSummaryForEdit!!.user.isNullOrEmpty()) {
binding.viewImageArtist.setTitleText(getString(R.string.suggested_edits_image_caption_summary_title_author))
binding.viewImageArtist.setDetailText(sourceSummaryForEdit!!.user)
} else {
binding.viewImageArtist.setTitleText(StringUtil.removeHTMLTags(sourceSummaryForEdit!!.metadata!!.artist()))
}
binding.viewImageDate.setDetailText(DateUtil.getReadingListsLastSyncDateString(sourceSummaryForEdit!!.timestamp!!))
binding.viewImageSource.setDetailText(sourceSummaryForEdit!!.metadata!!.credit())
binding.viewImageLicense.setDetailText(sourceSummaryForEdit!!.metadata!!.licenseShortName())
binding.viewArticleImage.loadImage(Uri.parse(sourceSummaryForEdit!!.getPreferredSizeThumbnailUrl()))
binding.viewArticleExtract.visibility = GONE
}
companion object {
fun newInstance(): SuggestedEditsItemFragment {
return SuggestedEditsCardsItemFragment()
}
}
}
|
apache-2.0
|
079f681dfe3b060e7df331e2d2189579
| 48.623824 | 185 | 0.533354 | 7.185656 | false | false | false | false |
Frederikam/FredBoat
|
FredBoat/src/main/java/fredboat/util/DiscordUtil.kt
|
1
|
2604
|
/*
* MIT License
*
* Copyright (c) 2017 Frederik Ar. Mikkelsen
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package fredboat.util
import fredboat.config.property.AppConfig
import fredboat.sentinel.Member
import fredboat.shared.constant.BotConstants
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
object DiscordUtil {
fun getHighestRolePosition(member: Member): Mono<Int> {
if (member.roles.isEmpty()) return Mono.just(-1) // @ everyone role
return Mono.create { sink ->
Flux.merge(member.roles.map { it.info })
.reduce { a, b ->
return@reduce if (a.position > b.position) a else b
}
.doOnError { sink.error(it) }
.subscribe { sink.success(it.position) }
}
}
/**
* @return true if this bot account is an "official" fredboat (music, patron, CE, etc).
* This is useful to lock down features that we only need internally, like polling the docker hub for pull stats.
*/
fun isOfficialBot(botId: Long): Boolean {
return (botId == BotConstants.MUSIC_BOT_ID
|| botId == BotConstants.PATRON_BOT_ID
|| botId == BotConstants.CUTTING_EDGE_BOT_ID
|| botId == BotConstants.BETA_BOT_ID
|| botId == BotConstants.MAIN_BOT_ID)
}
//https://discord.com/developers/docs/topics/gateway#sharding
fun getShardId(guildId: Long, appConfig: AppConfig) = ((guildId shr 22) % appConfig.shardCount).toInt()
}
|
mit
|
046865bed821ec1a38b02ec467355fac
| 40.333333 | 117 | 0.677035 | 4.311258 | false | true | false | false |
songful/PocketHub
|
app/src/main/java/com/github/pockethub/android/ui/item/news/IssuesEventItem.kt
|
1
|
2011
|
package com.github.pockethub.android.ui.item.news
import android.text.TextUtils
import android.view.View
import androidx.text.bold
import androidx.text.buildSpannedString
import com.github.pockethub.android.ui.view.OcticonTextView
import com.github.pockethub.android.util.AvatarLoader
import com.meisolsson.githubsdk.model.GitHubEvent
import com.meisolsson.githubsdk.model.payload.IssuesPayload
import com.xwray.groupie.kotlinandroidextensions.ViewHolder
import kotlinx.android.synthetic.main.news_item.*
class IssuesEventItem(
avatarLoader: AvatarLoader,
gitHubEvent: GitHubEvent
) : NewsItem(avatarLoader, gitHubEvent) {
override fun bind(holder: ViewHolder, position: Int) {
super.bind(holder, position)
val payload = gitHubEvent.payload() as IssuesPayload?
val action = payload?.action()
if (action != null) {
when (action) {
IssuesPayload.Action.Opened ->
holder.tv_event_icon.text = OcticonTextView.ICON_ISSUE_OPEN
IssuesPayload.Action.Reopened ->
holder.tv_event_icon.text = OcticonTextView.ICON_ISSUE_REOPEN
IssuesPayload.Action.Closed ->
holder.tv_event_icon.text = OcticonTextView.ICON_ISSUE_CLOSE
else -> holder.tv_event_icon.visibility = View.GONE
}
}
val issue = payload?.issue()
val details = buildSpannedString {
appendText(this, issue?.title())
}
if (TextUtils.isEmpty(details)) {
holder.tv_event_details.visibility = View.GONE
} else {
holder.tv_event_details.text = details
}
holder.tv_event.text = buildSpannedString {
boldActor(this, gitHubEvent)
append(" ${action?.name?.toLowerCase()} ")
bold {
append("issue " + issue?.number())
}
append(" on ")
boldRepo(this, gitHubEvent)
}
}
}
|
apache-2.0
|
16e7948ff74d144ebfb06b8ff841effa
| 33.672414 | 81 | 0.629538 | 4.612385 | false | false | false | false |
dahlstrom-g/intellij-community
|
plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/configuration/kpm/KotlinGradleSourceSetDataInitializer.kt
|
6
|
6916
|
// 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.gradleJava.configuration.kpm
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.project.ModuleData
import com.intellij.openapi.externalSystem.model.project.ProjectData
import com.intellij.openapi.externalSystem.model.project.ProjectId
import com.intellij.openapi.externalSystem.util.ExternalSystemConstants
import com.intellij.openapi.externalSystem.util.Order
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.PathUtilRt
import org.gradle.tooling.model.idea.IdeaModule
import org.jetbrains.kotlin.gradle.kpm.idea.IdeaKpmFragment
import org.jetbrains.kotlin.gradle.kpm.idea.name
import org.jetbrains.kotlin.idea.gradle.configuration.kpm.ModuleDataInitializer
import org.jetbrains.plugins.gradle.model.*
import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData
import org.jetbrains.plugins.gradle.service.project.GradleProjectResolver
import org.jetbrains.plugins.gradle.service.project.ProjectResolverContext
import java.util.*
import java.util.stream.Collectors
@Order(ExternalSystemConstants.UNORDERED + 1)
class KotlinGradleSourceSetDataInitializer : ModuleDataInitializer {
override fun initialize(
gradleModule: IdeaModule,
mainModuleNode: DataNode<ModuleData>,
projectDataNode: DataNode<ProjectData>,
resolverCtx: ProjectResolverContext,
initializerContext: ModuleDataInitializer.Context
) {
val sourceSetMap = projectDataNode.getUserData(GradleProjectResolver.RESOLVED_SOURCE_SETS)!!
val externalProject = resolverCtx.getExtraProject(gradleModule, ExternalProject::class.java)!!
val fragmentsByModules = initializerContext.model?.modules?.associateWith { it.fragments } ?: return
for ((module, fragments) in fragmentsByModules) {
for (fragment in fragments) {
val fragmentModuleId = calculateKotlinFragmentModuleId(gradleModule, fragment.coordinates, resolverCtx)
val existingSourceSetDataNode = sourceSetMap[fragmentModuleId]?.first
val moduleExternalName = calculateFragmentExternalModuleName(gradleModule, fragment)
val moduleInternalName = calculateFragmentInternalModuleName(
gradleModule,
externalProject,
fragment,
resolverCtx,
)
val fragmentData = existingSourceSetDataNode?.data ?: GradleSourceSetData(
fragmentModuleId,
moduleExternalName,
moduleInternalName,
initializerContext.mainModuleFileDirectoryPath.orEmpty(),
initializerContext.mainModuleConfigPath.orEmpty()
).also {
it.group = externalProject.group
it.version = externalProject.version
when (module.coordinates.moduleName) {
"main" -> {
it.publication = ProjectId(externalProject.group, externalProject.name, externalProject.version)
}
"test" -> {
it.productionModuleId = moduleInternalName
}
}
it.ideModuleGroup = initializerContext.moduleGroup
it.sdkName = initializerContext.jdkName
}
if (existingSourceSetDataNode == null) {
val fragmentDataNode = mainModuleNode.createChild(GradleSourceSetData.KEY, fragmentData)
sourceSetMap[fragmentModuleId] = com.intellij.openapi.util.Pair(
fragmentDataNode,
createExternalSourceSet(fragment, fragmentData)
)
}
}
}
}
companion object {
//TODO should it be visible for anyone outside initializer? Maybe introduce services for naming/routing fragments?
private fun calculateFragmentExternalModuleName(gradleModule: IdeaModule, fragment: IdeaKpmFragment): String =
"${gradleModule.name}:${fragment.coordinates.module.moduleName}.${fragment.name}"
private fun calculateFragmentInternalModuleName(
gradleModule: IdeaModule,
externalProject: ExternalProject,
fragment: IdeaKpmFragment,
resolverCtx: ProjectResolverContext,
): String {
val delimiter: String
val moduleName = StringBuilder()
val buildSrcGroup = resolverCtx.buildSrcGroup
if (resolverCtx.isUseQualifiedModuleNames) {
delimiter = "."
if (StringUtil.isNotEmpty(buildSrcGroup)) {
moduleName.append(buildSrcGroup).append(delimiter)
}
moduleName.append(gradlePathToQualifiedName(gradleModule.project.name, externalProject.qName))
} else {
delimiter = "_"
if (StringUtil.isNotEmpty(buildSrcGroup)) {
moduleName.append(buildSrcGroup).append(delimiter)
}
moduleName.append(gradleModule.name)
}
moduleName.append(delimiter)
moduleName.append("${fragment.coordinates.module.moduleName}.${fragment.name}")
return PathUtilRt.suggestFileName(moduleName.toString(), true, false)
}
private fun gradlePathToQualifiedName(
rootName: String,
gradlePath: String
): String = ((if (gradlePath.startsWith(":")) "$rootName." else "")
+ Arrays.stream(gradlePath.split(":".toRegex()).toTypedArray())
.filter { s: String -> s.isNotEmpty() }
.collect(Collectors.joining(".")))
}
private fun createExternalSourceSet(
fragment: IdeaKpmFragment,
gradleSourceSetData: GradleSourceSetData,
): ExternalSourceSet {
return DefaultExternalSourceSet().also { sourceSet ->
sourceSet.name = fragment.name
sourceSet.targetCompatibility = gradleSourceSetData.targetCompatibility
//TODO compute it properly (if required)
sourceSet.dependencies += emptyList<ExternalDependency>()
sourceSet.setSources(linkedMapOf(
fragment.computeSourceType() to DefaultExternalSourceDirectorySet().also { dirSet ->
dirSet.srcDirs = fragment.sourceDirs.toSet()
},
fragment.computeResourceType() to DefaultExternalSourceDirectorySet().also { dirSet ->
dirSet.srcDirs = fragment.resourceDirs.toSet()
}
).toMap())
}
}
}
|
apache-2.0
|
3e14518cf24500d6cf1478efff1e7350
| 46.047619 | 124 | 0.645171 | 6.034904 | false | false | false | false |
dahlstrom-g/intellij-community
|
plugins/grazie/src/main/kotlin/com/intellij/grazie/config/DetectionContext.kt
|
7
|
3525
|
package com.intellij.grazie.config
import ai.grazie.detector.ChainLanguageDetector
import ai.grazie.detector.LanguageDetector
import ai.grazie.detector.heuristics.list.ListDetector
import ai.grazie.detector.ngram.NgramDetector
import ai.grazie.nlp.langs.Language
import com.intellij.grazie.detection.hasWhitespaces
import com.intellij.util.xmlb.annotations.Property
import java.util.concurrent.ConcurrentHashMap
object DetectionContext {
data class State(@Property val disabled: Set<Language> = HashSet()) {
/** Disable from detection */
fun disable(langs: Iterable<Language>) = State(disabled + langs)
/** Enable for detection */
fun enable(langs: Iterable<Language>) = State(disabled - langs)
}
data class Local(val counter: ConcurrentHashMap<Language, Int> = ConcurrentHashMap()) {
companion object {
//Each text gives SIZE / SCORE_SIZE + 1 scores to own language.
//If LANGUAGE_SCORES / TOTAL_SCORES > NOTIFICATION_PROPORTION_THRESHOLD we suggest language
const val SCORE_SIZE = 100
const val NOTIFICATION_PROPORTION_THRESHOLD = 0.20
const val NOTIFICATION_TOTAL_THRESHOLD = 3
const val NGRAM_CONFIDENCE_THRESHOLD = 0.98
//More than half of all seen words are clearly from one language
const val LIST_CONFIDENCE_THRESHOLD = 0.51
//Require not less than 40 chars
const val TEXT_SIZE_THRESHOLD = 40
//Require not less than 4 words for non-hieroglyphic languages
const val WORDS_SIZE_THRESHOLD = 4
}
fun getToNotify(disabled: Set<Language>): Set<Language> {
val total = counter.values.sum()
val filtered = counter.filter { (_, myTotal) ->
myTotal > NOTIFICATION_TOTAL_THRESHOLD && (myTotal.toDouble() / total) > NOTIFICATION_PROPORTION_THRESHOLD
}.map { it.key }
val langs = filtered.filter { it != Language.UNKNOWN && it !in disabled }
return langs.toSet()
}
fun update(size: Int, wordsTotal: Int, details: ChainLanguageDetector.ChainDetectionResult) {
val result = details.result
val language = result.preferred
//Check if not unknown
if (language == Language.UNKNOWN) return
//Check threshold by text size is not met
if (size < TEXT_SIZE_THRESHOLD) return
//Check threshold by number of words is not met (if language has words at all)
if (language.hasWhitespaces && wordsTotal < WORDS_SIZE_THRESHOLD) return
if (language in ListDetector.supported) {
//Check if threshold by list detector is not met
val listResult = details[LanguageDetector.Type.List]?.detected ?: return
val maxList = listResult.maxByOrNull { it.probability } ?: return
if (maxList.probability < LIST_CONFIDENCE_THRESHOLD || maxList.lang != result.preferred) return
}
if (language in NgramDetector.supported) {
//Check if threshold by ngram detector is not met
val ngramResult = details[LanguageDetector.Type.Ngram]?.detected
//Check ngram only it was used. Otherwise, we believe to list detector
if (ngramResult != null) {
val maxNgram = ngramResult.maxByOrNull { it.probability } ?: return
if (maxNgram.probability < NGRAM_CONFIDENCE_THRESHOLD || maxNgram.lang != result.preferred) return
}
}
count(size, language)
}
private fun count(size: Int, lang: Language) {
counter[lang] = counter.getOrDefault(lang, 0) + (size / SCORE_SIZE + 1)
}
fun clear() {
counter.clear()
}
}
}
|
apache-2.0
|
df922345c4dacb6d6a15cf845b830705
| 36.5 | 114 | 0.690213 | 4.309291 | false | false | false | false |
randombyte-developer/free-blocks
|
src/main/kotlin/de/randombyte/freeblocks/ScrollListener.kt
|
1
|
2956
|
package de.randombyte.freeblocks
import org.spongepowered.api.Sponge
import org.spongepowered.api.entity.living.player.Player
import org.spongepowered.api.event.Listener
import org.spongepowered.api.event.filter.cause.Root
import org.spongepowered.api.event.item.inventory.ChangeInventoryEvent
import org.spongepowered.api.item.inventory.entity.Hotbar
import org.spongepowered.api.service.user.UserStorageService
import java.util.*
object ScrollListener {
private lateinit var plugin: FreeBlocks
fun init(plugin: FreeBlocks) {
this.plugin = plugin
Sponge.getEventManager().registerListeners(plugin, this)
}
private var lastEditor: UUID? = null
private var lastSelectedHotbarSlot = -1
@Listener
fun onChangeSelectedSlot(event: ChangeInventoryEvent.Held, @Root player: Player) {
if (FreeBlocks.currentEditor != player.uniqueId) return
val direction = getScrollingDirection()
if (direction == 0 || Math.abs(direction) > 3) return // Scrolled too fast todo
val scrolledEvent = CurrentEditorScrolledEvent(
FreeBlocks.currentEditor!!.toPlayer(),
direction,
event.cause)
Sponge.getEventManager().post(scrolledEvent)
}
/**
* Returns what the currentEditor has done.
* @return > 0 if scrolled up, == 0 if not scrolled, < 0 if scrolled down
*/
val hotbarCapacity = 9
private fun getScrollingDirection(): Int {
val selectedSlot = getSelectedHotbarSlot()
val direction = if (lastSelectedHotbarSlot == 0 && selectedSlot == hotbarCapacity - 1) {
// cursor jumped from left to right
-1
} else if (lastSelectedHotbarSlot == hotbarCapacity - 1 && selectedSlot == 0) {
// cursor jumped from right to left
+1
} else selectedSlot - lastSelectedHotbarSlot
lastSelectedHotbarSlot = selectedSlot
return direction
}
private fun getSelectedHotbarSlot(): Int {
if (FreeBlocks.currentEditor == null) throw RuntimeException("currentEditor is null!")
val currentSelectedHotbarSlot = FreeBlocks.currentEditor!!.toPlayer()
.inventory.query<Hotbar>(Hotbar::class.java).selectedSlotIndex
if (lastEditor == null) {
lastEditor = FreeBlocks.currentEditor
lastSelectedHotbarSlot = currentSelectedHotbarSlot
}
return currentSelectedHotbarSlot
}
/**
* Tries to get the [Player] from the [UUID].
* @throws [RuntimeException] if player wasn't found or is offline
* @return The player
*/
private fun UUID.toPlayer(): Player {
return Sponge.getServiceManager().provide(UserStorageService::class.java).get().get(this).orElseThrow {
RuntimeException("Didn't find player $this!")
}.player.orElseThrow {
RuntimeException("Player $this is currently offline!")
}
}
}
|
gpl-2.0
|
d2c2f3e23fcd8093723b3084442df459
| 37.907895 | 111 | 0.673545 | 5.001692 | false | false | false | false |
DreierF/MyTargets
|
app/src/main/java/de/dreier/mytargets/features/training/standardround/EditStandardRoundFragment.kt
|
1
|
10307
|
/*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets 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.
*
* MyTargets 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 de.dreier.mytargets.features.training.standardround
import android.app.Activity
import android.content.Intent
import androidx.databinding.DataBindingUtil
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.evernote.android.state.State
import de.dreier.mytargets.R
import de.dreier.mytargets.app.ApplicationInstance
import de.dreier.mytargets.base.adapters.dynamicitem.DynamicItemAdapter
import de.dreier.mytargets.base.adapters.dynamicitem.DynamicItemHolder
import de.dreier.mytargets.base.db.StandardRoundFactory
import de.dreier.mytargets.base.fragments.EditFragmentBase
import de.dreier.mytargets.base.navigation.NavigationController.Companion.INTENT
import de.dreier.mytargets.base.navigation.NavigationController.Companion.ITEM
import de.dreier.mytargets.databinding.FragmentEditStandardRoundBinding
import de.dreier.mytargets.databinding.ItemRoundTemplateBinding
import de.dreier.mytargets.features.settings.SettingsManager
import de.dreier.mytargets.shared.models.augmented.AugmentedStandardRound
import de.dreier.mytargets.shared.models.db.RoundTemplate
import de.dreier.mytargets.shared.models.db.StandardRound
import de.dreier.mytargets.utils.ToolbarUtils
import de.dreier.mytargets.utils.Utils
import de.dreier.mytargets.views.selector.DistanceSelector
import de.dreier.mytargets.views.selector.SelectorBase
import de.dreier.mytargets.views.selector.TargetSelector
import timber.log.Timber
class EditStandardRoundFragment : EditFragmentBase() {
private val standardRoundDAO = ApplicationInstance.db.standardRoundDAO()
@State
var standardRound: AugmentedStandardRound? = null
private var adapter: RoundTemplateAdapter? = null
private lateinit var binding: FragmentEditStandardRoundBinding
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = DataBindingUtil
.inflate(inflater, R.layout.fragment_edit_standard_round, container, false)
ToolbarUtils.setSupportActionBar(this, binding.toolbar)
ToolbarUtils.showUpAsX(this)
setHasOptionsMenu(true)
if (savedInstanceState == null) {
if (arguments != null) {
standardRound = arguments!!.getParcelable(ITEM)
}
if (standardRound == null) {
ToolbarUtils.setTitle(this, R.string.new_round_template)
binding.name.setText(R.string.custom_round)
standardRound = AugmentedStandardRound(
StandardRound(),
mutableListOf(getDefaultRoundTemplate())
)
} else {
ToolbarUtils.setTitle(this, R.string.edit_standard_round)
// Load saved values
if (standardRound!!.standardRound.club == StandardRoundFactory.CUSTOM) {
binding.name.setText(standardRound!!.standardRound.name)
} else {
standardRound!!.standardRound.id = 0L
binding.name.setText(
"%s %s".format(
getString(R.string.custom), standardRound!!.standardRound
.name
)
)
// When copying an existing standard round make sure
// we don't overwrite the other rounds templates
for (round in standardRound!!.roundTemplates) {
round.id = 0L
}
}
}
}
adapter = RoundTemplateAdapter(this, standardRound!!.roundTemplates)
binding.rounds.adapter = adapter
binding.addButton.setOnClickListener { onAddRound() }
binding.deleteStandardRound.setOnClickListener { onDeleteStandardRound() }
return binding.root
}
private fun getDefaultRoundTemplate(): RoundTemplate {
val round = RoundTemplate()
round.shotsPerEnd = SettingsManager.shotsPerEnd
round.endCount = SettingsManager.endCount
round.targetTemplate = SettingsManager.target
round.distance = SettingsManager.distance
return round
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
Utils.setupFabTransform(activity!!, binding.root)
}
private fun onAddRound() {
val newItemIndex = standardRound!!.roundTemplates.size
if (newItemIndex > 0) {
val r = standardRound!!.roundTemplates[newItemIndex - 1]
val roundTemplate = RoundTemplate()
roundTemplate.endCount = r.endCount
roundTemplate.shotsPerEnd = r.shotsPerEnd
roundTemplate.distance = r.distance
roundTemplate.targetTemplate = r.targetTemplate
standardRound!!.roundTemplates.add(roundTemplate)
} else {
Timber.w("This should never get executed") //TODO remove else part if no reports occur
standardRound!!.roundTemplates.add(getDefaultRoundTemplate())
}
adapter!!.notifyItemInserted(newItemIndex)
}
private fun onDeleteStandardRound() {
standardRoundDAO.deleteStandardRound(standardRound!!.standardRound)
navigationController.setResult(RESULT_STANDARD_ROUND_DELETED)
navigationController.finish()
}
override fun onSave() {
standardRound!!.standardRound.club = StandardRoundFactory.CUSTOM
standardRound!!.standardRound.name = binding.name.text.toString()
standardRoundDAO.saveStandardRound(
standardRound!!.standardRound,
standardRound!!.roundTemplates
)
val round = standardRound!!.roundTemplates[0]
SettingsManager.shotsPerEnd = round.shotsPerEnd
SettingsManager.endCount = round.endCount
SettingsManager.target = round.targetTemplate
SettingsManager.distance = round.distance
navigationController.setResultSuccess(standardRound!!)
navigationController.finish()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK && data != null) {
val intentData = data.getBundleExtra(INTENT)
val index = intentData.getInt(SelectorBase.INDEX)
when (requestCode) {
DistanceSelector.DISTANCE_REQUEST_CODE -> {
standardRound!!.roundTemplates[index].distance = data.getParcelableExtra(ITEM)
adapter!!.notifyItemChanged(index)
}
TargetSelector.TARGET_REQUEST_CODE -> {
standardRound!!.roundTemplates[index]
.targetTemplate = data.getParcelableExtra(ITEM)
adapter!!.notifyItemChanged(index)
}
}
}
}
private inner class RoundTemplateHolder internal constructor(view: View) :
DynamicItemHolder<RoundTemplate>(view) {
internal var binding = ItemRoundTemplateBinding.bind(view)
override fun onBind(
item: RoundTemplate,
position: Int,
fragment: Fragment,
removeListener: View.OnClickListener
) {
this.item = item
// Set title of round
binding.roundNumber.text = fragment.resources
.getQuantityString(R.plurals.rounds, position + 1, position + 1)
item.index = position
binding.distance.setOnClickListener { selectedItem, index ->
navigationController.navigateToDistance(
selectedItem!!,
index,
DistanceSelector.DISTANCE_REQUEST_CODE
)
}
binding.distance.itemIndex = position
binding.distance.setItem(item.distance)
// Target round
binding.target.setOnClickListener { selectedItem, index ->
navigationController.navigateToTarget(selectedItem!!, index)
}
binding.target.itemIndex = position
binding.target.setItem(item.targetTemplate)
// Ends
binding.endCount.textPattern = R.plurals.passe
binding.endCount.setOnValueChangedListener { item.endCount = it }
binding.endCount.value = item.endCount
// Shots per end
binding.shotCount.textPattern = R.plurals.arrow
binding.shotCount.minimum = 1
binding.shotCount.maximum = 12
binding.shotCount.setOnValueChangedListener { item.shotsPerEnd = it }
binding.shotCount.value = item.shotsPerEnd
if (position == 0) {
binding.remove.visibility = View.GONE
} else {
binding.remove.visibility = View.VISIBLE
binding.remove.setOnClickListener(removeListener)
}
}
}
private inner class RoundTemplateAdapter internal constructor(
fragment: Fragment,
list: MutableList<RoundTemplate>
) : DynamicItemAdapter<RoundTemplate>(fragment, list, R.string.round_removed) {
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): DynamicItemHolder<RoundTemplate> {
val v = inflater.inflate(R.layout.item_round_template, parent, false)
return RoundTemplateHolder(v)
}
}
companion object {
const val RESULT_STANDARD_ROUND_DELETED = Activity.RESULT_FIRST_USER
}
}
|
gpl-2.0
|
248761e39f25aeed4b635314560a9852
| 39.105058 | 98 | 0.654604 | 5.482447 | false | false | false | false |
DreierF/MyTargets
|
shared/src/main/java/de/dreier/mytargets/shared/utils/Circle.kt
|
1
|
3007
|
/*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets 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.
*
* MyTargets 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 de.dreier.mytargets.shared.utils
import android.graphics.Canvas
import android.graphics.Paint
import android.text.TextPaint
import de.dreier.mytargets.shared.models.Target
class Circle(private val density: Float) {
private val circleColorPaint = Paint()
private val textPaint = TextPaint()
init {
// Set up default Paint object
circleColorPaint.isAntiAlias = true
// Set up a default TextPaint object
textPaint.flags = Paint.ANTI_ALIAS_FLAG
textPaint.textAlign = Paint.Align.CENTER
}
fun draw(can: Canvas, x: Float, y: Float, zone: Int, radius: Int, arrow: Int, number: String?, ambientMode: Boolean, target: Target) {
val zoneBase = target.model.getZone(zone)
val fillColor = if (ambientMode) Color.BLACK else zoneBase.fillColor
val borderColor = if (ambientMode) Color.WHITE else Color.getStrokeColor(zoneBase.fillColor)
val textColor = if (ambientMode) Color.WHITE else zoneBase.textColor
val score = target.zoneToString(zone, arrow)
drawScore(can, x, y, radius * density, score,
if (ambientMode) null else number, fillColor, borderColor, textColor)
}
fun drawScore(canvas: Canvas, x: Float, y: Float, radius: Float, score: String, arrowNumber: String?, fillColor: Int, borderColor: Int, textColor: Int) {
val fontSize = (1.2323f * radius + 0.7953f).toInt()
// Draw the circles background
circleColorPaint.strokeWidth = 2f
circleColorPaint.style = Paint.Style.FILL_AND_STROKE
circleColorPaint.color = fillColor
canvas.drawCircle(x, y, radius, circleColorPaint)
// Draw the circles border
circleColorPaint.style = Paint.Style.STROKE
circleColorPaint.color = borderColor
canvas.drawCircle(x, y, radius, circleColorPaint)
// Draw the text inside the circle
textPaint.color = textColor
textPaint.textSize = fontSize.toFloat()
canvas.drawText(score, x, y + fontSize * 7 / 22.0f, textPaint)
if (arrowNumber != null) {
circleColorPaint.style = Paint.Style.FILL_AND_STROKE
circleColorPaint.color = -0xcccccd
canvas.drawCircle(x + radius * 0.8f, y + radius * 0.8f, radius * 0.5f, circleColorPaint)
textPaint.textSize = fontSize * 0.5f
textPaint.color = -0x1
canvas.drawText(arrowNumber, x + radius * 0.8f, y + radius * 1.05f, textPaint)
}
}
}
|
gpl-2.0
|
5beac2bd978318486c7b6a8f69ffcaf3
| 39.635135 | 157 | 0.678417 | 4.259207 | false | false | false | false |
facebook/redex
|
test/instr/KotlinCompanionObjTest.kt
|
1
|
1743
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import androidx.annotation.IntDef
/* Note: companion object in annotation class will be removed by AnnoKill + RMU pass, NOT KotlinObjectInliner pass*/
@IntDef(AnnoClass.START, AnnoClass.END)
annotation class AnnoClass {
companion object {
const val START = 0
const val END = 1
}
}
/* After KotlinObjectInliner + LocalDce + RMU, class LCompanionClass$Companion; should be removed*/
class CompanionClass(val greeting: String) {
fun greet(name: String) = "$greeting, $name!"
companion object {
val s: String = "Hello"
var s1 = "Hello2"
fun hello() = CompanionClass(s)
fun hello1(): Boolean {
if (s1 == "Hello2") {
return true
} else {
return false
}
}
fun get(): String {
return s1
}
}
fun get(): String {
return s
}
}
class AnotherCompanionClass {
companion object Test {
@JvmStatic var someOtherStr: String = "Bar"
@JvmStatic
fun funX(): String {
return someOtherStr
}
}
}
class ThirdCompanionClass {
companion object Test {
const val thirdStr: String = "Bar"
private fun funY(): String {
return thirdStr
}
}
fun get(): String {
return funY()
}
}
class Foo {
fun main() {
println(CompanionClass.hello().greet("Olive"))
println(CompanionClass.s)
println(CompanionClass.s1)
println(CompanionClass.hello1())
println(CompanionClass.get())
println(AnotherCompanionClass.funX())
println(AnnoClass.START)
val obj = ThirdCompanionClass()
println(obj.get())
}
}
|
mit
|
83dfb50960c45bccb91ef376e7141ab5
| 20.518519 | 116 | 0.650602 | 3.916854 | false | false | false | false |
ediTLJ/novelty
|
app/src/main/java/ro/edi/novelty/data/db/dao/NewsDao.kt
|
1
|
4032
|
/*
* Copyright 2019 Eduard Scarlat
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ro.edi.novelty.data.db.dao
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Query
import androidx.room.Transaction
import ro.edi.novelty.data.db.entity.DbNews
import ro.edi.novelty.model.News
@Dao
abstract class NewsDao : BaseDao<DbNews> {
@Transaction
@Query("SELECT news.id, news.feed_id, news.title, text, author, pub_date, news.url, upd_date, news_state.is_read, news_state.is_starred, feeds.title AS feed_title FROM news LEFT OUTER JOIN news_state ON news.id = news_state.id AND news.feed_id = news_state.feed_id LEFT OUTER JOIN feeds ON news.feed_id = feeds.id WHERE news_state.is_starred ORDER BY pub_date DESC")
protected abstract fun queryStarred(): LiveData<List<News>>
@Transaction
@Query("SELECT news.id, news.feed_id, news.title, text, author, pub_date, news.url, upd_date, news_state.is_read, news_state.is_starred, feeds.title AS feed_title FROM news LEFT OUTER JOIN news_state ON news.id = news_state.id AND news.feed_id = news_state.feed_id LEFT OUTER JOIN feeds ON news.feed_id = feeds.id WHERE feeds.is_starred ORDER BY pub_date DESC")
protected abstract fun query(): LiveData<List<News>>
@Transaction
@Query("SELECT news.id, news.feed_id, news.title, text, author, pub_date, news.url, upd_date, news_state.is_read, news_state.is_starred, feeds.title AS feed_title FROM news LEFT OUTER JOIN news_state ON news.id = news_state.id AND news.feed_id = news_state.feed_id LEFT OUTER JOIN feeds ON news.feed_id = feeds.id WHERE news.feed_id = :feedId ORDER BY pub_date DESC")
protected abstract fun query(feedId: Int): LiveData<List<News>>
/**
* Get info for the specified news id.
*
* @param newsId news id
*/
@Query("SELECT news.id, news.feed_id, news.title, text, author, pub_date, news.url, upd_date, news_state.is_read, news_state.is_starred, feeds.title AS feed_title FROM news LEFT OUTER JOIN news_state ON news.id = news_state.id AND news.feed_id = news_state.feed_id LEFT OUTER JOIN feeds ON news.feed_id = feeds.id WHERE news.id = :newsId")
abstract fun getInfo(newsId: Int): LiveData<News>
/**
* Get my news only for all feeds.
*/
fun getMyNews(): LiveData<List<News>> = queryStarred().getDistinct()
/**
* Get all news for my feeds only.
*/
fun getNews(): LiveData<List<News>> = query().getDistinct()
/**
* Get all news for the specified feed.
*
* @param feedId feed id
*/
fun getNews(feedId: Int): LiveData<List<News>> = query(feedId).getDistinct()
@Transaction
@Query("DELETE FROM news")
abstract fun deleteAll()
@Transaction
@Query("DELETE FROM news WHERE feed_id = :feedId")
abstract fun deleteAll(feedId: Int)
@Transaction
@Query("DELETE FROM news WHERE feed_id = :feedId AND upd_date < :untilDate AND id NOT IN (SELECT id FROM news_state WHERE feed_id = :feedId AND is_starred = 1)")
abstract fun deleteOlder(feedId: Int, untilDate: Long)
@Transaction
@Query("DELETE FROM news WHERE feed_id = :feedId AND id NOT IN (SELECT id FROM news_state WHERE feed_id = :feedId AND is_starred = 1) AND pub_date NOT IN (SELECT pub_date FROM news LEFT OUTER JOIN news_state ON news.id = news_state.id AND news.feed_id = news_state.feed_id WHERE news.feed_id = :feedId AND news_state.is_starred == 0 ORDER BY pub_date DESC LIMIT :keepCount)")
abstract fun deleteAllButLatest(feedId: Int, keepCount: Int)
}
|
apache-2.0
|
2934297f2d72f97339db93cedf22d488
| 50.050633 | 379 | 0.714782 | 3.568142 | false | false | false | false |
RuneSuite/client
|
api/src/main/java/org/runestar/client/api/util/CyclicCache.kt
|
1
|
829
|
package org.runestar.client.api.util
inline class CyclicCache<K, V>(val delegate: MutableMap<K, Value<V>>) {
constructor() : this(LinkedHashMap())
class Value<V>(private val v: V) {
var isActive: Boolean = true
fun get() = v.also { isActive = true }
}
inline fun get(k: K, loader: (K) -> V): V {
return delegate[k]?.get() ?: loader(k).also { delegate[k] = Value(it) }
}
/**
* Removes all entries which have not been accessed since the last call to [cycle]
*/
fun cycle() {
val vs = delegate.values.iterator()
while (vs.hasNext()) {
val v = vs.next()
if (!v.isActive) {
vs.remove()
} else {
v.isActive = false
}
}
}
fun clear() = delegate.clear()
}
|
mit
|
a086ab83e5886ad3b8ca5c19d1a090d4
| 23.411765 | 86 | 0.516285 | 3.855814 | false | false | false | false |
JetBrains/intellij-community
|
plugins/kotlin/gradle/gradle-tooling/impl/src/org/jetbrains/kotlin/idea/gradleTooling/reflect/KotlinTargetReflection.kt
|
1
|
3790
|
// 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.gradleTooling.reflect
import org.gradle.api.Named
import org.jetbrains.kotlin.idea.gradleTooling.getMethodOrNull
import org.jetbrains.kotlin.idea.gradleTooling.loadClassOrNull
fun KotlinTargetReflection(kotlinTarget: Any): KotlinTargetReflection = KotlinTargetReflectionImpl(kotlinTarget)
interface KotlinTargetReflection {
val isMetadataTargetClass: Boolean
val targetName: String
val presetName: String?
val disambiguationClassifier: String?
val platformType: String?
val gradleTarget: Named
val compilations: Collection<KotlinCompilationReflection>?
val nativeMainRunTasks: Collection<KotlinNativeMainRunTaskReflection>?
val artifactsTaskName: String?
val konanArtifacts: Collection<Any>?
}
private class KotlinTargetReflectionImpl(private val instance: Any) : KotlinTargetReflection {
override val gradleTarget: Named
get() = instance as Named
override val isMetadataTargetClass: Boolean by lazy {
val metadataTargetClass =
instance.javaClass.classLoader.loadClassOrNull("org.jetbrains.kotlin.gradle.plugin.mpp.KotlinMetadataTarget")
metadataTargetClass?.isInstance(instance) == true
}
override val targetName: String by lazy {
gradleTarget.name
}
override val presetName: String? by lazy {
instance.callReflectiveGetter<Any?>("getPreset", logger)
?.callReflectiveGetter("getName", logger)
}
override val disambiguationClassifier: String? by lazy {
val getterConditionMethod = "getUseDisambiguationClassifierAsSourceSetNamePrefix"
val useDisambiguationClassifier = if (instance.javaClass.getMethodOrNull(getterConditionMethod) != null)
instance.callReflectiveGetter(getterConditionMethod, logger)!!
else true
instance.callReflectiveGetter(
(if (useDisambiguationClassifier) "getDisambiguationClassifier"
else "getOverrideDisambiguationClassifierOnIdeImport"), logger
)
}
override val platformType: String? by lazy {
instance.callReflectiveAnyGetter("getPlatformType", logger)?.callReflectiveGetter("getName", logger)
}
override val compilations: Collection<KotlinCompilationReflection>? by lazy {
instance.callReflective("getCompilations", parameters(), returnType<Iterable<Any>>(), logger)?.map { compilation ->
KotlinCompilationReflection(compilation)
}
}
override val nativeMainRunTasks: Collection<KotlinNativeMainRunTaskReflection>? by lazy {
val executableClass = instance.javaClass.classLoader.loadClassOrNull(EXECUTABLE_CLASS) ?: return@lazy null
instance.callReflective("getBinaries", parameters(), returnType<Iterable<Any>>(), logger)
?.filterIsInstance(executableClass)
?.map { KotlinNativeMainRunTaskReflection(it) }
}
override val artifactsTaskName: String? by lazy {
instance.callReflectiveGetter("getArtifactsTaskName", logger)
}
override val konanArtifacts: Collection<Any>? by lazy {
if (!instance.javaClass.classLoader.loadClass(KOTLIN_NATIVE_TARGET_CLASS).isInstance(instance))
null
else
instance.callReflective("getBinaries", parameters(), returnType<Iterable<Any?>>(), logger)?.filterNotNull()
}
companion object {
private val logger = ReflectionLogger(KotlinTargetReflection::class.java)
private const val EXECUTABLE_CLASS = "org.jetbrains.kotlin.gradle.plugin.mpp.Executable"
private const val KOTLIN_NATIVE_TARGET_CLASS = "org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget"
}
}
|
apache-2.0
|
dea53c8dc38bbce416334b148b3d80a7
| 45.231707 | 123 | 0.737995 | 5.353107 | false | false | false | false |
youdonghai/intellij-community
|
python/src/com/jetbrains/python/console/PydevConsoleExecuteActionHandler.kt
|
1
|
8254
|
/*
* Copyright 2000-2014 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.jetbrains.python.console
import com.intellij.codeInsight.hint.HintManager
import com.intellij.execution.console.LanguageConsoleView
import com.intellij.execution.console.ProcessBackedConsoleExecuteActionHandler
import com.intellij.execution.process.ProcessHandler
import com.intellij.execution.ui.ConsoleViewContentType
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.psi.codeStyle.CodeStyleSettingsManager
import com.intellij.psi.util.PsiTreeUtil
import com.jetbrains.python.PythonFileType
import com.jetbrains.python.console.pydev.ConsoleCommunication
import com.jetbrains.python.console.pydev.ConsoleCommunicationListener
import com.jetbrains.python.psi.LanguageLevel
import com.jetbrains.python.psi.PyElementGenerator
import com.jetbrains.python.psi.PyFile
import com.jetbrains.python.psi.PyStatementList
import java.awt.Font
/**
* @author traff
*/
open class PydevConsoleExecuteActionHandler(private val myConsoleView: LanguageConsoleView,
processHandler: ProcessHandler,
val consoleCommunication: ConsoleCommunication) : ProcessBackedConsoleExecuteActionHandler(processHandler, false), ConsoleCommunicationListener {
private val project = myConsoleView.project
private val myEnterHandler = PyConsoleEnterHandler()
private var myIpythonInputPromptCount = 1
var isEnabled = false
set(value) {
field = value
updateConsoleState()
}
init {
this.consoleCommunication.addCommunicationListener(this)
}
override fun processLine(text: String) {
executeMultiLine(text)
}
private fun executeMultiLine(text: String) {
val commandText = if (!text.endsWith("\n")) {
text + "\n"
}
else {
text
}
sendLineToConsole(ConsoleCommunication.ConsoleCodeFragment(commandText, checkSingleLine(text)))
}
private fun checkSingleLine(text: String): Boolean {
val pyFile: PyFile =PyElementGenerator.getInstance(project).createDummyFile(myConsoleView.virtualFile.getUserData(LanguageLevel.KEY), text) as PyFile
return PsiTreeUtil.findChildOfAnyType(pyFile, PyStatementList::class.java) == null && pyFile.statements.size < 2
}
private fun sendLineToConsole(code: ConsoleCommunication.ConsoleCodeFragment) {
val consoleComm = consoleCommunication
if (!consoleComm.isWaitingForInput) {
executingPrompt()
}
if (ipythonEnabled && !consoleComm.isWaitingForInput && !code.getText().isBlank()) {
++myIpythonInputPromptCount;
}
consoleComm.execInterpreter(code) {}
}
private fun updateConsoleState() {
if (!isEnabled) {
executingPrompt()
}
else if (consoleCommunication.isWaitingForInput) {
waitingForInputPrompt()
}
else if (canExecuteNow()) {
if (consoleCommunication.needsMore()) {
more()
}
else {
inPrompt()
}
}
else {
executingPrompt()
}
}
fun inputReceived() {
if (consoleCommunication is PythonDebugConsoleCommunication) {
if (consoleCommunication.waitingForInput) {
consoleCommunication.waitingForInput = false
val console = myConsoleView
if (PyConsoleUtil.INPUT_PROMPT.equals(console.prompt) || PyConsoleUtil.HELP_PROMPT.equals(console.prompt)) {
console.prompt = PyConsoleUtil.ORDINARY_PROMPT
}
}
}
}
private fun inPrompt() {
if (ipythonEnabled) {
ipythonInPrompt()
}
else {
ordinaryPrompt()
}
}
private fun ordinaryPrompt() {
if (PyConsoleUtil.ORDINARY_PROMPT != myConsoleView.prompt) {
myConsoleView.prompt = PyConsoleUtil.ORDINARY_PROMPT
PyConsoleUtil.scrollDown(myConsoleView.currentEditor)
}
}
private val ipythonEnabled: Boolean
get() = PyConsoleUtil.getOrCreateIPythonData(myConsoleView.virtualFile).isIPythonEnabled
private fun ipythonInPrompt() {
myConsoleView.setPromptAttributes(object : ConsoleViewContentType("", ConsoleViewContentType.USER_INPUT_KEY) {
override fun getAttributes(): TextAttributes {
val attrs = super.getAttributes()
attrs.fontType = Font.PLAIN
return attrs
}
})
myConsoleView.prompt = "In[$myIpythonInputPromptCount]:"
PyConsoleUtil.scrollDown(myConsoleView.currentEditor)
}
private fun executingPrompt() {
myConsoleView.prompt = PyConsoleUtil.EXECUTING_PROMPT
}
private fun waitingForInputPrompt() {
if (PyConsoleUtil.INPUT_PROMPT != myConsoleView.prompt && PyConsoleUtil.HELP_PROMPT != myConsoleView.prompt) {
myConsoleView.prompt = PyConsoleUtil.INPUT_PROMPT
PyConsoleUtil.scrollDown(myConsoleView.currentEditor)
}
}
private fun more() {
val prompt = if (ipythonEnabled) {
PyConsoleUtil.IPYTHON_INDENT_PROMPT
}
else {
PyConsoleUtil.INDENT_PROMPT
}
if (prompt != myConsoleView.prompt) {
myConsoleView.prompt = prompt
PyConsoleUtil.scrollDown(myConsoleView.currentEditor)
}
}
override fun commandExecuted(more: Boolean) = updateConsoleState()
override fun inputRequested() = updateConsoleState()
val pythonIndent: Int
get() = CodeStyleSettingsManager.getSettings(project).getIndentSize(PythonFileType.INSTANCE)
val cantExecuteMessage: String
get() {
if (!isEnabled) {
return consoleIsNotEnabledMessage
}
else if (!canExecuteNow()) {
return prevCommandRunningMessage
}
else {
return "Can't execute the command"
}
}
override fun runExecuteAction(console: LanguageConsoleView) {
if (isEnabled) {
if (!canExecuteNow()) {
HintManager.getInstance().showErrorHint(console.consoleEditor, prevCommandRunningMessage)
}
else {
doRunExecuteAction(console)
}
}
else {
HintManager.getInstance().showErrorHint(console.consoleEditor, consoleIsNotEnabledMessage)
}
}
private fun doRunExecuteAction(console: LanguageConsoleView) {
val doc = myConsoleView.editorDocument
val endMarker = doc.createRangeMarker(doc.textLength, doc.textLength)
endMarker.isGreedyToLeft = false
endMarker.isGreedyToRight = true
val isComplete = myEnterHandler.handleEnterPressed(console.consoleEditor)
if (isComplete || consoleCommunication.isWaitingForInput) {
if (endMarker.endOffset - endMarker.startOffset > 0) {
ApplicationManager.getApplication().runWriteAction {
CommandProcessor.getInstance().runUndoTransparentAction {
doc.deleteString(endMarker.startOffset, endMarker.endOffset)
}
}
}
if (shouldCopyToHistory(console)) {
copyToHistoryAndExecute(console)
}
else {
processLine(myConsoleView.consoleEditor.document.text)
}
}
}
private fun copyToHistoryAndExecute(console: LanguageConsoleView) = super.runExecuteAction(console)
fun canExecuteNow(): Boolean = !consoleCommunication.isExecuting || consoleCommunication.isWaitingForInput
protected open val consoleIsNotEnabledMessage: String
get() = notEnabledMessage
companion object {
val prevCommandRunningMessage: String
get() = "Previous command is still running. Please wait or press Ctrl+C in console to interrupt."
val notEnabledMessage: String
get() = "Console is not enabled."
private fun shouldCopyToHistory(console: LanguageConsoleView): Boolean {
return !PyConsoleUtil.isPagingPrompt(console.prompt)
}
}
}
|
apache-2.0
|
ec94f5b34beb12647615b934d055b799
| 29.684015 | 189 | 0.719651 | 4.916021 | false | false | false | false |
JetBrains/intellij-community
|
plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/moduleConfigurators/TargetConfigurator.kt
|
1
|
8848
|
// Copyright 2000-2022 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.kotlin.tools.projectWizard.moduleConfigurators
import kotlinx.collections.immutable.toPersistentList
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.tools.projectWizard.KotlinNewProjectWizardBundle
import org.jetbrains.kotlin.tools.projectWizard.core.Reader
import org.jetbrains.kotlin.tools.projectWizard.core.buildList
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.ModuleConfiguratorSetting
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.BuildSystemIR
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.JvmToolchainConfigurationIR
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.gradle.irsList
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.gradle.multiplatform.DefaultTargetConfigurationIR
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.gradle.multiplatform.TargetAccessIR
import org.jetbrains.kotlin.tools.projectWizard.moduleConfigurators.JSConfigurator.Companion.compiler
import org.jetbrains.kotlin.tools.projectWizard.moduleConfigurators.JSConfigurator.Companion.jsCompilerParam
import org.jetbrains.kotlin.tools.projectWizard.moduleConfigurators.JSConfigurator.Companion.irOrLegacyCompiler
import org.jetbrains.kotlin.tools.projectWizard.moduleConfigurators.JSConfigurator.Companion.kind
import org.jetbrains.kotlin.tools.projectWizard.moduleConfigurators.JsBrowserBasedConfigurator.Companion.browserSubTarget
import org.jetbrains.kotlin.tools.projectWizard.moduleConfigurators.JsNodeBasedConfigurator.Companion.nodejsSubTarget
import org.jetbrains.kotlin.tools.projectWizard.moduleConfigurators.JvmModuleConfigurator.Companion.testFramework
import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.buildSystemType
import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.isGradle
import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.ModuleSubType
import org.jetbrains.kotlin.tools.projectWizard.settings.DisplayableSettingItem
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.Module
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.ModuleKind
interface TargetConfigurator : ModuleConfiguratorWithModuleType {
override val moduleKind get() = ModuleKind.target
fun canCoexistsWith(other: List<TargetConfigurator>): Boolean = true
fun Reader.createTargetIrs(module: Module): List<BuildSystemIR>
fun createInnerTargetIrs(reader: Reader, module: Module): List<BuildSystemIR> = emptyList()
}
abstract class TargetConfiguratorWithTests : ModuleConfiguratorWithTests, TargetConfigurator
interface SingleCoexistenceTargetConfigurator : TargetConfigurator {
override fun canCoexistsWith(other: List<TargetConfigurator>): Boolean =
other.none { it == this }
}
interface SimpleTargetConfigurator : TargetConfigurator {
val moduleSubType: ModuleSubType
override val moduleType get() = moduleSubType.moduleType
override val id get() = "${moduleSubType.name}Target"
override val suggestedModuleName: String? get() = moduleSubType.name
override fun Reader.createTargetIrs(
module: Module
): List<BuildSystemIR> = buildList {
+DefaultTargetConfigurationIR(
module.createTargetAccessIr(moduleSubType),
createInnerTargetIrs(this@createTargetIrs, module).toPersistentList()
)
}
}
internal fun Module.createTargetAccessIr(
moduleSubType: ModuleSubType,
additionalParams: List<Any?> = listOf()
) =
TargetAccessIR(
moduleSubType,
name.takeIf { it != moduleSubType.toString() },
additionalParams.filterNotNull()
)
interface JsTargetConfigurator : JSConfigurator, TargetConfigurator, SingleCoexistenceTargetConfigurator, ModuleConfiguratorWithSettings
enum class JsTargetKind(override val text: String) : DisplayableSettingItem {
LIBRARY(KotlinNewProjectWizardBundle.message("module.configurator.js.target.settings.kind.library")),
APPLICATION(KotlinNewProjectWizardBundle.message("module.configurator.js.target.settings.kind.application"))
}
enum class JsCompiler(override val text: String, val scriptValue: String) : DisplayableSettingItem {
IR(KotlinNewProjectWizardBundle.message("module.configurator.js.target.settings.compiler.ir"), "IR"),
LEGACY(KotlinNewProjectWizardBundle.message("module.configurator.js.target.settings.compiler.legacy"), "LEGACY"),
BOTH(KotlinNewProjectWizardBundle.message("module.configurator.js.target.settings.compiler.both"), "BOTH")
}
abstract class AbstractBrowserTargetConfigurator: JsTargetConfigurator, ModuleConfiguratorWithTests {
override fun getConfiguratorSettings(): List<ModuleConfiguratorSetting<*, *>> =
super<JsTargetConfigurator>.getConfiguratorSettings()
override val text = KotlinNewProjectWizardBundle.message("module.configurator.js.browser")
override fun defaultTestFramework(): KotlinTestFramework = KotlinTestFramework.JS
override fun Reader.createTargetIrs(
module: Module
): List<BuildSystemIR> = irsList {
+DefaultTargetConfigurationIR(
module.createTargetAccessIr(
ModuleSubType.js,
createAdditionalParams(module)
)
) {
browserSubTarget(module, this@createTargetIrs)
}
}
abstract fun Reader.createAdditionalParams(module: Module): List<String>
}
object JsBrowserTargetConfigurator : AbstractBrowserTargetConfigurator() {
@NonNls
override val id = "jsBrowser"
override fun Reader.createAdditionalParams(module: Module): List<String> = listOf(irOrLegacyCompiler(module))
}
object MppLibJsBrowserTargetConfigurator : AbstractBrowserTargetConfigurator() {
@NonNls
override val id = "mppLibJsBrowser"
override fun getConfiguratorSettings(): List<ModuleConfiguratorSetting<*, *>> {
return listOf(testFramework, kind, compiler)
}
override fun Reader.createAdditionalParams(module: Module): List<String> = jsCompilerParam(module)?.let { listOf(it) } ?: emptyList()
}
object JsNodeTargetConfigurator : JsTargetConfigurator {
@NonNls
override val id = "jsNode"
override val text = KotlinNewProjectWizardBundle.message("module.configurator.js.node")
override fun Reader.createTargetIrs(module: Module): List<BuildSystemIR> = irsList {
+DefaultTargetConfigurationIR(
module.createTargetAccessIr(
ModuleSubType.js,
listOf(irOrLegacyCompiler(module))
)
) {
nodejsSubTarget(module, this@createTargetIrs)
}
}
}
object CommonTargetConfigurator : TargetConfiguratorWithTests(), SimpleTargetConfigurator, SingleCoexistenceTargetConfigurator {
override val moduleSubType = ModuleSubType.common
override val text: String = KotlinNewProjectWizardBundle.message("module.configurator.common")
override fun defaultTestFramework(): KotlinTestFramework = KotlinTestFramework.COMMON
override fun getConfiguratorSettings(): List<ModuleConfiguratorSetting<*, *>> = emptyList()
}
object JvmTargetConfigurator : JvmModuleConfigurator,
TargetConfigurator,
SimpleTargetConfigurator {
override val moduleSubType = ModuleSubType.jvm
override val text: String = KotlinNewProjectWizardBundle.message("module.configurator.jvm")
override fun defaultTestFramework(): KotlinTestFramework = KotlinTestFramework.JUNIT5
override fun createInnerTargetIrs(
reader: Reader,
module: Module
): List<BuildSystemIR> = irsList {
+super<SimpleTargetConfigurator>.createInnerTargetIrs(reader, module)
reader {
inContextOfModuleConfigurator(module) {
val targetVersionValue = JvmModuleConfigurator.targetJvmVersion.reference.settingValue
if (buildSystemType.isGradle) {
+JvmToolchainConfigurationIR(targetVersionValue)
}
if (!module.hasAndroidSibling()) {
"withJava"()
}
}
val testFramework = inContextOfModuleConfigurator(module) { getTestFramework(module) }
if (testFramework != KotlinTestFramework.NONE) {
testFramework.usePlatform?.let { usePlatform ->
"testRuns[\"test\"].executionTask.configure" {
+"$usePlatform()"
}
}
}
}
}
private fun Module.hasAndroidSibling(): Boolean =
configurator is TargetConfigurator
&& parent?.subModules?.any { it.configurator is AndroidModuleConfigurator } ?: false
}
|
apache-2.0
|
610099dee411eda50ebe88fd8609ecb6
| 43.913706 | 158 | 0.759494 | 5.368932 | false | true | false | false |
google/iosched
|
mobile/src/main/java/com/google/samples/apps/iosched/ui/search/SearchViewModel.kt
|
1
|
5861
|
/*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.ui.search
import androidx.core.os.trace
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.samples.apps.iosched.model.userdata.UserSession
import com.google.samples.apps.iosched.shared.analytics.AnalyticsActions
import com.google.samples.apps.iosched.shared.analytics.AnalyticsHelper
import com.google.samples.apps.iosched.shared.domain.search.LoadSearchFiltersUseCase
import com.google.samples.apps.iosched.shared.domain.search.SessionSearchUseCase
import com.google.samples.apps.iosched.shared.domain.search.SessionSearchUseCaseParams
import com.google.samples.apps.iosched.shared.domain.settings.GetTimeZoneUseCase
import com.google.samples.apps.iosched.shared.result.Result
import com.google.samples.apps.iosched.shared.result.Result.Loading
import com.google.samples.apps.iosched.shared.result.successOr
import com.google.samples.apps.iosched.shared.util.TimeUtils
import com.google.samples.apps.iosched.ui.filters.FiltersViewModelDelegate
import com.google.samples.apps.iosched.ui.signin.SignInViewModelDelegate
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import org.threeten.bp.ZoneId
import javax.inject.Inject
@HiltViewModel
class SearchViewModel @Inject constructor(
private val analyticsHelper: AnalyticsHelper,
private val searchUseCase: SessionSearchUseCase,
getTimeZoneUseCase: GetTimeZoneUseCase,
loadFiltersUseCase: LoadSearchFiltersUseCase,
signInViewModelDelegate: SignInViewModelDelegate,
filtersViewModelDelegate: FiltersViewModelDelegate
) : ViewModel(),
SignInViewModelDelegate by signInViewModelDelegate,
FiltersViewModelDelegate by filtersViewModelDelegate {
private val _searchResults = MutableStateFlow<List<UserSession>>(emptyList())
val searchResults: StateFlow<List<UserSession>> = _searchResults
private val _isEmpty = MutableStateFlow(true)
val isEmpty: StateFlow<Boolean> = _isEmpty
private var searchJob: Job? = null
val timeZoneId: StateFlow<ZoneId> = flow {
if (getTimeZoneUseCase(Unit).successOr(true)) {
emit(TimeUtils.CONFERENCE_TIMEZONE)
} else {
emit(ZoneId.systemDefault())
}
}.stateIn(viewModelScope, SharingStarted.Lazily, ZoneId.systemDefault())
private var textQuery = ""
// Override because we also want to show result count when there's a text query.
private val _showResultCount = MutableStateFlow(false)
override val showResultCount: StateFlow<Boolean> = _showResultCount
init {
// Load filters
viewModelScope.launch {
setSupportedFilters(loadFiltersUseCase(Unit).successOr(emptyList()))
}
// Re-execute search when selected filters change
viewModelScope.launch {
selectedFilters.collect {
executeSearch()
}
}
// Re-execute search when signed in user changes.
// Required because we show star / reservation status.
viewModelScope.launch {
userInfo.collect {
executeSearch()
}
}
}
fun onSearchQueryChanged(query: String) {
val newQuery = query.trim().takeIf { it.length >= 2 } ?: ""
if (textQuery != newQuery) {
textQuery = newQuery
analyticsHelper.logUiEvent("Query: $newQuery", AnalyticsActions.SEARCH_QUERY_SUBMIT)
executeSearch()
}
}
private fun executeSearch() {
// Cancel any in-flight searches
searchJob?.cancel()
val filters = selectedFilters.value
if (textQuery.isEmpty() && filters.isEmpty()) {
clearSearchResults()
return
}
searchJob = viewModelScope.launch {
// The user could be typing or toggling filters rapidly. Giving the search job
// a slight delay and cancelling it on each call to this method effectively debounces.
delay(500)
trace("search-path-viewmodel") {
searchUseCase(
SessionSearchUseCaseParams(userIdValue, textQuery, filters)
).collect {
processSearchResult(it)
}
}
}
}
private fun clearSearchResults() {
_searchResults.value = emptyList()
// Explicitly set false to not show the "No results" state
_isEmpty.value = false
_showResultCount.value = false
resultCount.value = 0
}
private fun processSearchResult(searchResult: Result<List<UserSession>>) {
if (searchResult is Loading) {
return // avoids UI flickering
}
val sessions = searchResult.successOr(emptyList())
_searchResults.value = sessions
_isEmpty.value = sessions.isEmpty()
_showResultCount.value = true
resultCount.value = sessions.size
}
}
|
apache-2.0
|
ba3ab8ebdf086f1b33814890edaa7ec2
| 36.812903 | 98 | 0.706705 | 4.831822 | false | false | false | false |
spacecowboy/Feeder
|
app/src/main/java/com/nononsenseapps/feeder/db/room/SyncDevice.kt
|
1
|
1115
|
package com.nononsenseapps.feeder.db.room
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Ignore
import androidx.room.Index
import androidx.room.PrimaryKey
import com.nononsenseapps.feeder.db.COL_ID
import com.nononsenseapps.feeder.db.SYNC_DEVICE_TABLE_NAME
@Entity(
tableName = SYNC_DEVICE_TABLE_NAME,
indices = [
Index(value = ["sync_remote", "device_id"], unique = true),
Index(value = ["sync_remote"]),
],
foreignKeys = [
ForeignKey(
entity = SyncRemote::class,
parentColumns = [COL_ID],
childColumns = ["sync_remote"],
onDelete = ForeignKey.CASCADE,
)
]
)
data class SyncDevice @Ignore constructor(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = COL_ID) var id: Long = ID_UNSET,
@ColumnInfo(name = "sync_remote") var syncRemote: Long = ID_UNSET,
@ColumnInfo(name = "device_id") var deviceId: Long = ID_UNSET,
@ColumnInfo(name = "device_name") var deviceName: String = "",
) {
constructor() : this(id = ID_UNSET)
}
|
gpl-3.0
|
d4079121459acc43e92d174a7d01e9b2
| 30.857143 | 70 | 0.66278 | 3.844828 | false | false | false | false |
StepicOrg/stepik-android
|
app/src/main/java/org/stepik/android/domain/course/analytic/batch/CoursePreviewScreenOpenedAnalyticBatchEvent.kt
|
2
|
1354
|
package org.stepik.android.domain.course.analytic.batch
import org.stepik.android.domain.base.analytic.AnalyticEvent
import org.stepik.android.domain.base.analytic.AnalyticSource
import org.stepik.android.domain.course.analytic.CourseViewSource
import org.stepik.android.model.Course
import java.util.EnumSet
class CoursePreviewScreenOpenedAnalyticBatchEvent(
course: Course,
source: CourseViewSource
) : AnalyticEvent {
companion object {
private const val DATA = "data"
private const val PARAM_COURSE = "course"
private const val PARAM_SOURCE = "source"
private const val PARAM_PLATFORM = "platform"
private const val PARAM_POSITION = "position"
private const val PARAM_DATA = "data"
private const val PLATFORM_VALUE = "android"
private const val POSITION_VALUE = 1
}
override val name: String =
"catalog-click"
override val params: Map<String, Any> =
mapOf(
DATA to mapOf(
PARAM_COURSE to course.id,
PARAM_SOURCE to source.name,
PARAM_PLATFORM to PLATFORM_VALUE,
PARAM_POSITION to POSITION_VALUE,
PARAM_DATA to source.params
)
)
override val sources: EnumSet<AnalyticSource> =
EnumSet.of(AnalyticSource.STEPIK_API)
}
|
apache-2.0
|
e8929f1dd246bfd29126856dfc049292
| 31.261905 | 65 | 0.664697 | 4.558923 | false | false | false | false |
zdary/intellij-community
|
plugins/git4idea/src/git4idea/light/LightGitEditorHighlighterManager.kt
|
3
|
4109
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.light
import com.intellij.ide.lightEdit.LightEditService
import com.intellij.ide.lightEdit.LightEditorInfo
import com.intellij.ide.lightEdit.LightEditorInfoImpl
import com.intellij.ide.lightEdit.LightEditorListener
import com.intellij.openapi.Disposable
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vcs.ex.SimpleLocalLineStatusTracker
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.vcs.log.BaseSingleTaskController
import git4idea.index.isTracked
import git4idea.index.repositoryPath
import org.jetbrains.annotations.NonNls
class LightGitEditorHighlighterManager(val tracker: LightGitTracker) : Disposable {
private val singleTaskController = MySingleTaskController()
private var lst: SimpleLocalLineStatusTracker? = null
private val lightEditService
get() = LightEditService.getInstance()
init {
tracker.addUpdateListener(object : LightGitTrackerListener {
override fun update() {
lightEditService.selectedFileEditor?.let { fileEditor -> updateLst(fileEditor) }
}
}, this)
lightEditService.editorManager.addListener(object : LightEditorListener {
override fun afterSelect(editorInfo: LightEditorInfo?) {
if (editorInfo == null) {
dropLst()
return
}
if (editorInfo.file != lst?.virtualFile) {
dropLst()
updateLst(editorInfo.fileEditor)
}
}
}, this)
Disposer.register(tracker, this)
}
private fun readBaseVersion(file: VirtualFile, repositoryPath: String?) {
if (repositoryPath == null) {
lst?.setBaseRevision("")
return
}
singleTaskController.request(Request(file, repositoryPath))
}
private fun setBaseVersion(baseVersion: BaseVersion) {
if (lightEditService.selectedFile == baseVersion.file && lst?.virtualFile == baseVersion.file) {
if (baseVersion.text != null) {
lst?.setBaseRevision(baseVersion.text)
} else {
dropLst()
}
}
}
private fun updateLst(fileEditor: FileEditor) {
val editor = LightEditorInfoImpl.getEditor(fileEditor)
val file = fileEditor.file
if (editor == null || file == null) {
dropLst()
return
}
val status = tracker.getFileStatus(file)
if (!status.isTracked()) {
dropLst()
return
}
if (lst == null) {
lst = SimpleLocalLineStatusTracker.createTracker(lightEditService.project, editor.document, file)
}
readBaseVersion(file, status.repositoryPath)
}
private fun dropLst() {
lst?.release()
lst = null
}
override fun dispose() {
dropLst()
}
private inner class MySingleTaskController :
BaseSingleTaskController<Request, BaseVersion>("light.highlighter", this::setBaseVersion, this) {
override fun process(requests: List<Request>, previousResult: BaseVersion?): BaseVersion {
val request = requests.last()
try {
val content = getFileContentAsString(request.file, request.repositoryPath, tracker.gitExecutable)
return BaseVersion(request.file, StringUtil.convertLineSeparators(content))
} catch (e: VcsException) {
LOG.warn("Could not read base version for ${request.file}", e)
return BaseVersion(request.file, null)
}
}
override fun cancelRunningTasks(requests: List<Request>): Boolean = true
}
private data class Request(val file: VirtualFile, val repositoryPath: String)
private data class BaseVersion(val file: VirtualFile, val text: String?) {
override fun toString(): @NonNls String {
return "BaseVersion(file=$file, text=${text?.take(10) ?: "null"}"
}
}
companion object {
private val LOG = Logger.getInstance("#git4idea.light.LightGitEditorHighlighterManager")
}
}
|
apache-2.0
|
632c5fd6fde1bcd345ae796e48d1613d
| 31.872 | 140 | 0.714529 | 4.570634 | false | false | false | false |
leafclick/intellij-community
|
plugins/github/src/org/jetbrains/plugins/github/pullrequest/GHPRComponentFactory.kt
|
1
|
20007
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest
import com.intellij.codeInsight.AutoPopupController
import com.intellij.diff.editor.VCSContentVirtualFile
import com.intellij.ide.DataManager
import com.intellij.ide.actions.RefreshAction
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.components.Service
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.impl.EditorWindowHolder
import com.intellij.openapi.ide.CopyPasteManager
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ui.componentsList.components.ScrollablePanel
import com.intellij.openapi.ui.Splitter
import com.intellij.openapi.ui.VerticalFlowLayout
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.*
import com.intellij.ui.components.JBPanelWithEmptyText
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.CalledInAwt
import org.jetbrains.plugins.github.api.GithubApiRequestExecutor
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequest
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
import org.jetbrains.plugins.github.pullrequest.action.GHPRActionKeys
import org.jetbrains.plugins.github.pullrequest.action.GHPRListSelectionActionDataContext
import org.jetbrains.plugins.github.pullrequest.avatars.CachingGithubAvatarIconsProvider
import org.jetbrains.plugins.github.pullrequest.config.GithubPullRequestsProjectUISettings
import org.jetbrains.plugins.github.pullrequest.data.GHPRDataContext
import org.jetbrains.plugins.github.pullrequest.data.GHPRDataContextRepository
import org.jetbrains.plugins.github.pullrequest.data.GHPRDataProvider
import org.jetbrains.plugins.github.pullrequest.search.GithubPullRequestSearchPanel
import org.jetbrains.plugins.github.pullrequest.ui.*
import org.jetbrains.plugins.github.pullrequest.ui.changes.*
import org.jetbrains.plugins.github.pullrequest.ui.details.GHPRDescriptionPanel
import org.jetbrains.plugins.github.pullrequest.ui.details.GHPRMetadataPanel
import org.jetbrains.plugins.github.ui.util.SingleValueModel
import org.jetbrains.plugins.github.util.*
import java.awt.BorderLayout
import java.awt.Component
import java.awt.event.FocusEvent
import java.awt.event.FocusListener
import javax.swing.JComponent
import javax.swing.event.ListDataEvent
import javax.swing.event.ListDataListener
import javax.swing.event.ListSelectionEvent
@Service
internal class GHPRComponentFactory(private val project: Project) {
private val progressManager = ProgressManager.getInstance()
private val actionManager = ActionManager.getInstance()
private val copyPasteManager = CopyPasteManager.getInstance()
private val avatarLoader = CachingGithubUserAvatarLoader.getInstance()
private val imageResizer = GithubImageResizer.getInstance()
private var ghprVirtualFile: VCSContentVirtualFile? = null
private var ghprEditorContent: JComponent? = null
private val autoPopupController = AutoPopupController.getInstance(project)
private val projectUiSettings = GithubPullRequestsProjectUISettings.getInstance(project)
private val dataContextRepository = GHPRDataContextRepository.getInstance(project)
@CalledInAwt
fun createComponent(remoteUrl: GitRemoteUrlCoordinates, account: GithubAccount, requestExecutor: GithubApiRequestExecutor,
parentDisposable: Disposable): JComponent {
val contextDisposable = Disposer.newDisposable()
val contextValue = object : LazyCancellableBackgroundProcessValue<GHPRDataContext>(progressManager) {
override fun compute(indicator: ProgressIndicator) =
dataContextRepository.getContext(indicator, account, requestExecutor, remoteUrl).also {
Disposer.register(contextDisposable, it)
}
}
Disposer.register(parentDisposable, contextDisposable)
Disposer.register(parentDisposable, Disposable { contextValue.drop() })
val uiDisposable = Disposer.newDisposable()
Disposer.register(parentDisposable, uiDisposable)
val loadingModel = GHCompletableFutureLoadingModel<GHPRDataContext>()
val contentContainer = JBPanelWithEmptyText(null).apply {
background = UIUtil.getListBackground()
}
loadingModel.addStateChangeListener(object : GHLoadingModel.StateChangeListener {
override fun onLoadingCompleted() {
val dataContext = loadingModel.result
if (dataContext != null) {
var content = createContent(dataContext, uiDisposable)
if (Registry.`is`("show.log.as.editor.tab")) {
content = patchContent(content)
}
with(contentContainer) {
layout = BorderLayout()
add(content, BorderLayout.CENTER)
validate()
repaint()
}
}
}
})
loadingModel.future = contextValue.value
return GHLoadingPanel(loadingModel, contentContainer, uiDisposable,
GHLoadingPanel.EmptyTextBundle.Simple("", "Can't load data from GitHub")).apply {
errorHandler = GHLoadingErrorHandlerImpl(project, account) {
contextValue.drop()
loadingModel.future = contextValue.value
}
}
}
private fun patchContent(content: JComponent): JComponent {
var patchedContent = content
val onePixelSplitter = patchedContent as OnePixelSplitter
val splitter = onePixelSplitter.secondComponent as Splitter
patchedContent = splitter.secondComponent
onePixelSplitter.secondComponent = splitter.firstComponent
installEditor(onePixelSplitter)
return patchedContent
}
private fun installEditor(onePixelSplitter: OnePixelSplitter) {
ghprEditorContent = onePixelSplitter
ApplicationManager.getApplication().invokeLater({ tryOpenGHPREditorTab() }, ModalityState.NON_MODAL)
}
@CalledInAwt
private fun getOrCreateGHPRViewFile(): VirtualFile? {
ApplicationManager.getApplication().assertIsDispatchThread()
if (ghprEditorContent == null) return null
if (ghprVirtualFile == null) {
val content = ghprEditorContent ?: error("editor content should be created by this time")
ghprVirtualFile = VCSContentVirtualFile(content) { "GitHub Pull Requests" }
ghprVirtualFile?.putUserData(VCSContentVirtualFile.TabSelector) {
GithubUIUtil.findAndSelectGitHubContent(project, true)
}
}
Disposer.register(project, Disposable { ghprVirtualFile = null })
return ghprVirtualFile ?: error("error")
}
fun tryOpenGHPREditorTab() {
val file = getOrCreateGHPRViewFile() ?: return
val editors = FileEditorManager.getInstance(project).openFile(file, true)
assert(editors.size == 1) { "opened multiple log editors for $file" }
val editor = editors[0]
val component = editor.component
val holder = ComponentUtil.getParentOfType(EditorWindowHolder::class.java as Class<out EditorWindowHolder>, component as Component)
?: return
val editorWindow = holder.editorWindow
editorWindow.setFilePinned(file, true)
}
private fun createContent(dataContext: GHPRDataContext, disposable: Disposable): JComponent {
val avatarIconsProviderFactory = CachingGithubAvatarIconsProvider.Factory(avatarLoader, imageResizer, dataContext.requestExecutor)
val listSelectionHolder = GithubPullRequestsListSelectionHolderImpl()
val actionDataContext = GHPRListSelectionActionDataContext(dataContext, listSelectionHolder, avatarIconsProviderFactory)
val list = createListComponent(dataContext, listSelectionHolder, avatarIconsProviderFactory, disposable)
val dataProviderModel = createDataProviderModel(dataContext, listSelectionHolder, disposable)
val detailsLoadingModel = createDetailsLoadingModel(dataProviderModel, disposable)
val detailsModel = createValueModel(detailsLoadingModel)
val detailsPanel = createDetailsPanel(dataContext, detailsModel, avatarIconsProviderFactory, disposable)
val detailsLoadingPanel = GHLoadingPanel(detailsLoadingModel, detailsPanel, disposable,
GHLoadingPanel.EmptyTextBundle.Simple("Select pull request to view details",
"Can't load details")).apply {
errorHandler = GHLoadingErrorHandlerImpl(project, dataContext.account) { dataProviderModel.value?.reloadDetails() }
}
val changesModel = GHPRChangesModelImpl(project)
val diffHelper = GHPRChangesDiffHelperImpl(dataContext.reviewService,
avatarIconsProviderFactory, dataContext.securityService.currentUser)
val changesLoadingModel = createChangesLoadingModel(changesModel, diffHelper,
dataProviderModel, projectUiSettings, disposable)
val changesBrowser = GHPRChangesBrowser(changesModel, diffHelper, project)
val changesLoadingPanel = GHLoadingPanel(changesLoadingModel, changesBrowser, disposable,
GHLoadingPanel.EmptyTextBundle.Simple("Select pull request to view changes",
"Can't load changes",
"Pull request does not contain any changes")).apply {
errorHandler = GHLoadingErrorHandlerImpl(project, dataContext.account) { dataProviderModel.value?.reloadChanges() }
}
return OnePixelSplitter("Github.PullRequests.Component", 0.33f).apply {
background = UIUtil.getListBackground()
isOpaque = true
isFocusCycleRoot = true
firstComponent = list
secondComponent = OnePixelSplitter("Github.PullRequest.Preview.Component", 0.5f).apply {
firstComponent = detailsLoadingPanel
secondComponent = changesLoadingPanel
}.also {
(actionManager.getAction("Github.PullRequest.Details.Reload") as RefreshAction).registerCustomShortcutSet(it, disposable)
}
}.also {
changesBrowser.diffAction.registerCustomShortcutSet(it, disposable)
DataManager.registerDataProvider(it) { dataId ->
if (Disposer.isDisposed(disposable)) null
else when {
GHPRActionKeys.ACTION_DATA_CONTEXT.`is`(dataId) -> actionDataContext
else -> null
}
}
}
}
private fun createListComponent(dataContext: GHPRDataContext,
listSelectionHolder: GithubPullRequestsListSelectionHolder,
avatarIconsProviderFactory: CachingGithubAvatarIconsProvider.Factory,
disposable: Disposable): JComponent {
val list = GHPRList(copyPasteManager, avatarIconsProviderFactory, dataContext.listModel).apply {
emptyText.clear()
}.also {
it.addFocusListener(object : FocusListener {
override fun focusGained(e: FocusEvent?) {
if (it.selectedIndex < 0 && !it.isEmpty) it.selectedIndex = 0
}
override fun focusLost(e: FocusEvent?) {}
})
installPopup(it)
installSelectionSaver(it, listSelectionHolder)
val shortcuts = CompositeShortcutSet(CommonShortcuts.ENTER, CommonShortcuts.DOUBLE_CLICK_1)
EmptyAction.registerWithShortcutSet("Github.PullRequest.Timeline.Show", shortcuts, it)
ListSpeedSearch(it) { item -> item.title }
}
val search = GithubPullRequestSearchPanel(project, autoPopupController, dataContext.searchHolder).apply {
border = IdeBorderFactory.createBorder(SideBorder.BOTTOM)
}
val listReloadAction = actionManager.getAction("Github.PullRequest.List.Reload") as RefreshAction
val loaderPanel = GHPRListLoaderPanel(dataContext.listLoader, listReloadAction, list, search).apply {
errorHandler = GHLoadingErrorHandlerImpl(project, dataContext.account) {
dataContext.listLoader.reset()
}
}.also {
listReloadAction.registerCustomShortcutSet(it, disposable)
}
Disposer.register(disposable, Disposable {
Disposer.dispose(list)
Disposer.dispose(search)
Disposer.dispose(loaderPanel)
})
return loaderPanel
}
private fun createDetailsPanel(dataContext: GHPRDataContext,
detailsModel: SingleValueModel<GHPullRequest?>,
avatarIconsProviderFactory: CachingGithubAvatarIconsProvider.Factory,
parentDisposable: Disposable): JBPanelWithEmptyText {
val metaPanel = GHPRMetadataPanel(project, detailsModel,
dataContext.securityService,
dataContext.busyStateTracker,
dataContext.metadataService,
avatarIconsProviderFactory).apply {
border = JBUI.Borders.empty(4, 8, 4, 8)
}.also {
Disposer.register(parentDisposable, it)
}
val descriptionPanel = GHPRDescriptionPanel(detailsModel).apply {
border = JBUI.Borders.empty(4, 8, 8, 8)
}
val scrollablePanel = ScrollablePanel(VerticalFlowLayout(0, 0)).apply {
isOpaque = false
add(metaPanel)
add(descriptionPanel)
}
val scrollPane = ScrollPaneFactory.createScrollPane(scrollablePanel, true).apply {
viewport.isOpaque = false
isOpaque = false
}.also {
val actionGroup = actionManager.getAction("Github.PullRequest.Details.Popup") as ActionGroup
PopupHandler.installPopupHandler(it, actionGroup, ActionPlaces.UNKNOWN, actionManager)
}
scrollPane.isVisible = detailsModel.value != null
detailsModel.addValueChangedListener {
scrollPane.isVisible = detailsModel.value != null
}
val panel = JBPanelWithEmptyText(BorderLayout()).apply {
isOpaque = false
add(scrollPane, BorderLayout.CENTER)
}
detailsModel.addValueChangedListener {
panel.validate()
}
return panel
}
private fun installPopup(list: GHPRList) {
val popupHandler = object : PopupHandler() {
override fun invokePopup(comp: java.awt.Component, x: Int, y: Int) {
if (ListUtil.isPointOnSelection(list, x, y)) {
val popupMenu = actionManager
.createActionPopupMenu("GithubPullRequestListPopup",
actionManager.getAction("Github.PullRequest.ToolWindow.List.Popup") as ActionGroup)
popupMenu.setTargetComponent(list)
popupMenu.component.show(comp, x, y)
}
}
}
list.addMouseListener(popupHandler)
}
private fun installSelectionSaver(list: GHPRList, listSelectionHolder: GithubPullRequestsListSelectionHolder) {
var savedSelectionNumber: Long? = null
list.selectionModel.addListSelectionListener { e: ListSelectionEvent ->
if (!e.valueIsAdjusting) {
val selectedIndex = list.selectedIndex
if (selectedIndex >= 0 && selectedIndex < list.model.size) {
listSelectionHolder.selectionNumber = list.model.getElementAt(selectedIndex).number
savedSelectionNumber = null
}
}
}
list.model.addListDataListener(object : ListDataListener {
override fun intervalAdded(e: ListDataEvent) {
if (e.type == ListDataEvent.INTERVAL_ADDED)
(e.index0..e.index1).find { list.model.getElementAt(it).number == savedSelectionNumber }
?.run { ApplicationManager.getApplication().invokeLater { ScrollingUtil.selectItem(list, this) } }
}
override fun contentsChanged(e: ListDataEvent) {}
override fun intervalRemoved(e: ListDataEvent) {
if (e.type == ListDataEvent.INTERVAL_REMOVED) savedSelectionNumber = listSelectionHolder.selectionNumber
}
})
}
private fun createChangesLoadingModel(changesModel: GHPRChangesModel,
diffHelper: GHPRChangesDiffHelper,
dataProviderModel: SingleValueModel<GHPRDataProvider?>,
uiSettings: GithubPullRequestsProjectUISettings,
disposable: Disposable): GHPRChangesLoadingModel {
val model = GHPRChangesLoadingModel(changesModel, diffHelper, uiSettings.zipChanges)
projectUiSettings.addChangesListener(disposable) { model.zipChanges = projectUiSettings.zipChanges }
val requestChangesListener = object : GHPRDataProvider.RequestsChangedListener {
override fun commitsRequestChanged() {
model.dataProvider = model.dataProvider
}
}
dataProviderModel.addValueChangedListener {
model.dataProvider?.removeRequestsChangesListener(requestChangesListener)
model.dataProvider = dataProviderModel.value?.apply {
addRequestsChangesListener(disposable, requestChangesListener)
}
}
return model
}
private fun createDetailsLoadingModel(dataProviderModel: SingleValueModel<GHPRDataProvider?>,
parentDisposable: Disposable): GHCompletableFutureLoadingModel<GHPullRequest> {
val model = GHCompletableFutureLoadingModel<GHPullRequest>()
var listenerDisposable: Disposable? = null
dataProviderModel.addValueChangedListener {
val provider = dataProviderModel.value
model.future = provider?.detailsRequest
listenerDisposable = listenerDisposable?.let {
Disposer.dispose(it)
null
}
if (provider != null) {
val disposable = Disposer.newDisposable().apply {
Disposer.register(parentDisposable, this)
}
provider.addRequestsChangesListener(disposable, object : GHPRDataProvider.RequestsChangedListener {
override fun detailsRequestChanged() {
model.future = provider.detailsRequest
}
})
listenerDisposable = disposable
}
}
return model
}
private fun <T> createValueModel(loadingModel: GHSimpleLoadingModel<T>): SingleValueModel<T?> {
val model = SingleValueModel<T?>(null)
loadingModel.addStateChangeListener(object : GHLoadingModel.StateChangeListener {
override fun onLoadingCompleted() {
model.value = loadingModel.result
}
override fun onReset() {
model.value = loadingModel.result
}
})
return model
}
private fun createDataProviderModel(dataContext: GHPRDataContext,
listSelectionHolder: GithubPullRequestsListSelectionHolder,
parentDisposable: Disposable): SingleValueModel<GHPRDataProvider?> {
val model: SingleValueModel<GHPRDataProvider?> = SingleValueModel(null)
fun setNewProvider(provider: GHPRDataProvider?) {
val oldValue = model.value
if (oldValue != null && provider != null && oldValue.number != provider.number) {
model.value = null
}
model.value = provider
}
Disposer.register(parentDisposable, Disposable {
model.value = null
})
listSelectionHolder.addSelectionChangeListener(parentDisposable) {
setNewProvider(listSelectionHolder.selectionNumber?.let(dataContext.dataLoader::getDataProvider))
}
dataContext.dataLoader.addInvalidationListener(parentDisposable) {
val selection = listSelectionHolder.selectionNumber
if (selection != null && selection == it) {
setNewProvider(dataContext.dataLoader.getDataProvider(selection))
}
}
return model
}
}
|
apache-2.0
|
f0445a6c42804d375683095492cd305a
| 42.683406 | 140 | 0.7155 | 5.670918 | false | false | false | false |
exponent/exponent
|
android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/sqlite/SQLiteModule.kt
|
2
|
5409
|
// Copyright 2015-present 650 Industries. All rights reserved.
package abi43_0_0.expo.modules.sqlite
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import abi43_0_0.expo.modules.core.ExportedModule
import abi43_0_0.expo.modules.core.Promise
import abi43_0_0.expo.modules.core.interfaces.ExpoMethod
import java.io.File
import java.io.IOException
import java.util.*
private val TAG = SQLiteModule::class.java.simpleName
private val EMPTY_ROWS = arrayOf<Array<Any?>>()
private val EMPTY_COLUMNS = arrayOf<String?>()
private val EMPTY_RESULT = SQLiteModule.SQLitePluginResult(EMPTY_ROWS, EMPTY_COLUMNS, 0, 0, null)
private val DATABASES: MutableMap<String, SQLiteDatabase?> = HashMap()
class SQLiteModule(private val mContext: Context) : ExportedModule(mContext) {
override fun getName(): String {
return "ExponentSQLite"
}
@ExpoMethod
fun exec(dbName: String, queries: ArrayList<ArrayList<Any>>, readOnly: Boolean, promise: Promise) {
try {
val db = getDatabase(dbName)
val results = queries.map { sqlQuery ->
val sql = sqlQuery[0] as String
val bindArgs = convertParamsToStringArray(sqlQuery[1] as ArrayList<Any?>)
try {
if (isSelect(sql)) {
doSelectInBackgroundAndPossiblyThrow(sql, bindArgs, db)
} else { // update/insert/delete
if (readOnly) {
SQLitePluginResult(EMPTY_ROWS, EMPTY_COLUMNS, 0, 0, ReadOnlyException())
} else {
doUpdateInBackgroundAndPossiblyThrow(sql, bindArgs, db)
}
}
} catch (e: Throwable) {
SQLitePluginResult(EMPTY_ROWS, EMPTY_COLUMNS, 0, 0, e)
}
}
val data = pluginResultsToPrimitiveData(results)
promise.resolve(data)
} catch (e: Exception) {
promise.reject("SQLiteError", e)
}
}
@ExpoMethod
fun close(dbName: String, promise: Promise) {
DATABASES
.remove(dbName)
?.close()
promise.resolve(null)
}
// do a update/delete/insert operation
private fun doUpdateInBackgroundAndPossiblyThrow(
sql: String,
bindArgs: Array<String?>?,
db: SQLiteDatabase
): SQLitePluginResult {
return db.compileStatement(sql).use { statement ->
if (bindArgs != null) {
for (i in bindArgs.size downTo 1) {
if (bindArgs[i - 1] == null) {
statement.bindNull(i)
} else {
statement.bindString(i, bindArgs[i - 1])
}
}
}
if (isInsert(sql)) {
val insertId = statement.executeInsert()
val rowsAffected = if (insertId >= 0) 1 else 0
SQLitePluginResult(EMPTY_ROWS, EMPTY_COLUMNS, rowsAffected, insertId, null)
} else if (isDelete(sql) || isUpdate(sql)) {
val rowsAffected = statement.executeUpdateDelete()
SQLitePluginResult(EMPTY_ROWS, EMPTY_COLUMNS, rowsAffected, 0, null)
} else {
// in this case, we don't need rowsAffected or insertId, so we can have a slight
// perf boost by just executing the query
statement.execute()
EMPTY_RESULT
}
}
}
// do a select operation
private fun doSelectInBackgroundAndPossiblyThrow(
sql: String,
bindArgs: Array<String?>,
db: SQLiteDatabase
): SQLitePluginResult {
return db.rawQuery(sql, bindArgs).use { cursor ->
val numRows = cursor.count
if (numRows == 0) {
return EMPTY_RESULT
}
val numColumns = cursor.columnCount
val columnNames = cursor.columnNames
val rows: Array<Array<Any?>> = Array(numRows) { arrayOfNulls(numColumns) }
var i = 0
while (cursor.moveToNext()) {
val row = rows[i]
for (j in 0 until numColumns) {
row[j] = getValueFromCursor(cursor, j, cursor.getType(j))
}
rows[i] = row
i++
}
SQLitePluginResult(rows, columnNames, 0, 0, null)
}
}
private fun getValueFromCursor(cursor: Cursor, index: Int, columnType: Int): Any? {
return when (columnType) {
Cursor.FIELD_TYPE_FLOAT -> cursor.getDouble(index)
Cursor.FIELD_TYPE_INTEGER -> cursor.getLong(index)
Cursor.FIELD_TYPE_BLOB ->
// convert byte[] to binary string; it's good enough, because
// WebSQL doesn't support blobs anyway
String(cursor.getBlob(index))
Cursor.FIELD_TYPE_STRING -> cursor.getString(index)
else -> null
}
}
@Throws(IOException::class)
private fun pathForDatabaseName(name: String): String {
val directory = File("${mContext.filesDir}${File.separator}SQLite")
ensureDirExists(directory)
return "$directory${File.separator}$name"
}
@Throws(IOException::class)
private fun getDatabase(name: String): SQLiteDatabase {
var database: SQLiteDatabase? = null
val path = pathForDatabaseName(name)
if (File(path).exists()) {
database = DATABASES[name]
}
if (database == null) {
DATABASES.remove(name)
database = SQLiteDatabase.openOrCreateDatabase(path, null)
DATABASES[name] = database
}
return database!!
}
internal class SQLitePluginResult(
val rows: Array<Array<Any?>>,
val columns: Array<String?>,
val rowsAffected: Int,
val insertId: Long,
val error: Throwable?
)
private class ReadOnlyException : Exception("could not prepare statement (23 not authorized)")
}
|
bsd-3-clause
|
fa1f054787ed0bd26ecdcc884db43dd8
| 31.981707 | 101 | 0.650582 | 4.212617 | false | false | false | false |
Fotoapparat/Fotoapparat
|
fotoapparat/src/main/java/io/fotoapparat/hardware/Executor.kt
|
1
|
893
|
package io.fotoapparat.hardware
import android.os.Handler
import android.os.Looper
import java.util.concurrent.Executors
private val loggingExecutor = Executors.newSingleThreadExecutor()
private val mainThreadHandler = Handler(Looper.getMainLooper())
/**
* [java.util.concurrent.Executor] operating the [io.fotoapparat.result.PendingResult].
*/
internal val pendingResultExecutor = Executors.newSingleThreadExecutor()
/**
* [java.util.concurrent.Executor] operating the [io.fotoapparat.preview.PreviewStream].
*/
internal val frameProcessingExecutor = Executors.newSingleThreadExecutor()
/**
* Executes an operation in the main thread.
*/
internal fun executeLoggingThread(function: () -> Unit) = loggingExecutor.execute { function() }
/**
* Executes an operation in the main thread.
*/
internal fun executeMainThread(function: () -> Unit) = mainThreadHandler.post { function() }
|
apache-2.0
|
c628045ab1c45127f7967c663341e384
| 32.074074 | 96 | 0.778275 | 4.465 | false | false | false | false |
jotomo/AndroidAPS
|
app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAFragment.kt
|
1
|
4938
|
package info.nightscout.androidaps.plugins.aps.openAPSAMA
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import dagger.android.support.DaggerFragment
import info.nightscout.androidaps.R
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.aps.events.EventOpenAPSUpdateGui
import info.nightscout.androidaps.plugins.aps.events.EventOpenAPSUpdateResultGui
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.JSONFormatter
import info.nightscout.androidaps.utils.extensions.plusAssign
import info.nightscout.androidaps.utils.resources.ResourceHelper
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.openapsama_fragment.*
import org.json.JSONArray
import org.json.JSONException
import javax.inject.Inject
class OpenAPSAMAFragment : DaggerFragment() {
private var disposable: CompositeDisposable = CompositeDisposable()
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var openAPSAMAPlugin: OpenAPSAMAPlugin
@Inject lateinit var dateUtil: DateUtil
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.openapsama_fragment, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
openapsma_run.setOnClickListener {
openAPSAMAPlugin.invoke("OpenAPSAMA button", false)
}
}
@Synchronized
override fun onResume() {
super.onResume()
disposable += rxBus
.toObservable(EventOpenAPSUpdateGui::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
updateGUI()
}, { fabricPrivacy.logException(it) })
disposable += rxBus
.toObservable(EventOpenAPSUpdateResultGui::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
updateResultGUI(it.text)
}, { fabricPrivacy.logException(it) })
updateGUI()
}
@Synchronized
override fun onPause() {
super.onPause()
disposable.clear()
}
@Synchronized
private fun updateGUI() {
if (openapsma_result == null) return
openAPSAMAPlugin.lastAPSResult?.let { lastAPSResult ->
openapsma_result.text = JSONFormatter.format(lastAPSResult.json)
openapsma_request.text = lastAPSResult.toSpanned()
}
openAPSAMAPlugin.lastDetermineBasalAdapterAMAJS?.let { determineBasalAdapterAMAJS ->
openapsma_glucosestatus.text = JSONFormatter.format(determineBasalAdapterAMAJS.glucoseStatusParam)
openapsma_currenttemp.text = JSONFormatter.format(determineBasalAdapterAMAJS.currentTempParam)
try {
val iobArray = JSONArray(determineBasalAdapterAMAJS.iobDataParam)
openapsma_iobdata.text = TextUtils.concat(resourceHelper.gs(R.string.array_of_elements, iobArray.length()) + "\n", JSONFormatter.format(iobArray.getString(0)))
} catch (e: JSONException) {
aapsLogger.error(LTag.APS, "Unhandled exception", e)
@Suppress("SetTextI18n")
openapsma_iobdata.text = "JSONException see log for details"
}
openapsma_profile.text = JSONFormatter.format(determineBasalAdapterAMAJS.profileParam)
openapsma_mealdata.text = JSONFormatter.format(determineBasalAdapterAMAJS.mealDataParam)
openapsma_scriptdebugdata.text = determineBasalAdapterAMAJS.scriptDebug
}
if (openAPSAMAPlugin.lastAPSRun != 0L) {
openapsma_lastrun.text = dateUtil.dateAndTimeString(openAPSAMAPlugin.lastAPSRun)
}
openAPSAMAPlugin.lastAutosensResult?.let {
openapsma_autosensdata.text = JSONFormatter.format(it.json())
}
}
private fun updateResultGUI(text: String) {
openapsma_result.text = text
openapsma_glucosestatus.text = ""
openapsma_currenttemp.text = ""
openapsma_iobdata.text = ""
openapsma_profile.text = ""
openapsma_mealdata.text = ""
openapsma_autosensdata.text = ""
openapsma_scriptdebugdata.text = ""
openapsma_request.text = ""
openapsma_lastrun.text = ""
}
}
|
agpl-3.0
|
d0f1a1cdf963924514ba87f48ed6b59d
| 40.495798 | 175 | 0.707371 | 5.028513 | false | false | false | false |
mnowak32/EPIC
|
src/main/java/pl/cdbr/epic/model/Package.kt
|
1
|
1592
|
package pl.cdbr.epic.model
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.core.type.TypeReference
import com.fasterxml.jackson.databind.DeserializationContext
import com.fasterxml.jackson.databind.JsonDeserializer
import com.fasterxml.jackson.databind.JsonSerializer
import com.fasterxml.jackson.databind.SerializerProvider
import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import com.fasterxml.jackson.databind.annotation.JsonSerialize
import com.fasterxml.jackson.module.kotlin.jacksonTypeRef
import kotlin.reflect.full.createInstance
@JsonDeserialize(using = PackageDeserializer::class)
data class Package(val name: String)
class PackageDeserializer : JsonDeserializer<Package>() {
override fun deserialize(p: JsonParser, ctxt: DeserializationContext): Package {
val pack = p.readValueAs<Map<String, String>>(jacksonTypeRef<Map<String, String>>())
return Packager.of(pack["name"] ?: "none")
}
}
object Packager {
private val initial = listOf("DIP-4", "DIP-8", "DIP-10", "DIP-12", "DIP-14", "DIP-16", "DIP-18", "DIP-20", "TO-92", "TO-220")
val packs = mutableListOf<Package>()
fun initialData() = initial.map(::Package)
fun of(name: String): Package {
val p = packs.find { it.name == name }
return if (p == null) {
val newP = Package(name)
packs += newP
newP
} else {
p
}
}
fun load(packages: Collection<Package>) {
packages.forEach { of(it.name) }
}
}
|
mit
|
894ca05bc1f8443946810ddd36c80f2a
| 33.630435 | 129 | 0.704774 | 4.010076 | false | false | false | false |
kickstarter/android-oss
|
app/src/main/java/com/kickstarter/libs/utils/extensions/UriExt.kt
|
1
|
7853
|
@file:JvmName("UriExt")
package com.kickstarter.libs.utils.extensions
import android.net.Uri
import com.kickstarter.libs.utils.ObjectUtils
import com.kickstarter.libs.utils.Secrets
import java.util.regex.Pattern
fun Uri.host(): String {
return this.host ?: ""
}
fun Uri.lastPathSegment(): String {
return this.lastPathSegment ?: ""
}
fun Uri.path(): String {
return this.path ?: ""
}
fun Uri.query(): String {
return this.query ?: ""
}
const val SCHEME_KSR = "ksr"
const val SCHEME_HTTPS = "https"
/**
* Get token from Uri query params
* From "at={TOKEN}&ref=ksr_email_user_email_verification" to "{TOKEN}"
*/
fun Uri.getTokenFromQueryParams(): String {
return this.getQueryParameter("at") ?: ""
}
fun Uri.isSettingsUrl(): Boolean {
return this.toString().contains("/settings/notify_mobile_of_marketing_update/true")
}
/**
* Identify valid SCHEMAS "https:" or "ksr:"
*/
fun Uri.isKSScheme(): Boolean {
return (scheme == SCHEME_KSR || scheme == SCHEME_HTTPS)
}
/**
* Identify the Reward Fulfilled Deeplink
*/
fun Uri.isRewardFulfilledDl(): Boolean {
return isKSScheme() && isKickstarterUri(this.toString()) && PROJECT_REWARD_FULFILLMENT.matcher(path()).matches()
}
fun Uri.isVerificationEmailUrl(): Boolean {
return this.toString().contains(VERIFICATION)
}
fun Uri.isApiUri(webEndpoint: String): Boolean {
return isKickstarterUri(webEndpoint) && Secrets.RegExpPattern.API.matcher(host())
.matches()
}
fun Uri.isCheckoutUri(webEndpoint: String): Boolean {
return isKickstarterUri(webEndpoint) && NATIVE_CHECKOUT_PATTERN.matcher(path())
.matches()
}
fun Uri.isDiscoverCategoriesPath(): Boolean {
return DISCOVER_CATEGORIES_PATTERN.matcher(path()).matches()
}
fun Uri.isDiscoverScopePath(scope: String): Boolean {
val matcher = DISCOVER_SCOPE_PATTERN.matcher(path())
return matcher.matches() && scope == matcher.group(1)
}
fun Uri.isDiscoverPlacesPath(): Boolean {
return DISCOVER_PLACES_PATTERN.matcher(path()).matches()
}
fun Uri.isHivequeenUri(webEndpoint: String): Boolean {
return isKickstarterUri(webEndpoint) && Secrets.RegExpPattern.HIVEQUEEN.matcher(host()).matches()
}
fun Uri.isKickstarterUri(webEndpoint: String): Boolean {
return host() == Uri.parse(webEndpoint).host()
}
fun Uri.isKSFavIcon(webEndpoint: String): Boolean {
return isKickstarterUri(webEndpoint) && lastPathSegment() == "favicon.ico"
}
fun Uri.isWebViewUri(webEndpoint: String): Boolean {
return isKickstarterUri(webEndpoint) && !isKSFavIcon(webEndpoint)
}
fun Uri.isNewGuestCheckoutUri(webEndpoint: String): Boolean {
return isKickstarterUri(webEndpoint) && NEW_GUEST_CHECKOUT_PATTERN.matcher(path())
.matches()
}
fun Uri.isProjectUri(webEndpoint: String): Boolean {
return isKickstarterUri(webEndpoint) && PROJECT_PATTERN.matcher(path()).matches()
}
fun Uri.isProjectPreviewUri(webEndpoint: String): Boolean {
return isProjectUri(
webEndpoint
) && ObjectUtils.isNotNull(getQueryParameter("token"))
}
fun Uri.isSignupUri(webEndpoint: String): Boolean {
return isKickstarterUri(webEndpoint) && path() == "/signup"
}
fun Uri.isStagingUri(webEndpoint: String): Boolean {
return isKickstarterUri(webEndpoint) && Secrets.RegExpPattern.STAGING.matcher(host()).matches()
}
fun Uri.isCheckoutThanksUri(webEndpoint: String): Boolean {
return isKickstarterUri(webEndpoint) && CHECKOUT_THANKS_PATTERN.matcher(path())
.matches()
}
fun Uri.isModalUri(webEndpoint: String): Boolean {
return isKickstarterUri(webEndpoint) && getQueryParameter("modal") != null && getQueryParameter("modal") == "true"
}
fun Uri.isProjectSurveyUri(webEndpoint: String): Boolean {
return isKickstarterUri(webEndpoint) && PROJECT_SURVEY.matcher(path()).matches()
}
fun Uri.isProjectCommentUri(webEndpoint: String): Boolean {
return isKickstarterUri(webEndpoint) && PROJECT_COMMENTS_PATTERN.matcher(path())
.matches()
}
fun Uri.isProjectSaveUri(webEndpoint: String): Boolean {
return isKickstarterUri(webEndpoint) &&
PROJECT_PATTERN.matcher(path()).matches() &&
PROJECT_SAVE_QUERY_PATTERN.matcher(query()).matches()
}
fun Uri.isProjectUpdateCommentsUri(webEndpoint: String): Boolean {
return isKickstarterUri(webEndpoint) && PROJECT_UPDATE_COMMENTS_PATTERN.matcher(path()).matches()
}
fun Uri.isProjectUpdateUri(webEndpoint: String): Boolean {
return isKickstarterUri(webEndpoint) && PROJECT_UPDATE_PATTERN.matcher(path())
.matches()
}
fun Uri.isProjectUpdatesUri(webEndpoint: String): Boolean {
return isKickstarterUri(webEndpoint) && PROJECT_UPDATES_PATTERN.matcher(path())
.matches()
}
fun Uri.isUserSurveyUri(webEndpoint: String): Boolean {
return isKickstarterUri(webEndpoint) && USER_SURVEY.matcher(path()).matches()
}
fun Uri.isWebUri(webEndpoint: String): Boolean {
return isKickstarterUri(webEndpoint) && !isApiUri(webEndpoint)
}
fun Uri.isDiscoverSortParam(): Boolean {
return DISCOVER_SORT_PATTERN.matcher(path()).matches() &&
ObjectUtils.isNotNull(getQueryParameter("sort"))
}
private const val VERIFICATION = "/profile/verify_email"
// /projects/:creator_param/:project_param/checkouts/1/thanks
private val CHECKOUT_THANKS_PATTERN = Pattern.compile(
"\\A\\/projects(\\/[a-zA-Z0-9_-]+)?\\/[a-zA-Z0-9_-]+\\/checkouts\\/\\d+\\/thanks\\z"
)
// /discover/categories/param
private val DISCOVER_CATEGORIES_PATTERN = Pattern.compile("\\A\\/discover\\/categories\\/.*")
// /discover/param
private val DISCOVER_SCOPE_PATTERN = Pattern.compile("\\A\\/discover\\/([a-zA-Z0-9-_]+)\\z")
// /discover/places/param
private val DISCOVER_PLACES_PATTERN =
Pattern.compile("\\A\\/discover\\/places\\/[a-zA-Z0-9-_]+\\z")
// /discover/advanced?sort=param
private val DISCOVER_SORT_PATTERN = Pattern.compile("\\A\\/discover\\/advanced.*")
// /projects/:creator_param/:project_param/pledge
private val NATIVE_CHECKOUT_PATTERN = Pattern.compile(
"\\A\\/projects(\\/[a-zA-Z0-9_-]+)?\\/[a-zA-Z0-9_-]+\\/pledge\\z"
)
// /checkouts/:checkout_id/guest/new
private val NEW_GUEST_CHECKOUT_PATTERN = Pattern.compile(
"\\A\\/checkouts\\/[a-zA-Z0-9-_]+\\/guest\\/new\\z"
)
// /projects/:creator_param/:project_param
private val PROJECT_PATTERN = Pattern.compile(
"\\A\\/projects(\\/[a-zA-Z0-9_-]+)?\\/[a-zA-Z0-9_-]+\\/?\\z"
)
// /projects/:creator_param/:project_param/surveys/:survey_param
private val PROJECT_SURVEY = Pattern.compile(
"\\A\\/projects(\\/[a-zA-Z0-9_-]+)?\\/[a-zA-Z0-9_-]+\\/surveys\\/[a-zA-Z0-9-_]+\\z"
)
// /projects/:creator_param/:project_param/mark_reward_fulfilled/true
private val PROJECT_REWARD_FULFILLMENT = Pattern.compile(
"\\A/projects(\\/[a-zA-Z0-9_-]+)?\\/[a-zA-Z0-9_-]+\\/mark_reward_fulfilled/true+\\z"
)
// /projects/:creator_param/:project_param/comments
private val PROJECT_COMMENTS_PATTERN = Pattern.compile(
"\\A\\/projects(\\/[a-zA-Z0-9_-]+)?\\/[a-zA-Z0-9_-]+\\/comments\\z"
)
// save=true|false
private val PROJECT_SAVE_QUERY_PATTERN = Pattern.compile(
"save(\\=[a-zA-Z]+)"
)
// /projects/:creator_param/:project_param/posts/:update_param/comments
private val PROJECT_UPDATE_COMMENTS_PATTERN = Pattern.compile(
"\\A\\/projects(\\/[a-zA-Z0-9_-]+)?\\/[a-zA-Z0-9_-]+\\/posts\\/[a-zA-Z0-9-_]+\\/comments\\z"
)
// /projects/:creator_param/:project_param/posts/:update_param
private val PROJECT_UPDATE_PATTERN = Pattern.compile(
"\\A\\/projects(\\/[a-zA-Z0-9_-]+)?\\/[a-zA-Z0-9_-]+\\/posts\\/[a-zA-Z0-9-_]+\\z"
)
// /projects/:creator_param/:project_param/posts
private val PROJECT_UPDATES_PATTERN = Pattern.compile(
"\\A\\/projects(\\/[a-zA-Z0-9_-]+)?\\/[a-zA-Z0-9_-]+\\/posts\\z"
)
// /users/:user_param/surveys/:survey_response_id": userSurvey
private val USER_SURVEY = Pattern.compile(
"\\A\\/users(\\/[a-zA-Z0-9_-]+)?\\/surveys\\/[a-zA-Z0-9-_]+\\z"
)
|
apache-2.0
|
3a6d7a404d92d913ea9f47b6de292934
| 31.184426 | 118 | 0.695276 | 3.607258 | false | false | false | false |
zdary/intellij-community
|
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/models/DependencyUtils.kt
|
1
|
583
|
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models
import com.intellij.buildsystem.model.unified.UnifiedDependency
import com.jetbrains.packagesearch.intellij.plugin.api.model.StandardV2Package
internal fun UnifiedDependency.matchesCoordinates(apiPackage: StandardV2Package): Boolean =
coordinates.groupId == apiPackage.groupId &&
coordinates.artifactId == apiPackage.artifactId
internal fun InstalledDependency.matchesCoordinates(apiPackage: StandardV2Package): Boolean =
groupId == apiPackage.groupId && artifactId == apiPackage.artifactId
|
apache-2.0
|
71c296f7573d0f78c13a638e90ca16af
| 52 | 93 | 0.828473 | 4.818182 | false | false | false | false |
siosio/intellij-community
|
build/tasks/src/org/jetbrains/intellij/build/tasks/mergeJars.kt
|
1
|
7231
|
// 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.
@file:JvmName("JarBuilder")
@file:Suppress("ReplaceJavaStaticMethodWithKotlinAnalog")
package org.jetbrains.intellij.build.tasks
import com.intellij.util.lang.ImmutableZipEntry
import com.intellij.util.lang.ImmutableZipFile
import org.jetbrains.intellij.build.io.*
import java.nio.channels.FileChannel
import java.nio.file.FileSystems
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.PathMatcher
import java.util.*
import java.util.function.IntConsumer
import java.util.zip.ZipEntry
sealed interface Source {
val sizeConsumer: IntConsumer?
}
data class ZipSource(val file: Path, override val sizeConsumer: IntConsumer? = null) : Source, Comparable<ZipSource> {
override fun compareTo(other: ZipSource) = file.compareTo(other.file)
}
data class DirSource(val dir: Path, val excludes: List<PathMatcher>, override val sizeConsumer: IntConsumer? = null) : Source
fun createZipSource(file: Path, sizeConsumer: IntConsumer?): Any = ZipSource(file = file, sizeConsumer = sizeConsumer)
@JvmOverloads
fun buildJar(targetFile: Path, sources: List<Source>, logger: System.Logger?, dryRun: Boolean = false) {
logger?.debug {
"Build JAR (targetFile=$targetFile, sources=$sources)"
}
if (dryRun) {
for (source in sources) {
source.sizeConsumer?.accept(0)
}
return
}
Files.createDirectories(targetFile.parent)
FileChannel.open(targetFile, RW_CREATE_NEW).use { outChannel ->
val packageIndexBuilder = PackageIndexBuilder()
val zipCreator = ZipFileWriter(outChannel, deflater = null)
val uniqueNames = HashSet<String>()
for (source in sources) {
val positionBefore = outChannel.position()
if (source is DirSource) {
val archiver = ZipArchiver(method = ZipEntry.STORED, zipCreator, fileAdded = {
if (uniqueNames.add(it)) {
packageIndexBuilder.addFile(it)
true
}
else {
false
}
})
val normalizedDir = source.dir.toAbsolutePath().normalize()
archiver.setRootDir(normalizedDir, "")
compressDir(normalizedDir, archiver, excludes = source.excludes.takeIf { it.isNotEmpty() })
}
else {
ImmutableZipFile.load((source as ZipSource).file).use { zipFile ->
val entries = getFilteredEntries(zipFile, uniqueNames)
writeEntries(entries, zipCreator, zipFile)
packageIndexBuilder.add(entries)
}
}
source.sizeConsumer?.accept((outChannel.position() - positionBefore).toInt())
}
packageIndexBuilder.writeDirs(zipCreator)
packageIndexBuilder.writePackageIndex(zipCreator)
zipCreator.finish()
}
}
private fun getFilteredEntries(zipFile: ImmutableZipFile, uniqueNames: MutableSet<String>): List<ImmutableZipEntry> {
return zipFile.entries.filter {
val name = it.name
@Suppress("SpellCheckingInspection")
uniqueNames.add(name) &&
!name.endsWith(".kotlin_metadata") &&
name != "META-INF/MANIFEST.MF" && name != PACKAGE_INDEX_NAME &&
name != "license" && !name.startsWith("license/") &&
name != "META-INF/services/javax.xml.parsers.SAXParserFactory" &&
name != "META-INF/services/javax.xml.stream.XMLEventFactory" &&
name != "META-INF/services/javax.xml.parsers.DocumentBuilderFactory" &&
name != "META-INF/services/javax.xml.datatype.DatatypeFactory" &&
name != "native-image" && !name.startsWith("native-image/") &&
name != "native" && !name.startsWith("native/") &&
name != "licenses" && !name.startsWith("licenses/") &&
name != ".gitkeep" &&
name != "META-INF/CHANGES" &&
name != "META-INF/DEPENDENCIES" &&
name != "META-INF/LICENSE" &&
name != "META-INF/LICENSE.txt" &&
name != "META-INF/README.txt" &&
name != "META-INF/README.md" &&
name != "META-INF/NOTICE" &&
name != "META-INF/NOTICE.txt" &&
name != "LICENSE" &&
name != "LICENSE.md" &&
name != "module-info.class" &&
name != "license.txt" &&
name != "LICENSE.txt" &&
name != "COPYING.txt" &&
name != "about.html" &&
name != "pom.xml" &&
name != "THIRD_PARTY_LICENSES.txt" &&
name != "NOTICE.txt" &&
name != "NOTICE.md" &&
name != "META-INF/maven" &&
!name.startsWith("META-INF/maven/") &&
!name.startsWith("META-INF/INDEX.LIST") &&
(!name.startsWith("META-INF/") || (!name.endsWith(".DSA") && !name.endsWith(".SF") && !name.endsWith(".RSA")))
}
}
@Suppress("SpellCheckingInspection")
private val excludedFromMergeLibs = java.util.Set.of(
"jna", "Log4J", "sqlite", "Slf4j", "async-profiler",
"dexlib2", // android-only lib
"intellij-coverage", "intellij-test-discovery", // used as agent
"winp", "junixsocket-core", "pty4j", "grpc-netty-shaded", // contains native library
"protobuf", // https://youtrack.jetbrains.com/issue/IDEA-268753
)
fun isLibraryMergeable(libName: String): Boolean {
return !excludedFromMergeLibs.contains(libName) &&
!libName.startsWith("kotlin") &&
!libName.startsWith("projector-") &&
!libName.contains("-agent-") &&
!libName.startsWith("rd-") &&
!libName.contains("annotations", ignoreCase = true) &&
!libName.startsWith("junit", ignoreCase = true) &&
!libName.startsWith("cucumber-", ignoreCase = true) &&
!libName.contains("groovy", ignoreCase = true)
}
private val commonModuleExcludes = java.util.List.of(
FileSystems.getDefault().getPathMatcher("glob:**/icon-robots.txt"),
FileSystems.getDefault().getPathMatcher("glob:icon-robots.txt"),
FileSystems.getDefault().getPathMatcher("glob:.unmodified"),
FileSystems.getDefault().getPathMatcher("glob:classpath.index"),
)
fun addModuleSources(moduleName: String,
moduleNameToSize: MutableMap<String, Int>,
moduleOutputDir: Path,
modulePatches: Collection<Path>,
searchableOptionsRootDir: Path,
extraExcludes: Collection<String>,
sourceList: MutableList<Source>,
logger: System.Logger) {
logger.debug { " include output of module '$moduleName'" }
val sizeConsumer = IntConsumer {
moduleNameToSize.merge(moduleName, it) { oldValue, value -> oldValue + value }
}
// must be before module output to override
for (moduleOutputPatch in modulePatches) {
sourceList.add(DirSource(moduleOutputPatch, Collections.emptyList(), sizeConsumer))
logger.debug { " include $moduleOutputPatch with patches for module '$moduleName'" }
}
val searchableOptionsModuleDir = searchableOptionsRootDir.resolve(moduleName)
if (Files.exists(searchableOptionsModuleDir)) {
sourceList.add(DirSource(searchableOptionsModuleDir, Collections.emptyList(), sizeConsumer))
}
val excludes = if (extraExcludes.isEmpty()) {
commonModuleExcludes
}
else {
commonModuleExcludes.plus(extraExcludes.map { FileSystems.getDefault().getPathMatcher("glob:$it") })
}
sourceList.add(DirSource(dir = moduleOutputDir, excludes = excludes, sizeConsumer = sizeConsumer))
}
|
apache-2.0
|
6c92dbb7213cf29f102caae3db025f83
| 38.091892 | 158 | 0.674595 | 4.162925 | false | false | false | false |
jwren/intellij-community
|
platform/configuration-store-impl/src/defaultProjectElementNormalizer.kt
|
1
|
6787
|
// 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 com.intellij.configurationStore
import com.intellij.openapi.components.StoragePathMacros
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.io.FileUtil
import com.intellij.serviceContainer.ComponentManagerImpl
import com.intellij.util.LineSeparator
import com.intellij.util.SmartList
import com.intellij.util.io.exists
import com.intellij.util.io.outputStream
import org.jdom.Element
import org.jetbrains.jps.model.serialization.JpsProjectLoader
import java.nio.file.Path
import kotlin.collections.component1
import kotlin.collections.component2
internal fun normalizeDefaultProjectElement(defaultProject: Project, element: Element, projectConfigDir: Path) {
// first, process all known in advance components, because later all not known component names will be moved to misc.xml
// (no way to get service stat spec because class cannot be loaded due to performance reasons)
val iterator = element.getChildren("component").iterator()
for (component in iterator) {
when (val componentName = component.getAttributeValue("name")) {
"InspectionProjectProfileManager" -> {
iterator.remove()
val schemeDir = projectConfigDir.resolve("inspectionProfiles")
convertProfiles(component.getChildren("profile").iterator(), componentName, schemeDir, ::getProfileName)
component.removeChild("version")
writeProfileSettings(schemeDir, componentName, component)
}
"CopyrightManager" -> {
iterator.remove()
val schemeDir = projectConfigDir.resolve("copyright")
convertProfiles(component.getChildren("copyright").iterator(), componentName, schemeDir, ::getProfileName)
writeProfileSettings(schemeDir, componentName, component)
}
"libraryTable" -> {
iterator.remove()
val librariesDir = projectConfigDir.resolve("libraries")
convertProfiles(component.getChildren("library").iterator(), componentName, librariesDir) { library ->
library.getAttributeValue("name")
}
}
JpsProjectLoader.MODULE_MANAGER_COMPONENT -> {
iterator.remove()
}
}
}
moveComponentConfiguration(defaultProject, element, { it }) { projectConfigDir.resolve(it) }
}
private fun getProfileName(profile: Element): String? {
return profile.getChildren("option").find { it.getAttributeValue("name") == "myName" }?.getAttributeValue("value")
}
private fun writeProfileSettings(schemeDir: Path, componentName: String, component: Element) {
component.removeAttribute("name")
if (JDOMUtil.isEmpty(component)) {
return
}
val wrapper = Element("component").setAttribute("name", componentName)
component.name = "settings"
wrapper.addContent(component)
JDOMUtil.write(wrapper, schemeDir.resolve("profiles_settings.xml"))
}
private fun convertProfiles(profileIterator: MutableIterator<Element>,
componentName: String,
schemeDir: Path,
nameCallback: (Element) -> String?) {
for (profile in profileIterator) {
val schemeName = nameCallback(profile) ?: continue
profileIterator.remove()
val wrapper = Element("component").setAttribute("name", componentName)
wrapper.addContent(profile)
val path = schemeDir.resolve("${FileUtil.sanitizeFileName(schemeName, true)}.xml")
JDOMUtil.write(wrapper, path.outputStream(), "\n")
}
}
internal fun moveComponentConfiguration(defaultProject: Project,
element: Element,
storagePathResolver: (storagePath: String) -> String,
fileResolver: (name: String) -> Path) {
val componentElements = element.getChildren("component")
if (componentElements.isEmpty()) {
return
}
val storageNameToComponentNames = HashMap<String, MutableSet<String>>()
val workspaceComponentNames = HashSet(listOf("GradleLocalSettings"))
val ignoredComponentNames = HashSet<String>()
storageNameToComponentNames.put("workspace.xml", workspaceComponentNames)
fun processComponents(aClass: Class<*>) {
val stateAnnotation = getStateSpec(aClass) ?: return
@Suppress("MoveVariableDeclarationIntoWhen")
val storagePath = when {
stateAnnotation.name.isEmpty() -> "misc.xml"
else -> (stateAnnotation.storages.sortByDeprecated().firstOrNull() ?: return).path
}
when (storagePath) {
StoragePathMacros.WORKSPACE_FILE -> workspaceComponentNames.add(stateAnnotation.name)
StoragePathMacros.PRODUCT_WORKSPACE_FILE, StoragePathMacros.CACHE_FILE -> {
// ignore - this data should be not copied
ignoredComponentNames.add(stateAnnotation.name)
}
else -> storageNameToComponentNames.computeIfAbsent(storagePathResolver(storagePath)) { HashSet() }.add(stateAnnotation.name)
}
}
(defaultProject.picoContainer as ComponentManagerImpl).processAllImplementationClasses { aClass, _ ->
processComponents(aClass)
}
// fileResolver may return the same file for different storage names (e.g. for IPR project)
val storagePathToComponentStates = HashMap<Path, MutableList<Element>>()
val iterator = componentElements.iterator()
cI@ for (componentElement in iterator) {
iterator.remove()
val name = componentElement.getAttributeValue("name") ?: continue
if (ignoredComponentNames.contains(name)) {
continue
}
for ((storageName, componentNames) in storageNameToComponentNames) {
if (componentNames.contains(name)) {
storagePathToComponentStates.computeIfAbsent(fileResolver(storageName)) { SmartList() }.add(componentElement)
continue@cI
}
}
// ok, just save it to misc.xml
storagePathToComponentStates.computeIfAbsent(fileResolver("misc.xml")) { SmartList() }.add(componentElement)
}
for ((storageFile, componentStates) in storagePathToComponentStates) {
writeConfigFile(componentStates, storageFile)
}
}
private fun writeConfigFile(elements: List<Element>, file: Path) {
if (elements.isEmpty()) {
return
}
var wrapper = Element("project").setAttribute("version", "4")
if (file.exists()) {
try {
wrapper = JDOMUtil.load(file)
}
catch (e: Exception) {
LOG.warn(e)
}
}
for (it in elements) {
wrapper.addContent(it)
}
// .idea component configuration files uses XML prolog due to historical reasons
file.outputStream().use {
it.write(XML_PROLOG)
it.write(LineSeparator.LF.separatorBytes)
JDOMUtil.write(wrapper, it)
}
}
|
apache-2.0
|
3bb6da152fb537048f18621e86f0010b
| 36.921788 | 131 | 0.712539 | 4.975806 | false | true | false | false |
androidx/androidx
|
wear/compose/compose-material/src/commonMain/kotlin/androidx/wear/compose/material/Card.kt
|
3
|
21372
|
/*
* 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.wear.compose.material
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.Interaction
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material.ripple.rememberRipple
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.paint
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.LinearGradientShader
import androidx.compose.ui.graphics.Shader
import androidx.compose.ui.graphics.ShaderBrush
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.TileMode
import androidx.compose.ui.graphics.compositeOver
import androidx.compose.ui.graphics.painter.BrushPainter
import androidx.compose.ui.graphics.painter.ColorPainter
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import kotlin.math.min
/**
* Base level Wear Material [Card] that offers a single slot to take any content.
*
* Is used as the container for more opinionated [Card] components that take specific content such
* as icons, images, titles, subtitles and labels.
*
* The [Card] is Rectangle shaped rounded corners by default.
*
* Cards can be enabled or disabled. A disabled card will not respond to click events.
*
* For more information, see the
* [Cards](https://developer.android.com/training/wearables/components/cards)
* Wear OS Material design guide.
*
* Note that the Wear OS design guidance recommends a gradient or image background for Cards which
* is not the case for Mobile Cards. As a result you will see a backgroundPainter rather than a
* backgroundColor for Cards. If you want to workaround this recommendation you could use a
* [ColorPainter] to produce a solid colored background.
*
* @param onClick Will be called when the user clicks the card
* @param modifier Modifier to be applied to the card
* @param backgroundPainter A painter used to paint the background of the card. A card will
* normally have a gradient background. Use [CardDefaults.cardBackgroundPainter()] to obtain an
* appropriate painter
* @param contentColor The default color to use for content() unless explicitly set.
* @param enabled Controls the enabled state of the card. When false, this card will not
* be clickable and there will be no ripple effect on click. Wear cards do not have any specific
* elevation or alpha differences when not enabled - they are simply not clickable.
* @param contentPadding The spacing values to apply internally between the container and the
* content
* @param shape Defines the card's shape. It is strongly recommended to use the default as this
* shape is a key characteristic of the Wear Material Theme
* @param interactionSource The [MutableInteractionSource] representing the stream of
* [Interaction]s for this card. You can create and pass in your own remembered
* [MutableInteractionSource] if you want to observe [Interaction]s and customize the
* appearance / behavior of this card in different [Interaction]s.
* @param role The type of user interface element. Accessibility services might use this
* to describe the element or do customizations
*/
@Composable
public fun Card(
onClick: () -> Unit,
modifier: Modifier = Modifier,
backgroundPainter: Painter = CardDefaults.cardBackgroundPainter(),
contentColor: Color = MaterialTheme.colors.onSurfaceVariant,
enabled: Boolean = true,
contentPadding: PaddingValues = CardDefaults.ContentPadding,
shape: Shape = MaterialTheme.shapes.large,
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
role: Role? = null,
content: @Composable ColumnScope.() -> Unit,
) {
Column(
modifier = modifier
.fillMaxWidth()
.height(IntrinsicSize.Min)
.clip(shape = shape)
.paint(
painter = backgroundPainter,
contentScale = ContentScale.Crop
)
.clickable(
enabled = enabled,
onClick = onClick,
role = role,
indication = rememberRipple(),
interactionSource = interactionSource,
)
.padding(contentPadding)
) {
CompositionLocalProvider(
LocalContentColor provides contentColor,
LocalTextStyle provides MaterialTheme.typography.button,
) {
content()
}
}
}
/**
* Opinionated Wear Material [Card] that offers a specific 5 slot layout to show information about
* an application, e.g. a notification. AppCards are designed to show interactive elements from
* multiple applications. They will typically be used by the system UI, e.g. for showing a list of
* notifications from different applications. However it could also be adapted by individual
* application developers to show information about different parts of their application.
*
* The first row of the layout has three slots, 1) a small optional application [Image] or [Icon] of
* size [CardDefaults.AppImageSize]x[CardDefaults.AppImageSize] dp, 2) an application name
* (emphasised with the [CardColors.appColor()] color), it is expected to be a short start aligned
* [Text] composable, and 3) the time that the application activity has occurred which will be
* shown on the top row of the card, this is expected to be an end aligned [Text] composable
* showing a time relevant to the contents of the [Card].
*
* The second row shows a title, this is expected to be a single row of start aligned [Text].
*
* The rest of the [Card] contains the content which can be either [Text] or an [Image].
* If the content is text it can be single or multiple line and is expected to be Top and Start
* aligned.
*
* If more than one composable is provided in the content slot it is the responsibility of the
* caller to determine how to layout the contents, e.g. provide either a row or a column.
*
* Example of an [AppCard] with icon, title, time and two lines of body text:
* @sample androidx.wear.compose.material.samples.AppCardWithIcon
*
* For more information, see the
* [Cards](https://developer.android.com/training/wearables/components/cards)
* guide.
*
* @param onClick Will be called when the user clicks the card
* @param appName A slot for displaying the application name, expected to be a single line of start
* aligned text of [Typography.title3]
* @param time A slot for displaying the time relevant to the contents of the card, expected to be a
* short piece of end aligned text.
* @param title A slot for displaying the title of the card, expected to be one or two lines of
* start aligned text of [Typography.button]
* @param modifier Modifier to be applied to the card
* @param enabled Controls the enabled state of the card. When false, this card will not
* be clickable and there will be no ripple effect on click. Wear cards do not have any specific
* elevation or alpha differences when not enabled - they are simply not clickable.
* @param appImage A slot for a small ([CardDefaults.AppImageSize]x[CardDefaults.AppImageSize] )
* [Image] associated with the application.
* @param backgroundPainter A painter used to paint the background of the card. A card will
* normally have a gradient background. Use [CardDefaults.cardBackgroundPainter()] to obtain an
* appropriate painter
* @param contentColor The default color to use for content() slot unless explicitly set.
* @param appColor The default color to use for appName() and appImage() slots unless explicitly
* set.
* @param timeColor The default color to use for time() slot unless explicitly set.
* @param titleColor The default color to use for title() slot unless explicitly set.
*/
@Composable
public fun AppCard(
onClick: () -> Unit,
appName: @Composable RowScope.() -> Unit,
time: @Composable RowScope.() -> Unit,
title: @Composable RowScope.() -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
appImage: @Composable (RowScope.() -> Unit)? = null,
backgroundPainter: Painter = CardDefaults.cardBackgroundPainter(),
contentColor: Color = MaterialTheme.colors.onSurfaceVariant,
appColor: Color = contentColor,
timeColor: Color = contentColor,
titleColor: Color = MaterialTheme.colors.onSurface,
content: @Composable ColumnScope.() -> Unit,
) {
Card(
onClick = onClick,
modifier = modifier,
backgroundPainter = backgroundPainter,
enabled = enabled,
) {
Column {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
CompositionLocalProvider(
LocalTextStyle provides MaterialTheme.typography.caption1
) {
if (appImage != null) {
appImage()
Spacer(modifier = Modifier.width(6.dp))
}
CompositionLocalProvider(
LocalContentColor provides appColor,
) {
appName()
}
}
Spacer(modifier = Modifier.weight(1.0f))
CompositionLocalProvider(
LocalContentColor provides timeColor,
LocalTextStyle provides MaterialTheme.typography.caption1,
) {
time()
}
}
Spacer(modifier = Modifier.height(4.dp))
Row {
CompositionLocalProvider(
LocalContentColor provides titleColor,
LocalTextStyle provides MaterialTheme.typography.title3,
) {
title()
}
}
CompositionLocalProvider(
LocalContentColor provides contentColor,
LocalTextStyle provides MaterialTheme.typography.body1,
) {
content()
}
}
}
}
/**
* Opinionated Wear Material [Card] that offers a specific 3 slot layout to show interactive
* information about an application, e.g. a message. TitleCards are designed for use within an
* application.
*
* The first row of the layout has two slots. 1. a start aligned title (emphasised with the
* [titleColor] and expected to be start aligned text). The title text is expected to be a maximum
* of 2 lines of text. 2. An optional time that the application activity has occurred shown at the
* end of the row, expected to be an end aligned [Text] composable showing a time relevant to the
* contents of the [Card].
*
* The rest of the [Card] contains the content which is expected to be [Text] or a contained
* [Image].
*
* If the content is text it can be single or multiple line and is expected to be Top and Start
* aligned and of type of [Typography.body1].
*
* Overall the [title] and [content] text should be no more than 5 rows of text combined.
*
* If more than one composable is provided in the content slot it is the responsibility of the
* caller to determine how to layout the contents, e.g. provide either a row or a column.
*
* Example of a [TitleCard] with two lines of body text:
* @sample androidx.wear.compose.material.samples.TitleCardStandard
*
* Example of a title card with a background image:
* @sample androidx.wear.compose.material.samples.TitleCardWithImage
*
* For more information, see the
* [Cards](https://developer.android.com/training/wearables/components/cards)
* guide.
*
* @param onClick Will be called when the user clicks the card
* @param title A slot for displaying the title of the card, expected to be one or two lines of text
* of [Typography.button]
* @param modifier Modifier to be applied to the card
* @param enabled Controls the enabled state of the card. When false, this card will not
* be clickable and there will be no ripple effect on click. Wear cards do not have any specific
* elevation or alpha differences when not enabled - they are simply not clickable.
* @param time An optional slot for displaying the time relevant to the contents of the card,
* expected to be a short piece of end aligned text.
* @param backgroundPainter A painter used to paint the background of the card. A title card can
* have either a gradient background or an image background, use
* [CardDefaults.cardBackgroundPainter()] or [CardDefaults.imageBackgroundPainter()] to obtain an
* appropriate painter
* @param contentColor The default color to use for content() slot unless explicitly set.
* @param titleColor The default color to use for title() slot unless explicitly set.
* @param timeColor The default color to use for time() slot unless explicitly set.
*/
@Composable
public fun TitleCard(
onClick: () -> Unit,
title: @Composable RowScope.() -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
time: @Composable (RowScope.() -> Unit)? = null,
backgroundPainter: Painter = CardDefaults.cardBackgroundPainter(),
contentColor: Color = MaterialTheme.colors.onSurfaceVariant,
titleColor: Color = MaterialTheme.colors.onSurface,
timeColor: Color = contentColor,
content: @Composable ColumnScope.() -> Unit,
) {
Card(
onClick = onClick,
modifier = modifier,
backgroundPainter = backgroundPainter,
enabled = enabled,
) {
Column {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
CompositionLocalProvider(
LocalContentColor provides titleColor,
LocalTextStyle provides MaterialTheme.typography.title3,
) {
title()
}
if (time != null) {
Spacer(modifier = Modifier.weight(1.0f))
CompositionLocalProvider(
LocalContentColor provides timeColor,
LocalTextStyle provides MaterialTheme.typography.caption1,
) {
time()
}
}
}
Spacer(modifier = Modifier.height(2.dp))
CompositionLocalProvider(
LocalContentColor provides contentColor,
LocalTextStyle provides MaterialTheme.typography.body1,
) {
content()
}
}
}
}
/**
* Contains the default values used by [Card]
*/
public object CardDefaults {
/**
* Creates a [Painter] for background colors for a [Card]. Cards typically have a linear
* gradient for a background. The gradient will be between startBackgroundColor
* and endBackgroundColor and at an angle of 45 degrees.
*
* Cards should have a content color that contrasts with the background
* gradient.
*
* @param startBackgroundColor The background color used at the start of the gradient of this
* [Card]
* @param endBackgroundColor The background color used at the end of the gradient of this [Card]
* @param gradientDirection Whether the cards gradient should be start to end (indicated by
* [LayoutDirection.Ltr]) or end to start (indicated by [LayoutDirection.Rtl]).
*/
@Composable
public fun cardBackgroundPainter(
startBackgroundColor: Color =
MaterialTheme.colors.primary.copy(alpha = 0.30f)
.compositeOver(MaterialTheme.colors.background),
endBackgroundColor: Color =
MaterialTheme.colors.onSurfaceVariant.copy(alpha = 0.20f)
.compositeOver(MaterialTheme.colors.background),
gradientDirection: LayoutDirection = LocalLayoutDirection.current
): Painter {
return BrushPainter(FortyFiveDegreeLinearGradient(
colors = listOf(
startBackgroundColor,
endBackgroundColor
),
ltr = gradientDirection == LayoutDirection.Ltr)
)
}
/**
* Creates a [Painter] for the background of a [Card] that displays an Image with a scrim over
* the image to make sure that any content above the background will be legible.
*
* An Image background is a means to reinforce the meaning of information in a Card, e.g. To
* help to contextualize the information in a TitleCard
*
* Cards should have a content color that contrasts with the background image and scrim
*
* @param backgroundImagePainter The [Painter] to use to draw the background of the [Card]
* @param backgroundImageScrimBrush The [Brush] to use to paint a scrim over the background
* image to ensure that any text drawn over the image is legible
*/
@Composable
public fun imageWithScrimBackgroundPainter(
backgroundImagePainter: Painter,
backgroundImageScrimBrush: Brush = Brush.linearGradient(
colors = listOf(
MaterialTheme.colors.surface.copy(alpha = 1.0f),
MaterialTheme.colors.surface.copy(alpha = 0f)
)
)
): Painter {
return ImageWithScrimPainter(
imagePainter = backgroundImagePainter,
brush = backgroundImageScrimBrush
)
}
private val CardHorizontalPadding = 12.dp
private val CardVerticalPadding = 12.dp
/**
* The default content padding used by [Card]
*/
public val ContentPadding: PaddingValues = PaddingValues(
start = CardHorizontalPadding,
top = CardVerticalPadding,
end = CardHorizontalPadding,
bottom = CardVerticalPadding
)
/**
* The default size of the app icon/image when used inside a [AppCard].
*/
public val AppImageSize: Dp = 16.dp
}
/**
* A linear gradient that draws the gradient at 45 degrees from Top|Start.
*/
@Immutable
internal class FortyFiveDegreeLinearGradient internal constructor(
private val colors: List<Color>,
private val stops: List<Float>? = null,
private val tileMode: TileMode = TileMode.Clamp,
private val ltr: Boolean
) : ShaderBrush() {
override fun createShader(size: Size): Shader {
val minWidthHeight = min(size.height, size.width)
val from = if (ltr) Offset(0f, 0f) else Offset(minWidthHeight, 0f)
val to = if (ltr) Offset(minWidthHeight, minWidthHeight) else Offset(0f, minWidthHeight)
return LinearGradientShader(
colors = colors,
colorStops = stops,
from = from,
to = to,
tileMode = tileMode
)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is FortyFiveDegreeLinearGradient) return false
if (colors != other.colors) return false
if (stops != other.stops) return false
if (tileMode != other.tileMode) return false
if (ltr != other.ltr) return false
return true
}
override fun hashCode(): Int {
var result = colors.hashCode()
result = 31 * result + (stops?.hashCode() ?: 0)
result = 31 * result + tileMode.hashCode()
return result
}
override fun toString(): String {
return "FortyFiveDegreeLinearGradient(colors=$colors, " +
"stops=$stops, " +
"tileMode=$tileMode)"
}
}
|
apache-2.0
|
47d8aee97fffe82868ed0aa1f99fc69f
| 42.175758 | 100 | 0.688471 | 4.868337 | false | false | false | false |
androidx/androidx
|
health/connect/connect-client/src/main/java/androidx/health/connect/client/units/Mass.kt
|
3
|
7967
|
/*
* 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.health.connect.client.units
/**
* Represents a unit of mass. Supported units:
*
* - grams - see [Mass.grams], [Double.grams]
* - kilograms - see [Mass.kilograms], [Double.kilograms]
* - milligrams - see [Mass.milligrams], [Double.milligrams]
* - micrograms - see [Mass.micrograms], [Double.micrograms]
* - ounces - see [Mass.ounces], [Double.ounces]
* - pounds - see [Mass.pounds], [Double.pounds]
*/
class Mass private constructor(
private val value: Double,
private val type: Type,
) : Comparable<Mass> {
/** Returns the mass in grams. */
@get:JvmName("getGrams")
val inGrams: Double
get() = value * type.gramsPerUnit
/** Returns the mass in kilograms. */
@get:JvmName("getKilograms")
val inKilograms: Double
get() = get(type = Type.KILOGRAMS)
/** Returns the mass in milligrams. */
@get:JvmName("getMilligrams")
val inMilligrams: Double
get() = get(type = Type.MILLIGRAMS)
/** Returns the mass in micrograms. */
@get:JvmName("getMicrograms")
val inMicrograms: Double
get() = get(type = Type.MICROGRAMS)
/** Returns the mass in ounces. */
@get:JvmName("getOunces")
val inOunces: Double
get() = get(type = Type.OUNCES)
/** Returns the mass in pounds. */
@get:JvmName("getPounds")
val inPounds: Double
get() = get(type = Type.POUNDS)
private fun get(type: Type): Double =
if (this.type == type) value else inGrams / type.gramsPerUnit
/** Returns zero [Mass] of the same [Type]. */
internal fun zero(): Mass = ZEROS.getValue(type)
override fun compareTo(other: Mass): Int =
if (type == other.type) {
value.compareTo(other.value)
} else {
inGrams.compareTo(other.inGrams)
}
/*
* Generated by the IDE: Code -> Generate -> "equals() and hashCode()".
*/
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Mass) return false
if (value != other.value) return false
if (type != other.type) return false
return true
}
/*
* Generated by the IDE: Code -> Generate -> "equals() and hashCode()".
*/
override fun hashCode(): Int {
var result = value.hashCode()
result = 31 * result + type.hashCode()
return result
}
override fun toString(): String = "$value ${type.name.lowercase()}"
companion object {
private val ZEROS = Type.values().associateWith { Mass(value = 0.0, type = it) }
/** Creates [Mass] with the specified value in grams. */
@JvmStatic fun grams(value: Double): Mass = Mass(value, Type.GRAMS)
/** Creates [Mass] with the specified value in kilograms. */
@JvmStatic fun kilograms(value: Double): Mass = Mass(value, Type.KILOGRAMS)
/** Creates [Mass] with the specified value in milligrams. */
@JvmStatic fun milligrams(value: Double): Mass = Mass(value, Type.MILLIGRAMS)
/** Creates [Mass] with the specified value in micrograms. */
@JvmStatic fun micrograms(value: Double): Mass = Mass(value, Type.MICROGRAMS)
/** Creates [Mass] with the specified value in ounces. */
@JvmStatic fun ounces(value: Double): Mass = Mass(value, Type.OUNCES)
/** Creates [Mass] with the specified value in pounds. */
@JvmStatic fun pounds(value: Double): Mass = Mass(value, Type.POUNDS)
}
private enum class Type {
GRAMS {
override val gramsPerUnit: Double = 1.0
},
KILOGRAMS {
override val gramsPerUnit: Double = 1000.0
},
MILLIGRAMS {
override val gramsPerUnit: Double = 0.001
},
MICROGRAMS {
override val gramsPerUnit: Double = 0.000001
},
OUNCES {
override val gramsPerUnit: Double = 28.34952
},
POUNDS {
override val gramsPerUnit: Double = 453.59237
};
abstract val gramsPerUnit: Double
}
}
/** Creates [Mass] with the specified value in grams. */
@get:JvmSynthetic
val Double.grams: Mass
get() = Mass.grams(value = this)
/** Creates [Mass] with the specified value in grams. */
@get:JvmSynthetic
val Float.grams: Mass
get() = toDouble().grams
/** Creates [Mass] with the specified value in grams. */
@get:JvmSynthetic
val Long.grams: Mass
get() = toDouble().grams
/** Creates [Mass] with the specified value in grams. */
@get:JvmSynthetic
val Int.grams: Mass
get() = toDouble().grams
/** Creates [Mass] with the specified value in kilograms. */
@get:JvmSynthetic
val Double.kilograms: Mass
get() = Mass.kilograms(value = this)
/** Creates [Mass] with the specified value in kilograms. */
@get:JvmSynthetic
val Float.kilograms: Mass
get() = toDouble().kilograms
/** Creates [Mass] with the specified value in kilograms. */
@get:JvmSynthetic
val Long.kilograms: Mass
get() = toDouble().kilograms
/** Creates [Mass] with the specified value in kilograms. */
@get:JvmSynthetic
val Int.kilograms: Mass
get() = toDouble().kilograms
/** Creates [Mass] with the specified value in milligrams. */
@get:JvmSynthetic
val Double.milligrams: Mass
get() = Mass.milligrams(value = this)
/** Creates [Mass] with the specified value in milligrams. */
@get:JvmSynthetic
val Float.milligrams: Mass
get() = toDouble().milligrams
/** Creates [Mass] with the specified value in milligrams. */
@get:JvmSynthetic
val Long.milligrams: Mass
get() = toDouble().milligrams
/** Creates [Mass] with the specified value in milligrams. */
@get:JvmSynthetic
val Int.milligrams: Mass
get() = toDouble().milligrams
/** Creates [Mass] with the specified value in micrograms. */
@get:JvmSynthetic
val Double.micrograms: Mass
get() = Mass.micrograms(value = this)
/** Creates [Mass] with the specified value in micrograms. */
@get:JvmSynthetic
val Float.micrograms: Mass
get() = toDouble().micrograms
/** Creates [Mass] with the specified value in micrograms. */
@get:JvmSynthetic
val Long.micrograms: Mass
get() = toDouble().micrograms
/** Creates [Mass] with the specified value in micrograms. */
@get:JvmSynthetic
val Int.micrograms: Mass
get() = toDouble().micrograms
/** Creates [Mass] with the specified value in ounces. */
@get:JvmSynthetic
val Double.ounces: Mass
get() = Mass.ounces(value = this)
/** Creates [Mass] with the specified value in ounces. */
@get:JvmSynthetic
val Float.ounces: Mass
get() = toDouble().ounces
/** Creates [Mass] with the specified value in ounces. */
@get:JvmSynthetic
val Long.ounces: Mass
get() = toDouble().ounces
/** Creates [Mass] with the specified value in ounces. */
@get:JvmSynthetic
val Int.ounces: Mass
get() = toDouble().ounces
/** Creates [Mass] with the specified value in pounds. */
@get:JvmSynthetic
val Double.pounds: Mass
get() = Mass.pounds(value = this)
/** Creates [Mass] with the specified value in pounds. */
@get:JvmSynthetic
val Float.pounds: Mass
get() = toDouble().pounds
/** Creates [Mass] with the specified value in pounds. */
@get:JvmSynthetic
val Long.pounds: Mass
get() = toDouble().pounds
/** Creates [Mass] with the specified value in pounds. */
@get:JvmSynthetic
val Int.pounds: Mass
get() = toDouble().pounds
|
apache-2.0
|
7fb9c4da1baf4ab2d295d57f6428c501
| 29.064151 | 88 | 0.651814 | 4.01765 | false | false | false | false |
androidx/androidx
|
wear/watchface/watchface-complications/src/main/java/androidx/wear/watchface/complications/ComplicationDataSourceInfoRetriever.kt
|
3
|
17678
|
/*
* 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.wear.watchface.complications
import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.graphics.drawable.Icon
import android.os.Build
import android.os.IBinder
import android.support.wearable.complications.IPreviewComplicationDataCallback
import android.support.wearable.complications.IProviderInfoService
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.annotation.RestrictTo
import androidx.annotation.VisibleForTesting
import androidx.wear.watchface.complications.ComplicationDataSourceInfoRetriever.Result
import androidx.wear.watchface.complications.data.ComplicationData
import androidx.wear.watchface.complications.data.ComplicationType
import androidx.wear.watchface.complications.data.ComplicationType.Companion.fromWireType
import androidx.wear.watchface.complications.data.LongTextComplicationData
import androidx.wear.watchface.complications.data.MonochromaticImage
import androidx.wear.watchface.complications.data.MonochromaticImageComplicationData
import androidx.wear.watchface.complications.data.NoDataComplicationData
import androidx.wear.watchface.complications.data.PhotoImageComplicationData
import androidx.wear.watchface.complications.data.PlainComplicationText
import androidx.wear.watchface.complications.data.RangedValueComplicationData
import androidx.wear.watchface.complications.data.ShortTextComplicationData
import androidx.wear.watchface.complications.data.SmallImage
import androidx.wear.watchface.complications.data.SmallImageComplicationData
import androidx.wear.watchface.complications.data.SmallImageType
import androidx.wear.watchface.complications.data.toApiComplicationData
import androidx.wear.watchface.utility.TraceEvent
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.suspendCancellableCoroutine
import java.lang.IllegalArgumentException
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlinx.coroutines.CancellableContinuation
private typealias WireComplicationProviderInfo =
android.support.wearable.complications.ComplicationProviderInfo
/**
* Retrieves [Result] for a watch face's complications.
*
*
* To use construct an instance and call [retrieveComplicationDataSourceInfo] which returns an array
* of [Result] objects.
*
*
* Further calls to [retrieveComplicationDataSourceInfo] may be made using the same instance of this
* class, but [close] must be called when it is no longer needed. Once release has been
* called, further retrieval attempts will fail.
*/
public class ComplicationDataSourceInfoRetriever : AutoCloseable {
/** Results for [retrieveComplicationDataSourceInfo]. */
public class Result internal constructor(
/** The id for the complication slot, as passed to [retrieveComplicationDataSourceInfo]. */
public val slotId: Int,
/**
* Details of the complication data source for that complication, or `null` if no
* complication data source is currently configured.
*/
public val info: ComplicationDataSourceInfo?
)
private inner class ProviderInfoServiceConnection : ServiceConnection {
@SuppressLint("SyntheticAccessor")
override fun onServiceConnected(name: ComponentName, service: IBinder) {
deferredService.complete(IProviderInfoService.Stub.asInterface(service))
}
@SuppressLint("SyntheticAccessor")
override fun onBindingDied(name: ComponentName?) {
synchronized(lock) {
closed = true
}
deferredService.completeExceptionally(ServiceDisconnectedException())
}
@SuppressLint("SyntheticAccessor")
override fun onServiceDisconnected(name: ComponentName) {
synchronized(lock) {
closed = true
}
deferredService.completeExceptionally(ServiceDisconnectedException())
}
}
@SuppressLint("SyntheticAccessor")
private val serviceConnection: ServiceConnection = ProviderInfoServiceConnection()
private var context: Context? = null
private val deferredService = CompletableDeferred<IProviderInfoService>()
private val lock = Any()
/**
* @hide
*/
@VisibleForTesting
@RestrictTo(RestrictTo.Scope.LIBRARY)
public var closed: Boolean = false
private set
internal constructor(context: Context, intent: Intent) {
this.context = context
context.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)
}
/** @param context the current context */
public constructor(context: Context) : this(
context,
Intent(ACTION_GET_COMPLICATION_CONFIG).apply { setPackage(PROVIDER_INFO_SERVICE_PACKAGE) }
)
/** Exception thrown if the service disconnects. */
public class ServiceDisconnectedException : Exception()
/**
* @hide
*/
@VisibleForTesting
@RestrictTo(RestrictTo.Scope.LIBRARY)
public constructor(service: IProviderInfoService) {
deferredService.complete(service)
}
/**
* Requests [Result] for the specified complication ids on the specified
* watch face. When the info is received, the listener will receive a callback for each id.
* These callbacks will occur on the main thread.
*
*
* This will only work if the package of the current app is the same as the package of the
* specified watch face.
*
* @param watchFaceComponent the ComponentName of the WatchFaceService for which info is
* being requested
* @param watchFaceComplicationIds ids of the complications that info is being requested for
* @return An array of [Result]. If the look up fails null will be returned.
* @throws [ServiceDisconnectedException] if the service disconnected during the call.
*/
@Throws(ServiceDisconnectedException::class)
public suspend fun retrieveComplicationDataSourceInfo(
watchFaceComponent: ComponentName,
watchFaceComplicationIds: IntArray
): Array<Result>? =
TraceEvent("ComplicationDataSourceInfoRetriever.retrieveComplicationDataSourceInfo").use {
synchronized(lock) {
require(!closed) {
"retrieveComplicationDataSourceInfo called after close"
}
}
awaitDeferredService().getProviderInfos(
watchFaceComponent, watchFaceComplicationIds
)?.mapIndexed { index, info ->
Result(
watchFaceComplicationIds[index],
info?.toApiComplicationDataSourceInfo()
)
}?.toTypedArray()
}
/**
* Requests preview [ComplicationData] for a complication data source [ComponentName] and
* [ComplicationType]. Note if `null` is returned
* [ComplicationDataSourceInfo.fallbackPreviewData] can be used to generate fallback preview
* data based on the name and icon of the provider.
*
* @param complicationDataSourceComponent The [ComponentName] of the complication data source
* from which preview data is requested.
* @param complicationType The requested [ComplicationType] for the preview data.
* @return The preview [ComplicationData] or `null` if the complication data source component
* doesn't exist, or if it doesn't support complicationType, or if the remote service doesn't
* support this API.
* @throws [ServiceDisconnectedException] if the service disconnected during the call.
*/
@Throws(ServiceDisconnectedException::class)
@RequiresApi(Build.VERSION_CODES.R)
public suspend fun retrievePreviewComplicationData(
complicationDataSourceComponent: ComponentName,
complicationType: ComplicationType
): ComplicationData? = TraceEvent(
"ComplicationDataSourceInfoRetriever.requestPreviewComplicationData"
).use {
synchronized(lock) {
require(!closed) {
"retrievePreviewComplicationData called after close"
}
}
val service = awaitDeferredService()
if (service.apiVersion < 1) {
return null
}
return suspendCancellableCoroutine { continuation ->
val callback = PreviewComplicationDataCallback(service, continuation)
if (!service.requestPreviewComplicationData(
complicationDataSourceComponent,
complicationType.toWireComplicationType(),
callback
)
) {
callback.safeUnlinkToDeath()
continuation.resume(null)
}
}
}
private class PreviewComplicationDataCallback(
val service: IProviderInfoService,
var continuation: CancellableContinuation<ComplicationData?>?
) : IPreviewComplicationDataCallback.Stub() {
val deathObserver: IBinder.DeathRecipient = IBinder.DeathRecipient {
continuation?.resumeWithException(ServiceDisconnectedException())
}
init {
service.asBinder().linkToDeath(deathObserver, 0)
// Not a huge deal but we might as well unlink the deathObserver.
continuation?.invokeOnCancellation {
safeUnlinkToDeath()
}
}
override fun updateComplicationData(
data: android.support.wearable.complications.ComplicationData?
) {
safeUnlinkToDeath()
continuation!!.resume(data?.toApiComplicationData())
// Re http://b/249121838 this is important, it prevents a memory leak.
continuation = null
}
internal fun safeUnlinkToDeath() {
try {
service.asBinder().unlinkToDeath(deathObserver, 0)
} catch (e: NoSuchElementException) {
// This really shouldn't happen.
Log.w(TAG, "retrievePreviewComplicationData encountered", e)
}
}
}
private suspend fun awaitDeferredService(): IProviderInfoService =
TraceEvent("ComplicationDataSourceInfoRetriever.awaitDeferredService").use {
deferredService.await()
}
/**
* Releases the connection to the complication system used by this class. This must
* be called when the retriever is no longer needed.
*
*
* Any outstanding or subsequent futures returned by [retrieveComplicationDataSourceInfo] will
* resolve with null.
*
* This class implements the Java `AutoClosable` interface and
* may be used with try-with-resources.
*/
override fun close() {
synchronized(lock) {
if (closed) {
Log.e(
TAG,
"Error ComplicationDataSourceInfoRetriever.close called when already closed",
Throwable()
)
} else {
closed = true
try {
context?.unbindService(serviceConnection)
context = null
} catch (e: IllegalArgumentException) {
Log.e(TAG, "unbindService failed", e)
}
}
}
}
private companion object {
private const val TAG = "ComplicationDataS"
/** The package of the service that supplies complication data source info. */
private const val PROVIDER_INFO_SERVICE_PACKAGE = "com.google.android.wearable.app"
private const val ACTION_GET_COMPLICATION_CONFIG =
"android.support.wearable.complications.ACTION_GET_COMPLICATION_CONFIG"
}
}
/**
* Holder of details of a complication data source, for use by watch faces (for example,
* to show the current complication data source in settings). A
* [ComplicationDataSourceInfoRetriever] can be used to obtain references of this class for each
* of a watch face's complications.
*/
public class ComplicationDataSourceInfo(
/** The name of the application containing the complication data source. */
public val appName: String,
/** The name of the complication data source. */
public val name: String,
/** The icon for the complication data source. */
public val icon: Icon,
/** The type of the complication provided by the data source. */
public val type: ComplicationType,
/**
* The complication data source's {@link ComponentName}.
*
* This field is populated only on Android R and above and it is `null` otherwise.
*/
public val componentName: ComponentName?,
) {
/**
* Lazily constructed fallback preview [ComplicationData] based on this
* ComplicationDataSourceInfo. This is useful when
* [ComplicationDataSourceInfoRetriever.retrievePreviewComplicationData] returns `null` (e.g.
* on a pre-android R device).
*/
public val fallbackPreviewData: ComplicationData by lazy {
val contentDescription = PlainComplicationText.Builder(name).build()
when (type) {
ComplicationType.SHORT_TEXT ->
ShortTextComplicationData.Builder(
PlainComplicationText.Builder(
name.take(ShortTextComplicationData.MAX_TEXT_LENGTH)
).build(),
contentDescription
).setMonochromaticImage(
MonochromaticImage.Builder(icon).build()
).build()
ComplicationType.LONG_TEXT ->
LongTextComplicationData.Builder(
PlainComplicationText.Builder(name).build(),
contentDescription
).setMonochromaticImage(
MonochromaticImage.Builder(icon).build()
).build()
ComplicationType.SMALL_IMAGE ->
SmallImageComplicationData.Builder(
SmallImage.Builder(icon, SmallImageType.ICON).build(),
contentDescription
).build()
ComplicationType.MONOCHROMATIC_IMAGE ->
MonochromaticImageComplicationData.Builder(
MonochromaticImage.Builder(icon).build(),
contentDescription
).build()
ComplicationType.PHOTO_IMAGE ->
PhotoImageComplicationData.Builder(
icon,
contentDescription
).build()
ComplicationType.RANGED_VALUE ->
RangedValueComplicationData.Builder(
42f,
0f,
100f,
contentDescription
).setMonochromaticImage(MonochromaticImage.Builder(icon).build())
.setText(PlainComplicationText.Builder(name).build())
.build()
else -> NoDataComplicationData()
}
}
init {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
require(componentName != null) {
"ComponentName is required on Android R and above"
}
}
}
override fun toString(): String =
"ComplicationDataSourceInfo(appName=$appName, name=$name, type=$type" +
", icon=$icon, componentName=$componentName)"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as ComplicationDataSourceInfo
if (appName != other.appName) return false
if (name != other.name) return false
if (type != other.type) return false
if (icon != other.icon) return false
if (componentName != other.componentName) return false
return true
}
override fun hashCode(): Int {
var result = appName.hashCode()
result = 31 * result + name.hashCode()
result = 31 * result + type.hashCode()
result = 31 * result + icon.hashCode()
result = 31 * result + componentName.hashCode()
return result
}
/**
* Converts this value to [WireComplicationProviderInfo] object used for serialization.
*
* @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public fun toWireComplicationProviderInfo(): WireComplicationProviderInfo =
WireComplicationProviderInfo(
appName, name, icon, type.toWireComplicationType(),
componentName
)
}
// Ugh we need this since the linter wants the method signature all on one line...
typealias ApiInfo = ComplicationDataSourceInfo
/**
* @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public fun WireComplicationProviderInfo.toApiComplicationDataSourceInfo(): ApiInfo =
ComplicationDataSourceInfo(
appName!!, providerName!!, providerIcon!!, fromWireType(complicationType),
providerComponentName
)
|
apache-2.0
|
6c6633edca076ace1911c5c089f1e5bc
| 37.938326 | 100 | 0.669193 | 5.700742 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/completion/impl-k1/src/org/jetbrains/kotlin/idea/completion/smart/StaticMembers.kt
|
4
|
6266
|
// Copyright 2000-2022 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.kotlin.idea.completion.smart
import com.intellij.codeInsight.lookup.LookupElement
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.caches.resolve.resolveImportReference
import org.jetbrains.kotlin.idea.completion.LookupElementFactory
import org.jetbrains.kotlin.idea.completion.decorateAsStaticMember
import org.jetbrains.kotlin.idea.core.ExpectedInfo
import org.jetbrains.kotlin.idea.core.PropertyDelegateAdditionalData
import org.jetbrains.kotlin.idea.core.isVisible
import org.jetbrains.kotlin.idea.core.multipleFuzzyTypes
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.util.fuzzyReturnType
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtSimpleNameExpression
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension
import org.jetbrains.kotlin.types.TypeSubstitutor
import java.util.*
// adds java static members, enum members and members from companion object
class StaticMembers(
private val bindingContext: BindingContext,
private val lookupElementFactory: LookupElementFactory,
private val resolutionFacade: ResolutionFacade,
private val moduleDescriptor: ModuleDescriptor
) {
fun addToCollection(
collection: MutableCollection<LookupElement>,
expectedInfos: Collection<ExpectedInfo>,
context: KtSimpleNameExpression,
enumEntriesToSkip: Set<DeclarationDescriptor>
) {
val expectedInfosByClass = HashMap<ClassDescriptor, MutableList<ExpectedInfo>>()
for (expectedInfo in expectedInfos) {
for (fuzzyType in expectedInfo.multipleFuzzyTypes) {
val classDescriptor = fuzzyType.type.constructor.declarationDescriptor as? ClassDescriptor ?: continue
expectedInfosByClass.getOrPut(classDescriptor) { ArrayList() }.add(expectedInfo)
}
if (expectedInfo.additionalData is PropertyDelegateAdditionalData) {
val delegatesClass =
resolutionFacade.resolveImportReference(moduleDescriptor, FqName("kotlin.properties.Delegates")).singleOrNull()
if (delegatesClass is ClassDescriptor) {
addToCollection(
collection,
delegatesClass,
listOf(expectedInfo),
context,
enumEntriesToSkip,
SmartCompletionItemPriority.DELEGATES_STATIC_MEMBER
)
}
}
}
for ((classDescriptor, expectedInfosForClass) in expectedInfosByClass) {
if (!classDescriptor.name.isSpecial) {
addToCollection(
collection,
classDescriptor,
expectedInfosForClass,
context,
enumEntriesToSkip,
SmartCompletionItemPriority.STATIC_MEMBER
)
}
}
}
private fun addToCollection(
collection: MutableCollection<LookupElement>,
classDescriptor: ClassDescriptor,
expectedInfos: Collection<ExpectedInfo>,
context: KtSimpleNameExpression,
enumEntriesToSkip: Set<DeclarationDescriptor>,
defaultPriority: SmartCompletionItemPriority
) {
fun processMember(descriptor: DeclarationDescriptor) {
if (descriptor is DeclarationDescriptorWithVisibility && !descriptor.isVisible(
context,
null,
bindingContext,
resolutionFacade
)
) return
val matcher: (ExpectedInfo) -> ExpectedInfoMatch = when {
descriptor is CallableDescriptor -> {
val returnType = descriptor.fuzzyReturnType() ?: return
{ expectedInfo -> returnType.matchExpectedInfo(expectedInfo) }
}
DescriptorUtils.isEnumEntry(descriptor) && !enumEntriesToSkip.contains(descriptor) -> {
/* we do not need to check type of enum entry because it's taken from proper enum */
{ ExpectedInfoMatch.match(TypeSubstitutor.EMPTY) }
}
else -> return
}
val priority = when {
DescriptorUtils.isEnumEntry(descriptor) -> SmartCompletionItemPriority.ENUM_ENTRIES
else -> defaultPriority
}
collection.addLookupElements(descriptor, expectedInfos, matcher) { createLookupElements(it, priority) }
}
classDescriptor.staticScope.getContributedDescriptors().forEach(::processMember)
val companionObject = classDescriptor.companionObjectDescriptor
if (companionObject != null) {
companionObject.defaultType.memberScope.getContributedDescriptors()
.filter { !it.isExtension }
.forEach(::processMember)
}
val members = classDescriptor.defaultType.memberScope.getContributedDescriptors().filter { member ->
when (classDescriptor.kind) {
ClassKind.ENUM_CLASS -> member is ClassDescriptor // enum member
ClassKind.OBJECT -> member is CallableMemberDescriptor || DescriptorUtils.isNonCompanionObject(member)
else -> DescriptorUtils.isNonCompanionObject(member)
}
}
members.forEach(::processMember)
}
private fun createLookupElements(
memberDescriptor: DeclarationDescriptor,
priority: SmartCompletionItemPriority
): Collection<LookupElement> {
return lookupElementFactory.createStandardLookupElementsForDescriptor(memberDescriptor, useReceiverTypes = false)
.map {
it.decorateAsStaticMember(memberDescriptor, classNameAsLookupString = true)!!
.assignSmartCompletionPriority(priority)
}
}
}
|
apache-2.0
|
d00aac7849172eb3435234a4369975a3
| 43.757143 | 158 | 0.659432 | 6.25974 | false | false | false | false |
GunoH/intellij-community
|
python/src/com/jetbrains/python/newProject/NewProjectWizardDirectoryGeneratorAdapter.kt
|
2
|
2819
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.jetbrains.python.newProject
import com.intellij.ide.util.projectWizard.AbstractNewProjectStep
import com.intellij.ide.util.projectWizard.ProjectSettingsStepBase
import com.intellij.ide.util.projectWizard.WizardContext
import com.intellij.ide.wizard.GeneratorNewProjectWizard
import com.intellij.ide.wizard.NewProjectWizardStepPanel
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.VerticalFlowLayout
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.platform.DirectoryProjectGeneratorBase
import com.intellij.platform.GeneratorPeerImpl
import com.intellij.platform.ProjectGeneratorPeer
import javax.swing.Icon
import javax.swing.JButton
import javax.swing.JComponent
import javax.swing.JPanel
/**
* A base adapter class to turn a [GeneratorNewProjectWizard] into a
* [com.intellij.platform.DirectoryProjectGenerator] and register as an extension point.
*
* @see NewProjectWizardProjectSettingsStep
*/
open class NewProjectWizardDirectoryGeneratorAdapter<T>(val wizard: GeneratorNewProjectWizard) : DirectoryProjectGeneratorBase<T>() {
internal lateinit var panel: NewProjectWizardStepPanel
@Suppress("DialogTitleCapitalization")
override fun getName(): String = wizard.name
override fun getLogo(): Icon = wizard.icon
override fun generateProject(project: Project, baseDir: VirtualFile, settings: T, module: Module) {
panel.step.setupProject(project)
}
override fun createPeer(): ProjectGeneratorPeer<T> {
val context = WizardContext(null) {}
return object : GeneratorPeerImpl<T>() {
override fun getComponent(): JComponent {
panel = NewProjectWizardStepPanel(wizard.createStep(context))
return panel.component
}
}
}
}
/**
* A wizard-enabled project settings step that you should use for your [projectGenerator] in your
* [AbstractNewProjectStep.Customization.createProjectSpecificSettingsStep] to provide the project wizard UI and actions.
*/
class NewProjectWizardProjectSettingsStep<T>(private val projectGenerator: NewProjectWizardDirectoryGeneratorAdapter<T>)
: ProjectSettingsStepBase<T>(projectGenerator, null) {
init {
myCallback = AbstractNewProjectStep.AbstractCallback()
}
override fun createAndFillContentPanel(): JPanel =
JPanel(VerticalFlowLayout()).apply {
add(peer.component)
}
override fun registerValidators() {}
override fun getProjectLocation(): String =
projectGenerator.panel.step.context.projectFileDirectory
override fun getActionButton(): JButton =
super.getActionButton().apply {
addActionListener {
projectGenerator.panel.apply()
}
}
}
|
apache-2.0
|
09e9d51aa242f8b5f248f34e88579f7f
| 36.105263 | 133 | 0.787159 | 4.729866 | false | false | false | false |
yole/jitwatch-intellij
|
src/main/java/JitSourceAnnotator.kt
|
1
|
6829
|
package ru.yole.jitwatch
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.ExternalAnnotator
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.markup.EffectType
import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.openapi.util.Computable
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiWhiteSpace
import com.intellij.ui.JBColor
import org.adoptopenjdk.jitwatch.model.IMetaMember
import org.adoptopenjdk.jitwatch.model.MemberSignatureParts
import org.adoptopenjdk.jitwatch.model.bytecode.BCAnnotationType
import org.adoptopenjdk.jitwatch.model.bytecode.BytecodeInstruction
import org.adoptopenjdk.jitwatch.model.bytecode.LineAnnotation
import org.adoptopenjdk.jitwatch.model.bytecode.MemberBytecode
import org.adoptopenjdk.jitwatch.util.ParseUtil
import ru.yole.jitwatch.languages.LanguageSupport
import java.awt.Color
class JitSourceAnnotator : ExternalAnnotator<PsiFile, List<Pair<PsiElement, LineAnnotation>>>() {
override fun collectInformation(file: PsiFile): PsiFile? {
return file
}
override fun doAnnotate(psiFile: PsiFile?): List<Pair<PsiElement, LineAnnotation>>? {
if (psiFile == null) return null
val service = JitWatchModelService.getInstance(psiFile.project)
if (service.model == null) return null
service.loadBytecode(psiFile)
return ApplicationManager.getApplication().runReadAction(Computable {
mapBytecodeAnnotationsToSource(psiFile)
})
}
private fun mapBytecodeAnnotationsToSource(psiFile: PsiFile): List<Pair<PsiElement, LineAnnotation>> {
val result = mutableListOf<Pair<PsiElement, LineAnnotation>>()
val modelService = JitWatchModelService.getInstance(psiFile.project)
modelService.processBytecodeAnnotations(psiFile) { method, member, memberBytecode, instruction, lineAnnotations ->
for (lineAnnotation in lineAnnotations) {
val sourceElement = mapBytecodeAnnotationToSource(method, member, memberBytecode, instruction, lineAnnotation) ?: continue
result.add(sourceElement to lineAnnotation)
}
}
return result
}
private fun mapBytecodeAnnotationToSource(method: PsiElement,
member: IMetaMember,
memberBytecode: MemberBytecode,
instruction: BytecodeInstruction,
lineAnnotation: LineAnnotation): PsiElement? {
val languageSupport = LanguageSupport.forLanguage(method.language)
val sourceLine = memberBytecode.lineTable.findSourceLineForBytecodeOffset(instruction.offset)
if (sourceLine == -1) return null
val psiFile = method.containingFile ?: return null
val lineStartOffset = psiFile.findLineStart(sourceLine) ?: return null
return when (lineAnnotation.type) {
BCAnnotationType.INLINE_SUCCESS, BCAnnotationType.INLINE_FAIL -> {
val index = findSameLineCallIndex(memberBytecode, sourceLine, instruction)
val calleeMember = getMemberSignatureFromBytecodeComment(member, instruction)
if (calleeMember == null) {
LOG.info("Can't find callee by comment: " + instruction.comment)
return null
}
languageSupport.findCallToMember(psiFile, lineStartOffset, calleeMember, index)
}
BCAnnotationType.ELIMINATED_ALLOCATION -> {
val comment = instruction.comment.removePrefix("// class ")
languageSupport.findAllocation(psiFile, lineStartOffset, comment)
}
else -> null
}
}
private fun getMemberSignatureFromBytecodeComment(currentMember: IMetaMember,
instruction: BytecodeInstruction): MemberSignatureParts? {
var comment: String? = instruction.commentWithMemberPrefixStripped ?: return null
if (ParseUtil.bytecodeMethodCommentHasNoClassPrefix(comment)) {
val currentClass = currentMember.metaClass.fullyQualifiedName.replace('.', '/')
comment = currentClass + "." + comment
}
return MemberSignatureParts.fromBytecodeComment(comment)
}
private fun findSameLineCallIndex(memberBytecode: MemberBytecode,
sourceLine: Int,
invokeInstruction: BytecodeInstruction): Int {
var result = -1
val sameLineInstructions = memberBytecode.findInstructionsForSourceLine(sourceLine)
for (instruction in sameLineInstructions) {
if (instruction.opcode == invokeInstruction.opcode && instruction.comment == invokeInstruction.comment) {
result++
}
if (instruction == invokeInstruction) {
break
}
}
return result.coerceAtLeast(0)
}
private fun PsiFile.findLineStart(sourceLine: Int): Int? {
val document = PsiDocumentManager.getInstance(project).getDocument(this) ?: return null
val adjustedLine = sourceLine - 1
if (adjustedLine >= document.lineCount) return null
var lineStartOffset = document.getLineStartOffset(adjustedLine)
while (lineStartOffset < document.textLength && findElementAt(lineStartOffset) is PsiWhiteSpace) {
lineStartOffset++
}
return lineStartOffset
}
override fun apply(file: PsiFile, annotationResult: List<Pair<PsiElement, LineAnnotation>>?, holder: AnnotationHolder) {
if (annotationResult == null) return
for (pair in annotationResult) {
applyAnnotation(pair.first, pair.second, holder)
}
}
private fun applyAnnotation(element: PsiElement, lineAnnotation: LineAnnotation, holder: AnnotationHolder) {
val annotation = holder.createInfoAnnotation(element, lineAnnotation.annotation)
val color: Color? = when (lineAnnotation.type) {
BCAnnotationType.INLINE_SUCCESS, BCAnnotationType.ELIMINATED_ALLOCATION -> JBColor.GREEN
BCAnnotationType.INLINE_FAIL -> JBColor.RED
else -> null
}
if (color != null) {
annotation.enforcedTextAttributes = underline(color)
}
}
private fun underline(color: Color) = TextAttributes(null, null, color, EffectType.LINE_UNDERSCORE, 0)
companion object {
val LOG = Logger.getInstance(JitSourceAnnotator::class.java)
}
}
|
apache-2.0
|
165d656e86f889e9b8be655ea5cd4c77
| 43.344156 | 138 | 0.676819 | 5.394155 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/idea/tests/testData/multiplatform/multiplatformLibrary/js/js.kt
|
3
|
380
|
package sample
actual class <!LINE_MARKER("descr='Has declaration in common module'")!>Sample<!> {
actual fun <!LINE_MARKER("descr='Has declaration in common module'")!>checkMe<!>() = 12
}
actual object <!LINE_MARKER("descr='Has declaration in common module'")!>Platform<!> {
actual val <!LINE_MARKER("descr='Has declaration in common module'")!>name<!>: String = "JS"
}
|
apache-2.0
|
6b90565e39852c7934c82b8f68cb307b
| 41.333333 | 96 | 0.686842 | 4.222222 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/jvm-debugger/test/testData/variables/optimisedVariablesWithLambdas.kt
|
6
|
1596
|
package optimisedVariablesWithLambdas
// ATTACH_LIBRARY: maven(org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.2)
// SHOW_KOTLIN_VARIABLES
import kotlinx.coroutines.runBlocking
suspend fun foo(param1: Int, param2: Int, param3: Int) {
val a = "a"
//Breakpoint!
suspendUse(a)
val b = "b"
//Breakpoint!
suspendUse(b)
suspendUse(param1)
//Breakpoint!
block {
val c = "c"
//Breakpoint!
println("")
val d = "d"
//Breakpoint!
println("")
}
suspendBlock {
val e = "e"
//Breakpoint!
suspendUse(e)
val f = "f"
//Breakpoint!
suspendUse(f)
//Breakpoint!
}
inlineBlock {
val g = "g"
//Breakpoint!
suspendUse(g)
block {
val h = "h"
//Breakpoint!
println("")
}
suspendUse(param2)
inlineBlock {
val i = "i"
//Breakpoint!
suspendUse(i)
suspendUse(param3)
}
val j = "j"
//Breakpoint!
suspendUse(j)
}
suspendUse(a)
noinlineBlock {
val k = "k"
//Breakpoint!
println("")
}
//Breakpoint!
println("")
//Breakpoint!
}
fun main() = runBlocking {
foo(1, 2, 3)
}
suspend fun suspendUse(value: Any) {
}
inline fun inlineBlock(block: () -> Unit) = block()
inline fun noinlineBlock(noinline block: () -> Unit) = block()
fun block(block: () -> Unit) = block()
suspend fun suspendBlock(block: suspend () -> Unit) = block()
|
apache-2.0
|
e7661a4776e500ca9e21a37ae6cea575
| 17.136364 | 77 | 0.512531 | 3.864407 | false | false | false | false |
android/compose-samples
|
Jetsnack/app/src/main/java/com/example/jetsnack/model/Search.kt
|
1
|
3846
|
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.jetsnack.model
import androidx.compose.runtime.Immutable
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
/**
* A fake repo for searching.
*/
object SearchRepo {
fun getCategories(): List<SearchCategoryCollection> = searchCategoryCollections
fun getSuggestions(): List<SearchSuggestionGroup> = searchSuggestions
suspend fun search(query: String): List<Snack> = withContext(Dispatchers.Default) {
delay(200L) // simulate an I/O delay
snacks.filter { it.name.contains(query, ignoreCase = true) }
}
}
@Immutable
data class SearchCategoryCollection(
val id: Long,
val name: String,
val categories: List<SearchCategory>
)
@Immutable
data class SearchCategory(
val name: String,
val imageUrl: String
)
@Immutable
data class SearchSuggestionGroup(
val id: Long,
val name: String,
val suggestions: List<String>
)
/**
* Static data
*/
private val searchCategoryCollections = listOf(
SearchCategoryCollection(
id = 0L,
name = "Categories",
categories = listOf(
SearchCategory(
name = "Chips & crackers",
imageUrl = "https://source.unsplash.com/UsSdMZ78Q3E"
),
SearchCategory(
name = "Fruit snacks",
imageUrl = "https://source.unsplash.com/SfP1PtM9Qa8"
),
SearchCategory(
name = "Desserts",
imageUrl = "https://source.unsplash.com/_jk8KIyN_uA"
),
SearchCategory(
name = "Nuts ",
imageUrl = "https://source.unsplash.com/UsSdMZ78Q3E"
)
)
),
SearchCategoryCollection(
id = 1L,
name = "Lifestyles",
categories = listOf(
SearchCategory(
name = "Organic",
imageUrl = "https://source.unsplash.com/7meCnGCJ5Ms"
),
SearchCategory(
name = "Gluten Free",
imageUrl = "https://source.unsplash.com/m741tj4Cz7M"
),
SearchCategory(
name = "Paleo",
imageUrl = "https://source.unsplash.com/dt5-8tThZKg"
),
SearchCategory(
name = "Vegan",
imageUrl = "https://source.unsplash.com/ReXxkS1m1H0"
),
SearchCategory(
name = "Vegitarian",
imageUrl = "https://source.unsplash.com/IGfIGP5ONV0"
),
SearchCategory(
name = "Whole30",
imageUrl = "https://source.unsplash.com/9MzCd76xLGk"
)
)
)
)
private val searchSuggestions = listOf(
SearchSuggestionGroup(
id = 0L,
name = "Recent searches",
suggestions = listOf(
"Cheese",
"Apple Sauce"
)
),
SearchSuggestionGroup(
id = 1L,
name = "Popular searches",
suggestions = listOf(
"Organic",
"Gluten Free",
"Paleo",
"Vegan",
"Vegitarian",
"Whole30"
)
)
)
|
apache-2.0
|
5c72f893bca715a2b60c6d47cb37ef34
| 27.072993 | 87 | 0.574883 | 4.375427 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/printing/JKSymbolRenderer.kt
|
6
|
4128
|
// 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.kotlin.nj2k.printing
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiClass
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.PsiShortNamesCache
import org.jetbrains.kotlin.name.SpecialNames
import org.jetbrains.kotlin.nj2k.JKImportStorage
import org.jetbrains.kotlin.nj2k.escaped
import org.jetbrains.kotlin.nj2k.symbols.*
import org.jetbrains.kotlin.nj2k.tree.JKClassAccessExpression
import org.jetbrains.kotlin.nj2k.tree.JKQualifiedExpression
import org.jetbrains.kotlin.nj2k.tree.JKTreeElement
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
internal class JKSymbolRenderer(private val importStorage: JKImportStorage, project: Project) {
private val canBeShortenedClassNameCache = CanBeShortenedCache(project)
private fun JKSymbol.isFqNameExpected(owner: JKTreeElement?): Boolean {
if (owner?.isSelectorOfQualifiedExpression() == true) return false
return this is JKClassSymbol || isStaticMember || isEnumConstant
}
private fun JKSymbol.isFromJavaLangPackage() =
fqName.startsWith(JAVA_LANG_FQ_PREFIX)
fun renderSymbol(symbol: JKSymbol, owner: JKTreeElement?): String {
val name = symbol.name.escaped()
if (!symbol.isFqNameExpected(owner)) return name
val fqName = symbol.getDisplayFqName().escapedAsQualifiedName()
if (owner is JKClassAccessExpression && symbol.isFromJavaLangPackage()) return fqName
return when {
symbol is JKClassSymbol && canBeShortenedClassNameCache.canBeShortened(symbol) -> {
importStorage.addImport(fqName)
name
}
symbol.isStaticMember && symbol.containingClass?.isUnnamedCompanion == true -> {
val containingClass = symbol.containingClass ?: return fqName
val classContainingCompanion = containingClass.containingClass ?: return fqName
if (!canBeShortenedClassNameCache.canBeShortened(classContainingCompanion)) return fqName
importStorage.addImport(classContainingCompanion.getDisplayFqName())
"${classContainingCompanion.name.escaped()}.${SpecialNames.DEFAULT_NAME_FOR_COMPANION_OBJECT}.$name"
}
symbol.isEnumConstant || symbol.isStaticMember -> {
val containingClass = symbol.containingClass ?: return fqName
if (!canBeShortenedClassNameCache.canBeShortened(containingClass)) return fqName
importStorage.addImport(containingClass.getDisplayFqName())
"${containingClass.name.escaped()}.$name"
}
else -> fqName
}
}
private fun JKTreeElement.isSelectorOfQualifiedExpression() =
parent?.safeAs<JKQualifiedExpression>()?.selector == this
companion object {
private const val JAVA_LANG_FQ_PREFIX = "java.lang"
}
}
private class CanBeShortenedCache(project: Project) {
private val shortNameCache = PsiShortNamesCache.getInstance(project)
private val searchScope = GlobalSearchScope.allScope(project)
private val canBeShortenedCache = mutableMapOf<String, Boolean>().apply {
CLASS_NAMES_WHICH_HAVE_DIFFERENT_MEANINGS_IN_KOTLIN_AND_JAVA.forEach { name ->
this[name] = false
}
}
fun canBeShortened(symbol: JKClassSymbol): Boolean = canBeShortenedCache.getOrPut(symbol.name) {
var symbolsWithSuchNameCount = 0
val processSymbol = { _: PsiClass ->
symbolsWithSuchNameCount++
symbolsWithSuchNameCount <= 1 //stop if met more than one symbol with such name
}
shortNameCache.processClassesWithName(symbol.name, processSymbol, searchScope, null)
symbolsWithSuchNameCount == 1
}
companion object {
private val CLASS_NAMES_WHICH_HAVE_DIFFERENT_MEANINGS_IN_KOTLIN_AND_JAVA = setOf(
"Function",
"Serializable"
)
}
}
|
apache-2.0
|
1230d714583fb9e659656d2f776ce4d8
| 43.880435 | 158 | 0.707607 | 5.179423 | false | false | false | false |
smmribeiro/intellij-community
|
python/python-psi-impl/src/com/jetbrains/python/codeInsight/typing/PyTypedDictTypeProvider.kt
|
1
|
18188
|
// 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.jetbrains.python.codeInsight.typing
import com.intellij.openapi.util.Ref
import com.intellij.psi.PsiElement
import com.jetbrains.python.PyCustomType
import com.jetbrains.python.PyNames
import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider.*
import com.jetbrains.python.psi.*
import com.jetbrains.python.psi.impl.PyBuiltinCache
import com.jetbrains.python.psi.impl.PyCallExpressionNavigator
import com.jetbrains.python.psi.impl.PyEvaluator
import com.jetbrains.python.psi.impl.StubAwareComputation
import com.jetbrains.python.psi.impl.stubs.PyTypedDictStubImpl
import com.jetbrains.python.psi.stubs.PyTypedDictStub
import com.jetbrains.python.psi.types.*
import com.jetbrains.python.psi.types.PyTypedDictType.Companion.TYPED_DICT_FIELDS_PARAMETER
import com.jetbrains.python.psi.types.PyTypedDictType.Companion.TYPED_DICT_NAME_PARAMETER
import com.jetbrains.python.psi.types.PyTypedDictType.Companion.TYPED_DICT_TOTAL_PARAMETER
import java.util.*
import java.util.stream.Collectors
typealias TDFields = LinkedHashMap<String, PyTypedDictType.FieldTypeAndTotality>
class PyTypedDictTypeProvider : PyTypeProviderBase() {
override fun getReferenceExpressionType(referenceExpression: PyReferenceExpression, context: TypeEvalContext): PyType? {
return getTypedDictTypeForCallee(referenceExpression, context) ?: getTypedDictGetType(referenceExpression, context)
}
override fun getReferenceType(referenceTarget: PsiElement, context: TypeEvalContext, anchor: PsiElement?): Ref<PyType>? {
return PyTypeUtil.notNullToRef(getTypedDictTypeForResolvedCallee(referenceTarget, context))
}
override fun prepareCalleeTypeForCall(type: PyType?, call: PyCallExpression, context: TypeEvalContext): Ref<PyCallableType?>? {
return if (type is PyTypedDictType) Ref.create(type) else null
}
companion object {
val nameIsTypedDict = { name: String? -> name == TYPED_DICT || name == TYPED_DICT_EXT }
fun isTypedDict(expression: PyExpression, context: TypeEvalContext): Boolean {
return resolveToQualifiedNames(expression, context).any(nameIsTypedDict)
}
fun isTypingTypedDictInheritor(cls: PyClass, context: TypeEvalContext): Boolean {
val isTypingTD = { type: PyClassLikeType? ->
type is PyTypedDictType || nameIsTypedDict(type?.classQName)
}
if (checkIfClassIsDirectTypedDictInheritor(cls, context)) return true
val ancestors = cls.getAncestorTypes(context)
return ancestors.any(isTypingTD)
}
/**
* This method helps to avoid the situation when two processes try to get an element's type simultaneously
* and one of them ends up with null.
*/
private fun checkIfClassIsDirectTypedDictInheritor(cls: PyClass, context: TypeEvalContext): Boolean {
val stub = cls.stub
if (context.maySwitchToAST(cls) || stub == null) {
return cls.superClassExpressions.any { isTypedDict(it, context) }
}
else {
return stub.superClassesText.any { isTypedDict(PyUtil.createExpressionFromFragment(it, cls) ?: return false, context) }
}
}
private fun getTypedDictGetType(referenceTarget: PsiElement, context: TypeEvalContext): PyCallableType? {
val callExpression =
if (context.maySwitchToAST(referenceTarget)) PyCallExpressionNavigator.getPyCallExpressionByCallee(referenceTarget) else null
if (callExpression == null || callExpression.callee == null) return null
val receiver = callExpression.getReceiver(null) ?: return null
val type = context.getType(receiver)
if (type !is PyTypedDictType || type.isInferred()) return null
if (resolveToQualifiedNames(callExpression.callee!!, context).contains(MAPPING_GET)) {
val parameters = mutableListOf<PyCallableParameter>()
val builtinCache = PyBuiltinCache.getInstance(referenceTarget)
val elementGenerator = PyElementGenerator.getInstance(referenceTarget.project)
parameters.add(PyCallableParameterImpl.nonPsi("key", builtinCache.strType))
parameters.add(PyCallableParameterImpl.nonPsi("default", null,
elementGenerator.createExpressionFromText(LanguageLevel.forElement(referenceTarget),
"None")))
val key = PyEvaluator.evaluate(callExpression.getArgument(0, "key", PyExpression::class.java), String::class.java)
val defaultArgument = callExpression.getArgument(1, "default", PyExpression::class.java)
val default = if (defaultArgument != null) context.getType(defaultArgument) else PyNoneType.INSTANCE
val valueTypeAndTotality = type.fields[key]
return PyCallableTypeImpl(parameters,
when {
valueTypeAndTotality == null -> default
valueTypeAndTotality.isRequired -> valueTypeAndTotality.type
else -> PyUnionType.union(valueTypeAndTotality.type, default)
})
}
return null
}
private fun getTypedDictTypeForResolvedCallee(referenceTarget: PsiElement, context: TypeEvalContext): PyTypedDictType? {
return when (referenceTarget) {
is PyClass -> getTypedDictTypeForTypingTDInheritorAsCallee(referenceTarget, context, false)
is PyTargetExpression -> getTypedDictTypeForTarget(referenceTarget, context)
else -> null
}
}
private fun getTypedDictTypeForCallee(referenceExpression: PyReferenceExpression, context: TypeEvalContext): PyType? {
if (PyCallExpressionNavigator.getPyCallExpressionByCallee(referenceExpression) == null) return null
if (isTypedDict(referenceExpression, context)) {
val parameters = mutableListOf<PyCallableParameter>()
val builtinCache = PyBuiltinCache.getInstance(referenceExpression)
val languageLevel = LanguageLevel.forElement(referenceExpression)
val generator = PyElementGenerator.getInstance(referenceExpression.project)
parameters.add(PyCallableParameterImpl.nonPsi(TYPED_DICT_NAME_PARAMETER, builtinCache.getStringType(languageLevel)))
val dictClassType = builtinCache.dictType
parameters.add(PyCallableParameterImpl.nonPsi(TYPED_DICT_FIELDS_PARAMETER,
if (dictClassType != null) PyCollectionTypeImpl(dictClassType.pyClass, false,
listOf(builtinCache.strType, null))
else dictClassType))
parameters.add(
PyCallableParameterImpl.nonPsi(TYPED_DICT_TOTAL_PARAMETER,
builtinCache.boolType,
generator.createExpressionFromText(languageLevel, PyNames.TRUE)))
return PyCallableTypeImpl(parameters, null)
}
return null
}
private fun getTypedDictTypeForTypingTDInheritorAsCallee(cls: PyClass,
context: TypeEvalContext,
isInstance: Boolean): PyTypedDictType? {
if (isTypingTypedDictInheritor(cls, context)) {
return PyTypedDictType(cls.name ?: return null,
TDFields(collectFields(cls, context)),
false,
PyBuiltinCache.getInstance(cls).dictType?.pyClass ?: return null,
if (isInstance) PyTypedDictType.DefinitionLevel.INSTANCE else PyTypedDictType.DefinitionLevel.NEW_TYPE,
cls.getAncestorTypes(context).filterIsInstance<PyTypedDictType>(),
cls)
}
return null
}
private fun collectFields(cls: PyClass, context: TypeEvalContext): TDFields {
val fields = mutableMapOf<String, PyTypedDictType.FieldTypeAndTotality>()
val ancestors = cls.getAncestorTypes(context)
val typedDictCustomTypeIndex = ancestors.indexOfFirst { it is PyCustomType && nameIsTypedDict(it.classQName) }
// When some ancestor is located in another file its type will be PyClassType because of difference in getting ancestor types.
// (see com.jetbrains.python.psi.impl.PyClassImpl.fillSuperClassesNoSwitchToAst)
// When AST is unavailable, the type of resolved element is returned, TypedDict reference is resolved to PyClass,
// therefore the type of that PyClass is PyClassType.
// That's why in case when AST for ancestors is unavailable we need to collect fields from PyClassType instances.
if (typedDictCustomTypeIndex > 0) {
ancestors.take(typedDictCustomTypeIndex)
.forEach { if (it is PyClassType) fields.putAll(collectTypingTDInheritorFields(it.pyClass, context)) }
}
else {
ancestors.forEach { if (it is PyTypedDictType) fields.putAll(it.fields) }
}
fields.putAll(collectTypingTDInheritorFields(cls, context))
return TDFields(fields)
}
private fun collectTypingTDInheritorFields(cls: PyClass, context: TypeEvalContext): TDFields {
val type = cls.getType(context)
if (type is PyTypedDictType) {
return TDFields(type.fields)
}
val fields = mutableListOf<PyTargetExpression>()
cls.processClassLevelDeclarations { element, _ ->
if (element is PyTargetExpression && element.annotationValue != null) {
fields.add(element)
}
true
}
val totality = getTotality(cls)
val toTDFields = Collectors.toMap<PyTargetExpression, String, PyTypedDictType.FieldTypeAndTotality, TDFields>(
{ it.name },
{ field -> PyTypedDictType.FieldTypeAndTotality(field, context.getType(field), totality) },
{ _, v2 -> v2 },
{ TDFields() })
return fields.stream().collect(toTDFields)
}
private fun getTotality(cls: PyClass): Boolean {
return if (cls.stub != null) {
"total=False" !in cls.stub.superClassesText
}
else {
(cls.superClassExpressionList?.getKeywordArgument("total")?.valueExpression as? PyBoolLiteralExpression)?.value ?: true
}
}
private fun getTypedDictTypeForTarget(target: PyTargetExpression, context: TypeEvalContext): PyTypedDictType? {
return StubAwareComputation.on(target)
.withCustomStub { it.getCustomStub(PyTypedDictStub::class.java) }
.overStub { getTypedDictTypeFromStub(target, it, context, false) }
.withStubBuilder { PyTypedDictStubImpl.create(it) }
.compute(context)
}
fun getTypedDictTypeForResolvedElement(resolved: PsiElement, context: TypeEvalContext): PyType? {
if (resolved is PyClass && isTypingTypedDictInheritor(resolved, context)) {
return getTypedDictTypeForTypingTDInheritorAsCallee(resolved, context, true)
}
if (resolved is PyCallExpression) {
val callee = resolved.callee
if (callee is PyReferenceExpression && isTypedDict(callee, context)) {
val type = getTypedDictTypeFromAST(resolved, context)
if (type != null) {
return type
}
}
}
return null
}
private fun getTypedDictTypeFromAST(call: PyCallExpression, context: TypeEvalContext): PyTypedDictType? {
return if (context.maySwitchToAST(call)) {
getTypedDictTypeFromStub(call, PyTypedDictStubImpl.create(call), context, true)
}
else null
}
private fun getTypedDictTypeFromStub(targetOrCall: PsiElement,
stub: PyTypedDictStub?,
context: TypeEvalContext,
isInstance: Boolean): PyTypedDictType? {
if (stub == null) return null
val dictClass = PyBuiltinCache.getInstance(targetOrCall).dictType?.pyClass
if (dictClass == null) return null
val fields = stub.fields
val total = stub.isRequired
val typedDictFields = parseTypedDictFields(targetOrCall, fields, context, total)
return PyTypedDictType(stub.name,
typedDictFields,
false,
dictClass,
if (isInstance) PyTypedDictType.DefinitionLevel.INSTANCE else PyTypedDictType.DefinitionLevel.NEW_TYPE,
emptyList(),
getDeclaration(targetOrCall))
}
private fun parseTypedDictFields(anchor: PsiElement,
fields: Map<String, Optional<String>>,
context: TypeEvalContext,
total: Boolean): TDFields {
val result = TDFields()
for ((name, type) in fields) {
result[name] = parseTypedDictField(anchor, type.orElse(null), context, total)
}
return result
}
private fun getDeclaration(targetOrCall: PsiElement): PyQualifiedNameOwner? {
return when (targetOrCall) {
is PyTargetExpression -> targetOrCall
is PyCallExpression -> (targetOrCall.parent as? PyAssignmentStatement)?.leftHandSideExpression as? PyTargetExpression
else -> null
}
}
private fun parseTypedDictField(anchor: PsiElement,
type: String?,
context: TypeEvalContext,
total: Boolean): PyTypedDictType.FieldTypeAndTotality {
if (type == null) return PyTypedDictType.FieldTypeAndTotality(null, null)
val pyType = Ref.deref(getStringBasedType(type, anchor, context))
return PyTypedDictType.FieldTypeAndTotality(null, pyType, total)
}
/**
* If [expected] type is `typing.TypedDict[...]`,
* then tries to infer `typing.TypedDict[...]` for [expression],
* otherwise returns type inferred by [context].
*/
fun promoteToTypedDict(expression: PyExpression, expected: PyType?, context: TypeEvalContext): PyType? {
if (expected is PyTypedDictType) {
return newInstance(expression, context) ?: context.getType(expression)
}
else {
return context.getType(expression)
}
}
/**
* Tries to construct TypedDict type for a value that could be considered as TypedDict and downcasted to `typing.TypedDict[...]` type.
*/
private fun newInstance(expression: PyExpression, context: TypeEvalContext): PyType? {
return when (expression) {
is PyTupleExpression -> {
val elements = expression.elements
val classes = elements.mapNotNull { toTypedDictType(it, context) }
if (elements.size == classes.size) PyUnionType.union(classes) else null
}
else -> toTypedDictType(expression, context)
}
}
private fun toTypedDictType(expression: PyExpression, context: TypeEvalContext): PyType? {
if (expression is PyDictLiteralExpression) {
val fields = getTypingTDFieldsFromDictLiteral(expression, context)
if (fields != null) {
val dictClass = PyBuiltinCache.getInstance(expression).dictType?.pyClass
if (dictClass == null) return null
return PyTypedDictType("TypedDict", fields, true, dictClass,
PyTypedDictType.DefinitionLevel.INSTANCE,
emptyList())
}
}
else if (expression is PyCallExpression) {
val typedDictType = inferTypedDictFromCallExpression(expression, context)
if (typedDictType != null) return typedDictType
}
return null
}
fun inferTypedDictFromCallExpression(callExpression: PyCallExpression, context: TypeEvalContext): PyTypedDictType? {
val resolvedQualifiedNames = if (callExpression.callee != null) resolveToQualifiedNames(callExpression.callee!!, context)
else return null
if (resolvedQualifiedNames.any { it == PyNames.DICT }) {
val arguments = callExpression.arguments
if (arguments.size > 1) {
val fields = getTypingTDFieldsFromDictKeywordArguments(arguments, context)
if (fields != null) {
val dictClass = PyBuiltinCache.getInstance(callExpression).dictType?.pyClass
if (dictClass == null) return null
return PyTypedDictType("TypedDict", fields, true, dictClass,
PyTypedDictType.DefinitionLevel.INSTANCE,
emptyList())
}
}
}
return null
}
private fun getTypingTDFieldsFromDictLiteral(dictLiteral: PyDictLiteralExpression, context: TypeEvalContext): TDFields? {
val fields = LinkedHashMap<String, PyExpression?>()
dictLiteral.elements.forEach {
val name = it.key
val value = it.value
if (name !is PyStringLiteralExpression) return null
fields[name.stringValue] = value
}
return typedDictFieldsFromKeysAndValues(fields, context)
}
private fun getTypingTDFieldsFromDictKeywordArguments(keywordArguments: Array<PyExpression>, context: TypeEvalContext): TDFields? {
val fields = LinkedHashMap<String, PyExpression?>()
keywordArguments.forEach {
if (it !is PyKeywordArgument || it.keyword == null) return null
fields[it.keyword!!] = it.valueExpression
}
return typedDictFieldsFromKeysAndValues(fields, context)
}
private fun typedDictFieldsFromKeysAndValues(fields: Map<String, PyExpression?>, context: TypeEvalContext): TDFields {
val result = TDFields()
for ((key, value) in fields) {
result[key] = if (value != null) PyTypedDictType.FieldTypeAndTotality(value, context.getType(value))
else PyTypedDictType.FieldTypeAndTotality(null, null)
}
return result
}
}
}
|
apache-2.0
|
6c21307c64911e4f2b78cef793057066
| 45.876289 | 140 | 0.661755 | 5.521554 | false | false | false | false |
NlRVANA/Unity
|
app/src/main/java/com/zwq65/unity/ui/provider/TabArticleProvider.kt
|
1
|
1296
|
/*
* Copyright [2017] [NIRVANA PRIVATE LIMITED]
*
* 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.zwq65.unity.ui.provider
import com.zwq65.unity.di.FragmentScoped
import com.zwq65.unity.ui.fragment.TabArticleFragment
import com.zwq65.unity.ui.module.TabArticleModule
import dagger.Module
import dagger.android.ContributesAndroidInjector
/**
* ================================================
* <p>
* Created by NIRVANA on 2017/09/27
* Contact with <[email protected]>
* ================================================
*/
@Module
abstract class TabArticleProvider {
@FragmentScoped
@ContributesAndroidInjector(modules = [(TabArticleModule::class)])
internal abstract fun tabArticleFragment(): TabArticleFragment
}
|
apache-2.0
|
12f963a8c39535b51228ba32cfc54607
| 33.105263 | 78 | 0.683642 | 4.305648 | false | false | false | false |
CosmoRing/PokemonGoBot
|
src/main/kotlin/ink/abb/pogo/scraper/Main.kt
|
1
|
12446
|
/**
* Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information)
* This program comes with ABSOLUTELY NO WARRANTY;
* This is free software, and you are welcome to redistribute it under certain conditions.
*
* For more information, refer to the LICENSE file in this repositories root directory
*/
package ink.abb.pogo.scraper
import POGOProtos.Enums.TutorialStateOuterClass
import POGOProtos.Networking.Requests.Messages.GetPlayerMessageOuterClass
import POGOProtos.Networking.Requests.Messages.MarkTutorialCompleteMessageOuterClass
import POGOProtos.Networking.Requests.RequestTypeOuterClass
import com.pokegoapi.api.PokemonGo
import com.pokegoapi.api.device.DeviceInfo
import com.pokegoapi.auth.CredentialProvider
import com.pokegoapi.auth.GoogleAutoCredentialProvider
import com.pokegoapi.auth.GoogleUserCredentialProvider
import com.pokegoapi.auth.PtcCredentialProvider
import com.pokegoapi.exceptions.LoginFailedException
import com.pokegoapi.exceptions.RemoteServerException
import com.pokegoapi.main.ServerRequest
import com.pokegoapi.util.SystemTimeImpl
import ink.abb.pogo.scraper.controllers.ProgramController
import ink.abb.pogo.scraper.services.BotService
import ink.abb.pogo.scraper.util.Log
import ink.abb.pogo.scraper.util.credentials.GoogleAutoCredentials
import ink.abb.pogo.scraper.util.credentials.GoogleCredentials
import ink.abb.pogo.scraper.util.credentials.PtcCredentials
import ink.abb.pogo.scraper.util.toHexString
import okhttp3.Credentials
import okhttp3.OkHttpClient
import org.springframework.boot.SpringApplication
import org.springframework.context.ApplicationContext
import org.springframework.context.ConfigurableApplicationContext
import java.io.File
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.net.InetSocketAddress
import java.net.Proxy
import java.nio.file.Paths
import java.util.*
import java.util.logging.LogManager
import javax.swing.text.rtf.RTFEditorKit
val time = SystemTimeImpl()
fun getAuth(settings: Settings, http: OkHttpClient, writeToken: (String) -> Unit): CredentialProvider {
val credentials = settings.credentials
val auth = if (credentials is GoogleCredentials) {
if (credentials.token.isBlank()) {
val provider = GoogleUserCredentialProvider(http, time)
println("Please go to " + GoogleUserCredentialProvider.LOGIN_URL)
println("Enter authorisation code:")
val access = readLine()
// we should be able to login with this token
provider.login(access)
println("Refresh token:" + provider.refreshToken)
Log.normal("Setting Google refresh token in your config")
credentials.token = provider.refreshToken
writeToken(credentials.token)
provider
} else {
GoogleUserCredentialProvider(http, credentials.token, time)
}
} else if (credentials is GoogleAutoCredentials) {
GoogleAutoCredentialProvider(http, credentials.username, credentials.password, time)
} else if (credentials is PtcCredentials) {
try {
PtcCredentialProvider(http, credentials.username, credentials.password, time)
} catch (e: LoginFailedException) {
throw e
} catch (e: RemoteServerException) {
throw e
} catch (e: Exception) {
// sometimes throws ArrayIndexOutOfBoundsException or other RTE's
throw RemoteServerException(e)
}
} else {
throw IllegalStateException("Unknown credentials: ${credentials.javaClass}")
}
return auth
}
fun main(args: Array<String>) {
LogManager.getLogManager().reset()
com.pokegoapi.util.Log.setLevel(com.pokegoapi.util.Log.Level.NONE)
val pokemonGoBotApplication: ConfigurableApplicationContext = SpringApplication.run(PokemonGoBotApplication::class.java, *args)
ProgramController.addApplication(pokemonGoBotApplication)
}
fun loadProperties(filename: String): Properties {
val properties = Properties()
Log.green("Trying to read ${Paths.get(filename).toAbsolutePath()}")
var failed = false
try {
FileInputStream(filename).use {
try {
properties.load(it)
} catch (e: Exception) {
failed = true
}
}
} catch (e: FileNotFoundException) {
throw e
}
if (failed) {
FileInputStream(filename).use {
val rtfParser = RTFEditorKit()
val document = rtfParser.createDefaultDocument()
rtfParser.read(it.reader(), document, 0)
val text = document.getText(0, document.length)
properties.load(text.byteInputStream())
Log.red("Config file encoded as Rich Text Format (RTF)!")
}
}
return properties
}
fun startDefaultBot(http: OkHttpClient, service: BotService) {
var properties: Properties? = null
val attemptFilenames = arrayOf("config.properties", "config.properties.txt", "config.properties.rtf")
val dir = File(System.getProperty("java.class.path")).absoluteFile.parentFile
var filename = ""
fileLoop@ for (path in arrayOf(Paths.get("").toAbsolutePath(), dir)) {
for (attemptFilename in attemptFilenames) {
try {
filename = attemptFilename
properties = loadProperties("${path.toString()}/$filename")
break@fileLoop
} catch (e: FileNotFoundException) {
Log.red("$filename file not found")
}
}
}
if (properties == null) {
Log.red("No config files found. Exiting.")
System.exit(1)
return
} else {
val settings = SettingsParser(properties).createSettingsFromProperties()
service.addBot(startBot(settings, http, {
settings.writeProperty(filename, "token", it)
}))
}
}
fun startBot(settings: Settings, http: OkHttpClient, writeToken: (String) -> Unit = {}): Bot {
var proxyHttp: OkHttpClient? = null
if (!settings.proxyServer.equals("") && settings.proxyPort > 0) {
Log.normal("Setting up proxy server for bot " + settings.name + ": " + settings.proxyServer + ":" + settings.proxyPort)
val proxyType: Proxy.Type
if (settings.proxyType.equals("HTTP"))
proxyType = Proxy.Type.HTTP
else if (settings.proxyType.equals("SOCKS"))
proxyType = Proxy.Type.SOCKS
else
proxyType = Proxy.Type.DIRECT
proxyHttp = http.newBuilder()
.proxy(Proxy(proxyType, InetSocketAddress(settings.proxyServer, settings.proxyPort)))
.proxyAuthenticator { route, response ->
response.request().newBuilder()
.header("Proxy-Authorization", Credentials.basic(settings.proxyUsername, settings.proxyPassword))
.build()
}
.build()
}
Log.normal("Logging in to game server...")
val retryCount = 3
val errorTimeout = 1000L
var retries = retryCount
var auth: CredentialProvider? = null
do {
try {
if (proxyHttp == null)
auth = getAuth(settings, http, writeToken)
else
auth = getAuth(settings, proxyHttp, writeToken)
} catch (e: LoginFailedException) {
throw IllegalStateException("Server refused your login credentials. Are they correct?")
} catch (e: RemoteServerException) {
Log.red("Server returned unexpected error: ${e.message}")
if (retries-- > 0) {
Log.normal("Retrying...")
Thread.sleep(errorTimeout)
}
}
} while (auth == null && retries >= 0)
retries = retryCount
var api: PokemonGo? = null
do {
try {
if (proxyHttp == null)
api = PokemonGo(auth, http, time)
else
api = PokemonGo(auth, proxyHttp, time)
} catch (e: LoginFailedException) {
throw IllegalStateException("Server refused your login credentials. Are they correct?")
} catch (e: RemoteServerException) {
Log.red("Server returned unexpected error: ${e.message}")
if (retries-- > 0) {
Log.normal("Retrying...")
Thread.sleep(errorTimeout)
}
}
} while (api == null && retries >= 0)
if (api == null) {
throw IllegalStateException("Failed to login. Stopping")
}
Log.normal("Logged in successfully")
print("Getting profile data from pogo server")
while (api.playerProfile == null) {
print(".")
Thread.sleep(1000)
}
println(".")
Thread.sleep(1000)
val stats = try {
api.playerProfile.stats
} catch (e: Exception) {
null
}
if (stats == null) {
Log.yellow("Accepting ToS")
// apparently the account didn't except the ToS yet
val getPlayerMessageBuilder = GetPlayerMessageOuterClass.GetPlayerMessage.newBuilder()
val tosBuilder = MarkTutorialCompleteMessageOuterClass.MarkTutorialCompleteMessage.newBuilder()
.addTutorialsCompleted(TutorialStateOuterClass.TutorialState.LEGAL_SCREEN)
.setSendMarketingEmails(false)
.setSendPushNotifications(false)
val serverRequestsPlayer = ServerRequest(RequestTypeOuterClass.RequestType.GET_PLAYER, getPlayerMessageBuilder.build())
val serverRequestsTutorial = ServerRequest(RequestTypeOuterClass.RequestType.MARK_TUTORIAL_COMPLETE, tosBuilder.build())
api.requestHandler.sendServerRequests(serverRequestsPlayer, serverRequestsTutorial)
Thread.sleep(1000)
// set stats
api.inventories.updateInventories(true)
}
val devices = arrayOf(
Triple("iPad3,1", "iPad", "J1AP"),
Triple("iPad3,2", "iPad", "J2AP"),
Triple("iPad3,3", "iPad", "J2AAP"),
Triple("iPad3,4", "iPad", "P101AP"),
Triple("iPad3,5", "iPad", "P102AP"),
Triple("iPad3,6", "iPad", "P103AP"),
Triple("iPad4,1", "iPad", "J71AP"),
Triple("iPad4,2", "iPad", "J72AP"),
Triple("iPad4,3", "iPad", "J73AP"),
Triple("iPad4,4", "iPad", "J85AP"),
Triple("iPad4,5", "iPad", "J86AP"),
Triple("iPad4,6", "iPad", "J87AP"),
Triple("iPad4,7", "iPad", "J85mAP"),
Triple("iPad4,8", "iPad", "J86mAP"),
Triple("iPad4,9", "iPad", "J87mAP"),
Triple("iPad5,1", "iPad", "J96AP"),
Triple("iPad5,2", "iPad", "J97AP"),
Triple("iPad5,3", "iPad", "J81AP"),
Triple("iPad5,4", "iPad", "J82AP"),
Triple("iPad6,7", "iPad", "J98aAP"),
Triple("iPad6,8", "iPad", "J99aAP"),
Triple("iPhone5,1", "iPhone", "N41AP"),
Triple("iPhone5,2", "iPhone", "N42AP"),
Triple("iPhone5,3", "iPhone", "N48AP"),
Triple("iPhone5,4", "iPhone", "N49AP"),
Triple("iPhone6,1", "iPhone", "N51AP"),
Triple("iPhone6,2", "iPhone", "N53AP"),
Triple("iPhone7,1", "iPhone", "N56AP"),
Triple("iPhone7,2", "iPhone", "N61AP"),
Triple("iPhone8,1", "iPhone", "N71AP")
)
val osVersions = arrayOf("8.1.1", "8.1.2", "8.1.3", "8.2", "8.3", "8.4", "8.4.1",
"9.0", "9.0.1", "9.0.2", "9.1", "9.2", "9.2.1", "9.3", "9.3.1", "9.3.2", "9.3.3", "9.3.4")
// try to create unique identifier
val random = Random("PokemonGoBot-${settings.credentials.hashCode().toLong()}".hashCode().toLong())
val deviceInfo = DeviceInfo()
val deviceId = ByteArray(16)
random.nextBytes(deviceId)
deviceInfo.setDeviceId(deviceId.toHexString())
deviceInfo.setDeviceBrand("Apple")
val device = devices[random.nextInt(devices.size)]
deviceInfo.setDeviceModel(device.second)
deviceInfo.setDeviceModelBoot("${device.first}${0.toChar()}")
deviceInfo.setHardwareManufacturer("Apple")
deviceInfo.setHardwareModel("${device.third}${0.toChar()}")
deviceInfo.setFirmwareBrand("iPhone OS")
deviceInfo.setFirmwareType(osVersions[random.nextInt(osVersions.size)])
api.setDeviceInfo(deviceInfo)
val bot = Bot(api, settings)
bot.start()
return bot
}
|
gpl-3.0
|
3f68e6c3420094daa1c2c12154b46935
| 35.713864 | 131 | 0.635224 | 4.320028 | false | false | false | false |
bhubie/Expander
|
app/src/main/kotlin/com/wanderfar/expander/DynamicValue/DynamicValueTextView.kt
|
1
|
2712
|
/*
* Expander: Text Expansion Application
* Copyright (C) 2016 Brett Huber
*
* 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.wanderfar.expander.DynamicValue
import android.content.Context
import android.support.v7.widget.AppCompatTextView
import android.text.SpannableStringBuilder
import android.text.TextUtils
import android.util.AttributeSet
import com.wanderfar.expander.R
class DynamicValueTextView : AppCompatTextView {
var displayDrawableForDynamicValue : Boolean = true
var mIconSize: Int = 0
var mIconAlignment: Int = 0
var mIconTextSize: Int = 0
constructor(context: Context) : super(context) {
mIconSize = textSize.toInt()
mIconAlignment = textSize.toInt()
mIconTextSize = textSize.toInt()
}
constructor(context: Context, attrs: AttributeSet): super(context, attrs){
init(attrs)
}
constructor(context: Context, attrs: AttributeSet, defStyle: Int): super(context, attrs, defStyle) {
init(attrs)
}
fun init(attrs: AttributeSet) {
val array = context.obtainStyledAttributes(attrs, R.styleable.DynamicValueEditText)
displayDrawableForDynamicValue = array.getBoolean(
R.styleable.DynamicValueEditText_displayDrawableForDynamicValue, true)
mIconSize = textSize.toInt()
mIconAlignment = textSize.toInt()
mIconTextSize = textSize.toInt()
text = text
array.recycle()
}
override fun setText(text: CharSequence, type: BufferType) {
var text = text
if (displayDrawableForDynamicValue){
if (!TextUtils.isEmpty(text)) {
val builder = SpannableStringBuilder(text)
DynamicValueDrawableGenerator.addDynamicDrawables(context, builder,
mIconSize, mIconAlignment, mIconTextSize, 5.0f, 25.0f)
text = builder
}
}
super.setText(text, type)
}
fun setDisplayDynamicDrawable (displayDynamicDrawable : Boolean){
this.displayDrawableForDynamicValue = displayDynamicDrawable
}
}
|
gpl-3.0
|
8644f762e5a8a66259aa7ce943f2e80d
| 30.546512 | 104 | 0.693953 | 4.683938 | false | false | false | false |
sky-map-team/stardroid
|
app/src/main/java/com/google/android/stardroid/math/Geometry.kt
|
1
|
1796
|
// Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.android.stardroid.math
import com.google.android.stardroid.math.MathUtils.cos
import com.google.android.stardroid.math.MathUtils.sin
import java.util.*
/**
* Utilities for working with angles, distances, matrices, and time.
*
* @author Kevin Serafini
* @author Brent Bryan
* @author Dominic Widdows
* @author John Taylor
*/
/**
* Calculates the rotation matrix for a certain number of |degrees| about the
* given |axis|.
* @param degrees
* @param axis - must be a unit vector.
*/
fun calculateRotationMatrix(degrees: Float, axis: Vector3): Matrix3x3 {
// Construct the rotation matrix about this vector
val cosD = cos(degrees * DEGREES_TO_RADIANS)
val sinD = sin(degrees * DEGREES_TO_RADIANS)
val oneMinusCosD = 1f - cosD
val x = axis.x
val y = axis.y
val z = axis.z
val xs = x * sinD
val ys = y * sinD
val zs = z * sinD
val xm = x * oneMinusCosD
val ym = y * oneMinusCosD
val zm = z * oneMinusCosD
val xym = x * ym
val yzm = y * zm
val zxm = z * xm
return Matrix3x3(
x * xm + cosD, xym + zs, zxm - ys,
xym - zs, y * ym + cosD, yzm + xs,
zxm + ys, yzm - xs, z * zm + cosD
)
}
|
apache-2.0
|
aa10d2216223a95327b72b00dc362d17
| 29.440678 | 77 | 0.670379 | 3.40797 | false | false | false | false |
kerubistan/kerub
|
src/test/kotlin/com/github/kerubistan/kerub/model/GvinumStorageCapabilityTest.kt
|
2
|
1014
|
package com.github.kerubistan.kerub.model
import io.github.kerubistan.kroki.size.TB
import org.junit.Test
import org.junit.jupiter.api.assertThrows
import kotlin.test.assertEquals
class GvinumStorageCapabilityTest : AbstractDataRepresentationTest<GvinumStorageCapability>(){
override val testInstances = listOf(
GvinumStorageCapability(devices = listOf(
GvinumStorageCapabilityDrive(
name = "test-disk",
size = 4.TB,
device = "/dev/sda" // whatever
)
)
)
)
override val clazz = GvinumStorageCapability::class.java
@Test
fun validations() {
assertThrows<IllegalStateException>("No disk, no gvinum storage capability") {
GvinumStorageCapability(devices = listOf())
}
}
@Test
fun size() {
assertEquals(
3.TB,
GvinumStorageCapability(
devices = listOf(
GvinumStorageCapabilityDrive(name = "disk-1", device = "sda", size = 1.TB),
GvinumStorageCapabilityDrive(name = "disk-2", device = "sdb", size = 2.TB)
)).size
)
}
}
|
apache-2.0
|
f64ca658067920f2c5ec8bf117db9be4
| 24.375 | 94 | 0.699211 | 3.870229 | false | true | false | false |
square/sqldelight
|
sqldelight-idea-plugin/src/test/kotlin/com/squareup/sqldelight/intellij/intentions/TableAliasIntentionTest.kt
|
1
|
3110
|
package com.squareup.sqldelight.intellij.intentions
import com.google.common.truth.Truth.assertThat
import com.squareup.sqldelight.core.lang.SqlDelightFileType
import com.squareup.sqldelight.intellij.SqlDelightFixtureTestCase
class TableAliasIntentionTest : SqlDelightFixtureTestCase() {
fun testIntentionAvailableOnTableName() {
myFixture.configureByText(
SqlDelightFileType,
CREATE_TABLE + """
|SELECT first_name, last_name, number, team, name
|FROM hockey<caret>Player
|JOIN team ON hockeyPlayer.team = team.id;
""".trimMargin()
)
val intention = IntroduceTableAliasIntention()
assertThat(
intention.isAvailable(
myFixture.project,
myFixture.editor,
myFixture.file.findElementAt(myFixture.editor.caretModel.offset)!!
)
)
.isTrue()
}
fun testIntentionNotAvailableOnTableNameWithAlias() {
myFixture.configureByText(
SqlDelightFileType,
CREATE_TABLE + """
|SELECT first_name, last_name, number, team, name
|FROM hockey<caret>Player hp
|JOIN team ON hp.team = team.id;
""".trimMargin()
)
val intention = IntroduceTableAliasIntention()
assertThat(
intention.isAvailable(
myFixture.project,
myFixture.editor,
myFixture.file.findElementAt(myFixture.editor.caretModel.offset)!!
)
)
.isFalse()
}
fun testIntentionNotAvailableOnColumnQualifier() {
myFixture.configureByText(
SqlDelightFileType,
CREATE_TABLE + """
|SELECT id, tea<caret>m.name
|FROM team;
""".trimMargin()
)
val intention = IntroduceTableAliasIntention()
assertThat(
intention.isAvailable(
myFixture.project,
myFixture.editor,
myFixture.file.findElementAt(myFixture.editor.caretModel.offset)!!
)
)
.isFalse()
}
fun testIntentionExecution() {
myFixture.configureByText(
SqlDelightFileType,
CREATE_TABLE + """
|SELECT first_name, last_name, number, team, name
|FROM hockeyPlayer
|JOIN tea<caret>m ON hockeyPlayer.team = team.id;
""".trimMargin()
)
val intention = IntroduceTableAliasIntention()
intention.invoke(
myFixture.project,
myFixture.editor,
myFixture.file.findElementAt(myFixture.editor.caretModel.offset)!!
)
myFixture.checkResult(
CREATE_TABLE + """
|SELECT first_name, last_name, number, team, name
|FROM hockeyPlayer
|JOIN team t ON hockeyPlayer.team = t.id;
""".trimMargin()
)
}
companion object {
private val CREATE_TABLE = """
|CREATE TABLE hockeyPlayer(
| id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
| first_name TEXT NOT NULL,
| last_name TEXT NOT NULL,
| number INTEGER NOT NULL,
| team INTEGER NOT NULL,
| FOREIGN KEY (team) REFERENCES team(id)
|);
|
|CREATE TABLE team(
| id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
| name TEXT NOT NULL UNIQUE
|);
|""".trimMargin()
}
}
|
apache-2.0
|
e610481494bef24d5e3dc7ae334afe5b
| 26.280702 | 74 | 0.643408 | 4.712121 | false | true | false | false |
EMResearch/EvoMaster
|
core/src/main/kotlin/org/evomaster/core/search/service/monitor/SearchProcessMonitor.kt
|
1
|
10360
|
package org.evomaster.core.search.service.monitor
import com.google.gson.ExclusionStrategy
import com.google.gson.FieldAttributes
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.inject.Inject
import org.evomaster.core.EMConfig
import org.evomaster.core.output.TestSuiteFileName
import org.evomaster.core.output.service.TestSuiteWriter
import org.evomaster.core.problem.api.service.param.Param
import org.evomaster.core.problem.rest.RestCallAction
import org.evomaster.core.remote.service.RemoteController
import org.evomaster.core.search.*
import org.evomaster.core.search.gene.Gene
import org.evomaster.core.search.service.*
import org.evomaster.core.utils.ReportWriter.writeByChannel
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.io.File
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import javax.annotation.PostConstruct
/**
* monitor 1) how are rest actions or rest individual selected regarding how to sampleAll
* 2) how does targets update
*/
class SearchProcessMonitor: SearchListener {
@Inject
private lateinit var time: SearchTimeController
@Inject
private lateinit var config: EMConfig
@Inject
private lateinit var archive: Archive<*>
@Inject
private lateinit var idMapper: IdMapper
@Inject(optional = true)
private lateinit var writer: TestSuiteWriter
@Inject(optional = true)
private var controller: RemoteController? = null
private lateinit var overall : SearchOverall<*>
private var controllerName : String? = null
var eval: EvaluatedIndividual<*>? = null
var step : StepOfSearchProcess<*>? = null
var isMutated : Boolean = false
/**
* record the progress of saved steps
* */
private var tb = 1
companion object {
private val log: Logger = LoggerFactory.getLogger(SearchProcessMonitor::class.java)
/**
* all steps of search are archived under the DATA_FOLDER, e.g., @see org.evomaster.core.EMConfig.processFiles/data
* */
private const val DATA_FOLDER = "data"
/**
* a name of a file to save final Archive, and it can be found in @see org.evomaster.core.EMConfig.processFiles/overall.json
* */
private const val NAME = "overall"
/**
* all steps and overall produced by a search monitor are saved as json files.
* */
private const val FILE_TYPE = ".json"
private var gson : Gson? = null
private val skippedClasses = listOf(
StructuralElement::class.java.name,
/*
https://github.com/JetBrains/kotlin/blob/master/spec-docs/function-types.md
*/
"kotlin.jvm.functions.Function1"
)
private val strategy: ExclusionStrategy = object : ExclusionStrategy {
//TODO systematic way to configure the skipped field
override fun shouldSkipField(field: FieldAttributes): Boolean {
return field.name == "parent" || field.name == "bindingGenes"
}
//skip abstract StructuralElement element
override fun shouldSkipClass(clazz: Class<*>?): Boolean {
return clazz!= null && skippedClasses.contains(clazz.name)
}
}
}
@PostConstruct
fun postConstruct(){
initMonitorProcessOutputs()
if(config.enableProcessMonitor){
time.addListener(this)
if (config.processFormat == EMConfig.ProcessDataFormat.TEST_IND || config.processFormat == EMConfig.ProcessDataFormat.TARGET_TEST_IND){
val dto = try {
controller?.getControllerInfo()
}catch (e: Exception){
log.warn("Remote driver does not response with the exception message: ${e.cause!!.message}")
null
}
controllerName = dto?.fullName
}
}
}
override fun newActionEvaluated() {
if(config.enableProcessMonitor && config.processFormat == EMConfig.ProcessDataFormat.JSON_ALL){
step = StepOfSearchProcess(archive, time.evaluatedIndividuals, eval!!.individual, eval!!, System.currentTimeMillis(),isMutated)
}
}
fun <T: Individual> record(added: Boolean, improveArchive : Boolean, evalInd : EvaluatedIndividual<T>){
if(config.enableProcessMonitor){
if(config.processInterval == 0.0 || time.percentageUsedBudget() >= tb * config.processInterval/100.0){
when(config.processFormat){
EMConfig.ProcessDataFormat.JSON_ALL->{
if(evalInd != eval) throw IllegalStateException("Mismatched evaluated individual under monitor")
/*
step is assigned when an individual is evaluated (part of calculateCoverage of FitnessFunction),
but in order to record if the evaluated individual added into Archive, we need to save it after executing addIfNeeded in Archive
Since calculateCoverage is always followed by addIfNeed, the step should be not null.
*/
step!!.added = added
step!!.improvedArchive = improveArchive
saveStep(step!!.indexOfEvaluation, step!!)
if(config.showProgress) log.info("number of targets: ${step!!.populations.size}")
}
EMConfig.ProcessDataFormat.TEST_IND , EMConfig.ProcessDataFormat.TARGET_TEST_IND->{
saveStepAsTest(index = time.evaluatedIndividuals,evalInd = evalInd, doesIncludeTarget = config.processFormat == EMConfig.ProcessDataFormat.TARGET_TEST_IND)
}
}
if(config.processInterval > 0.0) tb++
}
}
}
private fun setOverall(){
val stp = config.stoppingCriterion.toString()+"_"+
(if(config.stoppingCriterion.toString().toLowerCase().contains("time")) config.timeLimitInSeconds().toString() else config.maxActionEvaluations)
this.overall = SearchOverall(stp, time.evaluatedIndividuals, eval!!.individual, eval!!, archive, idMapper, time.getStartTime())
}
private fun initMonitorProcessOutputs(){
val path = Paths.get(config.processFiles)
if(config.showProgress) log.info("Deleting all files in ${path.toUri()}")
if(Files.exists(path)){
Files.walk(path)
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach{
if(!it.delete())
log.warn("Fail to delete ${it.path}")
}
}
}
fun saveOverall(){
when(config.processFormat){
EMConfig.ProcessDataFormat.JSON_ALL-> {
setOverall()
writeByChannel(
Paths.get(getOverallProcessAsPath()),
getGsonBuilder()?.toJson(this.overall)?:throw IllegalStateException("gson builder is null"))
}
}
}
fun getOverallProcessAsPath() = "${config.processFiles}${File.separator}${getOverallFileName()}"
fun getStepAsPath(index: Int, isTargetFile: Boolean=false) = "${getStepDirAsPath()}${File.separator}${getProcessFileName(getStepName(index, isTargetFile), isTargetFile)}"
fun getStepDirAsPath() = "${config.processFiles}${File.separator}$DATA_FOLDER"
private fun saveStep(index:Int, v : StepOfSearchProcess<*>){
writeByChannel(
Paths.get(getStepAsPath(index)),
getGsonBuilder()?.toJson(v)?:throw java.lang.IllegalStateException("gson builder is null"))
}
private fun <T:Individual> saveStepAsTest(index: Int, evalInd: EvaluatedIndividual<T>, doesIncludeTarget : Boolean){
val name = getStepName(index, false)
val testFile = TestSuiteFileName(name)
val solution = Solution(individuals = mutableListOf(evalInd), testSuiteNamePrefix = name, testSuiteNameSuffix = "")
val content = writer.convertToCompilableTestCode(
solution = solution,
testSuiteFileName = testFile, controllerName = controllerName, controllerInput = null)
writeByChannel(
Paths.get(getStepAsPath(index)),
content)
if (doesIncludeTarget){
val info = archive.exportCoveredTargetsAsPair(solution)
writeByChannel(
Paths.get(getStepAsPath(index, true)),
info.map { it.first }.sorted().joinToString(System.lineSeparator()))
}
}
private fun getStepName(value: Int, isTargetFile: Boolean): String {
val num = String.format("%0${config.maxActionEvaluations.toString().length}d", value)
return when(config.processFormat){
EMConfig.ProcessDataFormat.JSON_ALL -> "EM_${num}Json"
EMConfig.ProcessDataFormat.TEST_IND-> "EM_${num}Test"
EMConfig.ProcessDataFormat.TARGET_TEST_IND-> "EM_${num}${if (isTargetFile) "Target" else "Test"}"
}
}
fun getOverallFileName() : String{
return NAME + FILE_TYPE
}
private fun getProcessFileName(name : String, isTargetFile : Boolean = false) = when(config.processFormat){
EMConfig.ProcessDataFormat.JSON_ALL-> "${name}.json"
EMConfig.ProcessDataFormat.TEST_IND -> TestSuiteFileName(name).getAsPath(config.outputFormat)
EMConfig.ProcessDataFormat.TARGET_TEST_IND -> {
if (isTargetFile) "${name}.txt"
else TestSuiteFileName(name).getAsPath(config.outputFormat)
}
}
private fun getGsonBuilder() : Gson? {
if (config.enableProcessMonitor && config.processFormat == EMConfig.ProcessDataFormat.JSON_ALL)
if (gson == null) gson = GsonBuilder().registerTypeAdapter(RestCallAction::class.java, InterfaceAdapter<RestCallAction>())
.registerTypeAdapter(Param::class.java, InterfaceAdapter<Param>())
.registerTypeAdapter(Gene::class.java, InterfaceAdapter<Gene>())
.setExclusionStrategies(strategy)
.create()
return gson
}
}
|
lgpl-3.0
|
11c311807f642d183ee23a741d268cef
| 39.627451 | 179 | 0.632625 | 4.945107 | false | true | false | false |
outware/neanderthal
|
neanderthal/src/main/kotlin/au/com/outware/neanderthal/presentation/adapter/PropertyAdapter.kt
|
1
|
3645
|
package au.com.outware.neanderthal.presentation.adapter
import androidx.recyclerview.widget.RecyclerView
import android.view.ViewGroup
import au.com.outware.neanderthal.data.model.Variant
import au.com.outware.neanderthal.presentation.adapter.delegate.*
import au.com.outware.neanderthal.presentation.presenter.EditVariantPresenter
import au.com.outware.neanderthal.util.extensions.serializableFields
import com.google.gson.annotations.SerializedName
import java.lang.reflect.Field
import java.util.*
/**
* @author Tim Mutton
*/
class PropertyAdapter : androidx.recyclerview.widget.RecyclerView.Adapter<androidx.recyclerview.widget.RecyclerView.ViewHolder>(),
EditVariantPresenter.AdapterSurface {
companion object {
private val VIEW_TYPE_VARIANT_NAME = 0
private val VIEW_TYPE_CHARACTER_SEQUENCE = 1
private val VIEW_TYPE_BOOLEAN = 2
private val VIEW_TYPE_NUMBER = 3
fun getPropertyName(configurationProperty: Field): String {
val name: String
if (configurationProperty.isAnnotationPresent(SerializedName::class.java)) {
name = configurationProperty.getAnnotation(SerializedName::class.java).value
} else {
name = configurationProperty.name
}
return name
}
}
private var variant: Variant? = null
private val properties: ArrayList<Field> = ArrayList()
private val delegates = HashSet<AdapterDelegate<Field>>()
private var setVariantName:Boolean = false
override fun setItem(variant: Variant) {
this.variant = variant
properties.addAll(variant.configuration!!.javaClass.serializableFields.sortedBy { selector -> selector.name })
setVariantName = (variant.name == null)
delegates.add(NamePropertyAdapterDelegate(variant, setVariantName, VIEW_TYPE_VARIANT_NAME))
delegates.add(CharacterSequencePropertyAdapterDelegate(variant, setVariantName, VIEW_TYPE_CHARACTER_SEQUENCE))
delegates.add(BooleanPropertyAdapterDelegate(variant, setVariantName, VIEW_TYPE_BOOLEAN))
delegates.add(NumericPropertyAdapterDelegate(variant, setVariantName, VIEW_TYPE_NUMBER))
}
override fun getItemViewType(position: Int): Int {
var viewType = -1
for(delegate in delegates) {
if(delegate.isForViewType(properties, position)) {
viewType = delegate.viewType
break
}
}
if(viewType == -1) {
throw IllegalArgumentException("Unsupported property type")
}
return viewType
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): androidx.recyclerview.widget.RecyclerView.ViewHolder {
var viewHolder: androidx.recyclerview.widget.RecyclerView.ViewHolder? = null
for(delegate in delegates) {
if(viewType == delegate.viewType) {
viewHolder = delegate.createViewHolder(parent)
break
}
}
if(viewHolder == null) {
throw IllegalArgumentException("Unsupported property type")
}
return viewHolder
}
override fun onBindViewHolder(holder: androidx.recyclerview.widget.RecyclerView.ViewHolder, position: Int) {
val viewType = holder.itemViewType
for(delegate in delegates) {
if(delegate.viewType == viewType) {
delegate.bindViewHolder(properties, position, holder)
break
}
}
}
override fun getItemCount(): Int {
return properties.size + if (setVariantName) 1 else 0
}
}
|
mit
|
052fc8c7c771d2e509502cb3803840db
| 35.45 | 130 | 0.679012 | 5.126582 | false | false | false | false |
oversecio/oversec_crypto
|
crypto/src/main/java/io/oversec/one/crypto/sym/ui/SymmetricTextEncryptionInfoFragment.kt
|
1
|
5041
|
package io.oversec.one.crypto.sym.ui
import android.app.Activity
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.text.format.DateUtils
import android.view.*
import android.widget.Button
import android.widget.TextView
import io.oversec.one.crypto.*
import io.oversec.one.crypto.sym.OversecKeystore2
import io.oversec.one.crypto.sym.SymUtil
import io.oversec.one.crypto.symbase.BaseSymmetricCryptoHandler
import io.oversec.one.crypto.symbase.SymmetricDecryptResult
import io.oversec.one.crypto.ui.AbstractTextEncryptionInfoFragment
import io.oversec.one.crypto.ui.EncryptionInfoActivity
class SymmetricTextEncryptionInfoFragment : AbstractTextEncryptionInfoFragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
mView = inflater.inflate(R.layout.encryption_info_text_sym, container, false)
super.onCreateView(inflater, container, savedInstanceState)
return mView
}
override fun setData(
activity: EncryptionInfoActivity,
encodedText: String,
tdr: BaseDecryptResult?,
uix: UserInteractionRequiredException?,
encryptionHandler: AbstractCryptoHandler
) {
super.setData(activity, encodedText, tdr, uix, encryptionHandler)
val lblSymKeyAlias = mView.findViewById<View>(R.id.lbl_sym_key_name) as TextView
val tvAvatar = mView.findViewById<View>(R.id.tvAvatar) as TextView
val tvSym = mView.findViewById<View>(R.id.tv_sym_key_name) as TextView
val lblConfirm = mView.findViewById<View>(R.id.lbl_key_confirm) as TextView
val tvConfirm = mView.findViewById<View>(R.id.tv_key_confirm) as TextView
val btKeyDetails = mView.findViewById<View>(R.id.btnKeyDetailsSym) as Button
if (tdr == null) {
lblSymKeyAlias.visibility = View.GONE
tvSym.visibility = View.GONE
tvAvatar.visibility = View.GONE
} else {
val r = tdr as SymmetricDecryptResult
val keyId = r.symmetricKeyId
if (keyId == null) {
btKeyDetails.visibility = View.GONE
} else {
btKeyDetails.setOnClickListener { KeyDetailsActivity.show(getActivity(), keyId) }
}
if (keyId == null) {
lblSymKeyAlias.visibility = View.GONE
tvSym.visibility = View.GONE
tvAvatar.visibility = View.GONE
lblConfirm.visibility = View.GONE
tvConfirm.visibility = View.GONE
} else {
val keystore = OversecKeystore2.getInstance(getActivity())
val name = keystore.getSymmetricKeyEncrypted(keyId)?.name
tvSym.text = name
SymUtil.applyAvatar(tvAvatar, name!!)
val confirmedDate = keystore.getConfirmDate(keyId)
tvConfirm.text =
if (confirmedDate == null) getActivity().getString(R.string.label_key_unconfirmed) else DateUtils.formatDateTime(
getActivity(),
confirmedDate.time,
0
)
tvConfirm.setCompoundDrawablesWithIntrinsicBounds(
0,
0,
if (confirmedDate == null) R.drawable.ic_warning_black_24dp else R.drawable.ic_done_black_24dp,
0
)
if (confirmedDate == null) {
tvConfirm.setTextColor(
ContextCompat.getColor(
getActivity(),
R.color.colorWarning
)
)
}
}
}
}
override fun onCreateOptionsMenu(activity: Activity, menu: Menu): Boolean {
activity.menuInflater.inflate(R.menu.sym_menu_encryption_info, menu)
return true
}
override fun onPrepareOptionsMenu(menu: Menu) {
menu.findItem(R.id.action_share_sym_base64).isVisible = mTdr != null
}
override fun onOptionsItemSelected(activity: Activity, item: MenuItem) {
val id = item.itemId
if (id == R.id.action_share_sym_base64) {
share(
activity,
BaseSymmetricCryptoHandler.getRawMessageJson(
CryptoHandlerFacade.getEncodedData(
activity,
mOrigText
)!!
)!!,
activity.getString(R.string.action_share_sym_base64)
)
} else {
super.onOptionsItemSelected(activity, item)
}
}
companion object {
fun newInstance(packagename: String?): SymmetricTextEncryptionInfoFragment {
val fragment = SymmetricTextEncryptionInfoFragment()
fragment.setArgs(packagename)
return fragment
}
}
}
|
gpl-3.0
|
304251ed2f89e6de94496892149d41d4
| 35.007143 | 137 | 0.598096 | 4.894175 | false | false | false | false |
square/sqldelight
|
sqldelight-gradle-plugin/src/test/integration-postgresql/src/test/kotlin/com/squareup/sqldelight/postgresql/integration/PostgreSqlTest.kt
|
1
|
978
|
package com.squareup.sqldelight.postgresql.integration
import com.google.common.truth.Truth.assertThat
import com.squareup.sqldelight.sqlite.driver.JdbcDriver
import org.junit.After
import org.junit.Before
import org.junit.Test
import java.sql.Connection
import java.sql.DriverManager
class PostgreSqlTest {
val conn = DriverManager.getConnection("jdbc:tc:postgresql:9.6.8:///my_db")
val driver = object : JdbcDriver() {
override fun getConnection() = conn
override fun closeConnection(connection: Connection) = Unit
}
val database = MyDatabase(driver)
@Before fun before() {
MyDatabase.Schema.create(driver)
}
@After fun after() {
conn.close()
}
@Test fun simpleSelect() {
database.dogQueries.insertDog("Tilda", "Pomeranian", true)
assertThat(database.dogQueries.selectDogs().executeAsOne())
.isEqualTo(
Dog(
name = "Tilda",
breed = "Pomeranian",
is_good = true
)
)
}
}
|
apache-2.0
|
2ce17e3ac6ea8f0c292e530d30238fa6
| 24.736842 | 77 | 0.691207 | 3.835294 | false | true | false | false |
EMResearch/EvoMaster
|
core/src/main/kotlin/org/evomaster/core/problem/graphql/service/GraphQLFitness.kt
|
1
|
15487
|
package org.evomaster.core.problem.graphql.service
import com.fasterxml.jackson.core.JsonProcessingException
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import org.evomaster.client.java.controller.api.dto.AdditionalInfoDto
import org.evomaster.core.Lazy
import org.evomaster.core.database.DbAction
import org.evomaster.core.logging.LoggingUtil
import org.evomaster.core.problem.graphql.*
import org.evomaster.core.problem.httpws.service.HttpWsFitness
import org.evomaster.core.problem.httpws.service.auth.NoAuth
import org.evomaster.core.remote.TcpUtils
import org.evomaster.core.search.ActionResult
import org.evomaster.core.search.EvaluatedIndividual
import org.evomaster.core.search.FitnessValue
import org.evomaster.core.search.gene.utils.GeneUtils
import org.evomaster.core.taint.TaintAnalysis
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import javax.ws.rs.ProcessingException
import javax.ws.rs.client.ClientBuilder
import javax.ws.rs.client.Entity
import javax.ws.rs.client.Invocation
import javax.ws.rs.core.NewCookie
open class GraphQLFitness : HttpWsFitness<GraphQLIndividual>() {
companion object {
private val log: Logger = LoggerFactory.getLogger(GraphQLFitness::class.java)
private val mapper: ObjectMapper = ObjectMapper()
}
override fun doCalculateCoverage(
individual: GraphQLIndividual,
targets: Set<Int>
): EvaluatedIndividual<GraphQLIndividual>? {
rc.resetSUT()
val cookies = getCookies(individual)
val tokens = getTokens(individual)
val actionResults: MutableList<ActionResult> = mutableListOf()
doDbCalls(individual.seeInitializingActions().filterIsInstance<DbAction>(), actionResults = actionResults)
val fv = FitnessValue(individual.size().toDouble())
val actions = individual.seeMainExecutableActions()
//run the test, one action at a time
for (i in actions.indices) {
val a = actions[i]
registerNewAction(a, i)
val ok = handleGraphQLCall(a, actionResults, cookies, tokens)
actionResults.filterIsInstance<GraphQlCallResult>()[i].stopping = !ok
if (!ok) {
break
}
}
//TODO
// if(actionResults.any { it is RestCallResult && it.getTcpProblem() }){
// /*
// If there are socket issues, we avoid trying to compute any coverage.
// The caller might restart the SUT and try again.
// Hopefully, this should be just a glitch...
// TODO if we see this happening often, we need to find a proper solution.
// For example, we could re-run the test, and see if this one always fails,
// while others in the archive do pass.
// It could be handled specially in the archive.
// */
// return null
// }
val dto = updateFitnessAfterEvaluation(targets, individual, fv)
?: return null
handleExtra(dto, fv)
val graphQLActionResults = actionResults.filterIsInstance<GraphQlCallResult>()
handleResponseTargets(fv, actions, graphQLActionResults, dto.additionalInfoList)
if (config.baseTaintAnalysisProbability > 0) {
Lazy.assert { graphQLActionResults.size == dto.additionalInfoList.size }
TaintAnalysis.doTaintAnalysis(individual, dto.additionalInfoList, randomness)
}
return EvaluatedIndividual(
fv,
individual.copy() as GraphQLIndividual,
actionResults,
trackOperator = individual.trackOperator,
index = time.evaluatedIndividuals,
config = config
)
}
protected fun handleResponseTargets(
fv: FitnessValue,
actions: List<GraphQLAction>,
actionResults: List<ActionResult>,
additionalInfoList: List<AdditionalInfoDto>
) {
(actionResults.indices)
.filter { actions[it] is GraphQLAction }
.filter { actionResults[it] is GraphQlCallResult }
.forEach {
val result = actionResults[it] as GraphQlCallResult
val status = result.getStatusCode() ?: -1
val name = actions[it].getName()
//objective for HTTP specific status code
val statusId = idMapper.handleLocalTarget("$status:$name")
fv.updateTarget(statusId, 1.0, it)
val location5xx: String? = getlocation5xx(status, additionalInfoList, it, result, name)
handleAdditionalStatusTargetDescription(fv, status, name, it, location5xx)
/*
we also have to check the actual response body...
but, unfortunately, currently there is no way to distinguish between user and server errors
https://github.com/graphql/graphql-spec/issues/698
*/
handleGraphQLErrors(fv, name, it, result, additionalInfoList)
}
}
/**
* handle targets with whether there exist errors in a gql action
*/
private fun handleGraphQLErrors(
fv: FitnessValue,
name: String,
actionIndex: Int,
result: GraphQlCallResult,
additionalInfoList: List<AdditionalInfoDto>
) {
val errorId = idMapper.handleLocalTarget(idMapper.getGQLErrorsDescriptiveWithMethodName(name))
val okId = idMapper.handleLocalTarget(idMapper.getGQLNoErrors(name))
val anyError = hasErrors(result)
if (anyError) {
fv.updateTarget(errorId, 1.0, actionIndex)
fv.updateTarget(okId, 0.5, actionIndex)
val graphQlError = getGraphQLErrorWithLineInfo(additionalInfoList, actionIndex, result, name)
if (graphQlError != null) {
val errorlineId = idMapper.handleLocalTarget(graphQlError)
fv.updateTarget(errorlineId, 1.0, actionIndex)
}
} else {
fv.updateTarget(okId, 1.0, actionIndex)
fv.updateTarget(errorId, 0.5, actionIndex)
}
}
/**
* @return description for graphql error with lastExecutedStatement
*/
open fun getGraphQLErrorWithLineInfo(
additionalInfoList: List<AdditionalInfoDto>,
indexOfAction: Int,
result: GraphQlCallResult,
name: String
): String? {
// handle with last statement
val last = additionalInfoList[indexOfAction].lastExecutedStatement ?: DEFAULT_FAULT_CODE
result.setLastStatementWhenGQLErrors(last)
// shall we add additional target with last?
return idMapper.getGQLErrorsDescriptiveWithMethodNameAndLine(
line = last,
method = name
)
}
private fun hasErrors(result: GraphQlCallResult): Boolean {
val errors = extractBodyInGraphQlResponse(result)?.findPath("errors") ?: return false
return !errors.isEmpty || !errors.isMissingNode
}
private fun extractBodyInGraphQlResponse(result: GraphQlCallResult): JsonNode? {
return try {
result.getBody()?.run { mapper.readTree(result.getBody()) }
} catch (e: JsonProcessingException) {
null
}
}
private fun handleAdditionalStatusTargetDescription(
fv: FitnessValue,
status: Int,
name: String,
indexOfAction: Int,
location5xx: String?
) {
val okId = idMapper.handleLocalTarget("HTTP_SUCCESS:$name")
val faultId = idMapper.handleLocalTarget("HTTP_FAULT:$name")
/*
GraphQL is not linked to HTTP.
So, no point to create specific testing targets for all HTTP status codes.
Most GraphQL implementations will actually return 200 even in the case of errors, including
crashed from thrown exceptions...
However, if in case there is a 500, we still to report it.
Still, the server could return other codes like 503 when out of resources...
or 401/403 when wrong auth...
*/
//OK -> 5xx being better than 4xx, as code executed
//FAULT -> 4xx worse than 2xx (can't find bugs if input is invalid)
if (status in 200..299) {
fv.updateTarget(okId, 1.0, indexOfAction)
fv.updateTarget(faultId, 0.5, indexOfAction)
} else {
fv.updateTarget(okId, 0.5, indexOfAction)
fv.updateTarget(faultId, 1.0, indexOfAction)
}
if (status == 500) {
Lazy.assert {
location5xx != null || config.blackBox
}
/*
500 codes "might" be bugs. To distinguish between different bugs
that crash the same endpoint, we need to know what was the last
executed statement in the SUT.
So, we create new targets for it.
*/
val postfix = if(location5xx==null) name else "${location5xx!!} $name"
val descriptiveId = idMapper.getFaultDescriptiveIdFor500(postfix)
val bugId = idMapper.handleLocalTarget(descriptiveId)
fv.updateTarget(bugId, 1.0, indexOfAction)
}
}
protected fun handleGraphQLCall(
action: GraphQLAction,
actionResults: MutableList<ActionResult>,
cookies: Map<String, List<NewCookie>>,
tokens: Map<String, String>
): Boolean {
/*
In GraphQL, there are 2 types of methods: Query and Mutation
- Query can be on either a GET or POST HTTP call
- Mutation must be on a POST (as changes are not idempotent)
For simplicity, for now we just do POST for Query as well, as anyway URL have limitations
on their length
*/
searchTimeController.waitForRateLimiter()
val gqlcr = GraphQlCallResult()
actionResults.add(gqlcr)
/*
TODO quite a lot of code here is the same as in Rest... need to refactor out into WsHttp
*/
val response = try {
createInvocation(action, cookies, tokens).invoke()
} catch (e: ProcessingException) {
/*
this could have happened for example if call ends up in an infinite redirection loop.
However, as we no longer follow 3xx automatically, it should not happen anymore
*/
when {
TcpUtils.isTooManyRedirections(e) -> {
gqlcr.setInfiniteLoop(true)
gqlcr.setErrorMessage(e.cause!!.message!!)
return false
}
TcpUtils.isTimeout(e) -> {
/*
This is very tricky. In theory it shouldn't happen that a REST call
does timeout (eg 10 seconds). But it might happen due to glitch,
or if very slow hardware. If it is a glitch, we do not want to
kill whole EM process, as might not happen again. If it is a
constant, we want to avoid using such test if possible, as it
would kill performance.
In any case, a generated test should never check assertions on time,
eg expect that a is SocketTimeoutException thrown. Not only because
maybe it was just a glitch, but also because the test might be run
on different machines (remote CI vs local development PC) with
different performance (and so the test would become flaky)
*/
gqlcr.setTimedout(true)
statistics.reportTimeout()
return false
}
TcpUtils.isOutOfEphemeralPorts(e) -> {
/*
This could happen if for any reason we run out of ephemeral ports.
In such a case, we wait X seconds, and try again, as OS might have released ports
meanwhile.
And while we are at it, let's release any hanging network resource
*/
client.close() //make sure to release any resource
client = ClientBuilder.newClient()
TcpUtils.handleEphemeralPortIssue()
createInvocation(action, cookies, tokens).invoke()
}
TcpUtils.isStreamClosed(e) || TcpUtils.isEndOfFile(e) -> {
/*
This should not really happen... but it does :( at least on Windows...
*/
log.warn("TCP connection to SUT problem: ${e.cause!!.message}")
gqlcr.setTcpProblem(true)
return false
}
else -> throw e
}
}
gqlcr.setStatusCode(response.status)
handlePossibleConnectionClose(response)
try {
if (response.hasEntity()) {
if (response.mediaType != null) {
gqlcr.setBodyType(response.mediaType)
}
/*
Note: here we are always assuming a JSON, so reading as string should be fine
*/
val body = response.readEntity(String::class.java)
if (body.length < configuration.maxResponseByteSize) {
gqlcr.setBody(body)
} else {
LoggingUtil.uniqueWarn(
log,
"A very large response body was retrieved from the action '${action.methodName}'." +
" If that was expected, increase the 'maxResponseByteSize' threshold" +
" in the configurations."
)
gqlcr.setTooLargeBody(true)
}
}
} catch (e: Exception) {
if (e is ProcessingException && TcpUtils.isTimeout(e)) {
gqlcr.setTimedout(true)
statistics.reportTimeout()
return false
} else {
log.warn("Failed to parse HTTP response: ${e.message}")
}
}
if (response.status == 401 && action.auth !is NoAuth) {
//this would likely be a misconfiguration in the SUT controller
log.warn("Got 401 although having auth for '${action.auth.name}'")
}
return true
}
fun createInvocation(
a: GraphQLAction,
cookies: Map<String, List<NewCookie>>,
tokens: Map<String, String>
): Invocation {
val uri = if (config.blackBox) {
config.bbTargetUrl
} else {
infoDto.baseUrlOfSUT.plus(infoDto.graphQLProblem.endpoint)
}
val fullUri = GeneUtils.applyEscapes(uri, GeneUtils.EscapeMode.URI, configuration.outputFormat)
val builder = client.target(fullUri).request("application/json")
handleHeaders(a, builder, cookies, tokens)
val bodyEntity = GraphQLUtils.generateGQLBodyEntity(a, config.outputFormat) ?: Entity.json(" ")
val invocation = builder.buildPost(bodyEntity)
return invocation
}
}
|
lgpl-3.0
|
616a05c5e409e3ded0fe3da02922c77a
| 37.051597 | 114 | 0.593465 | 5.128146 | false | false | false | false |
yuttadhammo/BodhiTimer
|
app/src/main/java/org/yuttadhammo/BodhiTimer/Util/Time.kt
|
1
|
5062
|
/*
* Time.kt
* Copyright (C) 2014-2022 BodhiTimer developers
*
* Distributed under terms of the GNU GPLv3 license.
*/
package org.yuttadhammo.BodhiTimer.Util
import android.content.Context
import android.text.TextUtils
import androidx.appcompat.app.AppCompatActivity
import org.yuttadhammo.BodhiTimer.R
import timber.log.Timber
import java.util.regex.Pattern
object Time {
const val TIME_SEPARATOR = " again "
private fun msFromNumbers(hour: Int, minutes: Int, seconds: Int): Int {
return hour * 60 * 60 * 1000 + minutes * 60 * 1000 + seconds * 1000
}
@JvmStatic
fun msFromArray(numbers: IntArray): Int {
return msFromNumbers(numbers[0], numbers[1], numbers[2])
}
private fun padWithZeroes(number: Int): String {
return if (number > 9) {
number.toString()
} else {
"0$number"
}
}
/**
* Converts a millisecond time to a string time
* Not meant to be pretty, but fast..
*
* @param ms the time in milliseconds
* @return the formatted string
*/
private fun ms2Str(ms: Int): String {
val time = time2Array(ms)
return if (time[0] == 0 && time[1] == 0) {
time[2].toString()
} else if (time[0] == 0) {
time[1].toString() + ":" + padWithZeroes(
time[2]
)
} else {
time[0].toString() + ":" + padWithZeroes(
time[1]
) + ":" + padWithZeroes(time[2])
}
}
/**
* Creates a time vector
*
* @param time the time in milliseconds
* @return [hour, minutes, seconds, ms]
*/
@JvmStatic
fun time2Array(time: Int): IntArray {
val ms = time % 1000
var seconds = time / 1000 // 3550000 / 1000 = 3550
var minutes = seconds / 60 // 59.16666
var hours = minutes / 60 // 0.9
if (hours > 60) hours = 60
minutes %= 60
seconds %= 60
val timeVec = IntArray(4)
timeVec[0] = hours
timeVec[1] = minutes
timeVec[2] = seconds
timeVec[3] = ms
return timeVec
}
@JvmStatic
fun time2humanStr(context: Context, time: Int): String {
val timeVec = time2Array(time)
val hour = timeVec[0]
val minutes = timeVec[1]
val seconds = timeVec[2]
val strList = ArrayList<String?>()
val res = context.resources
// string formatting
if (hour != 0) {
strList.add(res.getQuantityString(R.plurals.x_hours, hour, hour))
}
if (minutes != 0) {
strList.add(res.getQuantityString(R.plurals.x_mins, minutes, minutes))
}
if (seconds != 0 || seconds >= 0 && minutes == 0 && hour == 0) {
strList.add(res.getQuantityString(R.plurals.x_secs, seconds, seconds))
}
return TextUtils.join(", ", strList)
}
fun time2hms(time: Int): String {
return ms2Str(time)
}
@JvmStatic
fun str2complexTimeString(activity: AppCompatActivity, numberString: String): String {
val out: String
val stringArray = ArrayList<String?>()
val strings = numberString.split(TIME_SEPARATOR).toTypedArray()
for (string in strings) {
val atime = str2timeString(activity, string)
if (atime > 0) stringArray.add(atime.toString() + "#sys_def#" + activity.getString(R.string.sys_def))
}
out = TextUtils.join("^", stringArray)
return out
}
@JvmStatic
fun str2timeString(activity: AppCompatActivity, numberString: String): Int {
val res = activity.resources
val numbers = res.getStringArray(R.array.numbers)
var newString = numberString
for ((position, number) in numbers.withIndex()) {
val num = 60 - position
newString = newString.replace(number.toRegex(), num.toString())
}
val HOUR = Pattern.compile("([0-9]+) " + activity.getString(R.string.hour))
val MINUTE = Pattern.compile("([0-9]+) " + activity.getString(R.string.minute))
val SECOND = Pattern.compile("([0-9]+) " + activity.getString(R.string.second))
var hours = 0
var minutes = 0
var seconds = 0
var m = HOUR.matcher(newString)
while (m.find()) {
val match = m.group(1)
hours += match?.toInt() ?: 0
}
m = MINUTE.matcher(newString)
while (m.find()) {
val match = m.group(1)
minutes += match?.toInt() ?: 0
}
m = SECOND.matcher(newString)
while (m.find()) {
val match = m.group(1)
seconds += match?.toInt() ?: 0
}
Timber.d("Got numbers: $hours hours, $minutes minutes, $seconds seconds")
var total = hours * 60 * 60 * 1000 + minutes * 60 * 1000 + seconds * 1000
if (total > 60 * 60 * 60 * 1000 + 59 * 60 * 1000 + 59 * 1000) total =
60 * 60 * 60 * 1000 + 59 * 60 * 1000 + 59 * 1000
return total
}
}
|
gpl-3.0
|
9a21001bd92287e5d5a627aea4dfdf15
| 30.64375 | 113 | 0.557487 | 4.0626 | false | false | false | false |
aleksanderwozniak/WhatsThatFlag
|
app/src/main/java/me/wozappz/whatsthatflag/screens/game/GamePresenter.kt
|
1
|
4008
|
package me.wozappz.whatsthatflag.screens.game
import com.squareup.picasso.Callback
import me.wozappz.whatsthatflag.data.model.Model
import javax.inject.Inject
/**
* Created by olq on 20.11.17.
*/
class GamePresenter @Inject constructor(
private val view: GameScreenContract.View,
private val model: Model)
: GameScreenContract.Presenter {
var score = 0
var currentFlagId = 0
var amountOfLoadedCountries = 0
private var amountOfNetworkErrors = 0
override fun start() {
resetVariables()
view.showScore(score)
amountOfLoadedCountries = model.flagList.size
view.setButtonsClickability(false)
downloadImg(currentFlagId)
}
private fun resetVariables() {
score = 0
currentFlagId = 0
amountOfNetworkErrors = 0
}
private fun downloadImg(id: Int) {
val imgUrl = model.flagList[id].second
view.loadImg(imgUrl, callback = object : Callback {
override fun onSuccess() {
loadImgSuccess()
}
override fun onError() {
view.loadImg(imgUrl, false, object : Callback {
override fun onSuccess() {
loadImgSuccess()
}
override fun onError() {
amountOfNetworkErrors++
if (amountOfNetworkErrors < 3) {
view.displayMessageErrorLoadNextFlag()
goToNextFlag()
} else {
view.showNoConnectionAlert()
}
}
})
}
})
}
private fun loadImgSuccess() {
renameBtns(currentFlagId)
view.startAnswerTimer()
view.setButtonsClickability(true)
}
override fun redownloadImg(goToNext: Boolean) {
if (!goToNext) {
downloadImg(currentFlagId)
} else {
val currentFlag = model.flagList[currentFlagId].first
view.displayMessageFlagSkipped(currentFlag)
goToNextFlag()
}
}
private fun renameBtns(id: Int) {
val btnNames = model.getButtonNames(id)
view.renameButtons(btnNames)
view.showRemainingQuestions(amountOfLoadedCountries - currentFlagId)
}
override fun answerBtnClicked(selectedCountry: String) {
view.stopAnswerTimer()
val correctCountry = model.flagList[currentFlagId].first
val success = isAnswerCorrect(selectedCountry, correctCountry)
if (!success) {
view.animateWrongAnswer(selectedCountry, correctCountry)
} else {
view.animateCorrectAnswer(correctCountry)
}
view.setButtonsClickability(false)
}
private fun isAnswerCorrect(selectedCountry: String, correctCountry: String): Boolean {
if (selectedCountry == correctCountry) {
score++
view.showScore(score)
return true
}
return false
}
override fun animationTimerFinished() {
goToNextFlag()
}
private fun goToNextFlag() {
if (currentFlagId < amountOfLoadedCountries - 1) {
currentFlagId++
downloadImg(currentFlagId)
} else {
view.showRemainingQuestions(0)
view.showSummaryDialog(score, amountOfLoadedCountries)
}
}
override fun answerTimerFinished() {
val correctCountry = model.flagList[currentFlagId].first
view.animateCorrectAnswer(correctCountry, false)
view.setButtonsClickability(false)
}
override fun btnWTFclicked() {
view.stopAnswerTimer()
val currentFlag = model.flagList[currentFlagId].first
val url = model.getURLFromName(currentFlag)
view.displayFlagInfoInBrowser(url)
}
override fun backButtonClicked() {
view.showBackToMenuDialog()
}
}
|
apache-2.0
|
e9c5297237e4b389be1185d02a6d91e3
| 25.202614 | 91 | 0.591816 | 5.171613 | false | false | false | false |
xwiki-contrib/android-authenticator
|
app/src/main/java/org/xwiki/android/sync/contactdb/dao_repositories/DAOUserAccountsRepository.kt
|
1
|
1860
|
package org.xwiki.android.sync.contactdb.dao_repositories
import org.xwiki.android.sync.contactdb.UserAccount
import org.xwiki.android.sync.contactdb.UserAccountId
import org.xwiki.android.sync.contactdb.abstracts.AllUsersCacheRepository
import org.xwiki.android.sync.contactdb.abstracts.GroupsCacheRepository
import org.xwiki.android.sync.contactdb.abstracts.UserAccountsCookiesRepository
import org.xwiki.android.sync.contactdb.abstracts.UserAccountsRepository
import org.xwiki.android.sync.contactdb.dao.AccountsDao
class DAOUserAccountsRepository (
private val accountsDao: AccountsDao,
private val groupsCacheRepository: GroupsCacheRepository,
private val allUsersCacheRepository: AllUsersCacheRepository,
private val userAccountsCookiesRepository: UserAccountsCookiesRepository
) : UserAccountsRepository {
override suspend fun createAccount(userAccount: UserAccount): UserAccount? {
val id = accountsDao.insertAccount(userAccount)
return accountsDao.findById(id)
}
override suspend fun findByAccountName(name: String): UserAccount? = accountsDao.findByAccountName(name)
override suspend fun findByAccountId(id: UserAccountId): UserAccount? = accountsDao.findById(id)
override suspend fun updateAccount(userAccount: UserAccount) {
accountsDao.updateUser(userAccount)
}
override suspend fun deleteAccount(id: UserAccountId) {
val user = findByAccountId(id) ?: return
accountsDao.deleteUser(id)
val otherServerUsers = accountsDao.oneServerAccounts(user.serverAddress)
if (otherServerUsers.isEmpty()) {
groupsCacheRepository[id] = null
allUsersCacheRepository[id] = null
userAccountsCookiesRepository[id] = null
}
}
override suspend fun getAll(): List<UserAccount> = accountsDao.getAllAccount()
}
|
lgpl-2.1
|
718cf5d61fcfaac192bd825e08ad4867
| 41.295455 | 108 | 0.775806 | 4.986595 | false | false | false | false |
tonyofrancis/Fetch
|
fetch2/src/main/java/com/tonyodev/fetch2/database/DownloadDao.kt
|
1
|
3233
|
package com.tonyodev.fetch2.database
import android.arch.persistence.room.*
import com.tonyodev.fetch2.Status
import com.tonyodev.fetch2.database.DownloadDatabase.Companion.COLUMN_CREATED
import com.tonyodev.fetch2.database.DownloadDatabase.Companion.COLUMN_FILE
import com.tonyodev.fetch2.database.DownloadDatabase.Companion.COLUMN_GROUP
import com.tonyodev.fetch2.database.DownloadDatabase.Companion.COLUMN_ID
import com.tonyodev.fetch2.database.DownloadDatabase.Companion.COLUMN_IDENTIFIER
import com.tonyodev.fetch2.database.DownloadDatabase.Companion.COLUMN_PRIORITY
import com.tonyodev.fetch2.database.DownloadDatabase.Companion.COLUMN_STATUS
import com.tonyodev.fetch2.database.DownloadDatabase.Companion.COLUMN_TAG
import com.tonyodev.fetch2.database.DownloadDatabase.Companion.TABLE_NAME
@Dao
interface DownloadDao {
@Insert(onConflict = OnConflictStrategy.ABORT)
fun insert(downloadInfo: DownloadInfo): Long
@Insert(onConflict = OnConflictStrategy.ABORT)
fun insert(downloadInfoList: List<DownloadInfo>): List<Long>
@Delete
fun delete(downloadInfo: DownloadInfo)
@Delete
fun delete(downloadInfoList: List<DownloadInfo>)
@Query("DELETE FROM $TABLE_NAME")
fun deleteAll()
@Update(onConflict = OnConflictStrategy.REPLACE)
fun update(download: DownloadInfo)
@Update(onConflict = OnConflictStrategy.REPLACE)
fun update(downloadInfoList: List<DownloadInfo>)
@Query("SELECT * FROM $TABLE_NAME")
fun get(): List<DownloadInfo>
@Query("SELECT * FROM $TABLE_NAME WHERE $COLUMN_ID = :id")
fun get(id: Int): DownloadInfo?
@Query("SELECT * FROM $TABLE_NAME WHERE $COLUMN_ID IN (:ids)")
fun get(ids: List<Int>): List<DownloadInfo>
@Query("SELECT * FROM $TABLE_NAME WHERE $COLUMN_FILE = :file")
fun getByFile(file: String): DownloadInfo?
@Query("SELECT * FROM $TABLE_NAME WHERE $COLUMN_STATUS = :status")
fun getByStatus(status: Status): List<DownloadInfo>
@Query("SELECT * FROM $TABLE_NAME WHERE $COLUMN_STATUS IN (:statuses)")
fun getByStatus(statuses: List<@JvmSuppressWildcards Status>): List<DownloadInfo>
@Query("SELECT * FROM $TABLE_NAME WHERE $COLUMN_GROUP = :group")
fun getByGroup(group: Int): List<DownloadInfo>
@Query("SELECT * FROM $TABLE_NAME WHERE $COLUMN_GROUP = :group AND $COLUMN_STATUS IN (:statuses)")
fun getByGroupWithStatus(group: Int, statuses: List<@JvmSuppressWildcards Status>): List<DownloadInfo>
@Query("SELECT * FROM $TABLE_NAME WHERE $COLUMN_STATUS = :status ORDER BY $COLUMN_PRIORITY DESC, $COLUMN_CREATED ASC")
fun getPendingDownloadsSorted(status: Status): List<DownloadInfo>
@Query("SELECT * FROM $TABLE_NAME WHERE $COLUMN_STATUS = :status ORDER BY $COLUMN_PRIORITY DESC, $COLUMN_CREATED DESC")
fun getPendingDownloadsSortedDesc(status: Status): List<DownloadInfo>
@Query("SELECT * FROM $TABLE_NAME WHERE $COLUMN_IDENTIFIER = :identifier")
fun getDownloadsByRequestIdentifier(identifier: Long): List<DownloadInfo>
@Query("SELECT * FROM $TABLE_NAME WHERE $COLUMN_TAG = :tag")
fun getDownloadsByTag(tag: String): List<DownloadInfo>
@Query("SELECT DISTINCT $COLUMN_GROUP from $TABLE_NAME")
fun getAllGroupIds(): List<Int>
}
|
apache-2.0
|
a5d6d0a0bf6d8130581482d0ec464122
| 39.936709 | 123 | 0.751315 | 4.113232 | false | false | false | false |
jayrave/falkon
|
falkon-mapper-basic/src/main/kotlin/com/jayrave/falkon/mapper/lib/CompositeIdExtractFromHelper.kt
|
1
|
1824
|
package com.jayrave.falkon.mapper.lib
import com.jayrave.falkon.mapper.Column
import com.jayrave.falkon.mapper.Table
import java.util.*
import kotlin.reflect.KProperty1
/**
* Utility class to simplify implementation of [Table.extractFrom] for tables with
* composite ids i.e., for tables where multiple columns together serve as the primary key
*/
class CompositeIdExtractFromHelper<in ID : Any> private constructor(
private val columnToPropertyMap: Map<Column<*, *>, KProperty1<ID, *>>) {
fun <C> extractFrom(id: ID, column: Column<*, C>): C {
column.throwIfNotValidCandidateForExtractFrom()
val matchingColumn = columnToPropertyMap.findColumnWithName(column.name)
@Suppress("UNCHECKED_CAST")
return when {
matchingColumn != null -> columnToPropertyMap[matchingColumn]!!.get(id) as C
else -> throwSinceExtractFromHelperDoesNotKnowAboutColumn(
CompositeIdExtractFromHelper::class.qualifiedName!!, column
)
}
}
class Builder<ID : Any> {
private val map = HashMap<Column<*, *>, KProperty1<ID, *>>()
fun <C> add(column: Column<*, C>, property: KProperty1<ID, C>): Builder<ID> {
column.throwIfNotValidCandidateForExtractFrom()
map.put(column, property)
return this
}
fun build(): CompositeIdExtractFromHelper<ID> {
return CompositeIdExtractFromHelper(HashMap(map))
}
}
companion object {
private fun Map<Column<*, *>, *>.findColumnWithName(name: String): Column<*, *>? {
this.forEach {
if (it.key.name == name) {
return it.key
}
}
// No matching columns found!
return null
}
}
}
|
apache-2.0
|
24c7af7c3766aa8134315b2d9cce76cd
| 29.416667 | 90 | 0.615132 | 4.641221 | false | false | false | false |
duftler/orca
|
orca-kayenta/src/main/kotlin/com/netflix/spinnaker/orca/kayenta/model/KayentaCanaryContext.kt
|
1
|
3347
|
/*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.kayenta.model
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonProperty
import com.netflix.spinnaker.orca.kayenta.Thresholds
import java.time.Duration
import java.time.Instant
data class KayentaCanaryContext(
val metricsAccountName: String? = null,
val configurationAccountName: String? = null,
val storageAccountName: String? = null,
val canaryConfigId: String? = null,
val canaryConfigName: String? = null,
val scopes: List<CanaryConfigScope> = emptyList(),
val scoreThresholds: Thresholds = Thresholds(pass = 75, marginal = 50),
val siteLocal: Map<String, Any> = emptyMap(),
@Deprecated("Kept to support pipelines that haven't been updated to use lifetimeDuration")
@JsonProperty(access = JsonProperty.Access.READ_WRITE)
private val lifetimeHours: Int? = null,
@JsonProperty(access = JsonProperty.Access.READ_WRITE)
private val lifetimeDuration: Duration? = null,
@JsonProperty(access = JsonProperty.Access.READ_WRITE)
private val beginCanaryAnalysisAfterMins: Int = 0,
@JsonProperty(access = JsonProperty.Access.READ_WRITE)
private val baselineAnalysisOffsetInMins: Int = 0,
@JsonProperty(access = JsonProperty.Access.READ_WRITE)
private val lookbackMins: Int = 0,
@JsonProperty(access = JsonProperty.Access.READ_WRITE)
private val canaryAnalysisIntervalMins: Int? = null
) {
@JsonIgnore
val lifetime = when {
lifetimeDuration != null -> lifetimeDuration
lifetimeHours != null -> Duration.ofHours(lifetimeHours.toLong())
else -> null
}
@JsonIgnore
val beginCanaryAnalysisAfter = Duration.ofMinutes(beginCanaryAnalysisAfterMins.toLong())
@JsonIgnore
val baselineAnalysisOffset = Duration.ofMinutes(baselineAnalysisOffsetInMins.toLong())
@JsonIgnore
val lookback = Duration.ofMinutes(lookbackMins.toLong())
@JsonIgnore
val canaryAnalysisInterval = if (canaryAnalysisIntervalMins == null) null else Duration.ofMinutes(canaryAnalysisIntervalMins.toLong())
}
data class CanaryConfigScope(
val scopeName: String = "default",
val controlScope: String?,
val controlLocation: String?,
val experimentScope: String?,
val experimentLocation: String?,
val startTimeIso: String?,
val endTimeIso: String?,
val step: Long = 60, // TODO: clarify this is in seconds
val extendedScopeParams: Map<String, String> = emptyMap()
) {
// I don't love having these as separate properties but other things in Orca rely
// on serializing Instant as epoch Millis which is not what Kayenta wants.
@JsonIgnore
val startTime = if (startTimeIso == null) null else Instant.parse(startTimeIso)
@JsonIgnore
val endTime = if (endTimeIso == null) null else Instant.parse(endTimeIso)
}
|
apache-2.0
|
d9686c88e73d75443d3e0395b84a36b4
| 35.380435 | 136 | 0.759486 | 4.215365 | false | true | false | false |
manami-project/manami
|
manami-app/src/main/kotlin/io/github/manamiproject/manami/app/inconsistencies/lists/deadentries/DeadEntriesInconsistencyHandler.kt
|
1
|
2625
|
package io.github.manamiproject.manami.app.inconsistencies.lists.deadentries
import io.github.manamiproject.manami.app.cache.Cache
import io.github.manamiproject.manami.app.cache.CacheEntry
import io.github.manamiproject.manami.app.cache.Caches
import io.github.manamiproject.manami.app.cache.DeadEntry
import io.github.manamiproject.manami.app.inconsistencies.InconsistenciesSearchConfig
import io.github.manamiproject.manami.app.inconsistencies.InconsistencyHandler
import io.github.manamiproject.manami.app.lists.ignorelist.IgnoreListEntry
import io.github.manamiproject.manami.app.lists.watchlist.WatchListEntry
import io.github.manamiproject.manami.app.state.InternalState
import io.github.manamiproject.manami.app.state.State
import io.github.manamiproject.modb.core.logging.LoggerDelegate
import io.github.manamiproject.modb.core.models.Anime
import java.net.URI
internal class DeadEntriesInconsistencyHandler(
private val state: State = InternalState,
private val cache: Cache<URI, CacheEntry<Anime>> = Caches.defaultAnimeCache,
): InconsistencyHandler<DeadEntriesInconsistenciesResult> {
override fun calculateWorkload(): Int = state.watchList().size + state.ignoreList().size
override fun isExecutable(config: InconsistenciesSearchConfig): Boolean = config.checkDeadEntries
override fun execute(progressUpdate: (Int) -> Unit): DeadEntriesInconsistenciesResult {
log.info { "Starting check for dead entries in WatchList and IgnoreList." }
var progress = 0
val watchListResults: List<WatchListEntry> = state.watchList()
.asSequence()
.map {
progressUpdate.invoke(++progress)
it
}
.map { watchListEntry -> watchListEntry to cache.fetch(watchListEntry.link.uri) }
.filter { it.second is DeadEntry }
.map { it.first }
.toList()
val ignoreListResults: List<IgnoreListEntry> = state.ignoreList()
.asSequence()
.map {
progressUpdate.invoke(++progress)
it
}
.map { ignoreListEntry -> ignoreListEntry to cache.fetch(ignoreListEntry.link.uri) }
.filter { it.second is DeadEntry }
.map { it.first }
.toList()
log.info { "Finished check for dead entries in WatchList and IgnoreList." }
return DeadEntriesInconsistenciesResult(
watchListResults = watchListResults,
ignoreListResults = ignoreListResults,
)
}
companion object {
private val log by LoggerDelegate()
}
}
|
agpl-3.0
|
d4659f7e3931a905aba32674afced715
| 40.03125 | 101 | 0.705905 | 4.695886 | false | true | false | false |
commons-app/apps-android-commons
|
app/src/main/java/fr/free/nrw/commons/customselector/helper/ImageHelper.kt
|
2
|
2573
|
package fr.free.nrw.commons.customselector.helper
import fr.free.nrw.commons.customselector.model.Folder
import fr.free.nrw.commons.customselector.model.Image
/**
* Image Helper object, includes all the static functions and variables required by custom selector.
*/
object ImageHelper {
/**
* Custom selector preference key
*/
const val CUSTOM_SELECTOR_PREFERENCE_KEY: String = "custom_selector"
/**
* Switch state preference key
*/
const val SHOW_ALREADY_ACTIONED_IMAGES_PREFERENCE_KEY: String = "show_already_actioned_images"
/**
* Returns the list of folders from given image list.
*/
fun folderListFromImages(images: List<Image>): ArrayList<Folder> {
val folderMap: MutableMap<Long, Folder> = LinkedHashMap()
for (image in images) {
val bucketId = image.bucketId
val bucketName = image.bucketName
var folder = folderMap[bucketId]
if (folder == null) {
folder = Folder(bucketId, bucketName)
folderMap[bucketId] = folder
}
folder.images.add(image)
}
return ArrayList(folderMap.values)
}
/**
* Filters the images based on the given bucketId (folder)
*/
fun filterImages(images: ArrayList<Image>, bukketId: Long?): ArrayList<Image> {
if (bukketId == null) return images
val filteredImages = arrayListOf<Image>()
for (image in images) {
if (image.bucketId == bukketId) {
filteredImages.add(image)
}
}
return filteredImages
}
/**
* getIndex: Returns the index of image in given list.
*/
fun getIndex(list: ArrayList<Image>, image: Image): Int {
return list.indexOf(image)
}
/**
* getIndex: Returns the index of image in given list.
*/
fun getIndexFromId(list: ArrayList<Image>, imageId: Long): Int {
for(i in list){
if(i.id == imageId)
return list.indexOf(i)
}
return 0;
}
/**
* Gets the list of indices from the master list.
*/
fun getIndexList(list: ArrayList<Image>, masterList: ArrayList<Image>): ArrayList<Int> {
// Can be optimised as masterList is sorted by time.
val indexes = arrayListOf<Int>()
for(image in list) {
val index = getIndex(masterList, image)
if (index == -1) {
continue
}
indexes.add(index)
}
return indexes
}
}
|
apache-2.0
|
deb38c6dd967bf844352f462643e40a8
| 27.921348 | 100 | 0.58803 | 4.482578 | false | false | false | false |
nfrankel/kaadin
|
kaadin-core/src/main/kotlin/ch/frankel/kaadin/Grid.kt
|
1
|
7503
|
/*
* Copyright 2016 Nicolas Fränkel
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ch.frankel.kaadin
import com.vaadin.data.*
import com.vaadin.data.util.*
import com.vaadin.data.util.converter.*
import com.vaadin.ui.*
import com.vaadin.ui.Grid.*
import com.vaadin.ui.renderers.*
import com.vaadin.ui.renderers.ClickableRenderer.*
import java.text.DateFormat
import java.text.NumberFormat
import java.util.*
/**
* see http://demo.vaadin.com/sampler/#ui/grids-and-trees/grid
*/
fun HasComponents.grid(caption: String? = null,
dataSource: Container.Indexed = IndexedContainer(),
init: Grid.() -> Unit = {}): Grid {
return Grid()
.apply {
caption?.let { this.caption = caption }
this.containerDataSource = dataSource
}
.apply(init)
.addTo(this)
}
fun Grid.column(propertyId: Any, init: Column.() -> Unit = {}): Column = getColumn(propertyId).apply(init)
fun Grid.columns(propertyIds: List<Any>, init: Column.() -> Unit = {}): Unit =
propertyIds.forEach { column(it).apply(init) }
fun Grid.columns(vararg propertyIds: Any, init: Column.() -> Unit = {}): Unit = columns(propertyIds.toList(), init)
fun Grid.footerRowAtStart(init: FooterRow.() -> Unit = {}): FooterRow = prependFooterRow().apply(init)
fun Grid.footerRowAtEnd(init: FooterRow.() -> Unit = {}): FooterRow = appendFooterRow().apply(init)
fun Grid.footerRowAt(index: Int, init: FooterRow.() -> Unit = {}): FooterRow = addFooterRowAt(index).apply(init)
fun Grid.headerRowAtStart(init: HeaderRow.() -> Unit = {}): HeaderRow = prependHeaderRow().apply(init)
fun Grid.headerRowAtEnd(init: HeaderRow.() -> Unit = {}): HeaderRow = appendHeaderRow().apply(init)
fun Grid.headerRowAt(index: Int, init: HeaderRow.() -> Unit = {}): HeaderRow = addHeaderRowAt(index).apply(init)
fun Grid.cellStyleGenerator(generator: (CellReference) -> String?) = setCellStyleGenerator(generator)
fun Grid.cellStyleGenerator(className: String, predicate: (CellReference) -> Boolean) {
val computeClassName: (Boolean) -> String? = { if (it) className else null }
setCellStyleGenerator { computeClassName(predicate(it)) }
}
fun Grid.selectionMode(selectionMode: SelectionMode, init: SelectionModel.() -> Unit = {}): Unit {
setSelectionMode(selectionMode).apply(init)
}
// Because StaticRow is not public
fun HeaderRow.cell(propertyId: Any, init: HeaderCell.() -> Unit = {}): HeaderCell = getCell(propertyId).apply(init)
fun FooterRow.cell(propertyId: Any, init: FooterCell.() -> Unit = {}): FooterCell = getCell(propertyId).apply(init)
private abstract class KaadinAbstractConverter<P, M>(private val modelClass: Class<M>,
private val presentationClass: Class<P>) : Converter<P, M> {
override fun convertToModel(value: P, targetType: Class<out M>, locale: Locale) = throw UnsupportedOperationException("not implemented")
override fun getPresentationType() = presentationClass
override fun getModelType() = modelClass
}
private class KaadinLocaleConverter<P, M>(modelClass: Class<M>,
presentationClass: Class<P>,
private val convert: (value: M, locale: Locale) -> P) : KaadinAbstractConverter<P, M>(modelClass, presentationClass) {
override fun convertToPresentation(value: M, targetType: Class<out P>, locale: Locale) = convert(value, locale)
}
private class KaadinConverter<P, M>(modelClass: Class<M>,
presentationClass: Class<P>,
private val convert: (value: M) -> P) : KaadinAbstractConverter<P, M>(modelClass, presentationClass) {
override fun convertToPresentation(value: M, targetType: Class<out P>, locale: Locale) = convert(value)
}
fun <P, M> Column.converter(modelClass: Class<M>, presentationClass: Class<P>, convert: (value: M, locale: Locale) -> P): Converter<P, M> =
KaadinLocaleConverter(modelClass, presentationClass, convert).apply {
converter = this
}
fun <P, M> Column.converter(modelClass: Class<M>, presentationClass: Class<P>, convert: (value: M) -> P): Converter<P, M> =
KaadinConverter(modelClass, presentationClass, convert).apply {
converter = this
}
fun Column.bigDecimalConverter(): Unit {
converter = StringToBigDecimalConverter()
}
fun Column.bigIntegerConverter(): Unit {
converter = StringToBigIntegerConverter()
}
fun Column.booleanConverter(): Unit {
converter = StringToBooleanConverter()
}
fun Column.byteConverter(): Unit {
converter = StringToByteConverter()
}
fun Column.collectionConverter(): Unit {
converter = StringToCollectionConverter()
}
fun Column.doubleConverter(): Unit {
converter = StringToDoubleConverter()
}
fun Column.dateConverter(): Unit {
converter = StringToDateConverter()
}
fun Column.enumConverter(): Unit {
converter = StringToEnumConverter()
}
fun Column.floatConverter(): Unit {
converter = StringToFloatConverter()
}
fun Column.intConverter(): Unit {
converter = StringToIntegerConverter()
}
fun Column.longConverter(): Unit {
converter = StringToLongConverter()
}
fun Column.shortConverter(): Unit {
converter = StringToShortConverter()
}
fun <P, M> Column.converter(converter: Converter<P, M>): Unit {
this.converter = converter
}
fun Column.unsetConverter(): Unit {
converter = null
}
fun <T> Column.renderer(renderer: Renderer<T>): Unit {
this.renderer = renderer
}
fun <T> Column.renderer(renderer: Renderer<T>, converter: Converter<out T, Any>): Unit {
setRenderer(renderer, converter)
}
fun Column.buttonRenderer(nullRepresentation: String = "", onClick: (RendererClickEvent) -> Unit = {}): Unit {
renderer = ButtonRenderer(onClick, nullRepresentation)
}
fun Column.dateRenderer(formatString: String = "%s", locale: Locale = Locale.getDefault(), nullRepresentation: String = ""): Unit {
renderer = DateRenderer(formatString, locale, nullRepresentation)
}
fun Column.dateRenderer(format: DateFormat, nullRepresentation: String = ""): Unit {
renderer = DateRenderer(format, nullRepresentation)
}
fun Column.htmlRenderer(nullRepresentation: String = ""): Unit {
renderer = HtmlRenderer(nullRepresentation)
}
fun Column.imageRenderer(onClick: (RendererClickEvent) -> Unit = {}): Unit {
renderer = ImageRenderer(onClick)
}
fun Column.numberRenderer(formatString: String = "%s", locale: Locale = Locale.getDefault(), nullRepresentation: String = ""): Unit {
renderer = NumberRenderer(formatString, locale, nullRepresentation)
}
fun Column.numberRenderer(format: NumberFormat, nullRepresentation: String = ""): Unit {
renderer = NumberRenderer(format, nullRepresentation)
}
fun Column.progressBarRenderer(): Unit {
renderer = ProgressBarRenderer()
}
fun Column.textRenderer(nullRepresentation: String = ""): Unit {
renderer = TextRenderer(nullRepresentation)
}
|
apache-2.0
|
10b28591851be77a11e6f1e59a26788e
| 43.135294 | 160 | 0.699147 | 4.269778 | false | false | false | false |
luxons/seven-wonders
|
sw-engine/src/test/kotlin/org/luxons/sevenwonders/engine/effects/GoldIncreaseTest.kt
|
1
|
1353
|
package org.luxons.sevenwonders.engine.effects
import org.junit.experimental.theories.DataPoints
import org.junit.experimental.theories.Theories
import org.junit.experimental.theories.Theory
import org.junit.runner.RunWith
import org.luxons.sevenwonders.engine.SimplePlayer
import org.luxons.sevenwonders.engine.test.testBoard
import org.luxons.sevenwonders.engine.test.testTable
import org.luxons.sevenwonders.model.resources.ResourceType
import kotlin.test.assertEquals
@RunWith(Theories::class)
class GoldIncreaseTest {
@Theory
fun apply_increaseGoldWithRightAmount(initialAmount: Int, goldIncreaseAmount: Int, type: ResourceType) {
val board = testBoard(type, initialAmount)
val goldIncrease = GoldIncrease(goldIncreaseAmount)
goldIncrease.applyTo(board)
assertEquals(initialAmount + goldIncreaseAmount, board.gold)
}
@Theory
fun computePoints_isAlwaysZero(gold: Int) {
val goldIncrease = GoldIncrease(gold)
val player = SimplePlayer(0, testTable(5))
assertEquals(0, goldIncrease.computePoints(player))
}
companion object {
@JvmStatic
@DataPoints
fun goldAmounts(): IntArray = intArrayOf(-5, -1, 0, 1, 2, 5, 10)
@JvmStatic
@DataPoints
fun resourceTypes(): Array<ResourceType> = ResourceType.values()
}
}
|
mit
|
b5f408effc40934ee8a7fe3432b31c28
| 30.465116 | 108 | 0.734664 | 4.336538 | false | true | false | false |
ujpv/intellij-rust
|
src/main/kotlin/org/rust/ide/actions/RustStringLiteralJoinLinesHandler.kt
|
1
|
1463
|
package org.rust.ide.actions
import com.intellij.codeInsight.editorActions.JoinLinesHandlerDelegate
import com.intellij.codeInsight.editorActions.JoinLinesHandlerDelegate.CANNOT_JOIN
import com.intellij.openapi.editor.Document
import com.intellij.psi.PsiFile
import com.intellij.util.text.CharSequenceSubSequence
import org.rust.ide.typing.endsWithUnescapedBackslash
import org.rust.lang.core.psi.RustTokenElementTypes
import org.rust.lang.core.psi.impl.RustFile
import org.rust.lang.core.psi.util.elementType
class RustStringLiteralJoinLinesHandler : JoinLinesHandlerDelegate {
override fun tryJoinLines(document: Document, file: PsiFile, offsetNear: Int, end: Int): Int {
if (file !is RustFile) return CANNOT_JOIN
val text = document.charsSequence
val leftPsi = file.findElementAt(offsetNear) ?: return CANNOT_JOIN
val rightPsi = file.findElementAt(end) ?: return CANNOT_JOIN
if (leftPsi != rightPsi || leftPsi.elementType !in RustTokenElementTypes.STRING_LITERALS) return CANNOT_JOIN
var start = offsetNear
// Strip newline escape
if (CharSequenceSubSequence(text, 0, start + 1).endsWithUnescapedBackslash()) {
start--
while (start >= 0 && (text[start] == ' ' || text[start] == '\t')) {
start--
}
}
document.deleteString(start + 1, end)
document.insertString(start + 1, " ")
return start + 1
}
}
|
mit
|
2a7f18cc97098e114e5663e7f6a5b7f5
| 37.5 | 116 | 0.7054 | 4.515432 | false | false | false | false |
shyiko/ktlint
|
ktlint/src/main/kotlin/com/pinterest/ktlint/internal/FileUtils.kt
|
1
|
5751
|
package com.pinterest.ktlint.internal
import com.pinterest.ktlint.core.KtLint
import com.pinterest.ktlint.core.LintError
import com.pinterest.ktlint.core.RuleSet
import com.pinterest.ktlint.core.api.FeatureInAlphaState
import java.io.File
import java.nio.file.FileSystem
import java.nio.file.FileVisitResult
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.nio.file.SimpleFileVisitor
import java.nio.file.attribute.BasicFileAttributes
import kotlin.system.exitProcess
internal val workDir: String = File(".").canonicalPath
private val tildeRegex = Regex("^(!)?~")
internal fun FileSystem.fileSequence(
globs: List<String>,
rootDir: Path = Paths.get(".").toAbsolutePath().normalize()
): Sequence<Path> {
checkGlobsContainAbsolutePath(globs)
val pathMatchers = if (globs.isEmpty()) {
setOf(
getPathMatcher("glob:**$globSeparator*.kt"),
getPathMatcher("glob:**$globSeparator*.kts")
)
} else {
globs
.filterNot { it.startsWith("!") }
.map {
getPathMatcher(it.toGlob(rootDir))
}
}
val negatedPathMatchers = if (globs.isEmpty()) {
emptySet()
} else {
globs
.filter { it.startsWith("!") }
.map { getPathMatcher(it.removePrefix("!").toGlob(rootDir)) }
}
val result = mutableListOf<Path>()
Files.walkFileTree(
rootDir,
object : SimpleFileVisitor<Path>() {
override fun visitFile(
filePath: Path,
fileAttrs: BasicFileAttributes
): FileVisitResult {
if (negatedPathMatchers.none { it.matches(filePath) } &&
pathMatchers.any { it.matches(filePath) }
) {
result.add(filePath)
}
return FileVisitResult.CONTINUE
}
override fun preVisitDirectory(
dirPath: Path,
dirAttr: BasicFileAttributes
): FileVisitResult {
return if (Files.isHidden(dirPath)) {
FileVisitResult.SKIP_SUBTREE
} else {
FileVisitResult.CONTINUE
}
}
}
)
return result.asSequence()
}
private fun FileSystem.checkGlobsContainAbsolutePath(globs: List<String>) {
val rootDirs = rootDirectories.map { it.toString() }
globs
.map { it.removePrefix("!") }
.filter { glob ->
rootDirs.any { glob.startsWith(it) }
}
.run {
if (isNotEmpty()) {
throw IllegalArgumentException(
"KtLint does not support absolute path in globs:\n${joinToString(separator = "\n")}"
)
}
}
}
private fun String.toGlob(
rootDir: Path
): String {
val expandedPath = expandTilde(this)
val rootDirPath = rootDir
.toAbsolutePath()
.toString()
.run {
val normalizedPath = if (!endsWith(File.separator)) "$this${File.separator}" else this
normalizedPath.replace(File.separator, globSeparator)
}
return "glob:$rootDirPath$expandedPath"
}
internal val globSeparator: String get() {
val os = System.getProperty("os.name")
return when {
os.startsWith("windows", ignoreCase = true) -> "\\\\"
else -> "/"
}
}
/**
* List of paths to Java `jar` files.
*/
internal typealias JarFiles = List<String>
internal fun JarFiles.toFilesURIList() = map {
val jarFile = File(expandTilde(it))
if (!jarFile.exists()) {
println("Error: $it does not exist")
exitProcess(1)
}
jarFile.toURI().toURL()
}
// a complete solution would be to implement https://www.gnu.org/software/bash/manual/html_node/Tilde-Expansion.html
// this implementation takes care only of the most commonly used case (~/)
private fun expandTilde(path: String): String = path.replaceFirst(tildeRegex, System.getProperty("user.home"))
internal fun File.location(
relative: Boolean
) = if (relative) this.toRelativeString(File(workDir)) else this.path
/**
* Run lint over common kotlin file or kotlin script file.
*/
@OptIn(FeatureInAlphaState::class)
internal fun lintFile(
fileName: String,
fileContents: String,
ruleSets: List<RuleSet>,
userData: Map<String, String> = emptyMap(),
editorConfigPath: String? = null,
debug: Boolean = false,
lintErrorCallback: (LintError) -> Unit = {}
) {
KtLint.lint(
KtLint.ExperimentalParams(
fileName = fileName,
text = fileContents,
ruleSets = ruleSets,
userData = userData,
script = !fileName.endsWith(".kt", ignoreCase = true),
editorConfigPath = editorConfigPath,
cb = { e, _ ->
lintErrorCallback(e)
},
debug = debug,
isInvokedFromCli = true
)
)
}
/**
* Format a kotlin file or script file
*/
@OptIn(FeatureInAlphaState::class)
internal fun formatFile(
fileName: String,
fileContents: String,
ruleSets: Iterable<RuleSet>,
userData: Map<String, String>,
editorConfigPath: String?,
debug: Boolean,
cb: (e: LintError, corrected: Boolean) -> Unit
): String =
KtLint.format(
KtLint.ExperimentalParams(
fileName = fileName,
text = fileContents,
ruleSets = ruleSets,
userData = userData,
script = !fileName.endsWith(".kt", ignoreCase = true),
editorConfigPath = editorConfigPath,
cb = cb,
debug = debug,
isInvokedFromCli = true
)
)
|
mit
|
95c4292b9bf1d0803ddf252c4cb68122
| 28.64433 | 116 | 0.596244 | 4.589785 | false | false | false | false |
danrien/projectBlue
|
projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/playback/service/receivers/scrobble/PlaybackFileStartedScrobblerRegistration.kt
|
2
|
3727
|
package com.lasthopesoftware.bluewater.client.playback.service.receivers.scrobble
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.ServiceFile
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.FilePropertyHelpers
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.KnownFileProperties
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.ScopedCachedFilePropertiesProvider
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.ScopedFilePropertiesProvider
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.repository.FilePropertyCache
import com.lasthopesoftware.bluewater.client.browsing.library.revisions.ScopedRevisionProvider
import com.lasthopesoftware.bluewater.client.connection.IConnectionProvider
import com.lasthopesoftware.bluewater.client.connection.receivers.IConnectionDependentReceiverRegistration
import com.lasthopesoftware.bluewater.client.playback.service.broadcasters.PlaylistEvents
class PlaybackFileStartedScrobblerRegistration : IConnectionDependentReceiverRegistration {
companion object {
private val intents: Collection<IntentFilter> =
setOf(IntentFilter(PlaylistEvents.onPlaylistTrackStart))
}
override fun registerWithConnectionProvider(connectionProvider: IConnectionProvider): BroadcastReceiver {
val filePropertiesProvider = ScopedCachedFilePropertiesProvider(
connectionProvider,
FilePropertyCache.getInstance(),
ScopedFilePropertiesProvider(
connectionProvider,
ScopedRevisionProvider(connectionProvider),
FilePropertyCache.getInstance()
)
)
return PlaybackFileChangedScrobbleDroidProxy(
filePropertiesProvider,
ScrobbleIntentProvider.getInstance()
)
}
override fun forIntents(): Collection<IntentFilter> = intents
private class PlaybackFileChangedScrobbleDroidProxy(
private val scopedCachedFilePropertiesProvider: ScopedCachedFilePropertiesProvider,
private val scrobbleIntentProvider: ScrobbleIntentProvider
) : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val fileKey = intent.getIntExtra(PlaylistEvents.PlaybackFileParameters.fileKey, -1)
if (fileKey < 0) return
scopedCachedFilePropertiesProvider
.promiseFileProperties(ServiceFile(fileKey))
.then { fileProperties ->
val artist = fileProperties[KnownFileProperties.ARTIST]
val name = fileProperties[KnownFileProperties.NAME]
val album = fileProperties[KnownFileProperties.ALBUM]
val duration =
FilePropertyHelpers.parseDurationIntoMilliseconds(fileProperties).toLong()
val scrobbleDroidIntent = scrobbleIntentProvider.provideScrobbleIntent(true)
scrobbleDroidIntent.putExtra("artist", artist)
scrobbleDroidIntent.putExtra("album", album)
scrobbleDroidIntent.putExtra("track", name)
scrobbleDroidIntent.putExtra("secs", (duration / 1000).toInt())
fileProperties[KnownFileProperties.TRACK]
?.takeIf { it.isNotEmpty() }
?.also {
scrobbleDroidIntent.putExtra("tracknumber", it.toInt())
}
context.sendBroadcast(scrobbleDroidIntent)
}
}
}
}
|
lgpl-3.0
|
a88a58f86ee64d3b7921ae1872958aaa
| 49.364865 | 117 | 0.740542 | 5.925278 | false | false | false | false |
raniejade/kspec
|
kspec-core/src/main/kotlin/io/polymorphicpanda/kspec/helpers/MemoizedHelper.kt
|
1
|
450
|
package io.polymorphicpanda.kspec.helpers
import kotlin.reflect.KProperty
/**
* @author Ranie Jade Ramiso
*/
class MemoizedHelper<T>(val factory: () -> T) {
private var instance: T? = null
fun get(): T {
if (instance == null) {
instance = factory()
}
return instance!!
}
operator fun getValue(thisRef: Any?, property: KProperty<*>) = get()
fun forget() {
instance = null
}
}
|
mit
|
bc497e30eb6953efff252fea0704f3df
| 18.565217 | 72 | 0.577778 | 4.090909 | false | false | false | false |
danrien/projectBlue
|
projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/playback/service/notification/building/NowPlayingNotificationBuilder.kt
|
2
|
4814
|
package com.lasthopesoftware.bluewater.client.playback.service.notification.building
import android.content.Context
import android.graphics.Bitmap
import androidx.core.app.NotificationCompat
import com.lasthopesoftware.bluewater.R
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.ServiceFile
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.KnownFileProperties
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.ScopedCachedFilePropertiesProvider
import com.lasthopesoftware.bluewater.client.browsing.items.media.image.ProvideImages
import com.lasthopesoftware.bluewater.client.connection.IConnectionProvider
import com.lasthopesoftware.bluewater.client.playback.service.PlaybackService.Companion.pendingNextIntent
import com.lasthopesoftware.bluewater.client.playback.service.PlaybackService.Companion.pendingPauseIntent
import com.lasthopesoftware.bluewater.client.playback.service.PlaybackService.Companion.pendingPlayingIntent
import com.lasthopesoftware.bluewater.client.playback.service.PlaybackService.Companion.pendingPreviousIntent
import com.lasthopesoftware.bluewater.shared.UrlKeyHolder
import com.lasthopesoftware.bluewater.shared.promises.extensions.keepPromise
import com.namehillsoftware.handoff.promises.Promise
class NowPlayingNotificationBuilder(
private val context: Context,
private val mediaStyleNotificationSetup: SetupMediaStyleNotifications,
private val connectionProvider: IConnectionProvider,
private val scopedCachedFilePropertiesProvider: ScopedCachedFilePropertiesProvider,
private val imageProvider: ProvideImages
) : BuildNowPlayingNotificationContent, AutoCloseable {
private val lazyPlayingLoadingNotification by lazy {
addButtons(mediaStyleNotificationSetup.mediaStyleNotification, true)
.setOngoing(true)
.setContentTitle(context.getString(R.string.lbl_loading))
}
private val lazyNotPlayingLoadingNotification by lazy {
addButtons(mediaStyleNotificationSetup.mediaStyleNotification, false)
.setOngoing(false)
.setContentTitle(context.getString(R.string.lbl_loading))
}
private var viewStructure: ViewStructure? = null
@Synchronized
override fun promiseNowPlayingNotification(serviceFile: ServiceFile, isPlaying: Boolean): Promise<NotificationCompat.Builder> {
val urlKeyHolder = UrlKeyHolder(connectionProvider.urlProvider.baseUrl!!, serviceFile.key)
if (viewStructure?.urlKeyHolder != urlKeyHolder) {
viewStructure?.release()
viewStructure = null
}
val viewStructure = viewStructure ?: ViewStructure(urlKeyHolder).also { viewStructure = it }
viewStructure.promisedNowPlayingImage = viewStructure.promisedNowPlayingImage ?: imageProvider.promiseFileBitmap(serviceFile)
val promisedFileProperties = viewStructure.promisedFileProperties
?: scopedCachedFilePropertiesProvider.promiseFileProperties(serviceFile).also { viewStructure.promisedFileProperties = it }
return promisedFileProperties
.eventually { fileProperties ->
val artist = fileProperties[KnownFileProperties.ARTIST]
val name = fileProperties[KnownFileProperties.NAME]
val builder = addButtons(mediaStyleNotificationSetup.mediaStyleNotification, isPlaying)
.setOngoing(isPlaying)
.setContentTitle(name)
.setContentText(artist)
if (viewStructure.urlKeyHolder != urlKeyHolder) return@eventually Promise(builder)
viewStructure.promisedNowPlayingImage
?.then(
{ bitmap -> bitmap?.let(builder::setLargeIcon) },
{ builder }
)
.keepPromise(builder)
}
}
override fun getLoadingNotification(isPlaying: Boolean): NotificationCompat.Builder =
if (isPlaying) lazyPlayingLoadingNotification else lazyNotPlayingLoadingNotification
override fun close() { viewStructure?.release() }
private fun addButtons(builder: NotificationCompat.Builder, isPlaying: Boolean): NotificationCompat.Builder =
builder
.addAction(
NotificationCompat.Action(
R.drawable.av_rewind,
context.getString(R.string.btn_previous),
pendingPreviousIntent(context)
)
)
.addAction(
if (isPlaying) NotificationCompat.Action(
R.drawable.av_pause,
context.getString(R.string.btn_pause),
pendingPauseIntent(context)
) else NotificationCompat.Action(
R.drawable.av_play,
context.getString(R.string.btn_play),
pendingPlayingIntent(context)
)
)
.addAction(
NotificationCompat.Action(
R.drawable.av_fast_forward,
context.getString(R.string.btn_next),
pendingNextIntent(context)
)
)
private class ViewStructure(val urlKeyHolder: UrlKeyHolder<Int>) {
var promisedFileProperties: Promise<Map<String, String>>? = null
var promisedNowPlayingImage: Promise<Bitmap?>? = null
fun release() {
promisedNowPlayingImage?.cancel()
}
}
}
|
lgpl-3.0
|
7829b524246c57462bb6a2a2e49692c6
| 41.22807 | 128 | 0.807852 | 4.637765 | false | false | false | false |
alessio-b-zak/myRivers
|
android/app/src/main/java/com/epimorphics/android/myrivers/fragments/WIMSDataFragment.kt
|
1
|
6932
|
package com.epimorphics.android.myrivers.fragments
import android.os.Bundle
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.Toolbar
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageButton
import android.widget.TableLayout
import android.widget.TextView
import com.epimorphics.android.myrivers.R
import com.epimorphics.android.myrivers.activities.DataViewActivity
import com.epimorphics.android.myrivers.data.Measurement
import com.epimorphics.android.myrivers.data.WIMSPoint
import com.epimorphics.android.myrivers.helpers.FragmentHelper
/**
* A fragment occupying top part of the screen showcasing basic WIMSPoint Measurements.
* It is initiated by clicking a WIMSPoint marker in DataViewActivity
*
* @see <a href="https://github.com/alessio-b-zak/myRivers/blob/master/graphic%20assets/screenshots/wims_data_view.png">Screenshot</a>
* @see DataViewActivity
*/
open class WIMSDataFragment : FragmentHelper() {
private lateinit var mToolbar: Toolbar
private lateinit var mBackButton: ImageButton
private lateinit var mMoreInfoButton: Button
private lateinit var mWIMSDataView: View
private lateinit var mRecyclerView: RecyclerView
private lateinit var mWIMSDataFragment: WIMSDataFragment
private lateinit var mDataViewActivity: DataViewActivity
private lateinit var mMeasurementTable: TableLayout
/**
* Called when a fragment is created. Initiates mDataViewActivity
*
* @param savedInstanceState Saved state of the fragment
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
retainInstance = true
mDataViewActivity = activity as DataViewActivity
}
/**
* Called when a fragment view is created. Initiates and manipulates all required layout elements.
*
* @param inflater LayoutInflater
* @param container ViewGroup
* @param savedInstanceState Saved state of the fragment
*
* @return inflated and fully populated View
*/
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater!!.inflate(R.layout.fragment_wims_data_view, container, false)
mWIMSDataView = view
mWIMSDataFragment = this
// Initialise Recycler View and hide it so that map is visible
mRecyclerView = view.bind(R.id.wims_recycler_view)
mRecyclerView.visibility = View.INVISIBLE
mMeasurementTable = view.bind(R.id.wims_table)
mToolbar = view.bind(R.id.wims_data_toolbar)
mBackButton = view.bind(R.id.back_button_wims_data_view)
mBackButton.setOnClickListener { activity.onBackPressed() }
mMoreInfoButton = view.bind(R.id.info_button_wims_data_view)
mMoreInfoButton.setOnClickListener {
mDataViewActivity.openWIMSDetailsFragment()
}
mMoreInfoButton.visibility = View.INVISIBLE
return view
}
/**
* Shows a "More Info" Button. Called when all the data related to this WIMSPoint is populated.
*/
fun showMoreInfoButton() {
mMoreInfoButton.visibility = View.VISIBLE
}
/**
* Sets the text in the measurement table.
*
* @param wimsPoint WIMSPoint containing data to be populated
*/
fun setMeasurementsText(wimsPoint: WIMSPoint) {
val wimsName: TextView = mWIMSDataView.bind(R.id.wims_name)
// If wimsPoint.label is not null show wimsPoint.label as name, otherwise show wimsPoint.id
wimsName.text = if(wimsPoint.label != null) "Samples from ${wimsPoint.label}" else "Samples from ${wimsPoint.id}"
var rowIndex = 0
var tableHeaderRow = newTableRow(rowIndex++)
// set to true if wims.measurementMap contains at least one record of a general measurement
// i.e. pH, Temperature of Water and Conductivity@25C
val hasGeneralRecords = wimsPoint.measurementMap.any {
entry: Map.Entry<String, ArrayList<Measurement>> ->
WIMSPoint.generalGroup.contains(entry.key)
}
// If hasGeneralRecords populate data, otherwise show explanation message
if (hasGeneralRecords) {
addTextView(tableHeaderRow, "Determinand", 0.28, R.style.text_view_table_parent, Gravity.START)
addTextView(tableHeaderRow, "Sample Dates", 0.72, R.style.text_view_table_parent)
mMeasurementTable.addView(tableHeaderRow)
for (entry in WIMSPoint.generalGroup) {
if (wimsPoint.measurementMap.containsKey(entry) && wimsPoint.measurementMap[entry]!!.isNotEmpty()) {
val measurementList = arrayListOf<Measurement>()
for (measure in wimsPoint.measurementMap[entry]!!) {
measurementList.add(measure)
}
// Only show general measurements if there are more than 2 available
// Always show latest 3
if (measurementList.size > 2) {
tableHeaderRow = newTableRow(rowIndex++, true, 1)
val descriptor = measurementList[0].descriptor
addTextView(tableHeaderRow, entry, 0.28, R.style.text_view_table_parent_light, Gravity.START, 0, descriptor)
addTextView(tableHeaderRow, simplifyDate(measurementList[0].date), 0.24, R.style.text_view_table_parent_light, Gravity.END)
addTextView(tableHeaderRow, simplifyDate(measurementList[1].date), 0.24, R.style.text_view_table_parent_light, Gravity.END)
addTextView(tableHeaderRow, simplifyDate(measurementList[2].date), 0.24, R.style.text_view_table_parent_light, Gravity.END)
mMeasurementTable.addView(tableHeaderRow)
tableHeaderRow = newTableRow(rowIndex++, true, 1)
val unit = measurementList[0].unit
addTextView(tableHeaderRow, "($unit)", 0.28, R.style.text_view_table_child, Gravity.START)
addTextView(tableHeaderRow, measurementList[0].result.toString(), 0.24, R.style.text_view_table_child, Gravity.END)
addTextView(tableHeaderRow, measurementList[1].result.toString(), 0.24, R.style.text_view_table_child, Gravity.END)
addTextView(tableHeaderRow, measurementList[2].result.toString(), 0.24, R.style.text_view_table_child, Gravity.END)
mMeasurementTable.addView(tableHeaderRow)
}
}
}
} else {
val noDataExplanation: TextView = mWIMSDataView.bind(R.id.wims_no_data)
noDataExplanation.visibility = View.VISIBLE
}
}
}
|
mit
|
7b4d516e64fefda38792f6cd6beed93e
| 44.611842 | 147 | 0.675995 | 4.830662 | false | false | false | false |
JetBrains/resharper-unity
|
rider/src/main/kotlin/com/jetbrains/rider/plugins/unity/UnityIgnoredFileProvider.kt
|
1
|
2290
|
package com.jetbrains.rider.plugins.unity
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.changes.IgnoredFileDescriptor
import com.intellij.openapi.vcs.changes.IgnoredFileProvider
import com.intellij.openapi.vfs.VfsUtil
import com.jetbrains.rider.projectView.solutionDirectory
import java.io.File
class UnityIgnoredFileProvider : IgnoredFileProvider {
companion object {
val ignoredExtensions = hashSetOf(
".apk",
".unitypackage",
".pidb.meta",
"mdb.meta",
"pdb.meta"
)
}
override fun isIgnoredFile(project: Project, filePath: FilePath): Boolean {
if (!UnityProjectDiscoverer.getInstance(project).isUnityProject)
return false
val solDir = project.solutionDirectory
val ignoredFolders = arrayOf(
File(solDir, "Library"),
File(solDir, "library"),
File(solDir, "Temp"),
File(solDir, "temp"),
File(solDir, "Obj"),
File(solDir, "obj"),
File(solDir, "Build"),
File(solDir, "build"),
File(solDir, "Builds"),
File(solDir, "builds"),
File(solDir, "Logs"),
File(solDir, "logs"),
File(solDir, "MemoryCaptures"),
File(solDir, "memoryCaptures"),
getPluginPath(File(solDir, "Assets")),
getPluginPath(File(solDir, "assets"))
)
val name = filePath.name
if (name == "sysinfo.txt" || name == "crashlytics-build.properties")
return true
for (ext in ignoredExtensions)
if (name.endsWith(ext))
return true
for (ignoredFolder in ignoredFolders)
if (VfsUtil.isAncestor(ignoredFolder, filePath.ioFile, false))
return true
return false
}
private fun getPluginPath(file : File) : File {
return file.resolve("Plugins/Editor/Jetbrains")
}
override fun getIgnoredGroupDescription(): String {
return UnityBundle.message("text.unity.ignored.files")
}
override fun getIgnoredFiles(project: Project): MutableSet<IgnoredFileDescriptor> {
return mutableSetOf()
}
}
|
apache-2.0
|
530fa86425da350b50de88c5dc834239
| 30.383562 | 87 | 0.61048 | 4.702259 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.