repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
androidx/androidx | room/room-compiler-processing/src/main/java/androidx/room/compiler/processing/ksp/KspMessager.kt | 3 | 2996 | /*
* 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
*
* 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.room.compiler.processing.ksp
import androidx.room.compiler.processing.XAnnotation
import androidx.room.compiler.processing.XAnnotationValue
import androidx.room.compiler.processing.XElement
import androidx.room.compiler.processing.XMessager
import com.google.devtools.ksp.processing.KSPLogger
import com.google.devtools.ksp.symbol.KSNode
import com.google.devtools.ksp.symbol.NonExistLocation
import javax.tools.Diagnostic
internal class KspMessager(
private val logger: KSPLogger
) : XMessager() {
override fun onPrintMessage(
kind: Diagnostic.Kind,
msg: String,
element: XElement?,
annotation: XAnnotation?,
annotationValue: XAnnotationValue?
) {
if (element == null) {
internalPrintMessage(kind, msg)
return
}
// In Javac, the Messager requires all preceding parameters to report an error.
// In KSP, the KspLogger only needs the last so ignore the preceding parameters.
val nodes = sequence {
yield((annotationValue as? KspAnnotationValue)?.valueArgument)
yield((annotation as? KspAnnotation)?.ksAnnotated)
yield((element as? KspElement)?.declaration)
}.filterNotNull()
val ksNode = nodes.firstOrNull {
// pick first node with a location, if possible
it.location != NonExistLocation
} ?: nodes.firstOrNull() // fallback to the first non-null argument
// TODO: 10/8/21 Consider checking if the KspAnnotationValue is for an item in a value's
// list and adding that information to the error message if so (currently, we have to
// report an error on the list itself, so the information about the particular item is
// lost). https://github.com/google/ksp/issues/656
if (ksNode == null || ksNode.location == NonExistLocation) {
internalPrintMessage(kind, "$msg - ${element.fallbackLocationText}", ksNode)
} else {
internalPrintMessage(kind, msg, ksNode)
}
}
private fun internalPrintMessage(kind: Diagnostic.Kind, msg: String, ksNode: KSNode? = null) {
when (kind) {
Diagnostic.Kind.ERROR -> logger.error(msg, ksNode)
Diagnostic.Kind.WARNING -> logger.warn(msg, ksNode)
else -> logger.info(msg, ksNode)
}
}
}
| apache-2.0 | 9de4776c78d1bf248804fe0ed9c06f17 | 40.041096 | 98 | 0.682243 | 4.438519 | false | false | false | false |
Yusspy/Jolt-Sphere | core/src/org/joltsphere/scenes/Scene5.kt | 1 | 4184 | package org.joltsphere.scenes
import org.joltsphere.main.JoltSphereMain
import org.joltsphere.mechanics.WorldEntities
import org.joltsphere.mechanics.MapBodyBuilder
import org.joltsphere.mechanics.MountainClimbingPlayer
import org.joltsphere.mechanics.StreamBeamContactListener
import org.joltsphere.mechanics.StreamBeamTowedPlayer
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.Input.Keys
import com.badlogic.gdx.Screen
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType
import com.badlogic.gdx.maps.MapProperties
import com.badlogic.gdx.maps.tiled.TiledMap
import com.badlogic.gdx.maps.tiled.TmxMapLoader
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer
import com.badlogic.gdx.physics.box2d.World
import com.badlogic.gdx.physics.box2d.joints.DistanceJointDef
class Scene5(internal val game: JoltSphereMain) : Screen {
internal var world: World = World(Vector2(0f, -9.8f), false) //ignore inactive objects false
internal var debugRender: Box2DDebugRenderer = Box2DDebugRenderer()
internal var contLis: StreamBeamContactListener = StreamBeamContactListener()
internal var ent: WorldEntities = WorldEntities()
internal var streamBeam: StreamBeamTowedPlayer
internal var otherPlayer: MountainClimbingPlayer
internal lateinit var map: TiledMap
internal var mapProp: MapProperties
internal var mapWidth: Int = 0
internal var mapHeight: Int = 0
internal var ppm = JoltSphereMain.ppm
init {
ent.createFlatPlatform(world)
world = ent.world
world.setContactListener(contLis)
try {
map = TmxMapLoader().load("testing/test_map.tmx")
} catch (e: Exception) {
println("Sumthin Broke")
}
mapProp = map.properties
mapWidth = mapProp.get("width", Int::class.java) as Int * 320
mapHeight = mapProp.get("height", Int::class.java) as Int * 320
MapBodyBuilder.buildShapes(map, ppm, world, "terrain")
streamBeam = StreamBeamTowedPlayer(world, 450f, (mapHeight / 1.8f), Color.RED)
otherPlayer = MountainClimbingPlayer(world, 500f, (mapHeight / 1.8f), Color.BLUE)
val dDef = DistanceJointDef()
dDef.collideConnected = true
dDef.bodyA = streamBeam.body
dDef.length = 150 / ppm
dDef.frequencyHz = 3f
dDef.dampingRatio = 0.4f
dDef.bodyB = otherPlayer.body
dDef.localAnchorA.set(0f, 0f)
dDef.localAnchorB.set(0f, 0f)
world.createJoint(dDef)
}
private fun update(dt: Float) {
streamBeam.input(Keys.P, Keys.P, Keys.P, Keys.P, Keys.LEFT, Keys.RIGHT, Keys.UP)
streamBeam.reverseMovement(Keys.W, Keys.A, Keys.D)
otherPlayer.input(Keys.W, Keys.S, Keys.A, Keys.D, Keys.SHIFT_LEFT, true)
}
override fun render(dt: Float) {
update(dt)
Gdx.gl.glClearColor(0f, 0f, 0f, 1f)
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)
world.step(dt, 6, 2)
streamBeam.update(dt, 1)
otherPlayer.update(dt, 1)
game.shapeRender.begin(ShapeType.Filled)
streamBeam.shapeRender(game.shapeRender)
otherPlayer.shapeRender(game.shapeRender)
game.shapeRender.end()
debugRender.render(world, game.phys2DCam.combined)
game.batch.begin()
game.font.draw(game.batch, "" + Gdx.graphics.framesPerSecond, game.width * 0.27f, game.height * 0.85f)
game.batch.end()
game.cam.position.x = otherPlayer.body.position.x * ppm
game.cam.position.y = otherPlayer.body.position.y * ppm
game.phys2DCam.position.x = otherPlayer.body.position.x
game.phys2DCam.position.y = otherPlayer.body.position.y
game.cam.zoom = 1f
game.phys2DCam.zoom = 1f
game.cam.update()
game.phys2DCam.update()
}
override fun dispose() {
}
override fun resize(width: Int, height: Int) {
game.resize(width, height)
}
override fun show() {}
override fun pause() {}
override fun resume() {}
override fun hide() {}
} | agpl-3.0 | e8712401aad589a38921e1e1c2134cd9 | 30.231343 | 110 | 0.689532 | 3.513014 | false | false | false | false |
jayway/rest-assured | modules/kotlin-extensions/src/main/kotlin/io/restassured/module/kotlin/extensions/RestAssuredKotlinExtensions.kt | 2 | 2954 | /*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("FunctionName")
package io.restassured.module.kotlin.extensions
import io.restassured.RestAssured.`when`
import io.restassured.RestAssured.given
import io.restassured.internal.ResponseSpecificationImpl
import io.restassured.internal.ValidatableResponseImpl
import io.restassured.response.ExtractableResponse
import io.restassured.response.Response
import io.restassured.response.ValidatableResponse
import io.restassured.specification.RequestSender
import io.restassured.specification.RequestSpecification
// Main wrappers
/**
* A wrapper around [given] that starts building the request part of the test.
* @see given
*/
fun Given(block: RequestSpecification.() -> RequestSpecification): RequestSpecification = given().run(block)
/**
* A wrapper around [RequestSpecification.when] that configures how the request is dispatched.
* @see RequestSpecification.when
*/
infix fun RequestSpecification.When(block: RequestSpecification.() -> Response): Response = `when`().run(block)
/**
* A wrapper around [io.restassured.RestAssured.when] that configures how the request is dispatched.
* @see io.restassured.RestAssured.when
*/
fun When(block: RequestSender.() -> Response): Response = `when`().run(block)
/**
* A wrapper around [then] that allow configuration of response expectations.
* @see then
*/
infix fun Response.Then(block: ValidatableResponse.() -> Unit): ValidatableResponse = then()
.also(doIfValidatableResponseImpl {
forceDisableEagerAssert()
})
.apply(block)
.also(doIfValidatableResponseImpl {
forceValidateResponse()
})
/**
* A wrapper around [ExtractableResponse] that allow for extract data out of the response
* @see ExtractableResponse
*/
infix fun <T> Response.Extract(block: ExtractableResponse<Response>.() -> T): T = then().extract().run(block)
/**
* A wrapper around [ExtractableResponse] that allow for extract data out of the response
* @see ExtractableResponse
*/
infix fun <T> ValidatableResponse.Extract(block: ExtractableResponse<Response>.() -> T): T = extract().run(block)
// End main wrappers
private fun doIfValidatableResponseImpl(fn: ResponseSpecificationImpl.() -> Unit): (ValidatableResponse) -> Unit = { resp ->
if (resp is ValidatableResponseImpl) {
fn(resp.responseSpec)
}
} | apache-2.0 | e743373c94be501c23a6389efd4e739d | 35.036585 | 124 | 0.744753 | 4.25036 | false | false | false | false |
InfiniteSoul/ProxerAndroid | src/main/kotlin/me/proxer/app/chat/pub/message/ChatReportViewModel.kt | 1 | 1732 | package me.proxer.app.chat.pub.message
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import me.proxer.app.util.ErrorUtils
import me.proxer.app.util.extension.buildOptionalSingle
import me.proxer.app.util.extension.safeInject
import me.proxer.app.util.extension.subscribeAndLogErrors
import me.proxer.library.ProxerApi
import org.koin.core.KoinComponent
/**
* @author Ruben Gees
*/
class ChatReportViewModel : ViewModel(), KoinComponent {
val data = MutableLiveData<Unit?>()
val error = MutableLiveData<ErrorUtils.ErrorAction?>()
val isLoading = MutableLiveData<Boolean?>()
private val api by safeInject<ProxerApi>()
private var dataDisposable: Disposable? = null
override fun onCleared() {
dataDisposable?.dispose()
dataDisposable = null
super.onCleared()
}
fun sendReport(messageId: String, message: String) {
if (isLoading.value != true) {
dataDisposable?.dispose()
dataDisposable = api.chat.reportMessage(messageId, message)
.buildOptionalSingle()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe {
error.value = null
isLoading.value = true
}
.doAfterTerminate { isLoading.value = false }
.subscribeAndLogErrors({
data.value = Unit
}, {
error.value = ErrorUtils.handle(it)
})
}
}
}
| gpl-3.0 | a63351a1f003dc78cff31ab233c984f8 | 31.074074 | 71 | 0.647229 | 5.109145 | false | false | false | false |
handstandsam/ShoppingApp | app/src/main/java/com/handstandsam/shoppingapp/repository/SessionManager.kt | 1 | 1087 | package com.handstandsam.shoppingapp.repository
import com.handstandsam.shoppingapp.cart.ShoppingCart
import com.handstandsam.shoppingapp.models.User
import com.handstandsam.shoppingapp.preferences.UserPreferences
import kotlinx.coroutines.flow.MutableStateFlow
import timber.log.Timber
class SessionManager(
private val cart: ShoppingCart,
private val userPreferences: UserPreferences
) {
val currentUser = MutableStateFlow(userPreferences.getRememberedUser())
fun updateCurrentUser(user: User?) {
Timber.d("setCurrentUser: $user")
if (userPreferences.rememberMe) {
// Save to disk if we want to remember them
userPreferences.updateRememberedUser(user)
}
currentUser.value = user
}
val isLoggedIn: Boolean
get() {
val loggedIn = currentUser.value != null
Timber.d("isLoggedIn: $loggedIn")
return loggedIn
}
suspend fun logout() {
currentUser.value = null
userPreferences.updateRememberedUser(null)
cart.empty()
}
}
| apache-2.0 | 4b79a4296eda77b578e8e44a73792765 | 27.605263 | 75 | 0.689972 | 5.079439 | false | false | false | false |
bastman/kotlin-spring-jpa-examples | src/main/kotlin/com/example/demo/api/realestate/handler/brokers/crud/update/UpdateBrokerHandler.kt | 1 | 2771 | package com.example.demo.api.realestate.handler.brokers.crud.update
import com.example.demo.api.common.validation.validateRequest
import com.example.demo.api.realestate.domain.jpa.entities.Broker
import com.example.demo.api.realestate.domain.jpa.entities.BrokerAddress
import com.example.demo.api.realestate.domain.jpa.services.JpaBrokerService
import com.example.demo.api.realestate.handler.common.response.BrokerResponse
import com.example.demo.util.fp.pipe
import org.springframework.stereotype.Component
import org.springframework.validation.Validator
import java.util.*
@Component
class UpdateBrokerHandler(
private val validator: Validator,
private val jpaBrokerService: JpaBrokerService
) {
fun handle(brokerId: UUID, request: UpdateBrokerRequest): BrokerResponse =
execute(
brokerId = brokerId,
request = validator.validateRequest(request, "request")
)
private fun execute(brokerId: UUID, request: UpdateBrokerRequest): BrokerResponse {
val property = jpaBrokerService.getById(brokerId)
.copyWithUpdateRequest(request)
return BrokerResponse.of(
broker = jpaBrokerService.update(property)
)
}
}
private fun Broker.copyWithUpdateRequest(req: UpdateBrokerRequest): Broker =
this.pipe {
if (req.email != null) it.copy(email = req.email) else it
}.pipe {
if (req.companyName != null) it.copy(companyName = req.companyName.trim()) else it
}.pipe {
if (req.comment != null) it.copy(comment = req.comment.trim()) else it
}.pipe {
if (req.firstName != null) it.copy(firstName = req.firstName.trim()) else it
}.pipe {
if (req.lastName != null) it.copy(firstName = req.lastName.trim()) else it
}.pipe {
if (req.phoneNumber != null) it.copy(phoneNumber = req.phoneNumber.trim()) else it
}.pipe {
if (req.address != null) {
it.copy(address = it.address.copyWithUpdateRequest(req.address))
} else {
it
}
}
private fun BrokerAddress.copyWithUpdateRequest(
req: UpdateBrokerRequest.UpdateBrokerAddress
): BrokerAddress =
this.pipe {
if (req.country != null) it.copy(country = req.country.trim()) else it
}.pipe {
if (req.city != null) it.copy(city = req.city.trim()) else it
}.pipe {
if (req.state != null) it.copy(state = req.state.trim()) else it
}.pipe {
if (req.street != null) it.copy(street = req.street.trim()) else it
}.pipe {
if (req.number != null) it.copy(number = req.number.trim()) else it
}
| mit | 3f9b5aa12e0ebf07692a8c4a29afe61a | 39.75 | 94 | 0.63515 | 4.117385 | false | false | false | false |
ThomasVadeSmileLee/cyls | src/main/kotlin/org/smileLee/cyls/qqbot/MatchingVerifier.kt | 1 | 2388 | package org.smileLee.cyls.qqbot
class MatchingVerifier<T : QQBot<T>>(
val nodes: ArrayList<VerifyNode<T>>
) {
fun findAndRun(string: String, cyls: T) = nodes.any {
it.verifyAndRun(string, cyls)
}
operator fun VerifyNode<T>.unaryPlus() {
nodes.add(this@unaryPlus)
}
}
interface VerifyNode<T : QQBot<T>> {
fun matches(string: String, cyls: T): Boolean
fun verifyAndRun(string: String, cyls: T): Boolean
}
interface PathNode<T : QQBot<T>> : VerifyNode<T> {
val children: ArrayList<VerifyNode<T>>
}
interface RunnerNode<T : QQBot<T>> : VerifyNode<T> {
val runner: (String, T) -> Unit
override fun verifyAndRun(string: String, cyls: T) = if (matches(string, cyls)) {
runner(string, cyls)
true
} else false
}
open class AnyRunnerNode<T : QQBot<T>>(
override val children: ArrayList<VerifyNode<T>>,
override val runner: (String, T) -> Unit
) : RunnerNode<T>, PathNode<T> {
override fun matches(string: String, cyls: T) = children.any { it.matches(string, cyls) }
}
open class AllRunnerNode<T : QQBot<T>>(
override val children: ArrayList<VerifyNode<T>>,
override val runner: (String, T) -> Unit
) : RunnerNode<T>, PathNode<T> {
override fun matches(string: String, cyls: T) = children.all { it.matches(string, cyls) }
}
open class EqualNode<T : QQBot<T>>(
val string: String,
override val runner: (String, T) -> Unit
) : RunnerNode<T> {
override fun matches(string: String, cyls: T) = string == this.string
}
open class ContainNode<T : QQBot<T>>(
val subString: String,
override val runner: (String, T) -> Unit
) : RunnerNode<T> {
override fun matches(string: String, cyls: T) = string.contains(subString)
}
open class RegexNode<T : QQBot<T>>(
val regex: String,
override val runner: (String, T) -> Unit
) : RunnerNode<T> {
override fun matches(string: String, cyls: T) = string.matches(regex.toRegex())
}
open class ContainRegexNode<T : QQBot<T>>(
val regex: String,
override val runner: (String, T) -> Unit
) : RunnerNode<T> {
override fun matches(string: String, cyls: T) = string.contains(regex.toRegex())
}
open class DefaultRunnerNode<T : QQBot<T>>(
override val runner: (String, T) -> Unit
) : RunnerNode<T> {
override fun matches(string: String, cyls: T) = true
} | mit | deaf87a69229979a164885f5fa469a3e | 29.628205 | 93 | 0.643216 | 3.235772 | false | false | false | false |
REDNBLACK/advent-of-code2016 | src/main/kotlin/day13/Advent13.kt | 1 | 3119 | package day13
import day13.Pos.Pos2D
import java.util.*
/**
--- Day 13: A Maze of Twisty Little Cubicles ---
You arrive at the first floor of this new building to discover a much less welcoming environment than the shiny atrium of the last one. Instead, you are in a maze of twisty little cubicles, all alike.
Every location in this area is addressed by a pair of non-negative integers (x,y). Each such coordinate is either a wall or an open space. You can't move diagonally. The cube maze starts at 0,0 and seems to extend infinitely toward positive x and y; negative values are invalid, as they represent a location outside the building. You are in a small waiting area at 1,1.
While it seems chaotic, a nearby morale-boosting poster explains, the layout is actually quite logical. You can determine whether a given x,y coordinate will be a wall or an open space using a simple system:
Find x*x + 3*x + 2*x*y + y + y*y.
Add the office designer's favorite number (your puzzle input).
Find the binary representation of that sum; count the number of bits that are 1.
If the number of bits that are 1 is even, it's an open space.
If the number of bits that are 1 is odd, it's a wall.
For example, if the office designer's favorite number were 10, drawing walls as # and open spaces as ., the corner of the building containing 0,0 would look like this:
0123456789
0 .#.####.##
1 ..#..#...#
2 #....##...
3 ###.#.###.
4 .##..#..#.
5 ..##....#.
6 #...##.###
Now, suppose you wanted to reach 7,4. The shortest route you could take is marked as O:
0123456789
0 .#.####.##
1 .O#..#...#
2 #OOO.##...
3 ###O#.###.
4 .##OO#OO#.
5 ..##OOO.#.
6 #...##.###
Thus, reaching 7,4 would take a minimum of 11 steps (starting from your current location, 1,1).
What is the fewest number of steps required for you to reach 31,39?
--- Part Two ---
How many locations (distinct x,y coordinates, including your starting location) can you reach in at most 50 steps?
*/
fun main(args: Array<String>) {
println(findShortestPath(10, Pos(7, 4)).first == 11)
println(findShortestPath(1362, Pos(31, 39)))
//138
}
fun findShortestPath(size: Int, endPos: Pos): Pair<Int?, Int?> {
val positions = sequenceOf(Pos(1, 1, 0)).toCollection(LinkedList())
val visited = hashMapOf<Pos2D, Int>()
while (positions.isNotEmpty()) {
val curPos = positions.pop()
visited.put(curPos.to2D(), curPos.z)
positions += curPos.next(size).filter { it.to2D() !in visited || visited[it.to2D()] ?: 0 > it.z }
}
return visited[endPos.to2D()] to visited.count { it.value <= 50 }
}
data class Pos(val x: Int, val y: Int, val z: Int = 0) {
data class Pos2D(val x: Int, val y: Int)
fun to2D() = Pos2D(x, y)
fun isWall(size: Int) = Integer.toBinaryString(x * x + 3 * x + 2 * x * y + y + y * y + size)
.count { it == '1' } % 2 != 0
fun next(size: Int) = listOf(
Pos(x, y + 1, z + 1),
Pos(x, y - 1, z + 1),
Pos(x + 1, y, z + 1),
Pos(x - 1, y, z + 1)
)
.filter { !it.isWall(size) }
}
| mit | c2fe02db133b39ba92c431b2fed7a723 | 37.506173 | 369 | 0.633857 | 3.286617 | false | false | false | false |
Schlangguru/paperless-uploader | app/src/main/java/de/schlangguru/paperlessuploader/ui/main/MainView.kt | 1 | 4865 | package de.schlangguru.paperlessuploader.ui.main
import android.Manifest
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.content.Intent
import android.content.pm.PackageManager
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v4.content.ContextCompat
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.text.InputType
import android.view.Menu
import android.view.MenuItem
import android.widget.EditText
import android.widget.Toast
import de.schlangguru.paperlessuploader.R
import de.schlangguru.paperlessuploader.databinding.MainActivityBinding
import de.schlangguru.paperlessuploader.model.Document
import de.schlangguru.paperlessuploader.ui.settings.SettingsActivity
import kotlinx.android.synthetic.main.main_activity.*
class MainView : AppCompatActivity() {
private val PERMISSION_REQ_READ_EXTERNAL_STORAGE = 1
lateinit var vm: MainViewModel
lateinit var binding: MainActivityBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setupBindings()
setupEventObservers()
setSupportActionBar(toolbar)
processIntent()
vm.connectPaperless()
}
private fun setupBindings() {
vm = ViewModelProviders.of(this).get(MainViewModel::class.java)
binding = DataBindingUtil.setContentView(this, R.layout.main_activity)
binding.vm = vm
}
private fun setupEventObservers() {
vm.showCorrespondentsEvent.observe(this, Observer { doc ->
val correspondents = ArrayList<String>()
correspondents.addAll(vm.correspondents.toTypedArray())
correspondents.add("New...")
AlertDialog.Builder(this)
.setTitle("Correspondents")
.setItems(correspondents.toTypedArray()) { dialog, itemIdx ->
doc?.let {
if (itemIdx == vm.correspondents.size) {
dialog.dismiss()
createNewCorrespondent(doc)
} else {
it.correspondent.set(vm.correspondents[itemIdx])
}
}
}
.show()
})
}
private fun createNewCorrespondent(doc: Document) {
val input = EditText(this)
input.inputType = InputType.TYPE_CLASS_TEXT
AlertDialog.Builder(this)
.setTitle("New Correspondent")
.setView(input)
.setPositiveButton("OK", { _, _ -> doc.correspondent.set(input.text.toString()) })
.setNegativeButton("Cancel", { dialog, _ -> dialog.cancel() })
.show()
}
private fun processIntent() {
when (intent.action) {
Intent.ACTION_SEND -> enqueuePDFs(intent)
Intent.ACTION_SEND_MULTIPLE -> enqueuePDFs(intent)
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.itemId
when (id) {
R.id.action_settings -> showSettings()
R.id.action_refresh -> vm.connectPaperless()
}
return super.onOptionsItemSelected(item)
}
private fun showSettings() {
val intent = Intent(this, SettingsActivity::class.java)
startActivity(intent)
}
private fun enqueuePDFs(intent: Intent) {
// Check Permissions
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), PERMISSION_REQ_READ_EXTERNAL_STORAGE)
}
// Has Permission
else {
for (i in 0 until intent.clipData.itemCount) {
val uri = intent.clipData.getItemAt(i).uri
vm.enqueueDocument(uri)
}
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
if (requestCode == PERMISSION_REQ_READ_EXTERNAL_STORAGE) {
if (grantResults.size == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
processIntent()
} else {
Snackbar.make(rootLayout, "Permission denied. Can't read documents from storage.", Snackbar.LENGTH_SHORT).show()
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
}
}
| mit | f9dd5659e5373089721b6f4720c804f6 | 35.037037 | 134 | 0.634738 | 4.835984 | false | false | false | false |
PassionateWsj/YH-Android | app/src/main/java/com/intfocus/template/scanner/ScannerMode.kt | 1 | 3643 | package com.intfocus.template.scanner
import android.content.Context
import com.google.gson.Gson
import com.intfocus.template.constant.Params.USER_BEAN
import com.intfocus.template.util.FileUtil
import com.intfocus.template.util.HttpUtil
import com.intfocus.template.util.K
import com.intfocus.template.util.TempHost
import com.zbl.lib.baseframe.core.AbstractMode
import org.greenrobot.eventbus.EventBus
import org.xutils.common.Callback
import org.xutils.common.Callback.CancelledException
import org.xutils.common.task.PriorityExecutor
import org.xutils.http.RequestParams
import org.xutils.x
import java.io.File
import java.util.*
/**
* 扫码结果页 model
* @author Liurl21
* create at 2017/7/6 下午3:18
*/
class ScannerMode(var ctx: Context) : AbstractMode() {
var result: String? = null
var mUserSP = ctx.getSharedPreferences(USER_BEAN, Context.MODE_PRIVATE)
var gson = Gson()
var jsUrl = ""
var htmlUrl = ""
var store_id = ""
var currentBarcode = ""
fun requestData(barcode: String, storeId: String) {
currentBarcode = barcode
jsUrl = String.format(K.API_BAR_CODE_SCAN_DATA, TempHost.getHost(), storeId, barcode)
htmlUrl = String.format(K.API_BAR_CODE_SCAN_VIEW, TempHost.getHost(), storeId, barcode)
store_id = storeId
requestData()
}
override fun requestData() {
if (!jsUrl.isEmpty()) {
val params = RequestParams(jsUrl)
val jsFileName = String.format("store_%s_barcode_%s.js", store_id, currentBarcode)
val jsPath = String.format("%s/assets/javascripts/%s", FileUtil.sharedPath(ctx), jsFileName)
params.isAutoRename = false
params.saveFilePath = jsPath
params.executor = PriorityExecutor(2, true)
x.http().get(params, object : Callback.CommonCallback<File> {
override fun onCancelled(p0: CancelledException?) {}
override fun onError(p0: Throwable?, p1: Boolean) {
val result1 = ScannerRequest(false, 400)
result1.errorInfo = p0.toString()
EventBus.getDefault().post(result1)
}
override fun onFinished() {
}
override fun onSuccess(p0: File?) {
getHtml()
}
})
}
}
private fun getHtml() {
Thread(Runnable {
val htmlName = String.format("mobile_v2_store_%s_barcode_%s.html", store_id, currentBarcode)
val htmlPath = String.format("%s/%s", FileUtil.dirPath(ctx, K.K_HTML_DIR_NAME), htmlName)
val response = HttpUtil.httpGet(ctx, htmlUrl, HashMap<String, String>())
if (response["code"].equals("200")) {
var htmlContent = response["body"]
htmlContent = htmlContent!!.replace("/javascripts/", String.format("%s/javascripts/", "../../Shared/assets"))
htmlContent = htmlContent.replace("/stylesheets/", String.format("%s/stylesheets/", "../../Shared/assets"))
htmlContent = htmlContent.replace("/images/", String.format("%s/images/", "../../Shared/assets"))
FileUtil.writeFile(htmlPath, htmlContent)
val result1 = ScannerRequest(true, 200)
result1.htmlPath = htmlPath
EventBus.getDefault().post(result1)
} else {
val result1 = ScannerRequest(false, 400)
result1.errorInfo = response["code"] + response["body"]
EventBus.getDefault().post(result1)
}
}).start()
}
}
| gpl-3.0 | 1978a6600a52987b557cb9cd26d170a9 | 38.021505 | 125 | 0.616423 | 4.195376 | false | false | false | false |
trife/Field-Book | app/src/main/java/com/fieldbook/tracker/database/dao/ObservationVariableValueDao.kt | 1 | 2133 | package com.fieldbook.tracker.database.dao
import android.content.ContentValues
import androidx.core.content.contentValuesOf
import com.fieldbook.tracker.database.*
import com.fieldbook.tracker.database.Migrator.ObservationVariable
import com.fieldbook.tracker.database.Migrator.ObservationVariableValue
class ObservationVariableValueDao {
companion object {
fun getVariableValues(id: Int) = withDatabase { db ->
return@withDatabase db.query(ObservationVariableValue.tableName,
where = "${ObservationVariable.FK} = ?",
whereArgs = arrayOf("$id")).toTable()
}
fun update(varId: String, attrId: String, value: String) = withDatabase { db ->
db.update(ObservationVariableValue.tableName, ContentValues().apply {
put("observation_variable_attribute_value", value)
}, "${ObservationVariable.FK} = ? AND ${Migrator.ObservationVariableAttribute.FK} = ?", arrayOf(varId, attrId))
}
fun insert(min: String, max: String, categories: String, id: String) = withDatabase { db ->
//iterate trhough mapping of the old columns that are now attr/vals
mapOf(
"validValuesMin" to min,
"validValuesMax" to max,
"category" to categories,
).asSequence().forEach { attrValue ->
//TODO: commenting this out would create a sparse table from the unused attribute values
// if (attrValue.value.isNotEmpty()) {
val attrId = ObservationVariableAttributeDao.getAttributeIdByName(attrValue.key)
db.insert(ObservationVariableValue.tableName, null, contentValuesOf(
ObservationVariable.FK to id,
Migrator.ObservationVariableAttribute.FK to attrId,
"observation_variable_attribute_value" to attrValue.value
))
// }
}
}
// fun getAll() = withDatabase { it.query(ObservationVariableValue.tableName).toTable() }
}
} | gpl-2.0 | 21004d6e4680fd23adf732f7b33eee16 | 36.438596 | 123 | 0.62166 | 5.152174 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/kotlin-intellij/main/uk/co/reecedunn/intellij/plugin/core/vfs/VirtualFileExt.kt | 1 | 2368 | /*
* Copyright (C) 2018, 2020 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.core.vfs
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiManager
import com.intellij.testFramework.LightVirtualFileBase
import uk.co.reecedunn.intellij.plugin.core.io.decode
fun VirtualFile.toPsiFile(project: Project): PsiFile? = PsiManager.getInstance(project).findFile(this)
@Suppress("UNNECESSARY_SAFE_CALL", "RedundantNullableReturnType") // IntelliJ 2021.1 makes this non-null.
fun VirtualFile.decode(): String? = when (this) {
is EditedVirtualFile -> contents // Avoid String => InputStream => String round-trips.
else -> inputStream?.decode(charset)
}
val VirtualFile.originalFile: VirtualFile
get() = (this as? LightVirtualFileBase)?.originalFile ?: this
fun VirtualFile.isAncestorOf(file: VirtualFile): Boolean {
val fileParent = file.parent ?: return false
return this == fileParent || isAncestorOf(fileParent)
}
fun VirtualFile.relativePathTo(file: VirtualFile): String? = when (isAncestorOf(file)) {
true -> relativePathTo(file.parent, file.name)
else -> null
}
private fun VirtualFile.relativePathTo(file: VirtualFile?, path: String): String {
if (file == null || this == file) return path
return relativePathTo(file.parent, "${file.name}/$path")
}
fun VirtualFile.replace(oldValue: String, newValue: String, ignoreCase: Boolean = false): VirtualFile = when (this) {
is EditedVirtualFile -> EditedVirtualFile(
original,
contents.replace(oldValue, newValue, ignoreCase),
modificationStamp + 1
)
else -> EditedVirtualFile(
this,
decode()!!.replace(oldValue, newValue, ignoreCase),
modificationStamp + 1
)
}
| apache-2.0 | 231f6bc8e76a7a4b1e16b96ca0e035f6 | 37.193548 | 117 | 0.73353 | 4.251346 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/remote/notification/NotificationRemoteDataSourceImpl.kt | 1 | 2290 | package org.stepik.android.remote.notification
import io.reactivex.Completable
import io.reactivex.Single
import org.stepic.droid.model.NotificationCategory
import org.stepic.droid.notifications.model.Notification
import org.stepic.droid.notifications.model.NotificationStatuses
import ru.nobird.android.core.model.PagedList
import org.stepik.android.data.notification.source.NotificationRemoteDataSource
import org.stepik.android.remote.base.mapper.toPagedList
import org.stepik.android.remote.notification.model.NotificationRequest
import org.stepik.android.remote.notification.model.NotificationResponse
import org.stepik.android.remote.notification.model.NotificationStatusesResponse
import org.stepik.android.remote.notification.service.NotificationService
import javax.inject.Inject
class NotificationRemoteDataSourceImpl
@Inject
constructor(
private val notificationService: NotificationService
) : NotificationRemoteDataSource {
override fun putNotifications(vararg notificationIds: Long, isRead: Boolean): Completable =
Completable.concat(notificationIds.map { id ->
val notification = Notification()
notification.isUnread = !isRead
notificationService.putNotification(id, NotificationRequest(notification))
})
override fun getNotifications(notificationCategory: NotificationCategory, page: Int): Single<PagedList<Notification>> =
notificationService
.getNotifications(page, type = getNotificationCategoryString(notificationCategory))
.map { it.toPagedList(NotificationResponse::notifications) }
override fun markNotificationAsRead(notificationCategory: NotificationCategory): Completable =
notificationService
.markNotificationAsRead(getNotificationCategoryString(notificationCategory))
override fun getNotificationStatuses(): Single<List<NotificationStatuses>> =
notificationService
.getNotificationStatuses()
.map(NotificationStatusesResponse::notificationStatuses)
private fun getNotificationCategoryString(notificationCategory: NotificationCategory): String? =
if (notificationCategory === NotificationCategory.all) {
null
} else {
notificationCategory.name
}
} | apache-2.0 | 94de0ad7a3d7ab3ac36b551ba018d3b2 | 44.82 | 123 | 0.783406 | 5.612745 | false | false | false | false |
walleth/walleth | app/src/main/java/org/walleth/startup/StartupActivity.kt | 1 | 2500 | package org.walleth.startup
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.kethereum.model.Address
import org.koin.android.ext.android.inject
import org.koin.androidx.viewmodel.ext.android.viewModel
import org.ligi.kaxt.startActivityFromClass
import org.ligi.kaxtui.alert
import org.walleth.accounts.CreateAccountActivity
import org.walleth.data.EXTRA_KEY_ADDRESS
import org.walleth.data.addresses.CurrentAddressProvider
import org.walleth.overview.OverviewActivity
import org.walleth.startup.StartupStatus.*
class StartupActivity : AppCompatActivity() {
private val currentAddressProvider: CurrentAddressProvider by inject()
private val viewModel: StartupViewModel by viewModel()
private val createAccountActionForResult = registerForActivityResult(StartActivityForResult()) {
if (it.resultCode == Activity.RESULT_OK && it.data != null) {
val addressString = it.data?.getStringExtra(EXTRA_KEY_ADDRESS) ?: throw IllegalStateException("No EXTRA_KEY_ADDRESS in onActivityResult")
val address = Address(addressString)
lifecycleScope.launch(Dispatchers.Main) {
currentAddressProvider.setCurrent(address)
startActivityFromClass(OverviewActivity::class.java)
finish()
}
} else {
finish()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel.status.observe(this, Observer<StartupStatus> { status ->
when (status) {
is NeedsAddress -> {
createAccountActionForResult.launch(Intent(this, CreateAccountActivity::class.java))
}
is HasChainAndAddress -> {
startActivityFromClass(OverviewActivity::class.java)
finish()
}
is Timeout -> {
alert("chain must not be null - this should never happen - please let [email protected] if you see this. Thanks and sorry for the noise.") {
finish()
}
}
}
})
}
} | gpl-3.0 | 8c591c92ac72a25c3143d366bace0358 | 36.893939 | 162 | 0.6816 | 5.219207 | false | false | false | false |
Obaied/Dinger-kotlin | app/src/main/java/com/obaied/sohan/ui/base/BaseActivity.kt | 1 | 1195 | package com.joseph.sohan.ui.base
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.joseph.sohan.GlobalApplication
import com.joseph.sohan.injection.component.ActivityComponent
import com.joseph.sohan.injection.component.DaggerActivityComponent
import com.joseph.sohan.injection.module.ActivityModule
/**
* Created by ab on 19/03/2017.
*/
open class BaseActivity : AppCompatActivity() {
private var mActivityComponent: ActivityComponent? = null
private var isAttachToWindow = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mActivityComponent = DaggerActivityComponent.builder()
.activityModule(ActivityModule(this))
.applicationComponent(GlobalApplication.globalApp.mApplicationComponent)
.build()
}
fun activityComponent(): ActivityComponent? {
return mActivityComponent
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
isAttachToWindow = true
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
isAttachToWindow = false
}
}
| mit | 6611c368b12a4bd4b1ab6135d29cdde3 | 27.452381 | 88 | 0.725523 | 4.958506 | false | false | false | false |
GDGLima/CodeLab-Kotlin-Infosoft-2017 | Infosoft2017/app/src/main/java/com/emedinaa/infosoft2017/helpers/Extensions.kt | 1 | 1091 | package com.emedinaa.infosoft2017.helpers
/**
* Created by emedinaa on 5/09/17.
* Extensions
* https://kotlinlang.org/docs/reference/extensions.html
*/
fun formatDate(value:String):String{
val separate = value.split("/".toRegex())
val year:String= separate[0]
val month:String = separate[1]
val day:String= separate[2]
val sb = StringBuilder()
sb.append(day).append(" ").append(monthByValue(month))
return sb.toString()
}
fun monthByValue(month:String):String{
when(month){
"01"-> return "ENE"
"02"-> return "FEB"
"03"-> return "MAR"
"04"-> return "ABR"
"05"-> return "MAY"
"06"-> return "JUN"
"07"-> return "JUL"
"08"-> return "AGO"
"09"-> return "SEP"
"10"-> return "OCT"
"11"-> return "NOV"
"12"-> return "DIC"
}
return ""
}
fun dateByValue(day:String):String{
when(day){
"01"-> "Lun"
"02"-> "Mar"
"03"-> "Mie"
"04"-> "Jue"
"05"-> "Vie"
"06"-> "Sab"
"07"-> "Dom"
}
return ""
} | apache-2.0 | b03e256631e71df3123f522cca20dcdd | 21.75 | 58 | 0.522456 | 3.316109 | false | false | false | false |
GKZX-HN/MyGithub | app/src/main/java/com/gkzxhn/mygithub/ui/fragment/StarsFragment.kt | 1 | 3189 | package com.gkzxhn.mygithub.ui.fragment
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.Toolbar
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import com.gkzxhn.balabala.base.BaseFragment
import com.gkzxhn.balabala.mvp.contract.BaseView
import com.gkzxhn.mygithub.R
import com.gkzxhn.mygithub.base.App
import com.gkzxhn.mygithub.bean.info.Repo
import com.gkzxhn.mygithub.bean.info.Starred
import com.gkzxhn.mygithub.di.module.OAuthModule
import com.gkzxhn.mygithub.extension.dp2px
import com.gkzxhn.mygithub.mvp.presenter.StarsPresenter
import com.gkzxhn.mygithub.ui.adapter.StarsAdapter
import com.ldoublem.loadingviewlib.view.LVGhost
import kotlinx.android.synthetic.main.fragment_stars.*
import javax.inject.Inject
/**
* Created by Xuezhi on 2017/10/25.
*/
class StarsFragment : BaseFragment(), BaseView {
private lateinit var stars: Starred
private lateinit var loading: LVGhost
private lateinit var repo: Repo
@Inject
lateinit var presenter: StarsPresenter
private lateinit var adapter: StarsAdapter
override fun launchActivity(intent: Intent) {
}
override fun showLoading() {
loading = LVGhost(context)
val params = FrameLayout.LayoutParams(300f.dp2px().toInt(), 150f.dp2px().toInt(), Gravity.CENTER)
loading.layoutParams = params
loading.startAnim()
fl_stars.addView(loading)
}
override fun hideLoading() {
loading.stopAnim()
fl_stars.removeView(loading)
}
override fun showMessage() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun killMyself() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun initContentView() {
adapter = StarsAdapter(null)
rv_stars.layoutManager = LinearLayoutManager(context)
rv_stars.adapter = adapter
// val full_name = stars.full_name
// val description = stars.description
var intent: Intent
intent = Intent()
//repo = intent.getParcelableExtra<Repo>(IntentConstant.REPO)
// val username = repo.owner.login
presenter.getStarrde()
}
override fun initView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
return inflater!!.inflate(R.layout.fragment_stars, container, false)
}
override fun getStatusBar(): View? {
return status_view_stars
}
override fun getToolbar(): Toolbar? {
return toolbar_stars
}
override fun setupComponent() {
App.getInstance()
.baseComponent
.plus(OAuthModule(this))
.inject(this)
}
fun loadData(stars: List<Starred>) {
Log.i(javaClass.simpleName, stars[0].toString())
adapter.setNewData(stars)
}
fun getNewData() {
presenter.getStarrde()
}
} | gpl-3.0 | 64847d87812336fee9e5f259d251a99c | 28.266055 | 112 | 0.699592 | 4.263369 | false | false | false | false |
shahbazahmed1269/SPOJ | src/kotlincode/ABSYS.kt | 1 | 1202 | package kotlincode
/**
* Solution to SPOJ problem ABSYS
* @see <a href="http://www.spoj.com/problems/ABSYS/">http://www.spoj.com/problems/ABSYS/</a>
* @author Shahbaz Ahmed
*
*/
fun main(a: Array<String>) {
var xPos: Int = 0
var n = readLine().toString().toInt()
while (n-- > 0) {
readLine() // Ignore empty lines in between test cases
var rawOpList = readLine().toString().trim().replace(" ", "").split(Regex("[=|+]"))
for ((i, op) in rawOpList.withIndex()) {
if (op.contains("machula", ignoreCase = true)) {
xPos = i
}
}
when (xPos) {
0 -> {
val resOp = rawOpList[2].toInt() - rawOpList[1].toInt()
println("$resOp + ${rawOpList[1]} = ${rawOpList[2]}")
}
1 -> {
val resOp = rawOpList[2].toInt() - rawOpList[0].toInt()
println("${rawOpList[0]} + $resOp = ${rawOpList[2]}")
}
2 -> {
val resOp = rawOpList[0].toInt() + rawOpList[1].toInt()
println("${rawOpList[0]} + ${rawOpList[1]} = $resOp")
}
}
}
} | gpl-3.0 | 928f71125076b68e35e509eab4eb148c | 32.416667 | 93 | 0.467554 | 3.494186 | false | false | false | false |
xiprox/Tensuu | app/src/main/java/tr/xip/scd/tensuu/local/Credentials.kt | 1 | 1516 | package tr.xip.scd.tensuu.local
import android.content.Context
import android.content.SharedPreferences
import io.realm.SyncUser
import tr.xip.scd.tensuu.App.Companion.context
import tr.xip.scd.tensuu.realm.model.User
/**
* A SharedPreferences manager object that takes care of storing user credentials.
*/
object Credentials {
private val NAME = "credentials_storage"
private val KEY_EMAIL = "email"
private val KEY_NAME = "name"
private val KEY_ADMIN = "admin"
private val KEY_MODIFY = "modify"
private var prefs: SharedPreferences
init {
prefs = context.getSharedPreferences(NAME, Context.MODE_PRIVATE)
}
var email: String?
set(value) = prefs.edit().putString(KEY_EMAIL, value).apply()
get() = prefs.getString(KEY_EMAIL, null)
var name: String?
set(value) = prefs.edit().putString(KEY_NAME, value).apply()
get() = prefs.getString(KEY_NAME, null)
var isAdmin: Boolean
set(value) = prefs.edit().putBoolean(KEY_ADMIN, value).apply()
get() = prefs.getBoolean(KEY_ADMIN, false)
var canModify: Boolean
set(value) = prefs.edit().putBoolean(KEY_MODIFY, value).apply()
get() = prefs.getBoolean(KEY_MODIFY, false)
fun loadFrom(user: User) {
email = user.email
isAdmin = user.isAdmin ?: false
canModify = user.canModify ?: false
name = user.name
}
fun logout() {
SyncUser.currentUser().logout()
prefs.edit().clear().apply()
}
} | gpl-3.0 | 409549dd45875f52f7dd22e43f1c2ecc | 27.622642 | 82 | 0.654354 | 3.937662 | false | false | false | false |
maurocchi/chesslave | backend/src/main/java/io/chesslave/visual/model/SquareImage.kt | 2 | 924 | package io.chesslave.visual.model
import io.chesslave.model.Board
import io.chesslave.model.Square
import java.awt.image.BufferedImage
class SquareImage(board: BufferedImage, val square: Square, val flipped: Boolean) {
val image: BufferedImage by lazy { board.getSubimage(left(), top(), size, size) }
val size: Int = board.width / Board.SIZE
fun left(): Int = size * horizontalOffset(square.col)
fun right(): Int = size * (horizontalOffset(square.col) + 1)
fun top(): Int = size * verticalOffset(square.row)
fun bottom(): Int = size * (verticalOffset(square.row) + 1)
fun middleX(): Int = left() + size / 2
fun middleY(): Int = top() + size / 2
private fun horizontalOffset(col: Int): Int = if (flipped) Board.SIZE - 1 - col else col
private fun verticalOffset(row: Int): Int = if (flipped) row else Board.SIZE - 1 - row
override fun toString() = square.toString()
}
| gpl-2.0 | a1847ab33c607079e364d99dcb42948b | 29.8 | 92 | 0.677489 | 3.786885 | false | false | false | false |
just-4-fun/holomorph | src/main/kotlin/just4fun/holomorph/types/enum.kt | 1 | 1799 | package just4fun.holomorph.types
import just4fun.holomorph.EnclosedEntries
import just4fun.holomorph.EntryBuilder
import just4fun.holomorph.Type
import just4fun.holomorph.evalError
import kotlin.reflect.KClass
class EnumType<T: Any>(override val typeKlas: KClass<T>, val values: Array<Enum<*>>): Type<T> {
@Suppress("UNCHECKED_CAST")
override fun newInstance(): T = values[0] as T// should not be called
override fun asInstance(v: Any): T? = when (v) {
is String -> fromName(v)
is Int -> fromOrdinal(v)
else -> null
}
@Suppress("UNCHECKED_CAST")
private fun fromName(name: String): T? = values.find { it.name == name } as? T
@Suppress("UNCHECKED_CAST")
private fun fromOrdinal(n: Int): T? = values.find { it.ordinal == n } as? T
override fun fromEntries(subEntries: EnclosedEntries, expectNames: Boolean) = evalError("Entries", this)
override fun fromEntry(value: ByteArray) = evalError("ByteArray", this)
override fun fromEntry(value: String) = fromName(value)
override fun fromEntry(value: Long) = fromOrdinal(value.toInt())
override fun fromEntry(value: Int) = fromOrdinal(value)
override fun fromEntry(value: Short) = fromOrdinal(value.toInt())
override fun fromEntry(value: Byte) = fromOrdinal(value.toInt())
override fun fromEntry(value: Double) = fromOrdinal(value.toInt())
override fun fromEntry(value: Float) = fromOrdinal(value.toInt())
override fun fromEntry(value: Boolean) = fromOrdinal(if (value) 1 else 0)
@Suppress("UNCHECKED_CAST")
override fun fromEntry(value: Char) = values.find { it.name.startsWith(value, true) } as? T
override fun toEntry(value: T, name: String?, entryBuilder: EntryBuilder) = entryBuilder.Entry(name, (value as Enum<*>).name)
override fun toString() = typeName
override fun hashCode(): Int = typeKlas.hashCode()
} | apache-2.0 | ffae15213d6318f733a07f549a98b3b5 | 39.909091 | 126 | 0.73652 | 3.562376 | false | false | false | false |
orbite-mobile/monastic-jerusalem-community | app/src/main/java/pl/orbitemobile/wspolnoty/utilities/AboutDialogBuilder.kt | 1 | 1857 | /*
* Copyright (c) 2017. All Rights Reserved. Michal Jankowski orbitemobile.pl
*/
package pl.orbitemobile.wspolnoty.utilities
import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.net.Uri
import android.support.v7.app.AlertDialog
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import pl.orbitemobile.wspolnoty.R
class AboutDialogBuilder private constructor(){
companion object {
val instance = AboutDialogBuilder()
}
fun showAboutDialog(context: Context): Dialog {
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val builder = AlertDialog.Builder(context)
val mAboutView = inflater.inflate(R.layout.about_content, null, false)
builder.setView(mAboutView)
val dialog = builder.show()
dialog.setOnDismissListener(object : DialogInterface.OnDismissListener {
override fun onDismiss(dialog: DialogInterface) {
run { (mAboutView.parent as ViewGroup).removeView(mAboutView) }
}
})
setOepnUrl(mAboutView, context)
setCloseLayout(mAboutView, dialog)
return dialog
}
private fun setOepnUrl(mAboutView: View, context: Context) {
val author_layout = mAboutView.findViewById(R.id.author_layout)
author_layout.setOnClickListener {
val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse("http://" + context.getString(R.string.author_web)))
context.startActivity(browserIntent)
}
}
private fun setCloseLayout(mAboutView: View, dialog: Dialog) {
val close_layout = mAboutView.findViewById(R.id.close_layout)
close_layout.setOnClickListener { dialog.dismiss() }
}
}
| agpl-3.0 | 12bb10e2acf7778f21635694549bc4a5 | 34.711538 | 121 | 0.710285 | 4.379717 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/internal/AbstractBytecodeToolWindowTest.kt | 3 | 1961 | // 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.idea.internal
import org.jetbrains.kotlin.config.CommonConfigurationKeys
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.config.languageVersionSettings
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils
import java.io.File
abstract class AbstractBytecodeToolWindowTest : KotlinLightCodeInsightFixtureTestCase() {
override fun getProjectDescriptor() = KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE
fun doTest(testPath: String) {
val mainDir = File(testPath)
val mainFileName = mainDir.name + ".kt"
mainDir.listFiles { _, name -> name != mainFileName }.forEach { myFixture.configureByFile(testPath + "/" + it.name) }
val mainFileText = File("$testPath/$mainFileName").readText()
myFixture.configureByText(KotlinFileType.INSTANCE, mainFileText)
val file = myFixture.file as KtFile
val configuration = CompilerConfiguration().apply {
if (InTextDirectivesUtils.getPrefixedBoolean(mainFileText, "// INLINE:") == false) {
put(CommonConfigurationKeys.DISABLE_INLINE, true)
}
languageVersionSettings = file.languageVersionSettings
}
val bytecodes = KotlinBytecodeToolWindow.getBytecodeForFile(file, configuration)
assert(bytecodes is BytecodeGenerationResult.Bytecode) {
"Exception failed during compilation:\n$bytecodes"
}
}
}
| apache-2.0 | 9e79fb2e235e717931cfe9735b37fedf | 45.690476 | 158 | 0.759816 | 5.187831 | false | true | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/history/HistoryDiffCallback.kt | 1 | 2062 | package org.wordpress.android.ui.history
import android.os.Bundle
import androidx.recyclerview.widget.DiffUtil
import org.wordpress.android.ui.history.HistoryListItem.Revision
class HistoryDiffCallback(
private val oldList: List<HistoryListItem>,
private val newList: List<HistoryListItem>
) : DiffUtil.Callback() {
companion object {
const val AVATAR_CHANGED_KEY = "avatar_changed"
const val DISPLAY_NAME_CHANGED_KEY = "display_name_changed"
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldList[oldItemPosition] == newList[newItemPosition]
}
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
val oldItem = oldList[oldItemPosition]
val newItem = newList[newItemPosition]
return when {
oldItem is Revision && newItem is Revision -> oldItem.revisionId == newItem.revisionId
else -> false
}
}
override fun getOldListSize(): Int {
return oldList.size
}
override fun getNewListSize(): Int {
return newList.size
}
// currently only things that can change in Revision are avatar and display name of author
override fun getChangePayload(oldItemPosition: Int, newItemPosition: Int): Any? {
val oldItem = oldList[oldItemPosition]
val newItem = newList[newItemPosition]
if (oldItem is Revision && newItem is Revision) {
val changesBundle = Bundle()
if (oldItem.authorAvatarURL != newItem.authorAvatarURL) {
changesBundle.putString(AVATAR_CHANGED_KEY, newItem.authorAvatarURL)
}
if (oldItem.authorDisplayName != newItem.authorDisplayName) {
changesBundle.putString(DISPLAY_NAME_CHANGED_KEY, newItem.authorDisplayName)
}
if (changesBundle.keySet().size > 0) {
return changesBundle
}
}
return super.getChangePayload(oldItemPosition, newItemPosition)
}
}
| gpl-2.0 | b4a72d666469ffa77283315e39749cfd | 35.175439 | 98 | 0.670223 | 5.066339 | false | false | false | false |
hermantai/samples | kotlin/kotlin-and-android-development-featuring-jetpack/abl-api-client/src/main/kotlin/dev/mfazio/abl/api/models/BatterBoxScoreItemApiModel.kt | 1 | 857 | package dev.mfazio.abl.api.models
data class BatterBoxScoreItemApiModel(
val playerId: String,
val teamId: String,
val firstName: String,
val lastName: String,
val number: Int = 0,
val bats: HandApiModel = HandApiModel.Right,
val throws: HandApiModel = HandApiModel.Right,
val position: PositionApiModel = PositionApiModel.Unknown,
val boxScoreLastName: String?,
val games: Int,
val plateAppearances: Int,
val atBats: Int,
val runs: Int,
val hits: Int,
val doubles: Int,
val triples: Int,
val homeRuns: Int,
val rbi: Int,
val strikeouts: Int,
val baseOnBalls: Int,
val hitByPitch: Int,
val stolenBases: Int,
val caughtStealing: Int,
val gidp: Int,
val sacrificeHits: Int,
val sacrificeFlies: Int,
val errors: Int = 0,
val passedBalls: Int = 0
) | apache-2.0 | 596e0e767eec2840c8ea1306348459d4 | 25.8125 | 62 | 0.667445 | 3.441767 | false | false | false | false |
bkmioa/NexusRss | app/src/main/java/io/github/bkmioa/nexusrss/repository/JavaNetCookieJar.kt | 1 | 4202 | /*
* Copyright (C) 2015 Square, 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 io.github.bkmioa.nexusrss.repository;
import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.HttpUrl
import java.io.IOException
import java.net.CookieHandler
import java.net.HttpCookie
import java.util.Collections
import okhttp3.internal.cookieToString
import okhttp3.internal.delimiterOffset
import okhttp3.internal.platform.Platform
import okhttp3.internal.platform.Platform.Companion.WARN
import okhttp3.internal.trimSubstring
/** A cookie jar that delegates to a [java.net.CookieHandler]. */
class JavaNetCookieJar(private val cookieHandler: CookieHandler) : CookieJar {
override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
val cookieStrings = mutableListOf<String>()
for (cookie in cookies) {
cookieStrings.add(cookieToString(cookie, true))
}
val multimap = mapOf("Set-Cookie" to cookieStrings)
try {
cookieHandler.put(url.toUri(), multimap)
} catch (e: IOException) {
Platform.get().log("Saving cookies failed for " + url.resolve("/...")!!, WARN, e)
}
}
override fun loadForRequest(url: HttpUrl): List<Cookie> {
val cookieHeaders = try {
// The RI passes all headers. We don't have 'em, so we don't pass 'em!
cookieHandler.get(url.toUri(), emptyMap<String, List<String>>())
} catch (e: IOException) {
Platform.get().log("Loading cookies failed for " + url.resolve("/...")!!, WARN, e)
return emptyList()
}
var cookies: MutableList<Cookie>? = null
for ((key, value) in cookieHeaders) {
if (("Cookie".equals(key, ignoreCase = true) || "Cookie2".equals(key, ignoreCase = true)) &&
value.isNotEmpty()
) {
for (header in value) {
if (cookies == null) cookies = mutableListOf()
cookies.addAll(decodeHeaderAsJavaNetCookies(url, header))
}
}
}
return if (cookies != null) {
Collections.unmodifiableList(cookies)
} else {
emptyList()
}
}
/**
* Convert a request header to OkHttp's cookies via [HttpCookie]. That extra step handles
* multiple cookies in a single request header, which [Cookie.parse] doesn't support.
*/
private fun decodeHeaderAsJavaNetCookies(url: HttpUrl, header: String): List<Cookie> {
val result = mutableListOf<Cookie>()
var pos = 0
val limit = header.length
var pairEnd: Int
while (pos < limit) {
pairEnd = header.delimiterOffset(";,", pos, limit)
val equalsSign = header.delimiterOffset('=', pos, pairEnd)
val name = header.trimSubstring(pos, equalsSign)
if (name.startsWith("$")) {
pos = pairEnd + 1
continue
}
// We have either name=value or just a name.
var value = if (equalsSign < pairEnd) {
header.trimSubstring(equalsSign + 1, pairEnd)
} else {
""
}
// If the value is "quoted", drop the quotes.
if (value.startsWith("\"") && value.endsWith("\"")) {
value = value.substring(1, value.length - 1)
}
result.add(
Cookie.Builder()
.name(name)
.value(value)
.domain(url.host)
.build()
)
pos = pairEnd + 1
}
return result
}
} | apache-2.0 | c41a8b46e10039fa9cc28347d4271fc8 | 35.232759 | 104 | 0.591623 | 4.494118 | false | false | false | false |
jk1/intellij-community | plugins/github/src/org/jetbrains/plugins/github/util/GithubUtil.kt | 1 | 7325 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.util
import com.intellij.concurrency.JobScheduler
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.invokeAndWaitIfNeed
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Couple
import com.intellij.openapi.util.Pair
import com.intellij.openapi.util.ThrowableComputable
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VirtualFile
import git4idea.repo.GitRemote
import git4idea.repo.GitRepository
import org.jetbrains.plugins.github.authentication.GithubAuthenticationManager
import org.jetbrains.plugins.github.exceptions.GithubMissingTokenException
import java.io.IOException
import java.net.UnknownHostException
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.TimeUnit
/**
* Various utility methods for the GutHub plugin.
*/
object GithubUtil {
@JvmField
val LOG: Logger = Logger.getInstance("github")
const val SERVICE_DISPLAY_NAME: String = "GitHub"
const val DEFAULT_TOKEN_NOTE: String = "IntelliJ Plugin"
const val GIT_AUTH_PASSWORD_SUBSTITUTE: String = "x-oauth-basic"
@JvmStatic
fun addCancellationListener(run: () -> Unit): ScheduledFuture<*> {
return JobScheduler.getScheduler().scheduleWithFixedDelay(run, 1000, 300, TimeUnit.MILLISECONDS)
}
private fun addCancellationListener(indicator: ProgressIndicator, thread: Thread): ScheduledFuture<*> {
return addCancellationListener({ if (indicator.isCanceled) thread.interrupt() })
}
@Throws(IOException::class)
@JvmStatic
fun <T> runInterruptable(indicator: ProgressIndicator,
task: ThrowableComputable<T, IOException>): T {
var future: ScheduledFuture<*>? = null
try {
val thread = Thread.currentThread()
future = addCancellationListener(indicator, thread)
return task.compute()
}
finally {
if (future != null) future.cancel(true)
Thread.interrupted()
}
}
@JvmStatic
fun getErrorTextFromException(e: Throwable): String {
return if (e is UnknownHostException) {
"Unknown host: " + e.message
}
else StringUtil.notNullize(e.message, "Unknown error")
}
/**
* Splits full commit message into subject and description in GitHub style:
* First line becomes subject, everything after first line becomes description
* Also supports empty line that separates subject and description
*
* @param commitMessage full commit message
* @return couple of subject and description based on full commit message
*/
@JvmStatic
fun getGithubLikeFormattedDescriptionMessage(commitMessage: String?): Couple<String> {
//Trim original
val message = commitMessage?.trim { it <= ' ' } ?: ""
if (message.isEmpty()) {
return Couple.of("", "")
}
val firstLineEnd = message.indexOf("\n")
val subject: String
val description: String
if (firstLineEnd > -1) {
//Subject is always first line
subject = message.substring(0, firstLineEnd).trim { it <= ' ' }
//Description is all text after first line, we also trim it to remove empty lines on start of description
description = message.substring(firstLineEnd + 1).trim { it <= ' ' }
}
else {
//If we don't have any line separators and cannot detect description,
//we just assume that it is one-line commit and use full message as subject with empty description
subject = message
description = ""
}
return Couple.of(subject, description)
}
//region Deprecated
@JvmStatic
@Deprecated("{@link GithubAuthenticationManager}")
@Throws(IOException::class)
fun getValidAuthDataHolderFromConfig(project: Project,
authLevel: AuthLevel,
indicator: ProgressIndicator): GithubAuthDataHolder {
val authManager = GithubAuthenticationManager.getInstance()
var account = authManager.getSingleOrDefaultAccount(project)
if (account == null) {
account = invokeAndWaitIfNeed(ModalityState.any()) { authManager.requestNewAccount(project) }
}
if (account == null) throw ProcessCanceledException()
return if (authLevel.authType == GithubAuthData.AuthType.ANONYMOUS) {
GithubAuthDataHolder(GithubAuthData.createAnonymous(account.server.toString()))
}
else {
val token = authManager.getTokenForAccount(account) ?: throw GithubMissingTokenException(account)
GithubAuthDataHolder(GithubAuthData.createTokenAuth(account.server.toString(), token, true))
}
}
@JvmStatic
@Deprecated("{@link GithubGitHelper}", ReplaceWith("GithubGitHelper.findGitRepository(project, file)",
"org.jetbrains.plugins.github.util.GithubGitHelper"))
fun getGitRepository(project: Project, file: VirtualFile?): GitRepository? {
return GithubGitHelper.findGitRepository(project, file)
}
@Suppress("MemberVisibilityCanBePrivate")
@JvmStatic
@Deprecated("{@link GithubGitHelper}")
fun findGithubRemoteUrl(repository: GitRepository): String? {
val remote = findGithubRemote(repository) ?: return null
return remote.getSecond()
}
@Suppress("MemberVisibilityCanBePrivate")
@JvmStatic
@Deprecated("{@link org.jetbrains.plugins.github.api.GithubServerPath}, {@link GithubGitHelper}")
fun findGithubRemote(repository: GitRepository): Pair<GitRemote, String>? {
val server = GithubAuthenticationManager.getInstance().getSingleOrDefaultAccount(repository.project)?.server ?: return null
var githubRemote: Pair<GitRemote, String>? = null
for (gitRemote in repository.remotes) {
for (remoteUrl in gitRemote.urls) {
if (server.matches(remoteUrl)) {
val remoteName = gitRemote.name
if ("github" == remoteName || "origin" == remoteName) {
return Pair.create(gitRemote, remoteUrl)
}
if (githubRemote == null) {
githubRemote = Pair.create(gitRemote, remoteUrl)
}
break
}
}
}
return githubRemote
}
@JvmStatic
@Deprecated("{@link org.jetbrains.plugins.github.api.GithubServerPath}, {@link GithubGitHelper}")
fun findUpstreamRemote(repository: GitRepository): String? {
val server = GithubAuthenticationManager.getInstance().getSingleOrDefaultAccount(repository.project)?.server ?: return null
for (gitRemote in repository.remotes) {
val remoteName = gitRemote.name
if ("upstream" == remoteName) {
for (remoteUrl in gitRemote.urls) {
if (server.matches(remoteUrl)) {
return remoteUrl
}
}
return gitRemote.firstUrl
}
}
return null
}
@Suppress("DeprecatedCallableAddReplaceWith")
@JvmStatic
@Deprecated("{@link org.jetbrains.plugins.github.api.GithubServerPath}")
fun isRepositoryOnGitHub(repository: GitRepository): Boolean {
return findGithubRemoteUrl(repository) != null
}
//endregion
}
| apache-2.0 | 7fc3752ed2417cf5219d3ffb26a84dfc | 37.151042 | 140 | 0.711945 | 4.863878 | false | false | false | false |
ktorio/ktor | ktor-http/ktor-http-cio/common/src/io/ktor/http/cio/ConnectionOptions.kt | 1 | 5531 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.http.cio
import io.ktor.http.cio.internals.*
/**
* Represents a parsed `Connection` header
* @property close `true` for `Connection: close`
* @property keepAlive `true` for `Connection: keep-alive`
* @property upgrade `true` for `Connection: upgrade`
* @property extraOptions a list of extra connection header options other than close, keep-alive and upgrade
*/
public class ConnectionOptions(
public val close: Boolean = false,
public val keepAlive: Boolean = false,
public val upgrade: Boolean = false,
public val extraOptions: List<String> = emptyList()
) {
public companion object {
/**
* An instance for `Connection: close`
*/
public val Close: ConnectionOptions = ConnectionOptions(close = true)
/**
* An instance for `Connection: keep-alive`
*/
public val KeepAlive: ConnectionOptions = ConnectionOptions(keepAlive = true)
/**
* An instance for `Connection: upgrade`
*/
public val Upgrade: ConnectionOptions = ConnectionOptions(upgrade = true)
private val knownTypes = AsciiCharTree.build(
listOf("close" to Close, "keep-alive" to KeepAlive, "upgrade" to Upgrade),
{ it.first.length },
{ t, idx -> t.first[idx] }
)
/**
* Parse `Connection` header value
*/
public fun parse(connection: CharSequence?): ConnectionOptions? {
if (connection == null) return null
val known = knownTypes.search(connection, lowerCase = true, stopPredicate = { _, _ -> false })
if (known.size == 1) return known[0].second
return parseSlow(connection)
}
private fun parseSlow(connection: CharSequence): ConnectionOptions {
var idx = 0
var start = 0
val length = connection.length
var connectionOptions: ConnectionOptions? = null
var hopHeadersList: ArrayList<String>? = null
while (idx < length) {
do {
val ch = connection[idx]
if (ch != ' ' && ch != ',') {
start = idx
break
}
idx++
} while (idx < length)
while (idx < length) {
val ch = connection[idx]
if (ch == ' ' || ch == ',') break
idx++
}
val detected = knownTypes
.search(connection, start, idx, lowerCase = true, stopPredicate = { _, _ -> false })
.singleOrNull()
when {
detected == null -> {
if (hopHeadersList == null) {
hopHeadersList = ArrayList()
}
hopHeadersList.add(connection.substring(start, idx))
}
connectionOptions == null -> connectionOptions = detected.second
else -> {
connectionOptions = ConnectionOptions(
close = connectionOptions.close || detected.second.close,
keepAlive = connectionOptions.keepAlive || detected.second.keepAlive,
upgrade = connectionOptions.upgrade || detected.second.upgrade,
extraOptions = emptyList()
)
}
}
}
if (connectionOptions == null) connectionOptions = KeepAlive
return if (hopHeadersList == null) connectionOptions
else ConnectionOptions(
connectionOptions.close,
connectionOptions.keepAlive,
connectionOptions.upgrade,
hopHeadersList
)
}
}
override fun toString(): String = when {
extraOptions.isEmpty() -> {
when {
close && !keepAlive && !upgrade -> "close"
!close && keepAlive && !upgrade -> "keep-alive"
!close && keepAlive && upgrade -> "keep-alive, Upgrade"
else -> buildToString()
}
}
else -> buildToString()
}
private fun buildToString() = buildString {
val items = ArrayList<String>(extraOptions.size + 3)
if (close) items.add("close")
if (keepAlive) items.add("keep-alive")
if (upgrade) items.add("Upgrade")
if (extraOptions.isNotEmpty()) {
items.addAll(extraOptions)
}
items.joinTo(this)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
other as ConnectionOptions
if (close != other.close) return false
if (keepAlive != other.keepAlive) return false
if (upgrade != other.upgrade) return false
if (extraOptions != other.extraOptions) return false
return true
}
override fun hashCode(): Int {
var result = close.hashCode()
result = 31 * result + keepAlive.hashCode()
result = 31 * result + upgrade.hashCode()
result = 31 * result + extraOptions.hashCode()
return result
}
}
| apache-2.0 | 147a7a0f541bcf402c32832ccedac8e4 | 34.006329 | 118 | 0.527933 | 5.078972 | false | false | false | false |
DemonWav/MinecraftDev | src/main/kotlin/com/demonwav/mcdev/platform/mixin/debug/MixinPositionManager.kt | 1 | 5273 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.debug
import com.demonwav.mcdev.platform.mixin.util.MixinConstants
import com.demonwav.mcdev.platform.mixin.util.mixinTargets
import com.demonwav.mcdev.util.findContainingClass
import com.demonwav.mcdev.util.ifEmpty
import com.demonwav.mcdev.util.mapNotNull
import com.intellij.debugger.MultiRequestPositionManager
import com.intellij.debugger.NoDataException
import com.intellij.debugger.SourcePosition
import com.intellij.debugger.engine.DebugProcess
import com.intellij.debugger.engine.DebuggerUtils
import com.intellij.debugger.engine.JVMNameUtil
import com.intellij.debugger.impl.DebuggerUtilsEx
import com.intellij.debugger.requests.ClassPrepareRequestor
import com.intellij.ide.highlighter.JavaFileType
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiManager
import com.sun.jdi.AbsentInformationException
import com.sun.jdi.Location
import com.sun.jdi.ReferenceType
import com.sun.jdi.request.ClassPrepareRequest
import java.util.stream.Stream
import kotlin.streams.toList
class MixinPositionManager(private val debugProcess: DebugProcess) : MultiRequestPositionManager {
override fun getAcceptedFileTypes(): Set<FileType> = setOf(JavaFileType.INSTANCE)
@Throws(NoDataException::class)
override fun getSourcePosition(location: Location?): SourcePosition? {
location ?: throw NoDataException.INSTANCE
val type = location.declaringType()
// Check if mixin source map is present (Mixin sets the default stratum to Mixin)
if (type.defaultStratum() != MixinConstants.SMAP_STRATUM) {
throw NoDataException.INSTANCE
}
// Return the correct PsiFile based on the source path in the SMAP
try {
val path = location.sourcePath()
// The source path is the package (separated by slashes) and class name with the ".java" file extension
val className = path.removeSuffix(".java")
.replace('/', '.').replace('\\', '.')
val psiFile = findAlternativeSource(className, debugProcess.project) ?:
// Lookup class based on its qualified name (TODO: Support for anonymous classes)
DebuggerUtils.findClass(className, debugProcess.project, debugProcess.searchScope)?.navigationElement?.containingFile
if (psiFile != null) {
// File found, return correct source file
return SourcePosition.createFromLine(psiFile, location.lineNumber() - 1)
}
} catch (ignored: AbsentInformationException) {}
throw NoDataException.INSTANCE
}
private fun findAlternativeSource(className: String, project: Project): PsiFile? {
val alternativeSource = DebuggerUtilsEx.getAlternativeSourceUrl(className, project) ?: return null
val alternativeFile = VirtualFileManager.getInstance().findFileByUrl(alternativeSource) ?: return null
return PsiManager.getInstance(project).findFile(alternativeFile)
}
override fun getAllClasses(classPosition: SourcePosition): List<ReferenceType> {
return runReadAction {
findMatchingClasses(classPosition)
.flatMap { name -> debugProcess.virtualMachineProxy.classesByName(name).stream() }
.toList()
}
}
override fun locationsOfLine(type: ReferenceType, position: SourcePosition): List<Location> {
// Check if mixin source map is present (Mixin sets the default stratum to Mixin)
if (type.defaultStratum() == MixinConstants.SMAP_STRATUM) {
try {
// Return the line numbers from the correct source file
return type.locationsOfLine(MixinConstants.SMAP_STRATUM, position.file.name, position.line + 1)
} catch (ignored: AbsentInformationException) {}
}
throw NoDataException.INSTANCE
}
override fun createPrepareRequest(requestor: ClassPrepareRequestor, position: SourcePosition): ClassPrepareRequest {
throw UnsupportedOperationException("This class implements MultiRequestPositionManager, corresponding createPrepareRequests version should be used")
}
override fun createPrepareRequests(requestor: ClassPrepareRequestor, position: SourcePosition): List<ClassPrepareRequest> {
return runReadAction {
findMatchingClasses(position)
.mapNotNull { name -> debugProcess.requestsManager.createClassPrepareRequest(requestor, name) }
.toList()
}
}
private fun findMatchingClasses(position: SourcePosition): Stream<String> {
val classElement = position.elementAt?.findContainingClass() ?: throw NoDataException.INSTANCE
return classElement.mixinTargets
.ifEmpty { throw NoDataException.INSTANCE }
.stream()
// TODO: Support for anonymous classes
.mapNotNull(JVMNameUtil::getNonAnonymousClassName)
}
}
| mit | e5f7daa1671408a001a2fcc1b27f4be7 | 42.221311 | 156 | 0.723497 | 5.099613 | false | false | false | false |
google/android-fhir | demo/src/main/java/com/google/android/fhir/demo/PatientDetailsFragment.kt | 1 | 3965 | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.fhir.demo
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import com.google.android.fhir.FhirEngine
import com.google.android.fhir.demo.databinding.PatientDetailBinding
/**
* A fragment representing a single Patient detail screen. This fragment is contained in a
* [MainActivity].
*/
class PatientDetailsFragment : Fragment() {
private lateinit var fhirEngine: FhirEngine
private lateinit var patientDetailsViewModel: PatientDetailsViewModel
private val args: PatientDetailsFragmentArgs by navArgs()
private var _binding: PatientDetailBinding? = null
private val binding
get() = _binding!!
var editMenuItem: MenuItem? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = PatientDetailBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
fhirEngine = FhirApplication.fhirEngine(requireContext())
patientDetailsViewModel =
ViewModelProvider(
this,
PatientDetailsViewModelFactory(requireActivity().application, fhirEngine, args.patientId)
)
.get(PatientDetailsViewModel::class.java)
val adapter = PatientDetailsRecyclerViewAdapter(::onAddScreenerClick)
binding.recycler.adapter = adapter
(requireActivity() as AppCompatActivity).supportActionBar?.apply {
title = "Patient Card"
setDisplayHomeAsUpEnabled(true)
}
patientDetailsViewModel.livePatientData.observe(viewLifecycleOwner) {
adapter.submitList(it)
if (!it.isNullOrEmpty()) {
editMenuItem?.setEnabled(true)
}
}
patientDetailsViewModel.getPatientDetailData()
(activity as MainActivity).setDrawerEnabled(false)
}
private fun onAddScreenerClick() {
findNavController()
.navigate(
PatientDetailsFragmentDirections.actionPatientDetailsToScreenEncounterFragment(
args.patientId
)
)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.details_options_menu, menu)
editMenuItem = menu.findItem(R.id.menu_patient_edit)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
NavHostFragment.findNavController(this).navigateUp()
true
}
R.id.menu_patient_edit -> {
findNavController()
.navigate(PatientDetailsFragmentDirections.navigateToEditPatient(args.patientId))
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
| apache-2.0 | 932b45815c8eb9de14bedc93c8e4c79d | 32.319328 | 99 | 0.741488 | 4.714625 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/core/src/templates/kotlin/core/libc/templates/string.kt | 4 | 5109 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package core.libc.templates
import org.lwjgl.generator.*
val string = "LibCString".nativeClass(Module.CORE_LIBC) {
nativeDirective(
"""#ifdef LWJGL_WINDOWS
#define _CRT_SECURE_NO_WARNINGS
#endif""", beforeIncludes = true)
nativeImport("<string.h>")
documentation = "Native bindings to string.h."
opaque_p(
"memset",
"Fills a memory area with a constant byte.",
MultiType(
PointerMapping.DATA_SHORT,
PointerMapping.DATA_INT,
PointerMapping.DATA_LONG,
PointerMapping.DATA_FLOAT,
PointerMapping.DATA_DOUBLE,
byteArray = true
)..void.p("dest", "pointer to the memory area to fill"),
int("c", "byte to set"),
AutoSize("dest")..size_t("count", "number of bytes to fill"),
returnDoc = "the value of {@code dest}"
)
customMethod("""
/**
* Fills memory with a constant byte.
*
* @param dest pointer to destination
* @param c character to set
*
* @return the value of {@code dest}
*/
@NativeType("void *")
public static <T extends CustomBuffer<T>> long memset(@NativeType("void *") T dest, @NativeType("int") int c) {
return nmemset(memAddress(dest), c, Integer.toUnsignedLong(dest.remaining()) * dest.sizeof());
}""")
opaque_p(
"memcpy",
"Copies bytes between memory areas that must not overlap.",
MultiType(
PointerMapping.DATA_SHORT,
PointerMapping.DATA_INT,
PointerMapping.DATA_LONG,
PointerMapping.DATA_FLOAT,
PointerMapping.DATA_DOUBLE,
byteArray = true
)..void.p("dest", "pointer to the destination memory area"),
MultiType(
PointerMapping.DATA_SHORT,
PointerMapping.DATA_INT,
PointerMapping.DATA_LONG,
PointerMapping.DATA_FLOAT,
PointerMapping.DATA_DOUBLE,
byteArray = true
)..void.const.p("src", "pointer to the source memory area"),
AutoSize("src", "dest")..size_t("count", "the number of bytes to be copied"),
returnDoc = "the value of {@code dest}"
)
customMethod("""
/**
* Copies bytes between memory areas that must not overlap.
*
* @param dest pointer to the destination memory area
* @param src pointer to the source memory area
*
* @return the value of {@code dest}
*/
@NativeType("void *")
public static <T extends CustomBuffer<T>> long memcpy(@NativeType("void *") T dest, @NativeType("void const *") T src) {
if (CHECKS) {
check(src, dest.remaining());
}
return nmemcpy(memAddress(dest), memAddress(src), (long)src.remaining() * src.sizeof());
}""")
opaque_p(
"memmove",
"""
Copies {@code count} bytes from memory area {@code src} to memory area {@code dest}.
The memory areas may overlap: copying takes place as though the bytes in {@code src} are first copied into a temporary array that does not overlap
{@code src} or {@code dest}, and the bytes are then copied from the temporary array to {@code dest}.
""",
MultiType(
PointerMapping.DATA_SHORT,
PointerMapping.DATA_INT,
PointerMapping.DATA_LONG,
PointerMapping.DATA_FLOAT,
PointerMapping.DATA_DOUBLE,
byteArray = true
)..void.p("dest", "pointer to the destination memory area"),
MultiType(
PointerMapping.DATA_SHORT,
PointerMapping.DATA_INT,
PointerMapping.DATA_LONG,
PointerMapping.DATA_FLOAT,
PointerMapping.DATA_DOUBLE,
byteArray = true
)..void.const.p("src", "pointer to the source memory area"),
AutoSize("src", "dest")..size_t("count", "the number of bytes to be copied"),
returnDoc = "the value of {@code dest}"
)
customMethod("""
/**
* Copies {@code count} bytes from memory area {@code src} to memory area {@code dest}.
*
* <p>The memory areas may overlap: copying takes place as though the bytes in {@code src} are first copied into a temporary array that does not overlap
* {@code src} or {@code dest}, and the bytes are then copied from the temporary array to {@code dest}.</p>
*
* @param dest pointer to the destination memory area
* @param src pointer to the source memory area
*
* @return the value of {@code dest}
*/
@NativeType("void *")
public static <T extends CustomBuffer<T>> long memmove(@NativeType("void *") T dest, @NativeType("void const *") T src) {
if (CHECKS) {
check(src, dest.remaining());
}
return nmemmove(memAddress(dest), memAddress(src), (long)src.remaining() * src.sizeof());
}""")
charASCII.p(
"strerror",
"Returns string describing error number.",
int("errnum", "")
)
} | bsd-3-clause | 870029e75c735f2bf737151ff80296c5 | 33.527027 | 156 | 0.593267 | 4.42721 | false | false | false | false |
mikhalchenko-alexander/nirvana-player | src/main/kotlin/com/anahoret/nirvanaplayer/components/controls/TimeSlider.kt | 1 | 501 | package com.anahoret.nirvanaplayer.components.controls
import com.anahoret.nirvanaplayer.components.NoUiSlider
class TimeSlider(audio: Audio):
NoUiSlider(
onValueChange = { audio.setCurrentTime(it) }) {
fun setMaxTime(maxTime: String) {
val timeParts = maxTime.split(":")
val hours = timeParts[0].toDouble()
val minutes = timeParts[1].toDouble()
val seconds = timeParts[2].toDouble()
val maxValue = hours * 3600 + minutes * 60 + seconds
setMaxValue(maxValue)
}
}
| apache-2.0 | e39bb4cfa638fa0fc3ae3772ba1b2bfb | 26.833333 | 56 | 0.708583 | 3.604317 | false | false | false | false |
AshishKayastha/Movie-Guide | app/src/main/kotlin/com/ashish/movieguide/data/api/TVShowApi.kt | 1 | 3179 | package com.ashish.movieguide.data.api
import com.ashish.movieguide.data.models.EpisodeDetail
import com.ashish.movieguide.data.models.Rating
import com.ashish.movieguide.data.models.Results
import com.ashish.movieguide.data.models.SeasonDetail
import com.ashish.movieguide.data.models.Status
import com.ashish.movieguide.data.models.TVShow
import com.ashish.movieguide.data.models.TVShowDetail
import com.ashish.movieguide.utils.Constants.INCLUDE_IMAGE_LANGUAGE
import io.reactivex.Single
import retrofit2.http.Body
import retrofit2.http.DELETE
import retrofit2.http.GET
import retrofit2.http.POST
import retrofit2.http.Path
import retrofit2.http.Query
/**
* Created by Ashish on Dec 29.
*/
interface TVShowApi {
companion object {
const val ON_THE_AIR = "on_the_air"
const val POPULAR = "popular"
const val TOP_RATED = "top_rated"
const val AIRING_TODAY = "airing_today"
}
/* TV Shows */
@GET("tv/{tvShowType}")
fun getTVShows(
@Path("tvShowType") tvShowType: String?,
@Query("page") page: Int = 1
): Single<Results<TVShow>>
@GET("tv/{tvId}" + INCLUDE_IMAGE_LANGUAGE)
fun getTVShowDetail(
@Path("tvId") tvId: Long,
@Query("append_to_response") appendedResponse: String
): Single<TVShowDetail>
@POST("tv/{tvId}/rating")
fun rateTVShow(@Path("tvId") tvId: Long, @Body rating: Rating): Single<Status>
@DELETE("tv/{tvId}/rating")
fun deleteTVRating(@Path("tvId") tvId: Long): Single<Status>
/* Season */
@GET("tv/{tvId}/season/{seasonNumber}" + INCLUDE_IMAGE_LANGUAGE)
fun getSeasonDetail(
@Path("tvId") tvId: Long,
@Path("seasonNumber") seasonNumber: Int,
@Query("append_to_response") appendedResponse: String
): Single<SeasonDetail>
/* Episode */
@GET("tv/{tvId}/season/{seasonNumber}/episode/{episodeNumber}" + INCLUDE_IMAGE_LANGUAGE)
fun getEpisodeDetail(
@Path("tvId") tvId: Long,
@Path("seasonNumber") seasonNumber: Int,
@Path("episodeNumber") episodeNumber: Int,
@Query("append_to_response") appendedResponse: String
): Single<EpisodeDetail>
@POST("tv/{tvId}/season/{seasonNumber}/episode/{episodeNumber}/rating")
fun rateEpisode(
@Path("tvId") tvId: Long,
@Path("seasonNumber") seasonNumber: Int,
@Path("episodeNumber") episodeNumber: Int,
@Body rating: Rating
): Single<Status>
@DELETE("tv/{tvId}/season/{seasonNumber}/episode/{episodeNumber}/rating")
fun deleteEpisodeRating(@Path("tvId") tvId: Long,
@Path("seasonNumber") seasonNumber: Int,
@Path("episodeNumber") episodeNumber: Int
): Single<Status>
@GET("discover/tv")
fun discoverTVShow(
@Query("sort_by") sortBy: String = "popularity.desc",
@Query("air_date.gte") minAirDate: String? = null,
@Query("air_date.lte") maxAirDate: String? = null,
@Query("with_genres") genreIds: String? = null,
@Query("page") page: Int = 1
): Single<Results<TVShow>>
} | apache-2.0 | b40ae714d62c80ec18856710c5e0874b | 32.473684 | 92 | 0.642969 | 3.968789 | false | false | false | false |
ilya-g/intellij-markdown | src/org/intellij/markdown/flavours/gfm/GFMElementTypes.kt | 1 | 1015 | package org.intellij.markdown.flavours.gfm
import org.intellij.markdown.IElementType
import org.intellij.markdown.MarkdownElementType
public object GFMTokenTypes {
@JvmField
public val TILDE: IElementType = MarkdownElementType("~", true);
@JvmField
public val TABLE_SEPARATOR: IElementType = MarkdownElementType("TABLE_SEPARATOR", true)
@JvmField
public val GFM_AUTOLINK: IElementType = MarkdownElementType("GFM_AUTOLINK", true);
@JvmField
public val CHECK_BOX: IElementType = MarkdownElementType("CHECK_BOX", true);
@JvmField
public val CELL: IElementType = MarkdownElementType("CELL", true)
}
public object GFMElementTypes {
@JvmField
public val STRIKETHROUGH: IElementType = MarkdownElementType("STRIKETHROUGH");
@JvmField
public val TABLE: IElementType = MarkdownElementType("TABLE")
@JvmField
public val HEADER: IElementType = MarkdownElementType("HEADER")
@JvmField
public val ROW: IElementType = MarkdownElementType("ROW")
} | apache-2.0 | 293b29785638b5cfbb18d2a901966267 | 27.222222 | 91 | 0.743842 | 4.833333 | false | false | false | false |
dkandalov/katas | kotlin/src/katas/kotlin/diamond/Diamond7.kt | 1 | 1165 | package katas.kotlin.diamond
import nonstdlib.join
import datsok.shouldEqual
import org.junit.Test
class Diamond7 {
@Test fun `build a text diamond`() {
diamond(from = 'A', to = 'A') shouldEqual "A"
diamond(from = 'A', to = 'B') shouldEqual
"-A-\n" +
"B-B\n" +
"-A-"
diamond(from = 'A', to = 'C') shouldEqual
"--A--\n" +
"-B-B-\n" +
"C---C\n" +
"-B-B-\n" +
"--A--"
diamond(from = 'A', to = 'D') shouldEqual
"---A---\n" +
"--B-B--\n" +
"-C---C-\n" +
"D-----D\n" +
"-C---C-\n" +
"--B-B--\n" +
"---A---"
}
private fun diamond(from: Char, to: Char): String {
return (0..(to - from))
.map {
val padLeft = 0.until(to - from - it).map{ "-" }.join("")
val padRight = 0.until(it).map{ "-" }.join("")
padLeft + (from + it) + padRight
}
.map { it + it.reversed().drop(1) }
.let { it + it.reversed().drop(1) }
.join("\n")
}
} | unlicense | 03a93fce8e91dc75278d20d02235d387 | 26.761905 | 73 | 0.376824 | 3.406433 | false | false | false | false |
elpassion/el-space-android | el-space-app/src/main/java/pl/elpassion/elspace/hub/report/edit/ReportEditController.kt | 1 | 6299 | package pl.elpassion.elspace.hub.report.edit
import io.reactivex.Completable
import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.addTo
import io.reactivex.rxkotlin.withLatestFrom
import pl.elpassion.elspace.common.SchedulersSupplier
import pl.elpassion.elspace.common.extensions.catchOnError
import pl.elpassion.elspace.hub.project.Project
import pl.elpassion.elspace.hub.report.*
class ReportEditController(private val report: Report,
private val view: ReportEdit.View,
private val api: ReportEdit.Api,
private val schedulers: SchedulersSupplier) {
private val subscriptions = CompositeDisposable()
fun onCreate() {
showReport()
Observable.merge(editReportClicks(), removeReportClicks())
.subscribe()
.addTo(subscriptions)
}
fun onDestroy() {
subscriptions.clear()
}
fun onDateChanged(date: String) {
view.showDate(date)
}
fun onProjectChanged(project: Project) {
view.showProject(project)
}
private fun showReport() {
view.showReportType(report.type)
view.showDate(report.date)
if (report is HourlyReport) {
showHourlyReport(report)
}
}
private fun editReportClicks() = view.editReportClicks()
.withLatestFrom(reportTypeChanges()) { model, handler -> model to handler }
.switchMap {
callApiToEdit(it)
.doOnComplete { view.close() }
.catchOnError {
when (it) {
is EmptyProjectError -> view.showEmptyProjectError()
is EmptyDescriptionError -> view.showEmptyDescriptionError()
else -> view.showError(it)
}
}
.toObservable<Unit>()
}
private fun removeReportClicks() = view.removeReportClicks()
.switchMap {
callApiToRemove(report.id)
.doOnComplete { view.close() }
.catchOnError { view.showError(it) }
.toObservable<Unit>()
}
private fun reportTypeChanges() = view.reportTypeChanges()
.startWith(report.type)
.doOnNext { onReportTypeChanged(it) }
.map { chooseReportEditHandler(it) }
private fun chooseReportEditHandler(reportType: ReportType) = when (reportType) {
ReportType.REGULAR -> regularReportEditHandler
ReportType.PAID_VACATIONS -> paidVacationReportEditHandler
ReportType.UNPAID_VACATIONS -> unpaidVacationReportEditHandler
ReportType.SICK_LEAVE -> sickLeaveReportEditHandler
ReportType.PAID_CONFERENCE -> paidConferenceReportEditHandler
}
private fun callApiToEdit(modelCallPair: Pair<ReportViewModel, (ReportViewModel) -> Completable>) =
modelCallPair.second(modelCallPair.first)
.subscribeOn(schedulers.backgroundScheduler)
.observeOn(schedulers.uiScheduler)
.addLoader()
private fun callApiToRemove(reportId: Long) =
api.removeReport(reportId)
.subscribeOn(schedulers.backgroundScheduler)
.observeOn(schedulers.uiScheduler)
.addLoader()
private fun showHourlyReport(report: HourlyReport) {
view.showReportedHours(report.reportedHours)
if (report is RegularHourlyReport) {
view.showProject(report.project)
view.showDescription(report.description)
}
}
private fun onReportTypeChanged(reportType: ReportType) = when (reportType) {
ReportType.REGULAR -> view.showRegularForm()
ReportType.PAID_VACATIONS -> view.showPaidVacationsForm()
ReportType.UNPAID_VACATIONS -> view.showUnpaidVacationsForm()
ReportType.SICK_LEAVE -> view.showSickLeaveForm()
ReportType.PAID_CONFERENCE -> view.showPaidConferenceForm()
}
private val regularReportEditHandler = { model: ReportViewModel ->
(model as RegularViewModel).run {
when {
project === null -> Completable.error(EmptyProjectError())
description.isBlank() -> Completable.error(EmptyDescriptionError())
else -> editRegularReport(this, project)
}
}
}
private val paidVacationReportEditHandler = { model: ReportViewModel ->
(model as PaidVacationsViewModel).let {
api.editReport(report.id, ReportType.PAID_VACATIONS.id, model.selectedDate, model.hours, null, null)
}
}
private val unpaidVacationReportEditHandler = { model: ReportViewModel ->
api.editReport(report.id, ReportType.UNPAID_VACATIONS.id, model.selectedDate, null, null, null)
}
private val sickLeaveReportEditHandler = { model: ReportViewModel ->
api.editReport(report.id, ReportType.SICK_LEAVE.id, model.selectedDate, null, null, null)
}
private val paidConferenceReportEditHandler = { model: ReportViewModel ->
api.editReport(report.id, ReportType.PAID_CONFERENCE.id, model.selectedDate, null, null, null)
}
private fun editRegularReport(model: RegularViewModel, project: Project) =
api.editReport(report.id, ReportType.REGULAR.id, model.selectedDate, model.hours, model.description, project.id)
private fun Completable.addLoader() = this
.doOnSubscribe { view.showLoader() }
.doFinally { view.hideLoader() }
}
private val Report.type: ReportType
get() = when (this) {
is RegularHourlyReport -> ReportType.REGULAR
is PaidVacationHourlyReport -> ReportType.PAID_VACATIONS
is DailyReport -> when (reportType) {
DailyReportType.UNPAID_VACATIONS -> ReportType.UNPAID_VACATIONS
DailyReportType.SICK_LEAVE -> ReportType.SICK_LEAVE
DailyReportType.PAID_CONFERENCE -> ReportType.PAID_CONFERENCE
}
}
class EmptyProjectError : NullPointerException()
class EmptyDescriptionError : IllegalArgumentException() | gpl-3.0 | df34573de4b93f0f3264331687c74412 | 38.622642 | 124 | 0.636926 | 4.768357 | false | false | false | false |
flesire/ontrack | ontrack-extension-git/src/main/java/net/nemerosa/ontrack/extension/git/model/BasicGitConfiguration.kt | 1 | 8567 | package net.nemerosa.ontrack.extension.git.model
import com.fasterxml.jackson.annotation.JsonIgnore
import net.nemerosa.ontrack.extension.issues.model.IssueServiceConfigurationRepresentation
import net.nemerosa.ontrack.git.GitRepository
import net.nemerosa.ontrack.model.form.Form
import net.nemerosa.ontrack.model.form.Form.defaultNameField
import net.nemerosa.ontrack.model.form.Password
import net.nemerosa.ontrack.model.form.Selection
import net.nemerosa.ontrack.model.form.Text
import net.nemerosa.ontrack.model.support.ConfigurationDescriptor
import net.nemerosa.ontrack.model.support.UserPassword
import net.nemerosa.ontrack.model.support.UserPasswordConfiguration
import java.util.*
import java.util.function.Function
/**
* Git configuration based on direct definition.
*
* @property name Name of this configuration
* @property remote Remote path to the source repository
* @property user User name
* @property password User password
* @property commitLink Link to a commit, using {commit} as placeholder
* @property fileAtCommitLink Link to a file at a given commit, using {commit} and {path} as placeholders
* @property indexationInterval Indexation interval
* @property indexationInterval Indexation interval
* @property issueServiceConfigurationIdentifier ID to the
* [net.nemerosa.ontrack.extension.issues.model.IssueServiceConfiguration] associated
* with this repository.
*/
// TODO #532 Workaround
open class BasicGitConfiguration(
private val name: String,
val remote: String,
private val user: String?,
private val password: String?,
val commitLink: String?,
val fileAtCommitLink: String?,
val indexationInterval: Int,
val issueServiceConfigurationIdentifier: String?
) : UserPasswordConfiguration<BasicGitConfiguration> {
override fun getName(): String = name
override fun getUser(): String? = user
override fun getPassword(): String? = password
fun withUser(user: String?) = BasicGitConfiguration(
name,
remote,
user,
password,
commitLink,
fileAtCommitLink,
indexationInterval,
issueServiceConfigurationIdentifier
)
override fun withPassword(password: String?) = BasicGitConfiguration(
name,
remote,
user,
password,
commitLink,
fileAtCommitLink,
indexationInterval,
issueServiceConfigurationIdentifier
)
fun withName(name: String) = BasicGitConfiguration(
name,
remote,
user,
password,
commitLink,
fileAtCommitLink,
indexationInterval,
issueServiceConfigurationIdentifier
)
fun withRemote(remote: String) = BasicGitConfiguration(
name,
remote,
user,
password,
commitLink,
fileAtCommitLink,
indexationInterval,
issueServiceConfigurationIdentifier
)
fun withIssueServiceConfigurationIdentifier(issueServiceConfigurationIdentifier: String?) = BasicGitConfiguration(
name,
remote,
user,
password,
commitLink,
fileAtCommitLink,
indexationInterval,
issueServiceConfigurationIdentifier
)
val gitRepository: GitRepository
@JsonIgnore
get() {
val credentials = credentials
return GitRepository(
TYPE,
name,
remote,
credentials.map { it.user }.orElse(""),
credentials.map { it.password }.orElse("")
)
}
@JsonIgnore
override fun getCredentials(): Optional<UserPassword> {
return if (user != null && user.isNotBlank())
Optional.of(UserPassword(user, password ?: ""))
else
Optional.empty()
}
override fun obfuscate(): BasicGitConfiguration {
return withPassword("")
}
@JsonIgnore
override fun getDescriptor(): ConfigurationDescriptor {
return ConfigurationDescriptor(
name,
String.format("%s (%s)", name, remote)
)
}
override fun clone(targetConfigurationName: String, replacementFunction: Function<String, String>): BasicGitConfiguration {
return BasicGitConfiguration(
targetConfigurationName,
replacementFunction.apply(remote),
user?.let { replacementFunction.apply(it) },
password,
commitLink?.let { replacementFunction.apply(it) },
fileAtCommitLink?.let { replacementFunction.apply(it) },
indexationInterval,
issueServiceConfigurationIdentifier
)
}
fun asForm(availableIssueServiceConfigurations: List<IssueServiceConfigurationRepresentation>): Form {
return form(availableIssueServiceConfigurations)
.with(defaultNameField().readOnly().value(name))
.fill("remote", remote)
.fill("user", user)
.fill("password", "")
.fill("commitLink", commitLink)
.fill("fileAtCommitLink", fileAtCommitLink)
.fill("indexationInterval", indexationInterval)
.fill("issueServiceConfigurationIdentifier", issueServiceConfigurationIdentifier)
}
companion object {
const val TYPE = "basic"
@JvmStatic
fun empty(): BasicGitConfiguration {
return BasicGitConfiguration(
"",
"",
"",
"",
"",
"",
0,
""
)
}
@JvmStatic
fun form(availableIssueServiceConfigurations: List<IssueServiceConfigurationRepresentation>): Form {
return Form.create()
.with(defaultNameField())
.with(
Text.of("remote")
.label("Remote")
.help("Remote path to the source repository")
)
.with(
Text.of("user")
.label("User")
.length(16)
.optional()
)
.with(
Password.of("password")
.label("Password")
.length(40)
.optional()
)
.with(
Text.of("commitLink")
.label("Commit link")
.length(250)
.optional()
.help("Link to a commit, using {commit} as placeholder")
)
.with(
Text.of("fileAtCommitLink")
.label("File at commit link")
.length(250)
.optional()
.help("Link to a file at a given commit, using {commit} and {path} as placeholders")
)
.with(
net.nemerosa.ontrack.model.form.Int.of("indexationInterval")
.label("Indexation interval")
.min(0)
.max(60 * 24)
.value(0)
.help("@file:extension/git/help.net.nemerosa.ontrack.extension.git.model.GitConfiguration.indexationInterval.tpl.html")
)
.with(
Selection.of("issueServiceConfigurationIdentifier")
.label("Issue configuration")
.help("Select an issue service that is sued to associate tickets and issues to the source.")
.optional()
.items(availableIssueServiceConfigurations)
)
}
}
}
| mit | d878c7474049353a256ac3725b5a16e9 | 35.76824 | 155 | 0.530057 | 5.949306 | false | true | false | false |
nibarius/opera-park-android | app/src/main/java/se/barsk/park/datatypes/OwnCar.kt | 1 | 524 | package se.barsk.park.datatypes
import java.util.*
/**
* A representation of the users own car
*/
data class OwnCar(override val regNo: String, override val owner: String, val nickName: String = "car", val id: String = UUID.randomUUID().toString()) : Car() {
var parked = false // Not part of hash code / equals
/**
* Returns true if the given car is the same (real world car) as this one,
* that is if their license plate match.
*/
fun isSameCar(otherCar: OwnCar) = regNo == otherCar.regNo
} | mit | 622315e99d3941397b5066162fbe9394 | 31.8125 | 160 | 0.671756 | 3.690141 | false | false | false | false |
paplorinc/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/hint/ImplementationViewElement.kt | 2 | 3666 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.hint
import com.intellij.navigation.NavigationItem
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiBinaryFile
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.util.PsiTreeUtil
import javax.swing.Icon
/**
* A single element shown in the Show Implementations view.
*
* @author yole
*/
abstract class ImplementationViewElement {
abstract val project: Project
abstract val isNamed: Boolean
abstract val name: String?
abstract val presentableText: String
abstract val containingFile: VirtualFile?
abstract val text: String?
abstract val locationText: String?
abstract val locationIcon: Icon?
abstract val containingMemberOrSelf: ImplementationViewElement
abstract val elementForShowUsages: PsiElement?
abstract fun navigate(focusEditor: Boolean)
}
class PsiImplementationViewElement(val psiElement: PsiElement) : ImplementationViewElement() {
override val project: Project
get() = psiElement.project
override val isNamed: Boolean
get() = psiElement is PsiNamedElement
override val name: String?
get() = (psiElement as? PsiNamedElement)?.name
override val containingFile: VirtualFile?
get() = psiElement.containingFile?.originalFile?.virtualFile
override val text: String?
get() = ImplementationViewComponent.getNewText(psiElement)
override val presentableText: String
get() {
val presentation = (psiElement as? NavigationItem)?.presentation
val vFile = containingFile ?: return ""
val presentableName = vFile.presentableName
if (presentation == null) {
return presentableName
}
val elementPresentation = presentation.presentableText
val locationString = presentation.locationString
return if (vFile.name == elementPresentation + "." + vFile.extension) {
presentableName + if (!StringUtil.isEmptyOrSpaces(locationString)) " $locationString" else ""
}
else {
"$presentableName ($elementPresentation)"
}
}
override val locationText: String?
get() = ElementLocationUtil.renderElementLocation(psiElement, Ref())
override val locationIcon: Icon?
get() = Ref<Icon>().also { ElementLocationUtil.renderElementLocation(psiElement, it) }.get()
override val containingMemberOrSelf: ImplementationViewElement
get() {
val parent = PsiTreeUtil.getStubOrPsiParent(psiElement)
if (parent == null || (parent is PsiFile && parent.virtualFile == containingFile)) {
return this
}
return PsiImplementationViewElement(parent)
}
override fun navigate(focusEditor: Boolean) {
val navigationElement = psiElement.navigationElement
val file = navigationElement.containingFile?.originalFile ?: return
val virtualFile = file.virtualFile ?: return
val project = psiElement.project
val fileEditorManager = FileEditorManagerEx.getInstanceEx(project)
val descriptor = OpenFileDescriptor(project, virtualFile, navigationElement.textOffset)
fileEditorManager.openTextEditor(descriptor, focusEditor)
}
override val elementForShowUsages: PsiElement?
get() = if (psiElement !is PsiBinaryFile) psiElement else null
}
| apache-2.0 | 1daf4e032b509d47e650b610fd4599f1 | 35.29703 | 140 | 0.758592 | 5.008197 | false | false | false | false |
lisuperhong/ModularityApp | KaiyanModule/src/main/java/com/lisuperhong/openeye/ui/activity/HotContentActivity.kt | 1 | 2531 | package com.lisuperhong.openeye.ui.activity
import android.graphics.Typeface
import android.os.Bundle
import android.widget.Toast
import com.company.commonbusiness.base.BaseApplication
import com.company.commonbusiness.base.activity.BaseMvpActivity
import com.company.commonbusiness.base.adapter.BaseFragmentAdapter
import com.company.commonbusiness.base.fragment.BaseFragment
import com.lisuperhong.openeye.R
import com.lisuperhong.openeye.mvp.contract.TabInfoContract
import com.lisuperhong.openeye.mvp.model.bean.TabInfoBean
import com.lisuperhong.openeye.mvp.presenter.TabInfoPresenter
import com.lisuperhong.openeye.ui.fragment.rank.TabRankFragment
import com.lisuperhong.openeye.utils.Constant
import kotlinx.android.synthetic.main.activity_hot_content.*
class HotContentActivity : BaseMvpActivity<TabInfoPresenter>(), TabInfoContract.View {
private val titleList = ArrayList<String>()
private val fragmentList = ArrayList<BaseFragment>()
override val layoutId: Int
get() = R.layout.activity_hot_content
override fun setPresenter() {
presenter = TabInfoPresenter(this)
}
override fun initView() {
toolbarTitleTv.text = "热门内容"
toolbarBackIv.setOnClickListener {
onBackPressed()
}
presenter?.getPopularTabInfo(intent.getStringExtra(Constant.INTENT_TAG_POPULAR_URL))
}
override fun initData(savedInstanceState: Bundle?) {
}
override fun showTabInfo(tabInfoBean: TabInfoBean) {
tabInfoBean.tabInfo.tabList.mapTo(titleList) { it.name }
tabInfoBean.tabInfo.tabList.mapTo(fragmentList) { TabRankFragment.newInstance(it.apiUrl) }
hotViewPager.adapter = BaseFragmentAdapter(supportFragmentManager, fragmentList, titleList)
hotViewPager.offscreenPageLimit = tabInfoBean.tabInfo.tabList.size - 1
slidingTabLayout.setViewPager(hotViewPager)
slidingTabLayout.currentTab = tabInfoBean.tabInfo.defaultIdx
// 设置tab字体(不起作用?)
val fontType =
Typeface.createFromAsset(
BaseApplication.context.assets,
"fonts/FZLanTingHeiS-L-GB-Regular.TTF"
)
(0 until titleList.size)
.forEach {
slidingTabLayout.getTitleView(it).typeface = fontType
}
}
override fun showLoading() {
}
override fun hideLoading() {
}
override fun showMessage(message: String) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show()
}
}
| apache-2.0 | 63e2c2d8042f143de5d4f7b8417b563e | 33.342466 | 99 | 0.724372 | 4.452931 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/RoundNumberFix.kt | 1 | 2838 | // 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.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveImportReference
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.idea.util.ImportInsertHelper
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.createExpressionByPattern
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.typeUtil.isDouble
import org.jetbrains.kotlin.types.typeUtil.isFloat
import org.jetbrains.kotlin.types.typeUtil.isInt
import org.jetbrains.kotlin.types.typeUtil.isLong
class RoundNumberFix(
element: KtExpression,
type: KotlinType,
private val disableIfAvailable: IntentionAction? = null
) : KotlinQuickFixAction<KtExpression>(element), LowPriorityAction {
private val isTarget = type.isLongOrInt() && element.analyze(BodyResolveMode.PARTIAL).getType(element)?.isDoubleOrFloat() == true
private val roundFunction = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(type).let { "roundTo$it" }
override fun isAvailable(project: Project, editor: Editor?, file: KtFile) =
disableIfAvailable?.isAvailable(project, editor, file) != true && isTarget
override fun getText() = KotlinBundle.message("round.using.0", roundFunction)
override fun getFamilyName() = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val replaced = element.replaced(KtPsiFactory(project).createExpressionByPattern("$0.$roundFunction()", element))
file.resolveImportReference(FqName("kotlin.math.$roundFunction")).firstOrNull()?.also {
ImportInsertHelper.getInstance(project).importDescriptor(file, it)
}
editor?.caretModel?.moveToOffset(replaced.endOffset)
}
private fun KotlinType.isLongOrInt() = this.isLong() || this.isInt()
private fun KotlinType.isDoubleOrFloat() = this.isDouble() || this.isFloat()
} | apache-2.0 | e7f0eabed9a359722d6ee68dca27749a | 47.948276 | 158 | 0.791755 | 4.462264 | false | false | false | false |
JetBrains/teamcity-dnx-plugin | plugin-dotnet-agent/src/main/kotlin/jetbrains/buildServer/agent/CommandLineExecutorImpl.kt | 1 | 1799 | package jetbrains.buildServer.agent
import com.intellij.execution.configurations.GeneralCommandLine
import org.apache.log4j.Logger
import java.io.File
class CommandLineExecutorImpl : CommandLineExecutor {
override fun tryExecute(commandLine: CommandLine, executionTimeoutSeconds: Int): CommandLineResult? {
val cmd = GeneralCommandLine()
cmd.exePath = commandLine.executableFile.path
cmd.setWorkingDirectory(File(commandLine.workingDirectory.path))
cmd.addParameters(commandLine.arguments.map { it.value })
val currentEnvironment = System.getenv().toMutableMap()
for ((name, value) in commandLine.environmentVariables) {
currentEnvironment[name] = value
}
currentEnvironment.getOrPut("HOME") { System.getProperty("user.home") }
cmd.envParams = currentEnvironment
LOG.info("Execute command line: ${cmd.commandLineString}")
val executor = jetbrains.buildServer.CommandLineExecutor(cmd)
return executor.runProcess(executionTimeoutSeconds)?.let {
val result = CommandLineResult(
it.exitCode,
it.outLines.toList(),
it.stderr.split("\\r?\\n").toList())
if (LOG.isDebugEnabled) {
val resultStr = StringBuilder()
resultStr.append("Exit code: ${it.exitCode}")
resultStr.append("Stdout:\n${it.stdout}")
resultStr.append("Stderr:\n${it.stderr}")
LOG.debug("Result:\n$resultStr")
} else {
LOG.info("Exits with code: ${it.exitCode}")
}
return result
}
}
companion object {
private val LOG = Logger.getLogger(CommandLineExecutorImpl::class.java)
}
} | apache-2.0 | f7c4814ed33adefe4ec44b4e0318af52 | 37.297872 | 105 | 0.631462 | 4.98338 | false | false | false | false |
DeflatedPickle/Quiver | packsquashstep/src/main/kotlin/com/deflatedpickle/quiver/packsquashstep/PackSquashStep.kt | 1 | 4212 | /* Copyright (c) 2021 DeflatedPickle under the MIT license */
package com.deflatedpickle.quiver.packsquashstep
import com.deflatedpickle.haruhi.util.ConfigUtil
import com.deflatedpickle.marvin.Slug
import com.deflatedpickle.marvin.Version
import com.deflatedpickle.marvin.exceptions.UnsupportedOperatingSystemException
import com.deflatedpickle.marvin.extensions.Thread
import com.deflatedpickle.marvin.util.OSUtil
import com.deflatedpickle.quiver.packexport.api.BulkExportStep
import com.deflatedpickle.quiver.packexport.api.ExportStepType
import java.io.BufferedInputStream
import java.io.File
import java.io.IOException
import java.nio.file.Files
import javax.swing.ProgressMonitor
import org.apache.logging.log4j.LogManager
import org.oxbow.swingbits.dialog.task.TaskDialogs
object PackSquashStep : BulkExportStep() {
private val logger = LogManager.getLogger()
override fun getSlug(): Slug = Slug(
"DeflatedPickle",
"PackSquash",
Version(1, 0, 0)
)
override fun getType(): ExportStepType = ExportStepType.ZIPPER
override fun getIncompatibleTypes(): Collection<ExportStepType> = listOf(
ExportStepType.ZIPPER
)
override fun processFile(
file: File,
progressMonitor: ProgressMonitor
) {
var progress = 0
progressMonitor.maximum = Files.walk(file.toPath()).count().toInt()
val system = when (OSUtil.getOS()) {
OSUtil.OS.WINDOWS -> ""
OSUtil.OS.LINUX -> "linux"
OSUtil.OS.MAC -> "macos"
else -> throw UnsupportedOperatingSystemException(OSUtil.os)
}
val settings = ConfigUtil.getSettings<PackSquashStepSettings>("deflatedpickle@pack_squash_step#1.0.0")?.let { settings ->
val arguments = """
|resource_pack_directory = "."
|output_file_path = "${file.parentFile.absolutePath}/${file.nameWithoutExtension}.zip"
|${File(settings.settings).readText()}
""".trimMargin()
// println(arguments)
this.logger.debug("Starting PackSquash")
val process = ProcessBuilder(
"${File(".").canonicalPath}/${settings.location}/${settings.executable}" + if (OSUtil.isWindows()) ".exe" else "-$system",
"-"
)
.directory(file)
.redirectInput(ProcessBuilder.Redirect.PIPE)
.redirectOutput(ProcessBuilder.Redirect.PIPE)
.redirectError(ProcessBuilder.Redirect.INHERIT)
.start().apply {
try {
if (this.isAlive) {
for (line in arguments.lines()) {
outputStream.write(
"$line${System.lineSeparator()}".toByteArray()
)
}
outputStream.flush()
outputStream.close()
}
} catch (e: IOException) {
e.printStackTrace()
TaskDialogs.showException(e)
}
}
PackSquashStepPlugin.processList.add(process)
Thread("${getSlug().name} Feed") {
val outputStream = BufferedInputStream(
process.inputStream
)
try {
outputStream.bufferedReader().forEachLine {
if (progressMonitor.isCanceled) {
this.logger.debug("The PackSquash task was cancelled")
process.destroyForcibly()
return@forEachLine
}
this.logger.trace(it)
progressMonitor.note = it
progressMonitor.setProgress(++progress)
}
PackSquashStepPlugin.processList
} catch (e: IOException) {
}
progressMonitor.close()
}.start()
this.logger.debug("Started the PackSquash thread")
}
}
}
| mit | 461ef9ce9d363c4866d588fe2aac0348 | 38 | 138 | 0.55793 | 5.258427 | false | false | false | false |
zdary/intellij-community | platform/platform-impl/src/com/intellij/ide/cds/CDSPaths.kt | 13 | 2944 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.cds
import com.google.common.hash.Hashing
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.util.SystemInfo
import java.io.File
import java.time.LocalDateTime
class CDSPaths private constructor(val baseDir: File,
val dumpOutputFile: File,
val cdsClassesHash: String) {
val classesErrorMarkerFile = File(baseDir, "${cdsClassesHash}.error")
val classesListFile = File(baseDir, "${cdsClassesHash}.txt")
val classesPathFile = File(baseDir, "${cdsClassesHash}.classpath")
val classesArchiveFile = File(baseDir, "${cdsClassesHash}.jsa")
fun isSame(jsaFile: File?) = jsaFile != null && jsaFile == classesArchiveFile && jsaFile.isFile
fun isOurFile(file: File?) = file == classesErrorMarkerFile || file == classesListFile || file == classesPathFile || file == classesArchiveFile
fun mkdirs() {
baseDir.mkdirs()
dumpOutputFile.parentFile?.mkdirs()
}
fun markError(message: String) {
classesErrorMarkerFile.writeText("Failed on ${LocalDateTime.now()}: $message")
}
// re-compute installed plugins cache and see if there plugins were not changed
fun hasSameEnvironmentToBuildCDSArchive() = computePaths().cdsClassesHash == current.cdsClassesHash
companion object {
private val systemDir get() = File(PathManager.getSystemPath())
val freeSpaceForCDS get() = systemDir.freeSpace
val current: CDSPaths by lazy { computePaths() }
private fun computePaths(): CDSPaths {
val baseDir = File(systemDir, "cds")
val hasher = Hashing.sha256().newHasher()
// make sure the system folder was not moved
hasher.putString(baseDir.absolutePath, Charsets.UTF_8)
// make sure IDE folder was not moved
hasher.putString(PathManager.getHomePath(), Charsets.UTF_8)
val info = ApplicationInfo.getInstance()
//IntelliJ product
hasher.putString(info.build.asString(), Charsets.UTF_8)
//java runtime
hasher.putString(SystemInfo.getOsNameAndVersion(), Charsets.UTF_8)
hasher.putString(SystemInfo.JAVA_RUNTIME_VERSION, Charsets.UTF_8)
hasher.putString(SystemInfo.JAVA_VENDOR, Charsets.UTF_8)
hasher.putString(SystemInfo.JAVA_VERSION, Charsets.UTF_8)
//active plugins
PluginManagerCore.getLoadedPlugins().sortedBy { it.pluginId.idString }.forEach {
hasher.putString(it.pluginId.idString + ":" + it.version, Charsets.UTF_8)
}
val cdsClassesHash = "${info.build.asString()}-${hasher.hash()}"
val dumpLog = File(PathManager.getLogPath(), "cds-dump.log")
return CDSPaths(baseDir, dumpLog, cdsClassesHash)
}
}
}
| apache-2.0 | 23840b6ed5eb58703a909ec2c1e34e9e | 38.783784 | 145 | 0.711957 | 4.310395 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/casts/asSafe.kt | 2 | 259 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
fun foo(x: Any) = x as? Runnable
fun box(): String {
val r = object : Runnable {
override fun run() {}
}
return if (foo(r) === r) "OK" else "Fail"
}
| apache-2.0 | 48670bbc0c029013ed6927eb8e858942 | 22.545455 | 72 | 0.637066 | 3.011628 | false | false | false | false |
smmribeiro/intellij-community | notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/r/inlays/components/Separator.kt | 9 | 3413 | /*
* 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 org.jetbrains.plugins.notebooks.visualization.r.inlays.components
import com.intellij.ide.ui.UISettings
import com.intellij.openapi.actionSystem.ActionToolbar
import com.intellij.ui.JBColor
import com.intellij.ui.paint.LinePainter2D
import com.intellij.util.ui.JBDimension
import com.intellij.util.ui.JBUI
import java.awt.Dimension
import java.awt.FontMetrics
import java.awt.Graphics
import java.awt.Graphics2D
import javax.swing.JComponent
import javax.swing.SwingConstants
/** Public copy of MySeparator class from ActionToolbarImpl. Draws a separator in toolbar.*/
class MySeparator(private val myText: String?) : JComponent() {
private var myOrientation: Int = SwingConstants.HORIZONTAL
init {
font = JBUI.Fonts.toolbarSmallComboBoxFont()
}
override fun getPreferredSize(): Dimension {
val gap = JBUI.scale(2)
val center = JBUI.scale(3)
val width = gap * 2 + center
val height = JBUI.scale(24)
if (myOrientation != SwingConstants.HORIZONTAL) {
return JBDimension(height, width, true)
}
return if (myText != null) {
val fontMetrics = getFontMetrics(font)
val textWidth = getTextWidth(fontMetrics, myText, graphics)
JBDimension(width + gap * 2 + textWidth, Math.max(fontMetrics.height, height), true)
} else {
JBDimension(width, height, true)
}
}
private fun getMaxButtonHeight(): Int {
return ActionToolbar.NAVBAR_MINIMUM_BUTTON_SIZE.height
}
private fun getMaxButtonWidth(): Int {
return ActionToolbar.NAVBAR_MINIMUM_BUTTON_SIZE.width
}
override fun paintComponent(g: Graphics) {
if (parent == null) return
val gap = JBUI.scale(2)
val center = JBUI.scale(3)
val offset: Int = if (myOrientation == SwingConstants.HORIZONTAL) {
parent.height - getMaxButtonHeight() - 1
} else {
parent.width - getMaxButtonWidth() - 1
}
g.color = JBUI.CurrentTheme.CustomFrameDecorations.separatorForeground()
if (myOrientation == SwingConstants.HORIZONTAL) {
val y2 = parent.height - gap * 2 - offset
LinePainter2D.paint(g as Graphics2D, center.toDouble(), gap.toDouble(), center.toDouble(), y2.toDouble())
if (myText != null) {
val fontMetrics = getFontMetrics(font)
val top = (height - fontMetrics.height) / 2
UISettings.setupAntialiasing(g)
g.setColor(JBColor.foreground())
g.drawString(myText, gap * 2 + center + gap, top + fontMetrics.ascent)
}
} else {
LinePainter2D.paint(g as Graphics2D, gap.toDouble(), center.toDouble(), (parent.width - gap * 2 - offset).toDouble(), center.toDouble())
}
}
private fun getTextWidth(fontMetrics: FontMetrics, text: String, graphics: Graphics?): Int {
if (graphics == null) {
return fontMetrics.stringWidth(text)
}
val g = graphics.create()
try {
UISettings.setupAntialiasing(g)
return fontMetrics.getStringBounds(text, g).bounds.width
} finally {
g.dispose()
}
}
}
| apache-2.0 | 9396b1f3d9ab6080ffd5de736cbcc268 | 34.185567 | 148 | 0.640785 | 4.415265 | false | false | false | false |
smmribeiro/intellij-community | python/pydevSrc/com/jetbrains/python/debugger/pydev/ClientModeDebuggerStatusHolder.kt | 12 | 3320 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.debugger.pydev
import java.util.concurrent.locks.Condition
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
/**
* The status of the debugger looking from IDE side.
*
* @see ClientModeMultiProcessDebugger
*/
private enum class ClientModeDebuggerStatus {
/**
* The status before trying to connect to the main process.
*
* @see ClientModeMultiProcessDebugger.waitForConnect
*/
INITIAL,
/**
* The status after requesting to establish the connection with the main
* process but before the connection succeeded or failed.
*
* @see ClientModeMultiProcessDebugger.waitForConnect
*/
CONNECTING,
/**
* Indicates that this [ClientModeMultiProcessDebugger] has connected
* at least to one (the main one) Python debugging process.
*
* *As Python debugging process does not start the underlying Python
* script before we send him [RunCommand] so the first process we
* connected to is the main Python script process.*
*/
CONNECTED,
/**
* Corresponds to one of the two alternatives:
* - the debugger script process is terminated;
* - the user requested to detach IDE from the debugger script.
*/
DISCONNECTION_INITIATED
}
internal class ClientModeDebuggerStatusHolder {
private val lock: ReentrantLock = ReentrantLock()
private val condition: Condition = lock.newCondition()
/**
* Guarded by [lock].
*/
private var status: ClientModeDebuggerStatus = ClientModeDebuggerStatus.INITIAL
/**
* Switches the current status from "initial" to "connecting".
*
* @throws IllegalStateException if the current status is not initial
*/
fun onConnecting() {
lock.withLock {
if (status != ClientModeDebuggerStatus.INITIAL) throw IllegalStateException()
status = ClientModeDebuggerStatus.CONNECTING
condition.signalAll()
}
}
/**
* Switches the current status from "connecting" to "connected". Returns
* whether the switch succeeded.
*/
fun onConnected(): Boolean =
lock.withLock {
if (status == ClientModeDebuggerStatus.CONNECTING) {
status = ClientModeDebuggerStatus.CONNECTED
condition.signalAll()
return@withLock true
}
else {
return@withLock false
}
}
/**
* Switches the current status to "disconnecting" unconditionally.
*/
fun onDisconnectionInitiated() {
lock.withLock {
status = ClientModeDebuggerStatus.DISCONNECTION_INITIATED
condition.signalAll()
}
}
/**
* Causes the current thread to wait until the status is changed from
* "connecting" to "connected" or "disconnected".
*
* Returns `true` if the status becomes "connected" and `false` otherwise.
*
* @throws IllegalStateException if the current state is "initial"
*/
fun awaitWhileConnecting(): Boolean =
lock.withLock {
if (status == ClientModeDebuggerStatus.INITIAL) throw IllegalStateException()
while (status == ClientModeDebuggerStatus.CONNECTING) {
condition.await()
}
return@awaitWhileConnecting status == ClientModeDebuggerStatus.CONNECTED
}
} | apache-2.0 | 0faee2adfb12448b7a0b86e4a28fe31d | 26.907563 | 140 | 0.704819 | 4.585635 | false | false | false | false |
smmribeiro/intellij-community | java/java-analysis-api/src/com/intellij/lang/jvm/actions/JvmElementActionsFactory.kt | 8 | 1949 | // 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 com.intellij.lang.jvm.actions
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.lang.jvm.JvmClass
import com.intellij.lang.jvm.JvmMethod
import com.intellij.lang.jvm.JvmModifiersOwner
import com.intellij.lang.jvm.JvmParameter
/**
* Extension Point provides language-abstracted code modifications for JVM-based languages.
*
* Each method should return list of code modifications which could be empty.
* If method returns empty list this means that operation on given elements is not supported or not yet implemented for a language.
*
* Every new added method should return empty list by default and then be overridden in implementations for each language if it is possible.
*/
abstract class JvmElementActionsFactory {
open fun createChangeModifierActions(target: JvmModifiersOwner, request: ChangeModifierRequest): List<IntentionAction> = emptyList()
open fun createAddAnnotationActions(target: JvmModifiersOwner, request: AnnotationRequest): List<IntentionAction> = emptyList()
open fun createAddFieldActions(targetClass: JvmClass, request: CreateFieldRequest): List<IntentionAction> = emptyList()
open fun createAddMethodActions(targetClass: JvmClass, request: CreateMethodRequest): List<IntentionAction> = emptyList()
open fun createAddConstructorActions(targetClass: JvmClass, request: CreateConstructorRequest): List<IntentionAction> = emptyList()
open fun createChangeParametersActions(target: JvmMethod, request: ChangeParametersRequest): List<IntentionAction> = emptyList()
open fun createChangeTypeActions(target: JvmMethod, request: ChangeTypeRequest): List<IntentionAction> = emptyList()
open fun createChangeTypeActions(target: JvmParameter, request: ChangeTypeRequest): List<IntentionAction> = emptyList()
}
| apache-2.0 | 90b38b9315ff78aa2fddbddb3a5a33d1 | 56.323529 | 158 | 0.813751 | 4.946701 | false | false | false | false |
simasch/simon | src/main/java/ch/simas/monitor/boundry/CheckController.kt | 1 | 3293 | package ch.simas.monitor.boundry
import ch.simas.monitor.control.MeasurementRepository
import ch.simas.monitor.entity.Measurement
import ch.simas.monitor.xml.Hosts
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import java.io.File
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
import java.time.format.DateTimeFormatter
import javax.xml.bind.JAXBContext
import javax.xml.bind.JAXBException
import javax.xml.bind.Unmarshaller
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping("/check")
open class CheckController(@Value("\${simon.config.hosts}") val config: String, @Autowired val measurementRepository: MeasurementRepository) {
private val log: Log = LogFactory.getLog(CheckController::class.toString())
@RequestMapping("/latest")
fun getLatest(): Hosts {
val hosts = loadConfiguration(config)
hosts.group.forEach { group ->
group.host.forEach { host ->
val measurements = measurementRepository.find(host.url, 1, null, null)
if (!measurements.isEmpty()) {
val measurement = measurements[0]
host.status = measurement.status
host.duration = measurement.duration
host.timestamp = measurement.timestamp.format(DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss"))
}
}
}
return hosts
}
@RequestMapping
@Scheduled(initialDelay = 1 * 60 * 1000, fixedRate = 1 * 60 * 5000)
fun check() {
try {
val hosts = loadConfiguration(config)
hosts.group.forEach { group ->
group.host.forEach { host ->
val start = System.currentTimeMillis()
val obj = URL(host.url)
try {
val connection = obj.openConnection() as HttpURLConnection
val responseCode = connection.responseCode
host.status = "" + responseCode
host.duration = System.currentTimeMillis() - start
connection.disconnect();
} catch (e: Exception) {
log.error(e.message, e)
host.status = e.message
}
measurementRepository.createMeasurement(host.name, host.url, host.status, host.duration)
}
}
} catch (e: IOException) {
throw RuntimeException(e)
}
}
private fun loadConfiguration(configFile: String): Hosts {
try {
val file = File(configFile)
val jaxbContext = JAXBContext.newInstance(Hosts::class.java)
val unmarshaller = jaxbContext.createUnmarshaller()
val hosts = unmarshaller.unmarshal(file) as Hosts
return hosts
} catch (e: JAXBException) {
throw RuntimeException(e)
}
}
}
| apache-2.0 | 417f29d957b4e94ce7888bafff9c7da9 | 36.420455 | 142 | 0.620711 | 4.856932 | false | true | false | false |
fabmax/kool | kool-core/src/jvmMain/kotlin/de/fabmax/kool/platform/vk/pipeline/PipelineManager.kt | 1 | 4265 | package de.fabmax.kool.platform.vk.pipeline
import de.fabmax.kool.pipeline.Pipeline
import de.fabmax.kool.pipeline.RenderPass
import de.fabmax.kool.platform.vk.SwapChain
import de.fabmax.kool.platform.vk.VkRenderPass
import de.fabmax.kool.platform.vk.VkSystem
import de.fabmax.kool.util.logD
class PipelineManager(val sys: VkSystem) {
private val onScreenPipelineConfigs = mutableSetOf<PipelineAndRenderPass>()
private var swapChain: SwapChain? = null
private val createdPipelines = mutableMapOf<ULong, CreatedPipeline>()
fun onSwapchainDestroyed() {
swapChain = null
createdPipelines.clear()
}
fun onSwapchainCreated(swapChain: SwapChain) {
this.swapChain = swapChain
onScreenPipelineConfigs.forEach { createOnScreenPipeline(it.pipeline, it.koolRenderPass, swapChain.renderPass) }
}
fun hasPipeline(pipeline: Pipeline, renderPass: Long): Boolean =
createdPipelines[pipeline.pipelineHash]?.existsForRenderPass(renderPass) ?: false
fun addPipelineConfig(pipeline: Pipeline, nImages: Int, koolRenderPass: RenderPass, renderPass: VkRenderPass, dynVp: Boolean) {
if (renderPass === swapChain?.renderPass) {
if (onScreenPipelineConfigs.add(PipelineAndRenderPass(pipeline, koolRenderPass))) {
logD { "New on screen pipeline: ${pipeline.name}" }
createOnScreenPipeline(pipeline, koolRenderPass, renderPass)
}
} else {
val gp = GraphicsPipeline(sys, koolRenderPass, renderPass, 1, dynVp, pipeline, nImages)
sys.device.addDependingResource(gp)
val createdPipeline = createdPipelines.getOrPut(pipeline.pipelineHash) { CreatedPipeline(false) }
createdPipeline.addRenderPassPipeline(renderPass, gp)
}
}
private fun createOnScreenPipeline(pipeline: Pipeline, koolRenderPass: RenderPass, renderPass: VkRenderPass) {
val swapChain = this.swapChain ?: return
val gp = GraphicsPipeline(sys, koolRenderPass, renderPass, sys.physicalDevice.msaaSamples, true, pipeline, swapChain.nImages)
swapChain.addDependingResource(gp)
val createdPipeline = createdPipelines.getOrPut(pipeline.pipelineHash) { CreatedPipeline(true) }
createdPipeline.addRenderPassPipeline(renderPass, gp)
}
fun getPipeline(pipeline: Pipeline, renderPass: Long): GraphicsPipeline {
return createdPipelines[pipeline.pipelineHash]?.graphicsPipelines?.get(renderPass)
?: throw NoSuchElementException("Unknown pipeline config: ${pipeline.pipelineHash}")
}
fun getPipeline(pipeline: Pipeline): CreatedPipeline? {
return createdPipelines[pipeline.pipelineHash]
}
inner class CreatedPipeline(private val isOnScreen: Boolean) {
val graphicsPipelines = mutableMapOf<Long, GraphicsPipeline>()
fun existsForRenderPass(renderPass: Long) = graphicsPipelines.containsKey(renderPass)
fun addRenderPassPipeline(renderPass: VkRenderPass, graphicsPipeline: GraphicsPipeline) {
graphicsPipelines[renderPass.vkRenderPass] = graphicsPipeline
}
fun freeDescriptorSetInstance(pipeline: Pipeline) {
// find GraphicsPipeline containing pipelineInstance
val iterator = graphicsPipelines.values.iterator()
for (gp in iterator) {
if (gp.freeDescriptorSetInstance(pipeline) && gp.isEmpty()) {
// all descriptor set instances of this particular pipeline are freed, destroy it..
if (isOnScreen) {
swapChain?.removeDependingResource(gp)
} else {
sys.device.removeDependingResource(gp)
}
gp.destroy()
iterator.remove()
}
}
if (graphicsPipelines.isEmpty()) {
// all pipelines destroyed, remove CreatedPipeline instance
createdPipelines.remove(pipeline.pipelineHash) != null
onScreenPipelineConfigs.removeIf { it.pipeline == pipeline }
}
}
}
private class PipelineAndRenderPass(val pipeline: Pipeline, val koolRenderPass: RenderPass)
} | apache-2.0 | a670ccaa1076723e134ea87ac4c3430f | 44.382979 | 133 | 0.680891 | 5.029481 | false | true | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/viewmodels/MessageCreatorViewModel.kt | 1 | 6200 | package com.kickstarter.viewmodels
import androidx.annotation.NonNull
import com.kickstarter.R
import com.kickstarter.libs.ActivityViewModel
import com.kickstarter.libs.Environment
import com.kickstarter.libs.rx.transformers.Transformers.errors
import com.kickstarter.libs.rx.transformers.Transformers.takeWhen
import com.kickstarter.libs.rx.transformers.Transformers.values
import com.kickstarter.libs.utils.ObjectUtils
import com.kickstarter.libs.utils.extensions.isPresent
import com.kickstarter.models.MessageThread
import com.kickstarter.models.Project
import com.kickstarter.ui.IntentKey
import com.kickstarter.ui.activities.MessageCreatorActivity
import rx.Observable
import rx.subjects.BehaviorSubject
import rx.subjects.PublishSubject
interface MessageCreatorViewModel {
interface Inputs {
/** Call when the message edit text changes. */
fun messageBodyChanged(messageBody: String)
/** Call when the send message button has been clicked. */
fun sendButtonClicked()
}
interface Outputs {
/** Emits the creator's name to display in the message edit text hint. */
fun creatorName(): Observable<String>
/** Emits when the progress bar should be visible. */
fun progressBarIsVisible(): Observable<Boolean>
/** Emits a boolean that determines if the send button should be enabled. */
fun sendButtonIsEnabled(): Observable<Boolean>
/** Emits the MessageThread that the successfully sent message belongs to. */
fun showMessageThread(): Observable<MessageThread>
/** Emits when the message failed to successfully. */
fun showSentError(): Observable<Int>
/** Emits when the message was sent successfully but the thread failed to load. */
fun showSentSuccess(): Observable<Int>
}
class ViewModel(environment: Environment) : ActivityViewModel<MessageCreatorActivity>(environment), Inputs, Outputs {
private val messageBodyChanged = PublishSubject.create<String>()
private val sendButtonClicked = PublishSubject.create<Void>()
private val creatorName = BehaviorSubject.create<String>()
private val progressBarIsVisible = BehaviorSubject.create<Boolean>()
private val sendButtonIsEnabled = BehaviorSubject.create<Boolean>()
private val showMessageThread = BehaviorSubject.create<MessageThread>()
private val showSentError = BehaviorSubject.create<Int>()
private val showSentSuccess = BehaviorSubject.create<Int>()
private val apiClient = requireNotNull(environment.apiClient())
private val apolloClient = requireNotNull(environment.apolloClient())
val inputs: Inputs = this
val outputs: Outputs = this
init {
val project = intent()
.map { it.getParcelableExtra(IntentKey.PROJECT) as Project? }
.filter { ObjectUtils.isNotNull(it) }
.map { requireNotNull(it) }
project
.map { it.creator().name() }
.compose(bindToLifecycle())
.subscribe(this.creatorName)
val sendMessage = Observable.combineLatest(project, this.messageBodyChanged.startWith("")) { p, u -> SendMessage(p, u) }
this.messageBodyChanged
.map { it.isPresent() }
.distinctUntilChanged()
.subscribe(this.sendButtonIsEnabled)
val sendMessageNotification = sendMessage
.compose(takeWhen<SendMessage, Void>(this.sendButtonClicked))
.switchMap { sendMessage(it).materialize() }
.compose(bindToLifecycle())
.share()
sendMessageNotification
.compose(errors())
.map { R.string.social_error_could_not_send_message_backer }
.subscribe {
this.showSentError.onNext(it)
this.progressBarIsVisible.onNext(false)
this.sendButtonIsEnabled.onNext(true)
}
sendMessageNotification
.compose(values())
.switchMap { fetchThread(it) }
.filter(ObjectUtils::isNotNull)
.subscribe(this.showMessageThread)
}
private fun fetchThread(conversationId: Long): Observable<MessageThread> {
val fetchThreadNotification = this.apiClient.fetchMessagesForThread(conversationId)
.compose(bindToLifecycle())
.materialize()
.share()
fetchThreadNotification
.compose(errors())
.map { R.string.Your_message_has_been_sent }
.subscribe(this.showSentSuccess)
return fetchThreadNotification
.compose(values())
.map { it.messageThread() }
}
private fun sendMessage(sendMessage: SendMessage): Observable<Long> {
return this.apolloClient.sendMessage(sendMessage.project, sendMessage.project.creator(), sendMessage.body)
.doOnSubscribe {
this.progressBarIsVisible.onNext(true)
this.sendButtonIsEnabled.onNext(false)
}
}
override fun messageBodyChanged(messageBody: String) {
this.messageBodyChanged.onNext(messageBody)
}
override fun sendButtonClicked() {
this.sendButtonClicked.onNext(null)
}
@NonNull
override fun creatorName(): Observable<String> = this.creatorName
@NonNull
override fun progressBarIsVisible(): Observable<Boolean> = this.progressBarIsVisible
@NonNull
override fun sendButtonIsEnabled(): Observable<Boolean> = this.sendButtonIsEnabled
@NonNull
override fun showMessageThread(): Observable<MessageThread> = this.showMessageThread
@NonNull
override fun showSentError(): Observable<Int> = this.showSentError
@NonNull
override fun showSentSuccess(): Observable<Int> = this.showSentSuccess
data class SendMessage(val project: Project, val body: String)
}
}
| apache-2.0 | c6d169d85e4c95441fe34636ba999a66 | 37.993711 | 132 | 0.649839 | 5.358686 | false | false | false | false |
fabmax/kool | kool-demo/src/commonMain/kotlin/de/fabmax/kool/demo/physics/terrain/OceanFloorRenderPass.kt | 1 | 2280 | package de.fabmax.kool.demo.physics.terrain
import de.fabmax.kool.pipeline.OffscreenRenderPass2d
import de.fabmax.kool.pipeline.TexFormat
import de.fabmax.kool.pipeline.renderPassConfig
import de.fabmax.kool.scene.Group
import de.fabmax.kool.scene.PerspectiveCamera
import de.fabmax.kool.scene.PerspectiveProxyCam
import de.fabmax.kool.scene.Scene
import de.fabmax.kool.util.MdColor
class OceanFloorRenderPass(mainScene: Scene, val terrainTiles: TerrainTiles) : OffscreenRenderPass2d(Group(), renderPassConfig {
name = "OceanFloorPass"
setDynamicSize()
addColorTexture(TexFormat.RGBA)
setDepthTexture(false)
}) {
val renderGroup: Group
get() = drawNode as Group
init {
isUpdateDrawNode = false
clearColor = MdColor.GREY
(drawNode as Group).apply {
for (i in 0 until TerrainTiles.TILE_CNT_XY) {
for (j in 0 until TerrainTiles.TILE_CNT_XY) {
if (terrainTiles.getMinElevation(i, j) < Ocean.OCEAN_FLOOR_HEIGHT_THRESH) {
+terrainTiles.getTile(i, j)
}
}
}
}
mainScene.addOffscreenPass(this)
mainScene.onRenderScene += { ctx ->
val mapW = (mainScene.mainRenderPass.viewport.width * RENDER_SIZE_FACTOR).toInt()
val mapH = (mainScene.mainRenderPass.viewport.height * RENDER_SIZE_FACTOR).toInt()
if (isEnabled && mapW > 0 && mapH > 0 && (mapW != width || mapH != height)) {
resize(mapW, mapH, ctx)
}
}
// onBeforeRenderQueue += {
// (terrainTiles.terrainShader?.uniforms?.get(Terrain.TERRAIN_SHADER_DISCARD_HEIGHT) as? Uniform1f)?.value = OCEAN_FLOOR_HEIGHT_THRESH
// }
// onAfterRenderQueue += {
// (terrainTiles.terrainShader?.uniforms?.get(Terrain.TERRAIN_SHADER_DISCARD_HEIGHT) as? Uniform1f)?.value = 1000f
// }
val proxyCamera = PerspectiveProxyCam(mainScene.camera as PerspectiveCamera)
onBeforeCollectDrawCommands += {
proxyCamera.sync(mainScene.mainRenderPass, it)
}
camera = proxyCamera
lighting = mainScene.lighting
}
companion object {
const val RENDER_SIZE_FACTOR = 0.5f
}
} | apache-2.0 | 3a9c8142d3af49b72bf4b2de00fa59e8 | 35.206349 | 145 | 0.638596 | 3.90411 | false | false | false | false |
ingokegel/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ChildSingleSecondEntityImpl.kt | 1 | 10315 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
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.EntityLink
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 com.intellij.workspaceModel.storage.impl.extractOneToAbstractOneParent
import com.intellij.workspaceModel.storage.impl.updateOneToAbstractOneParentOfChild
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Abstract
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ChildSingleSecondEntityImpl : ChildSingleSecondEntity, WorkspaceEntityBase() {
companion object {
internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(ParentSingleAbEntity::class.java,
ChildSingleAbstractBaseEntity::class.java,
ConnectionId.ConnectionType.ABSTRACT_ONE_TO_ONE, false)
val connections = listOf<ConnectionId>(
PARENTENTITY_CONNECTION_ID,
)
}
@JvmField
var _commonData: String? = null
override val commonData: String
get() = _commonData!!
override val parentEntity: ParentSingleAbEntity
get() = snapshot.extractOneToAbstractOneParent(PARENTENTITY_CONNECTION_ID, this)!!
@JvmField
var _secondData: String? = null
override val secondData: String
get() = _secondData!!
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: ChildSingleSecondEntityData?) : ModifiableWorkspaceEntityBase<ChildSingleSecondEntity>(), ChildSingleSecondEntity.Builder {
constructor() : this(ChildSingleSecondEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ChildSingleSecondEntity 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().isCommonDataInitialized()) {
error("Field ChildSingleAbstractBaseEntity#commonData should be initialized")
}
if (_diff != null) {
if (_diff.extractOneToAbstractOneParent<WorkspaceEntityBase>(PARENTENTITY_CONNECTION_ID, this) == null) {
error("Field ChildSingleAbstractBaseEntity#parentEntity should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] == null) {
error("Field ChildSingleAbstractBaseEntity#parentEntity should be initialized")
}
}
if (!getEntityData().isSecondDataInitialized()) {
error("Field ChildSingleSecondEntity#secondData 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 ChildSingleSecondEntity
this.entitySource = dataSource.entitySource
this.commonData = dataSource.commonData
this.secondData = dataSource.secondData
if (parents != null) {
this.parentEntity = parents.filterIsInstance<ParentSingleAbEntity>().single()
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var commonData: String
get() = getEntityData().commonData
set(value) {
checkModificationAllowed()
getEntityData().commonData = value
changedProperty.add("commonData")
}
override var parentEntity: ParentSingleAbEntity
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToAbstractOneParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false,
PARENTENTITY_CONNECTION_ID)]!! as ParentSingleAbEntity
}
else {
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as ParentSingleAbEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToAbstractOneParentOfChild(PARENTENTITY_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value
}
changedProperty.add("parentEntity")
}
override var secondData: String
get() = getEntityData().secondData
set(value) {
checkModificationAllowed()
getEntityData().secondData = value
changedProperty.add("secondData")
}
override fun getEntityData(): ChildSingleSecondEntityData = result ?: super.getEntityData() as ChildSingleSecondEntityData
override fun getEntityClass(): Class<ChildSingleSecondEntity> = ChildSingleSecondEntity::class.java
}
}
class ChildSingleSecondEntityData : WorkspaceEntityData<ChildSingleSecondEntity>() {
lateinit var commonData: String
lateinit var secondData: String
fun isCommonDataInitialized(): Boolean = ::commonData.isInitialized
fun isSecondDataInitialized(): Boolean = ::secondData.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ChildSingleSecondEntity> {
val modifiable = ChildSingleSecondEntityImpl.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): ChildSingleSecondEntity {
val entity = ChildSingleSecondEntityImpl()
entity._commonData = commonData
entity._secondData = secondData
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ChildSingleSecondEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return ChildSingleSecondEntity(commonData, secondData, entitySource) {
this.parentEntity = parents.filterIsInstance<ParentSingleAbEntity>().single()
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
res.add(ParentSingleAbEntity::class.java)
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ChildSingleSecondEntityData
if (this.entitySource != other.entitySource) return false
if (this.commonData != other.commonData) return false
if (this.secondData != other.secondData) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ChildSingleSecondEntityData
if (this.commonData != other.commonData) return false
if (this.secondData != other.secondData) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + commonData.hashCode()
result = 31 * result + secondData.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + commonData.hashCode()
result = 31 * result + secondData.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | 3265225e73321ca20c54b57f6f4ef745 | 36.373188 | 165 | 0.704508 | 5.695748 | false | false | false | false |
leafclick/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/transformations/indexedProperty/IndexedPropertyAnnotationChecker.kt | 1 | 2179 | /*
* Copyright 2000-2016 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 org.jetbrains.plugins.groovy.transformations.indexedProperty
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.HighlightSeverity
import org.jetbrains.plugins.groovy.annotator.checkers.CustomAnnotationChecker
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration
class IndexedPropertyAnnotationChecker : CustomAnnotationChecker() {
override fun checkApplicability(holder: AnnotationHolder, annotation: GrAnnotation): Boolean {
if (annotation.qualifiedName != indexedPropertyFqn) return false
val modifierList = annotation.owner as? GrModifierList ?: return true
val parent = modifierList.parent as? GrVariableDeclaration ?: return true
val field = parent.variables.singleOrNull() as? GrField ?: return true
if (!field.isProperty) {
holder.newAnnotation(HighlightSeverity.ERROR, "@IndexedProperty is applicable to properties only").range(annotation).create()
return true
}
if (field.getIndexedComponentType() == null) {
val elementToHighlight = field.typeElementGroovy ?: field.nameIdentifierGroovy
val message = "Property is not indexable. Type must be array or list but found ${field.type.presentableText}"
holder.createErrorAnnotation(elementToHighlight, message)
}
return true
}
} | apache-2.0 | da44ee48681c1300d8e19b67a70e6a5a | 45.382979 | 131 | 0.781092 | 4.63617 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/gradle/gradle-idea/src/org/jetbrains/kotlin/idea/scripting/gradle/importing/KotlinDslSyncListener.kt | 1 | 4919 | // 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.idea.scripting.gradle.importing
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListener
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListenerAdapter
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskType
import com.intellij.openapi.externalSystem.service.execution.ExternalSystemJdkUtil
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.projectRoots.JdkUtil
import org.jetbrains.kotlin.idea.configuration.GRADLE_SYSTEM_ID
import org.jetbrains.kotlin.idea.core.script.ScriptDefinitionContributor
import org.jetbrains.kotlin.idea.scripting.gradle.GradleScriptDefinitionsContributor
import org.jetbrains.kotlin.idea.scripting.gradle.roots.GradleBuildRootsManager
import org.jetbrains.kotlin.idea.scripting.gradle.validateGradleSdk
import org.jetbrains.plugins.gradle.service.GradleInstallationManager
import org.jetbrains.plugins.gradle.settings.GradleExecutionSettings
import org.jetbrains.plugins.gradle.settings.GradleSettings
import org.jetbrains.plugins.gradle.util.GradleConstants
import java.util.*
class KotlinDslSyncListener : ExternalSystemTaskNotificationListenerAdapter() {
companion object {
val instance: KotlinDslSyncListener?
get() =
ExternalSystemTaskNotificationListener.EP_NAME.findExtension(KotlinDslSyncListener::class.java)
}
internal val tasks = WeakHashMap<ExternalSystemTaskId, KotlinDslGradleBuildSync>()
override fun onStart(id: ExternalSystemTaskId, workingDir: String?) {
if (!isGradleProjectResolve(id)) return
if (workingDir == null) return
val task = KotlinDslGradleBuildSync(workingDir, id)
synchronized(tasks) { tasks[id] = task }
// project may be null in case of new project
val project = id.findProject() ?: return
task.project = project
GradleBuildRootsManager.getInstance(project)?.markImportingInProgress(workingDir)
}
override fun onEnd(id: ExternalSystemTaskId) {
if (!isGradleProjectResolve(id)) return
val sync = synchronized(tasks) { tasks.remove(id) } ?: return
// project may be null in case of new project
val project = id.findProject() ?: return
if (sync.gradleHome == null) {
sync.gradleHome = ServiceManager
.getService(GradleInstallationManager::class.java)
.getGradleHome(project, sync.workingDir)
?.path
}
if (sync.javaHome == null) {
sync.javaHome = ExternalSystemApiUtil
.getExecutionSettings<GradleExecutionSettings>(project, sync.workingDir, GradleConstants.SYSTEM_ID)
.javaHome
}
sync.javaHome = sync.javaHome?.takeIf { JdkUtil.checkForJdk(it) }
?: run {
// roll back to specified in GRADLE_JVM if for some reason sync.javaHome points to corrupted SDK
val gradleJvm = GradleSettings.getInstance(project).getLinkedProjectSettings(sync.workingDir)?.gradleJvm
try {
ExternalSystemJdkUtil.getJdk(project, gradleJvm)?.homePath
} catch (e: Exception) {
null
}
}
GradleSettings.getInstance(project).getLinkedProjectSettings(sync.workingDir)?.validateGradleSdk(project, sync.javaHome)
@Suppress("DEPRECATION")
ScriptDefinitionContributor.find<GradleScriptDefinitionsContributor>(project)?.reloadIfNeeded(
sync.workingDir, sync.gradleHome, sync.javaHome
)
saveScriptModels(project, sync)
}
override fun onFailure(id: ExternalSystemTaskId, e: Exception) {
if (!isGradleProjectResolve(id)) return
val sync = synchronized(tasks) { tasks[id] } ?: return
sync.failed = true
}
override fun onCancel(id: ExternalSystemTaskId) {
if (!isGradleProjectResolve(id)) return
val cancelled = synchronized(tasks) { tasks.remove(id) }
// project may be null in case of new project
val project = id.findProject() ?: return
cancelled?.let {
GradleBuildRootsManager.getInstance(project)?.markImportingInProgress(it.workingDir, false)
if (it.failed) {
reportErrors(project, it)
}
}
}
private fun isGradleProjectResolve(id: ExternalSystemTaskId) =
id.type == ExternalSystemTaskType.RESOLVE_PROJECT &&
id.projectSystemId == GRADLE_SYSTEM_ID
}
| apache-2.0 | afe900edea478ed0c466659a94e89a10 | 42.149123 | 158 | 0.709697 | 5.092133 | false | false | false | false |
androidx/androidx | compose/foundation/foundation/src/androidAndroidTest/kotlin/androidx/compose/foundation/relocation/FakeScrollable.kt | 3 | 1881 | /*
* 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.compose.foundation.relocation
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
/**
* Returns a [bringIntoViewResponder] modifier that implements [BringIntoViewResponder] by
* offsetting the local rect by [parentOffset] and handling the request by calling
* [onBringIntoView]. Note that [onBringIntoView] will not be called if [parentOffset] is zero,
* since that means the scrollable doesn't actually need to scroll anything to satisfy the
* request.
*/
@OptIn(ExperimentalFoundationApi::class)
internal fun Modifier.fakeScrollable(
parentOffset: Offset = Offset.Zero,
onBringIntoView: suspend (() -> Rect?) -> Unit
): Modifier = bringIntoViewResponder(
object : BringIntoViewResponder {
override fun calculateRectForParent(localRect: Rect): Rect =
localRect.translate(parentOffset)
override suspend fun bringChildIntoView(localRect: () -> Rect?) {
onBringIntoView(localRect)
}
})
.wrapContentSize(align = Alignment.TopStart, unbounded = true) | apache-2.0 | 201d4eb9cc08da36d170648df973ae99 | 39.913043 | 95 | 0.756512 | 4.436321 | false | false | false | false |
djkovrik/YapTalker | data/src/main/java/com/sedsoftware/yaptalker/data/repository/YapLoginSessionRepository.kt | 1 | 4162 | package com.sedsoftware.yaptalker.data.repository
import android.util.Log
import com.sedsoftware.yaptalker.data.exception.RequestErrorException
import com.sedsoftware.yaptalker.data.mapper.LoginSessionInfoMapper
import com.sedsoftware.yaptalker.data.mapper.ServerResponseMapper
import com.sedsoftware.yaptalker.data.network.site.YapApi
import com.sedsoftware.yaptalker.data.network.site.YapLoader
import com.sedsoftware.yaptalker.data.system.SchedulersProvider
import com.sedsoftware.yaptalker.domain.device.CookieStorage
import com.sedsoftware.yaptalker.domain.entity.base.LoginSessionInfo
import com.sedsoftware.yaptalker.domain.repository.LoginSessionRepository
import io.reactivex.Completable
import io.reactivex.Single
import javax.inject.Inject
class YapLoginSessionRepository @Inject constructor(
private val dataLoader: YapLoader,
private val yapApi: YapApi,
private val cookieStorage: CookieStorage,
private val dataMapper: LoginSessionInfoMapper,
private val responseMapper: ServerResponseMapper,
private val schedulers: SchedulersProvider
) : LoginSessionRepository {
companion object {
private const val LOGIN_COOKIE_DATE = 1
private const val LOGIN_REFERRER = "http://www.yaplakal.com/forum/"
private const val LOGIN_SUBMIT = "Вход"
private const val SIGN_OUT_SUCCESS_MARKER = "Вы вышли"
private const val SIGN_IN_SUCCESS_MARKER = "Спасибо"
}
override fun getLoginSessionInfo(): Single<LoginSessionInfo> =
dataLoader
.loadAuthorizedUserInfo()
.map(dataMapper)
.subscribeOn(schedulers.io())
override fun requestSignIn(userLogin: String, userPassword: String, anonymously: Boolean): Completable =
dataLoader
.signIn(
cookieDate = LOGIN_COOKIE_DATE,
privacy = anonymously,
password = userPassword,
userName = userLogin,
referer = LOGIN_REFERRER,
submit = LOGIN_SUBMIT,
userKey = "$userLogin${System.currentTimeMillis()}".toMd5()
)
.map(responseMapper)
.flatMapCompletable { response ->
if (response.text.contains(SIGN_IN_SUCCESS_MARKER)) {
Completable.complete()
} else {
Completable.error(RequestErrorException("Unable to complete sign in request."))
}
}
.subscribeOn(schedulers.io())
override fun requestSignOut(userKey: String): Completable =
dataLoader
.signOut(userKey)
.map(responseMapper)
.flatMapCompletable { response ->
if (response.text.contains(SIGN_OUT_SUCCESS_MARKER)) {
Completable.complete()
} else {
Completable.error(RequestErrorException("Unable to complete sign out request."))
}
}
.subscribeOn(schedulers.io())
override fun requestSignInWithApi(userLogin: String, userPassword: String): Completable =
yapApi
.authUser(
name = userLogin,
password = userPassword
)
.flatMapCompletable { response ->
Log.d("NewAuth", "Response: $response")
val sid = response.user?.sid.orEmpty()
if (sid.isNotEmpty()) {
cookieStorage.saveCookie("SID=$sid")
}
Completable.complete()
}
.subscribeOn(schedulers.io())
@Suppress("MagicNumber")
private fun String.toMd5(): String {
val digest = java.security.MessageDigest.getInstance("MD5")
digest.update(this.toByteArray())
val messageDigest = digest.digest()
val hexString = StringBuffer()
for (i in 0 until messageDigest.size) {
var hex = Integer.toHexString(0xFF and messageDigest[i].toInt())
while (hex.length < 2)
hex = "0$hex"
hexString.append(hex)
}
return hexString.toString()
}
}
| apache-2.0 | dbfa98cfc6c5ec2ef48c88966aec4559 | 38.09434 | 108 | 0.629102 | 4.933333 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/view/CoroutineDumpPanel.kt | 2 | 11678 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.debugger.coroutine.view
import com.intellij.codeInsight.highlighting.HighlightManager
import com.intellij.debugger.actions.ThreadDumpAction
import com.intellij.execution.ui.ConsoleView
import com.intellij.icons.AllIcons
import com.intellij.ide.DataManager
import com.intellij.ide.ExporterToTextFile
import com.intellij.ide.ui.UISettings
import com.intellij.notification.NotificationGroup
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.colors.EditorColors
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.ide.CopyPasteManager
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.MessageType
import com.intellij.openapi.ui.Splitter
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.openapi.wm.ToolWindowId
import com.intellij.ui.*
import com.intellij.ui.components.JBList
import com.intellij.unscramble.AnalyzeStacktraceUtil
import com.intellij.util.PlatformIcons
import org.jetbrains.kotlin.idea.debugger.coroutine.KotlinDebuggerCoroutinesBundle
import org.jetbrains.kotlin.idea.debugger.coroutine.data.CompleteCoroutineInfoData
import java.awt.BorderLayout
import java.awt.Color
import java.awt.datatransfer.StringSelection
import java.io.File
import javax.swing.*
import javax.swing.event.DocumentEvent
/**
* Panel with dump of coroutines
*/
class CoroutineDumpPanel(
project: Project,
consoleView: ConsoleView,
toolbarActions: DefaultActionGroup,
val dump: List<CompleteCoroutineInfoData>
) :
JPanel(BorderLayout()), DataProvider {
private var exporterToTextFile: ExporterToTextFile
private var mergedDump = ArrayList<CompleteCoroutineInfoData>()
val filterField = SearchTextField()
val filterPanel = JPanel(BorderLayout())
private val coroutinesList = JBList(DefaultListModel<Any>())
init {
mergedDump.addAll(dump)
filterField.addDocumentListener(object : DocumentAdapter() {
override fun textChanged(e: DocumentEvent) {
updateCoroutinesList()
}
})
filterPanel.apply {
add(JLabel(KotlinDebuggerCoroutinesBundle.message("coroutine.dump.filter.field")), BorderLayout.WEST)
add(filterField)
isVisible = false
}
coroutinesList.apply {
cellRenderer = CoroutineListCellRenderer()
selectionMode = ListSelectionModel.SINGLE_SELECTION
addListSelectionListener {
val index = selectedIndex
if (index >= 0) {
val selection = model.getElementAt(index) as CompleteCoroutineInfoData
AnalyzeStacktraceUtil.printStacktrace(consoleView, stringStackTrace(selection))
} else {
AnalyzeStacktraceUtil.printStacktrace(consoleView, "")
}
repaint()
}
}
exporterToTextFile =
MyToFileExporter(project, dump)
val filterAction = FilterAction().apply {
registerCustomShortcutSet(
ActionManager.getInstance().getAction(IdeActions.ACTION_FIND).shortcutSet,
coroutinesList
)
}
toolbarActions.apply {
add(filterAction)
add(
CopyToClipboardAction(dump, project)
)
add(ActionManager.getInstance().getAction(IdeActions.ACTION_EXPORT_TO_TEXT_FILE))
add(MergeStackTracesAction())
}
add(
ActionManager.getInstance()
.createActionToolbar("CoroutinesDump", toolbarActions, false).component,
BorderLayout.WEST
)
val leftPanel = JPanel(BorderLayout()).apply {
add(filterPanel, BorderLayout.NORTH)
add(ScrollPaneFactory.createScrollPane(coroutinesList, SideBorder.LEFT or SideBorder.RIGHT), BorderLayout.CENTER)
}
val splitter = Splitter(false, 0.3f).apply {
firstComponent = leftPanel
secondComponent = consoleView.component
}
add(splitter, BorderLayout.CENTER)
ListSpeedSearch(coroutinesList).comparator = SpeedSearchComparator(false, true)
updateCoroutinesList()
val editor = CommonDataKeys.EDITOR.getData(
DataManager.getInstance()
.getDataContext(consoleView.preferredFocusableComponent)
)
editor?.document?.addDocumentListener(object : DocumentListener {
override fun documentChanged(e: com.intellij.openapi.editor.event.DocumentEvent) {
val filter = filterField.text
if (StringUtil.isNotEmpty(filter)) {
highlightOccurrences(filter, project, editor)
}
}
}, consoleView)
}
private fun updateCoroutinesList() {
val text = if (filterPanel.isVisible) filterField.text else ""
val selection = coroutinesList.selectedValue
val model = coroutinesList.model as DefaultListModel<Any>
model.clear()
var selectedIndex = 0
var index = 0
val states = if (UISettings.getInstance().state.mergeEqualStackTraces) mergedDump else dump
for (state in states) {
if (StringUtil.containsIgnoreCase(stringStackTrace(state), text) ||
StringUtil.containsIgnoreCase(state.descriptor.name, text)) {
model.addElement(state)
if (selection === state) {
selectedIndex = index
}
index++
}
}
if (!model.isEmpty) {
coroutinesList.selectedIndex = selectedIndex
}
coroutinesList.revalidate()
coroutinesList.repaint()
}
internal fun highlightOccurrences(filter: String, project: Project, editor: Editor) {
val highlightManager = HighlightManager.getInstance(project)
val documentText = editor.document.text
var i = -1
while (true) {
val nextOccurrence = StringUtil.indexOfIgnoreCase(documentText, filter, i + 1)
if (nextOccurrence < 0) {
break
}
i = nextOccurrence
highlightManager.addOccurrenceHighlight(
editor, i, i + filter.length, EditorColors.TEXT_SEARCH_RESULT_ATTRIBUTES,
HighlightManager.HIDE_BY_TEXT_CHANGE, null
)
}
}
override fun getData(dataId: String): Any? = if (PlatformDataKeys.EXPORTER_TO_TEXT_FILE.`is`(dataId)) exporterToTextFile else null
private fun getAttributes(infoData: CompleteCoroutineInfoData): SimpleTextAttributes {
return when {
infoData.isSuspended() -> SimpleTextAttributes.GRAY_ATTRIBUTES
infoData.stackTrace.isEmpty() -> SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, Color.GRAY.brighter())
else -> SimpleTextAttributes.REGULAR_ATTRIBUTES
}
}
private inner class CoroutineListCellRenderer : ColoredListCellRenderer<Any>() {
@Suppress("HardCodedStringLiteral")
override fun customizeCellRenderer(list: JList<*>, value: Any, index: Int, selected: Boolean, hasFocus: Boolean) {
val infoData = value as CompleteCoroutineInfoData
val state = infoData.descriptor
icon = fromState(state.state)
val attrs = getAttributes(infoData)
append(state.name + " (", attrs)
var detail: String? = state.state.name
if (detail == null) {
detail = state.state.name
}
if (detail.length > 30) {
detail = detail.substring(0, 30) + "..."
}
append(detail, attrs)
append(")", attrs)
}
}
private inner class FilterAction : ToggleAction(
KotlinDebuggerCoroutinesBundle.message("coroutine.dump.filter.action"),
KotlinDebuggerCoroutinesBundle.message("coroutine.dump.filter.description"),
AllIcons.General.Filter
), DumbAware {
override fun isSelected(e: AnActionEvent): Boolean {
return filterPanel.isVisible
}
override fun setSelected(e: AnActionEvent, state: Boolean) {
filterPanel.isVisible = state
if (state) {
IdeFocusManager.getInstance(AnAction.getEventProject(e)).requestFocus(filterField, true)
filterField.selectText()
}
updateCoroutinesList()
}
override fun getActionUpdateThread() = ActionUpdateThread.BGT
}
private inner class MergeStackTracesAction : ToggleAction(
KotlinDebuggerCoroutinesBundle.message("coroutine.dump.merge.action"),
KotlinDebuggerCoroutinesBundle.message("coroutine.dump.merge.description"),
AllIcons.Actions.Collapseall
), DumbAware {
override fun isSelected(e: AnActionEvent): Boolean {
return UISettings.getInstance().state.mergeEqualStackTraces
}
override fun setSelected(e: AnActionEvent, state: Boolean) {
UISettings.getInstance().state.mergeEqualStackTraces = state
updateCoroutinesList()
}
override fun getActionUpdateThread() = ActionUpdateThread.BGT
}
private class CopyToClipboardAction(private val myCoroutinesDump: List<CompleteCoroutineInfoData>, private val myProject: Project) :
DumbAwareAction(
KotlinDebuggerCoroutinesBundle.message("coroutine.dump.copy.action"),
KotlinDebuggerCoroutinesBundle.message("coroutine.dump.copy.description"),
PlatformIcons.COPY_ICON
) {
override fun actionPerformed(e: AnActionEvent) {
val buf = StringBuilder()
buf.append(KotlinDebuggerCoroutinesBundle.message("coroutine.dump.full.title")).append("\n\n")
for (state in myCoroutinesDump) {
buf.append(stringStackTrace(state)).append("\n\n")
}
CopyPasteManager.getInstance().setContents(StringSelection(buf.toString()))
group.createNotification(
KotlinDebuggerCoroutinesBundle.message("coroutine.dump.full.copied"),
MessageType.INFO
).notify(myProject)
}
private val group = NotificationGroup.toolWindowGroup("Analyze coroutine dump", ToolWindowId.RUN, false)
}
private class MyToFileExporter(
private val myProject: Project,
private val infoData: List<CompleteCoroutineInfoData>
) : ExporterToTextFile {
override fun getReportText() = buildString {
for (state in infoData)
append(stringStackTrace(state)).append("\n\n")
}
override fun getDefaultFilePath() = (myProject.basePath ?: "") + File.separator + defaultReportFileName
override fun canExport() = infoData.isNotEmpty()
private val defaultReportFileName = "coroutines_report.txt"
}
}
private fun stringStackTrace(info: CompleteCoroutineInfoData) =
buildString {
appendLine("\"${info.descriptor.name}\", state: ${info.descriptor.state}")
info.stackTrace.forEach {
append("\t")
append(ThreadDumpAction.renderLocation(it.location))
append("\n")
}
}
| apache-2.0 | 197eb5009359b7314d1d19c021719b4c | 37.797342 | 136 | 0.657818 | 5.308182 | false | false | false | false |
siosio/intellij-community | platform/collaboration-tools/src/com/intellij/collaboration/ui/codereview/commits/CommitNodeComponent.kt | 1 | 2556 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.collaboration.ui.codereview.commits
import com.intellij.util.ui.JBDimension
import com.intellij.util.ui.JBInsets
import com.intellij.util.ui.MacUIUtil
import com.intellij.vcs.log.paint.PaintParameters
import java.awt.Graphics
import java.awt.Graphics2D
import java.awt.Rectangle
import java.awt.RenderingHints
import java.awt.geom.Ellipse2D
import java.awt.geom.Rectangle2D
import javax.swing.JComponent
class CommitNodeComponent : JComponent() {
var type = Type.SINGLE
init {
isOpaque = false
}
override fun getPreferredSize() = JBDimension(
PaintParameters.getNodeWidth(PaintParameters.ROW_HEIGHT),
PaintParameters.ROW_HEIGHT
)
override fun paintComponent(g: Graphics) {
val rect = Rectangle(size)
JBInsets.removeFrom(rect, insets)
val g2 = g as Graphics2D
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL,
if (MacUIUtil.USE_QUARTZ) RenderingHints.VALUE_STROKE_PURE else RenderingHints.VALUE_STROKE_NORMALIZE)
if (isOpaque) {
g2.color = background
g2.fill(Rectangle2D.Float(rect.x.toFloat(), rect.y.toFloat(), rect.width.toFloat(), rect.height.toFloat()))
}
g2.color = foreground
drawNode(g2, rect)
if (type == Type.LAST || type == Type.MIDDLE) {
drawEdgeUp(g2, rect)
}
if (type == Type.FIRST || type == Type.MIDDLE) {
drawEdgeDown(g2, rect)
}
}
private fun drawNode(g: Graphics2D, rect: Rectangle) {
val radius = PaintParameters.getCircleRadius(rect.height)
val circle = Ellipse2D.Double(rect.centerX - radius, rect.centerY - radius, radius * 2.0, radius * 2.0)
g.fill(circle)
}
private fun drawEdgeUp(g: Graphics2D, rect: Rectangle) {
val y1 = 0.0
val y2 = rect.centerY
drawEdge(g, rect, y1, y2)
}
private fun drawEdgeDown(g: Graphics2D, rect: Rectangle) {
val y1 = rect.centerY
val y2 = rect.maxY
drawEdge(g, rect, y1, y2)
}
private fun drawEdge(g: Graphics2D, rect: Rectangle, y1: Double, y2: Double) {
val x = rect.centerX
val width = PaintParameters.getLineThickness(rect.height)
val line = Rectangle2D.Double(x - width / 2, y1 - 0.5, width.toDouble(), y1 + y2 + 0.5)
g.fill(line)
}
enum class Type {
SINGLE, FIRST, MIDDLE, LAST
}
} | apache-2.0 | 067398c88764de562da2e0c2181542c1 | 30.182927 | 140 | 0.68975 | 3.53527 | false | false | false | false |
jwren/intellij-community | plugins/gitlab/src/org/jetbrains/plugins/gitlab/authentication/GitLabLoginUtil.kt | 6 | 2435 | // 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.plugins.gitlab.authentication
import com.intellij.collaboration.auth.ui.login.LoginModel
import com.intellij.collaboration.auth.ui.login.TokenLoginDialog
import com.intellij.collaboration.auth.ui.login.TokenLoginInputPanelFactory
import com.intellij.collaboration.auth.ui.login.TokenLoginPanelModel
import com.intellij.openapi.project.Project
import org.jetbrains.plugins.gitlab.api.GitLabServerPath
import org.jetbrains.plugins.gitlab.authentication.accounts.GitLabAccount
import org.jetbrains.plugins.gitlab.authentication.ui.GitLabTokenLoginPanelModel
import javax.swing.JComponent
object GitLabLoginUtil {
internal fun logInViaToken(
project: Project, parentComponent: JComponent,
uniqueAccountPredicate: (GitLabServerPath, String) -> Boolean
): Pair<GitLabAccount, String>? {
val model = GitLabTokenLoginPanelModel(uniqueAccountPredicate).apply {
serverUri = GitLabServerPath.DEFAULT_SERVER.uri
}
val loginState = showLoginDialog(project, parentComponent, model, false)
if (loginState is LoginModel.LoginState.Connected) {
return GitLabAccount(name = loginState.username, server = model.getServerPath()) to model.token
}
return null
}
internal fun updateToken(
project: Project, parentComponent: JComponent,
account: GitLabAccount,
uniqueAccountPredicate: (GitLabServerPath, String) -> Boolean
): String? {
val predicateWithoutCurrent: (GitLabServerPath, String) -> Boolean = { serverPath, username ->
if (serverPath == account.server && username == account.name) true
else uniqueAccountPredicate(serverPath, username)
}
val model = GitLabTokenLoginPanelModel(predicateWithoutCurrent).apply {
serverUri = account.server.uri
}
val loginState = showLoginDialog(project, parentComponent, model, true)
if (loginState is LoginModel.LoginState.Connected) {
return model.token
}
return null
}
private fun showLoginDialog(
project: Project,
parentComponent: JComponent,
model: TokenLoginPanelModel,
serverFieldDisabled: Boolean
): LoginModel.LoginState {
TokenLoginDialog(project, parentComponent, model) {
TokenLoginInputPanelFactory(model).create(serverFieldDisabled, null)
}.showAndGet()
return model.loginState.value
}
} | apache-2.0 | 1feefdaf4c078a669dbf069b9dffd604 | 38.290323 | 120 | 0.768789 | 4.56848 | false | false | false | false |
tlaukkan/kotlin-web-vr | client/src/vr/webvr/InputController.kt | 1 | 3241 | package vr.webvr
import lib.threejs.Object3D
import vr.webvr.devices.InputDevice
import lib.webvrapi.Gamepad
import lib.webvrapi.getGamepads
import lib.webvrapi.navigator
import vr.client.VrClient
import vr.webvr.devices.OpenVrGamepad
import vr.webvr.tools.SelectTool
import vr.webvr.tools.NoneTool
import kotlin.browser.window
class InputController(val vrClient: VrClient) {
val displayController = vrClient.displayController
var inputDevices: MutableMap<Int, InputDevice> = mutableMapOf()
var inputDeviceModels: MutableMap<String, Object3D> = mutableMapOf()
init {
this.detectInputDevices()
this.processInput()
}
fun render() {
for (inputDevice in inputDevices.values) {
if (inputDevice.gamepad != null) {
inputDevice.render()
}
}
}
fun processInput() {
window.setTimeout({ processInput() }, 100, null)
for (inputDevice in inputDevices.values) {
if (inputDevice.gamepad != null) {
inputDevice.processInput()
}
}
}
fun detectInputDevices() {
window.setTimeout({ detectInputDevices()}, 1000, null)
var gamepads: Array<Gamepad> = navigator.getGamepads()
for (gamepad: Gamepad in gamepads) {
if (gamepad == undefined) {
continue
}
//println("Detecting gamepads: " + gamepad.pose)
if (gamepad != null && gamepad.connected && gamepad.pose != null && this.inputDevices[gamepad.index] == null) {
val controller: InputDevice
if ("OpenVR Gamepad".equals(gamepad.id)) {
controller = OpenVrGamepad(this, gamepad.index, gamepad.id)
} else {
println("Unknown gamepad ${gamepad.id}")
continue
}
controller.standingMatrix = displayController.standingMatrix
this.inputDevices[gamepad.index] = controller
println("InputDevice added: " + gamepad.index + ":" + gamepad.id)
}
}
for (index in inputDevices.keys) {
var controller = inputDevices[index]!!
var gamepad: Gamepad = navigator.getGamepads()[controller.index]
// Delete controller if gamepad does not exist or is of different type.
if (gamepad == null || (gamepad.id != controller.type || !gamepad.connected || gamepad.pose == null) ) {
displayController.scene.remove(controller.entity)
inputDevices.remove(index)
println("InputDevice removed: " + gamepad.index + ":" + gamepad.id)
continue
}
if (!controller.addedToScene) {
// Set model and add to scene
val model = this.inputDeviceModels[gamepad.id]
if (model != null) {
// If model has not been set then attempt to set it.
controller.addedToScene = true
controller.entity.add(model.clone(true))
displayController.scene.add(controller.entity)
}
}
}
}
} | mit | db0da15eacf5ed2e77fbd534650bf9c6 | 32.42268 | 123 | 0.575131 | 4.710756 | false | false | false | false |
Cognifide/gradle-aem-plugin | src/main/kotlin/com/cognifide/gradle/aem/common/instance/provision/step/DeployPackageStep.kt | 1 | 1840 | package com.cognifide.gradle.aem.common.instance.provision.step
import com.cognifide.gradle.aem.common.instance.Instance
import com.cognifide.gradle.aem.common.instance.provision.ProvisionException
import com.cognifide.gradle.aem.common.instance.provision.Provisioner
import com.cognifide.gradle.common.utils.toLowerCamelCase
class DeployPackageStep(provisioner: Provisioner) : AbstractStep(provisioner) {
val source = aem.obj.typed<Any>()
val sourceProperties by lazy { DeployPackageSource.from(source.get(), aem) }
val file by lazy {
val sourceFile = provisioner.fileResolver.get(source.get()).file
aem.packageOptions.wrapper.wrap(sourceFile).also { common.checksumFile(it) }
}
val name = aem.obj.string { convention(aem.obj.provider { sourceProperties.name }) }
override fun validate() {
if (!source.isPresent) {
throw ProvisionException("Deploy package source is not defined!")
}
}
override fun init() {
logger.debug("Resolved package '${name.get()}' to be deployed is located at path: '$file'")
}
override fun action(instance: Instance) = instance.sync {
logger.info("Deploying package '${name.get()}' to $instance")
awaitIf { packageManager.deploy(file) }
}
fun isDeployedOn(instance: Instance) = instance.sync.packageManager.isDeployed(file)
fun notDeployedOn(instance: Instance) = !isDeployedOn(instance)
init {
id.convention(name.map { "deployPackage/${it.toLowerCamelCase()}" })
description.convention(name.map { "Deploying package '${name.get()}'" })
version.convention(aem.obj.provider { sourceProperties.version })
if (aem.prop.boolean("instance.provision.deployPackage.strict") == true) {
condition { notDeployedOn(instance) }
}
}
}
| apache-2.0 | 4470c99ea46086c22aad8fe928122962 | 36.55102 | 99 | 0.695652 | 4.134831 | false | false | false | false |
erdo/asaf-project | example-kt-03adapters/src/main/java/foo/bar/example/foreadapterskt/ui/playlist/mutable/MutableListView.kt | 1 | 3123 | package foo.bar.example.foreadapterskt.ui.playlist.mutable
import android.content.Context
import android.util.AttributeSet
import android.widget.RelativeLayout
import androidx.recyclerview.widget.LinearLayoutManager
import co.early.fore.adapters.CrossFadeRemover
import co.early.fore.core.observer.Observer
import co.early.fore.kt.core.logging.Logger
import foo.bar.example.foreadapterskt.OG
import foo.bar.example.foreadapterskt.feature.playlist.mutable.MutablePlaylistModel
import kotlinx.android.synthetic.main.view_playlists_immutable.view.*
import kotlinx.android.synthetic.main.view_playlists_mutable.view.*
/**
* Copyright © 2015-2020 early.co. All rights reserved.
*/
class MutableListView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : RelativeLayout(context, attrs, defStyleAttr) {
//models that we need to sync with
private val mutablePlaylistModel: MutablePlaylistModel = OG[MutablePlaylistModel::class.java]
private val logger: Logger = OG[Logger::class.java]
private lateinit var mutablePlaylistAdapter: MutablePlaylistAdapter
//single observer reference
private var observer = Observer { syncView() }
override fun onFinishInflate() {
super.onFinishInflate()
setupClickListeners()
setupAdapters()
}
private fun setupClickListeners() {
updatable_add_button.setOnClickListener { mutablePlaylistModel.addNTracks(1) }
updatable_clear_button.setOnClickListener { mutablePlaylistModel.removeAllTracks() }
updatable_add5_button.setOnClickListener { mutablePlaylistModel.addNTracks(5) }
updatable_remove5_button.setOnClickListener { mutablePlaylistModel.removeNTracks(5) }
updatable_add100_button.setOnClickListener { mutablePlaylistModel.addNTracks(100) }
updatable_remove100_button.setOnClickListener { mutablePlaylistModel.removeNTracks(100) }
}
private fun setupAdapters() {
mutablePlaylistAdapter = MutablePlaylistAdapter(mutablePlaylistModel)
updatable_list_recycleview.apply {
layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
adapter = mutablePlaylistAdapter
itemAnimator = CrossFadeRemover()
setHasFixedSize(true)
}
}
fun syncView() {
logger.i("syncView()")
updatable_totaltracks_textview.text = mutablePlaylistModel.itemCount.toString()
updatable_clear_button.isEnabled = !mutablePlaylistModel.isEmpty()
updatable_remove5_button.isEnabled = mutablePlaylistModel.hasAtLeastNItems(5)
updatable_remove100_button.isEnabled = mutablePlaylistModel.hasAtLeastNItems(100)
mutablePlaylistAdapter.notifyDataSetChangedAuto()
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
mutablePlaylistModel.addObserver(observer)
syncView() // <- don't forget this
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
mutablePlaylistModel.removeObserver(observer)
}
}
| apache-2.0 | a847faefdfdfdd5915db763761d1d483 | 38.025 | 97 | 0.742793 | 4.694737 | false | false | false | false |
ThiagoGarciaAlves/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/ResolveUtil.kt | 1 | 6174 | /*
* Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
@file:Suppress("LoopToCallChain")
package org.jetbrains.plugins.groovy.lang.resolve
import com.intellij.openapi.util.Key
import com.intellij.psi.*
import com.intellij.psi.scope.ElementClassHint
import com.intellij.psi.scope.ElementClassHint.DeclarationKind
import com.intellij.psi.scope.NameHint
import com.intellij.psi.scope.PsiScopeProcessor
import com.intellij.psi.util.CachedValueProvider.Result
import com.intellij.psi.util.CachedValuesManager.getCachedValue
import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement
import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement
import org.jetbrains.plugins.groovy.lang.psi.api.util.GrStatementOwner
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.DefaultConstructor
import org.jetbrains.plugins.groovy.lang.psi.util.skipSameTypeParents
import org.jetbrains.plugins.groovy.lang.resolve.processors.DynamicMembersHint
import org.jetbrains.plugins.groovy.lang.resolve.processors.GroovyResolveKind
import org.jetbrains.plugins.groovy.lang.resolve.processors.GroovyResolverProcessor
@JvmField
val NON_CODE = Key.create<Boolean?>("groovy.process.non.code.members")
fun initialState(processNonCodeMembers: Boolean) = ResolveState.initial().put(NON_CODE, processNonCodeMembers)
fun ResolveState.processNonCodeMembers(): Boolean = get(NON_CODE).let { it == null || it }
fun treeWalkUp(place: PsiElement, processor: PsiScopeProcessor, state: ResolveState): Boolean {
return ResolveUtil.treeWalkUp(place, place, processor, state)
}
fun GrStatementOwner.processStatements(lastParent: PsiElement?, processor: (GrStatement) -> Boolean): Boolean {
var run = if (lastParent == null) lastChild else lastParent.prevSibling
while (run != null) {
if (run is GrStatement && !processor(run)) return false
run = run.prevSibling
}
return true
}
fun GrStatementOwner.processLocals(processor: PsiScopeProcessor, state: ResolveState, lastParent: PsiElement?, place: PsiElement): Boolean {
return !processor.shouldProcessLocals() || processStatements(lastParent) {
it.processDeclarations(processor, state, null, place)
}
}
fun PsiScopeProcessor.checkName(name: String, state: ResolveState): Boolean {
val expectedName = getName(state) ?: return true
return expectedName == name
}
fun PsiScopeProcessor.getName(state: ResolveState): String? = getHint(NameHint.KEY)?.getName(state)
fun shouldProcessDynamicMethods(processor: PsiScopeProcessor): Boolean {
return processor.getHint(DynamicMembersHint.KEY)?.shouldProcessMethods() ?: false
}
fun PsiScopeProcessor.shouldProcessDynamicProperties(): Boolean {
return getHint(DynamicMembersHint.KEY)?.shouldProcessProperties() ?: false
}
fun PsiScopeProcessor.shouldProcessLocals(): Boolean = shouldProcess(GroovyResolveKind.VARIABLE)
fun PsiScopeProcessor.shouldProcessMethods(): Boolean {
return ResolveUtil.shouldProcessMethods(getHint(ElementClassHint.KEY))
}
fun PsiScopeProcessor.shouldProcessClasses(): Boolean {
return ResolveUtil.shouldProcessClasses(getHint(ElementClassHint.KEY))
}
fun PsiScopeProcessor.shouldProcessMembers(): Boolean {
val hint = getHint(ElementClassHint.KEY) ?: return true
return hint.shouldProcess(DeclarationKind.CLASS) ||
hint.shouldProcess(DeclarationKind.FIELD) ||
hint.shouldProcess(DeclarationKind.METHOD)
}
fun PsiScopeProcessor.shouldProcessTypeParameters(): Boolean {
if (shouldProcessClasses()) return true
val groovyKindHint = getHint(GroovyResolveKind.HINT_KEY) ?: return true
return groovyKindHint.shouldProcess(GroovyResolveKind.TYPE_PARAMETER)
}
fun PsiScopeProcessor.shouldProcessProperties(): Boolean {
return this is GroovyResolverProcessor && isPropertyResolve
}
fun PsiScopeProcessor.shouldProcessPackages(): Boolean = shouldProcess(GroovyResolveKind.PACKAGE)
private fun PsiScopeProcessor.shouldProcess(kind: GroovyResolveKind): Boolean {
val resolveKindHint = getHint(GroovyResolveKind.HINT_KEY)
if (resolveKindHint != null) return resolveKindHint.shouldProcess(kind)
val elementClassHint = getHint(ElementClassHint.KEY) ?: return true
return kind.declarationKinds.any(elementClassHint::shouldProcess)
}
fun wrapClassType(type: PsiType, context: PsiElement) = TypesUtil.createJavaLangClassType(type, context.project, context.resolveScope)
fun getDefaultConstructor(clazz: PsiClass): PsiMethod {
return getCachedValue(clazz) {
Result.create(DefaultConstructor(clazz), clazz)
}
}
fun GroovyFileBase.processClassesInFile(processor: PsiScopeProcessor, state: ResolveState): Boolean {
if (!processor.shouldProcessClasses()) return true
val scriptClass = scriptClass
if (scriptClass != null && !ResolveUtil.processElement(processor, scriptClass, state)) return false
for (definition in typeDefinitions) {
if (!ResolveUtil.processElement(processor, definition, state)) return false
}
return true
}
fun GroovyFileBase.processClassesInPackage(processor: PsiScopeProcessor, state: ResolveState, place: PsiElement = this): Boolean {
if (!processor.shouldProcessClasses()) return true
val aPackage = JavaPsiFacade.getInstance(project).findPackage(packageName) ?: return true
return aPackage.processDeclarations(PackageSkippingProcessor(processor), state, null, place)
}
val PsiScopeProcessor.annotationHint: AnnotationHint? get() = getHint(AnnotationHint.HINT_KEY)
fun PsiScopeProcessor.isAnnotationResolve(): Boolean {
val hint = annotationHint ?: return false
return hint.isAnnotationResolve
}
fun PsiScopeProcessor.isNonAnnotationResolve(): Boolean {
val hint = annotationHint ?: return false
return !hint.isAnnotationResolve
}
fun GrCodeReferenceElement.isAnnotationReference(): Boolean {
val (possibleAnnotation, _) = skipSameTypeParents()
return possibleAnnotation is GrAnnotation
}
| apache-2.0 | d241e4c8ea309e14cd00abc64e4b638d | 41.57931 | 140 | 0.806122 | 4.617801 | false | false | false | false |
busybusy/AnalyticsKit-Android | analyticskit/src/test/kotlin/com/busybusy/analyticskit_android/MockProvider.kt | 2 | 2051 | /*
* Copyright 2016 - 2022 busybusy, 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.busybusy.analyticskit_android
import com.busybusy.analyticskit_android.AnalyticsKitProvider.PriorityFilter
/**
* Provides an implementation of the [AnalyticsKitProvider] interface that facilitates testing.
*
* @author John Hunt on 3/8/16.
*/
class MockProvider : AnalyticsKitProvider {
var sentEvents: MutableMap<String, AnalyticsEvent> = mutableMapOf()
var eventTimes: MutableMap<String, Long> = mutableMapOf()
var priorityLevel = 0
var myPriorityFilter: PriorityFilter = PriorityFilter { priorityLevel ->
priorityLevel <= [email protected]
}
fun setPriorityUpperBound(priorityLevel: Int): MockProvider {
this.priorityLevel = priorityLevel
return this
}
override fun getPriorityFilter(): PriorityFilter = myPriorityFilter
override fun sendEvent(event: AnalyticsEvent) {
sentEvents[event.name()] = event
if (event.isTimed()) {
val startTime = System.currentTimeMillis()
eventTimes[event.name()] = startTime
}
}
override fun endTimedEvent(timedEvent: AnalyticsEvent) {
val endTime = System.currentTimeMillis()
val startTime = eventTimes.remove(timedEvent.name())
if (startTime != null) {
timedEvent.putAttribute(EVENT_DURATION, endTime - startTime)
}
}
companion object {
const val EVENT_DURATION = "event_duration"
}
}
| apache-2.0 | 9225150945250de6b4a67218cb2ea4d0 | 33.762712 | 95 | 0.699659 | 4.547672 | false | false | false | false |
Softmotions/ncms | ncms-engine/ncms-engine-core/src/main/java/com/softmotions/ncms/adm/AdmUIResourcesRS.kt | 1 | 2564 | package com.softmotions.ncms.adm
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import com.google.inject.Inject
import com.softmotions.ncms.NcmsEnvironment
import com.softmotions.weboot.i18n.I18n
import com.softmotions.weboot.security.WBSecurityContext
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import javax.ws.rs.GET
import javax.ws.rs.Path
import javax.ws.rs.PathParam
import javax.ws.rs.Produces
import javax.ws.rs.core.Context
/**
* Accessible GUI resources configuration provider.
* @author Adamansky Anton ([email protected])
*/
@Path("adm/ui")
@Produces("application/json;charset=UTF-8")
@JvmSuppressWildcards
open class AdmUIResourcesRS
@Inject
constructor(
private val env: NcmsEnvironment,
private val mapper: ObjectMapper,
private val msg: I18n,
private val sctx: WBSecurityContext) {
/**
* List of qooxdoo widgets available for user.
* @param section Section name widgets belongs to
*/
@GET
@Path("widgets/{section}")
open fun parts(@Context req: HttpServletRequest,
@Context resp: HttpServletResponse,
@PathParam("section") section: String): JsonNode {
// language fix todo review it
req.getParameter("qxLocale")?.let {
val cloc = msg.getLocale(req).toString()
if (it != cloc) {
msg.saveRequestLang(it, req, resp)
}
}
val arr = mapper.createArrayNode()
val user = sctx.getWSUser(req)
val xcfg = env.xcfg()
val cpath = "ui.$section.widget"
for (hc in xcfg.subPattern(cpath)) {
val widgetRoles = env.attrArray(hc.textXPath("@roles"))
if (widgetRoles.isEmpty() || user.isHasAnyRole(*widgetRoles)) {
val qxClass = hc.textXPath("@qxClass")
val icon = hc.textXPath("@qxIcon")
val on = mapper.createObjectNode().put("qxClass", qxClass)
val label = msg.get(qxClass + ".label", req)
on.put("label", label)
if (icon != null) {
on.put("icon", icon)
}
on.put("extra", hc.boolXPath("@extra", false))
val argsNode = on.putArray("args")
for (arg in env.attrArray(hc.textXPath("@args"))) {
argsNode.add(arg)
}
arr.add(on)
}
}
return arr
}
}
| apache-2.0 | df9dc9152a579b0feed650e8bcc585b8 | 31.455696 | 75 | 0.606474 | 4.076312 | false | false | false | false |
breadwallet/breadwallet-android | app/src/main/java/com/breadwallet/ui/provekey/PaperKeyProveController.kt | 1 | 5273 | /**
* BreadWallet
*
* Created by Pablo Budelli <[email protected]> on 10/10/19.
* Copyright (c) 2019 breadwallet LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.breadwallet.ui.provekey
import android.os.Bundle
import android.view.View
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import com.breadwallet.R
import com.breadwallet.databinding.ControllerPaperKeyProveBinding
import com.breadwallet.tools.animation.SpringAnimator
import com.breadwallet.tools.util.Utils
import com.breadwallet.ui.BaseMobiusController
import com.breadwallet.ui.ViewEffect
import com.breadwallet.ui.controllers.SignalController
import com.breadwallet.ui.flowbind.clicks
import com.breadwallet.ui.flowbind.textChanges
import com.breadwallet.ui.navigation.OnCompleteAction
import com.breadwallet.ui.provekey.PaperKeyProve.E
import com.breadwallet.ui.provekey.PaperKeyProve.F
import com.breadwallet.ui.provekey.PaperKeyProve.M
import com.breadwallet.util.normalize
import drewcarlson.mobius.flow.FlowTransformer
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.merge
private const val EXTRA_PHRASE = "phrase"
private const val EXTRA_ON_COMPLETE = "on-complete"
class PaperKeyProveController(args: Bundle) :
BaseMobiusController<M, E, F>(args),
SignalController.Listener {
constructor(phrase: List<String>, onComplete: OnCompleteAction) : this(
bundleOf(
EXTRA_PHRASE to phrase,
EXTRA_ON_COMPLETE to onComplete.name
)
)
private val phrase: List<String> = arg(EXTRA_PHRASE)
private val onComplete = OnCompleteAction.valueOf(arg(EXTRA_ON_COMPLETE))
override val defaultModel = M.createDefault(phrase, onComplete)
override val update = PaperKeyProveUpdate
override val flowEffectHandler: FlowTransformer<F, E>
get() = createPaperKeyProveHandler()
private val binding by viewBinding(ControllerPaperKeyProveBinding::inflate)
override fun bindView(modelFlow: Flow<M>): Flow<E> {
return with(binding) {
merge(
submitBtn.clicks().map { E.OnSubmitClicked },
firstWord.textChanges().map { E.OnFirstWordChanged(it.normalize()) },
secondWord.textChanges().map { E.OnSecondWordChanged(it.normalize()) }
)
}
}
override fun onDetach(view: View) {
super.onDetach(view)
Utils.hideKeyboard(activity)
}
override fun M.render() {
with(binding) {
ifChanged(M::firstWordState) {
firstWord.setTextColor(
activity!!.getColor(
if (firstWordState == M.WordState.VALID) R.color.light_gray
else R.color.red_text
)
)
checkMark1.isVisible = firstWordState == M.WordState.VALID
}
ifChanged(M::secondWordSate) {
secondWord.setTextColor(
activity!!.getColor(
if (secondWordSate == M.WordState.VALID) R.color.light_gray
else R.color.red_text
)
)
checkMark2.isVisible = secondWordSate == M.WordState.VALID
}
ifChanged(M::firstWordIndex) {
firstWordLabel.text =
activity!!.getString(R.string.ConfirmPaperPhrase_word, firstWordIndex + 1)
}
ifChanged(M::secondWordIndex) {
secondWordLabel.text =
activity!!.getString(R.string.ConfirmPaperPhrase_word, secondWordIndex + 1)
}
}
}
override fun handleViewEffect(effect: ViewEffect) {
when (effect) {
is F.ShakeWords -> {
if (effect.first) {
SpringAnimator.failShakeAnimation(applicationContext, binding.firstWord)
}
if (effect.second) {
SpringAnimator.failShakeAnimation(applicationContext, binding.secondWord)
}
}
}
}
override fun onSignalComplete() {
eventConsumer.accept(E.OnBreadSignalShown)
}
}
| mit | 5176c4c4df2c9239dec5b67a2f847f7a | 37.489051 | 95 | 0.666793 | 4.514555 | false | false | false | false |
fossasia/rp15 | app/src/main/java/org/fossasia/openevent/general/event/EventsFragment.kt | 1 | 17620 | package org.fossasia.openevent.general.event
import android.graphics.Color
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.appcompat.app.AlertDialog
import androidx.core.view.isVisible
import androidx.core.widget.NestedScrollView
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import androidx.navigation.Navigation.findNavController
import androidx.navigation.fragment.FragmentNavigatorExtras
import kotlinx.android.synthetic.main.content_no_internet.view.noInternetCard
import kotlinx.android.synthetic.main.content_no_internet.view.retry
import kotlinx.android.synthetic.main.dialog_reset_password.view.confirmNewPassword
import kotlinx.android.synthetic.main.dialog_reset_password.view.newPassword
import kotlinx.android.synthetic.main.dialog_reset_password.view.textInputLayoutConfirmNewPassword
import kotlinx.android.synthetic.main.dialog_reset_password.view.textInputLayoutNewPassword
import kotlinx.android.synthetic.main.fragment_events.view.eventsRecycler
import kotlinx.android.synthetic.main.fragment_events.view.locationTextView
import kotlinx.android.synthetic.main.fragment_events.view.shimmerEvents
import kotlinx.android.synthetic.main.fragment_events.view.eventsEmptyView
import kotlinx.android.synthetic.main.fragment_events.view.emptyEventsText
import kotlinx.android.synthetic.main.fragment_events.view.scrollView
import kotlinx.android.synthetic.main.fragment_events.view.notification
import kotlinx.android.synthetic.main.fragment_events.view.swiperefresh
import kotlinx.android.synthetic.main.fragment_events.view.newNotificationDot
import kotlinx.android.synthetic.main.fragment_events.view.toolbar
import kotlinx.android.synthetic.main.fragment_events.view.toolbarLayout
import kotlinx.android.synthetic.main.fragment_events.view.newNotificationDotToolbar
import kotlinx.android.synthetic.main.fragment_events.view.notificationToolbar
import org.fossasia.openevent.general.R
import org.fossasia.openevent.general.BottomIconDoubleClick
import org.fossasia.openevent.general.StartupViewModel
import org.fossasia.openevent.general.utils.RESET_PASSWORD_TOKEN
import org.fossasia.openevent.general.common.EventClickListener
import org.fossasia.openevent.general.common.FavoriteFabClickListener
import org.fossasia.openevent.general.data.Preference
import org.fossasia.openevent.general.search.location.SAVED_LOCATION
import org.fossasia.openevent.general.utils.extensions.nonNull
import org.koin.androidx.viewmodel.ext.android.viewModel
import org.fossasia.openevent.general.utils.Utils.setToolbar
import org.fossasia.openevent.general.utils.Utils.progressDialog
import org.fossasia.openevent.general.utils.Utils.show
import org.fossasia.openevent.general.utils.extensions.setPostponeSharedElementTransition
import org.fossasia.openevent.general.utils.extensions.setStartPostponedEnterTransition
import org.fossasia.openevent.general.utils.extensions.hideWithFading
import org.fossasia.openevent.general.utils.extensions.showWithFading
import org.jetbrains.anko.design.longSnackbar
const val BEEN_TO_WELCOME_SCREEN = "beenToWelcomeScreen"
const val EVENTS_FRAGMENT = "eventsFragment"
class EventsFragment : Fragment(), BottomIconDoubleClick {
private val eventsViewModel by viewModel<EventsViewModel>()
private val startupViewModel by viewModel<StartupViewModel>()
private lateinit var rootView: View
private val preference = Preference()
private val eventsListAdapter = EventsListAdapter()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
setPostponeSharedElementTransition()
rootView = inflater.inflate(R.layout.fragment_events, container, false)
if (preference.getString(SAVED_LOCATION).isNullOrEmpty() &&
!preference.getBoolean(BEEN_TO_WELCOME_SCREEN, false)) {
preference.putBoolean(BEEN_TO_WELCOME_SCREEN, true)
findNavController(requireActivity(), R.id.frameContainer).navigate(R.id.welcomeFragment)
}
setToolbar(activity, show = false)
val progressDialog = progressDialog(context, getString(R.string.loading_message))
val token = arguments?.getString(RESET_PASSWORD_TOKEN)
if (token != null)
showResetPasswordAlertDialog(token)
startupViewModel.resetPasswordEmail
.nonNull()
.observe(viewLifecycleOwner, Observer {
findNavController(rootView).navigate(
EventsFragmentDirections.actionEventsToAuth(email = it, redirectedFrom = EVENTS_FRAGMENT)
)
})
startupViewModel.dialogProgress
.nonNull()
.observe(viewLifecycleOwner, Observer {
progressDialog.show(it)
})
rootView.eventsRecycler.layoutManager =
GridLayoutManager(activity, resources.getInteger(R.integer.events_column_count))
rootView.eventsRecycler.adapter = eventsListAdapter
rootView.eventsRecycler.isNestedScrollingEnabled = false
startupViewModel.syncNotifications()
startupViewModel.fetchSettings()
handleNotificationDotVisibility(
preference.getBoolean(NEW_NOTIFICATIONS, false))
startupViewModel.newNotifications
.nonNull()
.observe(viewLifecycleOwner, Observer {
handleNotificationDotVisibility(it)
})
eventsViewModel.pagedEvents
.nonNull()
.observe(this, Observer { list ->
eventsListAdapter.submitList(list)
})
eventsViewModel.progress
.nonNull()
.observe(viewLifecycleOwner, Observer {
if (it) {
rootView.shimmerEvents.startShimmer()
showEmptyMessage(false)
showNoInternetScreen(false)
} else {
rootView.shimmerEvents.stopShimmer()
rootView.swiperefresh.isRefreshing = false
showEmptyMessage(eventsListAdapter.currentList?.isEmpty() ?: true)
}
rootView.shimmerEvents.isVisible = it
})
eventsViewModel.message
.nonNull()
.observe(viewLifecycleOwner, Observer {
rootView.longSnackbar(it)
})
eventsViewModel.loadLocation()
if (rootView.locationTextView.text == getString(R.string.enter_location)) {
rootView.emptyEventsText.text = getString(R.string.choose_preferred_location_message)
} else {
rootView.emptyEventsText.text = getString(R.string.no_events_message)
}
rootView.locationTextView.text = eventsViewModel.savedLocation.value
rootView.toolbar.title = rootView.locationTextView.text
eventsViewModel.savedLocation
.nonNull()
.observe(viewLifecycleOwner, Observer {
if (eventsViewModel.lastSearch != it) {
eventsViewModel.lastSearch = it
eventsViewModel.clearEvents()
}
})
eventsViewModel.connection
.nonNull()
.observe(viewLifecycleOwner, Observer { isConnected ->
val currentPagedEvents = eventsViewModel.pagedEvents.value
if (currentPagedEvents != null) {
showNoInternetScreen(false)
eventsListAdapter.submitList(currentPagedEvents)
} else {
if (isConnected) {
eventsViewModel.loadLocationEvents()
} else {
showNoInternetScreen(true)
}
}
})
rootView.locationTextView.setOnClickListener {
findNavController(rootView).navigate(EventsFragmentDirections.actionEventsToSearchLocation())
}
rootView.retry.setOnClickListener {
if (eventsViewModel.savedLocation.value != null && eventsViewModel.isConnected()) {
eventsViewModel.loadLocationEvents()
}
showNoInternetScreen(!eventsViewModel.isConnected())
}
rootView.swiperefresh.setColorSchemeColors(Color.BLUE)
rootView.swiperefresh.setOnRefreshListener {
showNoInternetScreen(!eventsViewModel.isConnected())
eventsViewModel.clearEvents()
eventsViewModel.clearLastSearch()
if (!eventsViewModel.isConnected()) {
rootView.swiperefresh.isRefreshing = false
} else {
eventsViewModel.loadLocationEvents()
}
}
startupViewModel.isRefresh
.nonNull()
.observe(viewLifecycleOwner, Observer {
if (it) refreshData()
})
return rootView
}
private fun refreshData() {
eventsViewModel.loadLocationEvents()
startupViewModel.fetchSettings()
startupViewModel.syncNotifications()
}
private fun handleNotificationDotVisibility(isVisible: Boolean) {
rootView.newNotificationDot.isVisible = isVisible
rootView.newNotificationDotToolbar.isVisible = isVisible
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
rootView.eventsRecycler.viewTreeObserver.addOnGlobalLayoutListener {
setStartPostponedEnterTransition()
}
rootView.notification.setOnClickListener {
moveToNotification()
}
rootView.notificationToolbar.setOnClickListener {
moveToNotification()
}
val eventClickListener: EventClickListener = object : EventClickListener {
override fun onClick(eventID: Long, imageView: ImageView) {
findNavController(rootView).navigate(EventsFragmentDirections.actionEventsToEventsDetail(eventID),
FragmentNavigatorExtras(imageView to "eventDetailImage"))
}
}
val redirectToLogin = object : RedirectToLogin {
override fun goBackToLogin() {
findNavController(rootView)
.navigate(EventsFragmentDirections.actionEventsToAuth(redirectedFrom = EVENTS_FRAGMENT))
}
}
val favFabClickListener: FavoriteFabClickListener = object : FavoriteFabClickListener {
override fun onClick(event: Event, itemPosition: Int) {
if (eventsViewModel.isLoggedIn()) {
event.favorite = !event.favorite
eventsViewModel.setFavorite(event, event.favorite)
eventsListAdapter.notifyItemChanged(itemPosition)
} else {
EventUtils.showLoginToLikeDialog(requireContext(),
layoutInflater, redirectToLogin, event.originalImageUrl, event.name)
}
}
}
val hashTagClickListener: EventHashTagClickListener = object : EventHashTagClickListener {
override fun onClick(hashTagValue: String) {
openSearch(hashTagValue)
}
}
eventsListAdapter.apply {
onEventClick = eventClickListener
onFavFabClick = favFabClickListener
onHashtagClick = hashTagClickListener
}
rootView.scrollView.setOnScrollChangeListener { _: NestedScrollView?, _: Int, scrollY: Int, _: Int, _: Int ->
if (scrollY > rootView.locationTextView.y + rootView.locationTextView.height &&
!rootView.toolbarLayout.isVisible) rootView.toolbarLayout.showWithFading()
else if (scrollY < rootView.locationTextView.y + rootView.locationTextView.height &&
rootView.toolbarLayout.isVisible) rootView.toolbarLayout.hideWithFading()
}
}
override fun onDestroyView() {
rootView.swiperefresh.setOnRefreshListener(null)
eventsListAdapter.apply {
onEventClick = null
onFavFabClick = null
onHashtagClick = null
}
super.onDestroyView()
}
private fun moveToNotification() {
startupViewModel.mutableNewNotifications.value = false
findNavController(rootView).navigate(EventsFragmentDirections.actionEventsToNotification())
}
private fun openSearch(hashTag: String) {
findNavController(rootView).navigate(EventsFragmentDirections.actionEventsToSearchResults(
query = "",
location = Preference().getString(SAVED_LOCATION).toString(),
date = getString(R.string.anytime),
type = hashTag))
}
private fun showNoInternetScreen(show: Boolean) {
if (show) {
rootView.shimmerEvents.isVisible = false
rootView.eventsEmptyView.isVisible = false
eventsListAdapter.clear()
}
rootView.noInternetCard.isVisible = show
}
private fun showEmptyMessage(show: Boolean) {
rootView.eventsEmptyView.isVisible = show
}
private fun showResetPasswordAlertDialog(token: String) {
val layout = layoutInflater.inflate(R.layout.dialog_reset_password, null)
val alertDialog = AlertDialog.Builder(requireContext())
.setTitle(getString(R.string.title_change_password))
.setView(layout)
.setPositiveButton(getString(R.string.change)) { _, _ ->
startupViewModel.checkAndReset(token, layout.newPassword.text.toString())
}
.setNegativeButton(getString(R.string.cancel)) { dialog, _ ->
dialog.cancel()
}
.setCancelable(false)
.show()
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = false
layout.newPassword.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(p0: Editable?) {
/* to make PasswordToggle visible again, if made invisible
after empty field error
*/
if (!layout.textInputLayoutNewPassword.isEndIconVisible) {
layout.textInputLayoutNewPassword.isEndIconVisible = true
}
if (layout.newPassword.text.toString().length >= 8) {
layout.textInputLayoutNewPassword.error = null
layout.textInputLayoutNewPassword.isErrorEnabled = false
} else {
layout.textInputLayoutNewPassword.error = getString(R.string.invalid_password_message)
}
if (layout.confirmNewPassword.text.toString() == layout.newPassword.text.toString()) {
layout.textInputLayoutConfirmNewPassword.error = null
layout.textInputLayoutConfirmNewPassword.isErrorEnabled = false
} else {
layout.textInputLayoutConfirmNewPassword.error =
getString(R.string.invalid_confirm_password_message)
}
when (layout.textInputLayoutConfirmNewPassword.isErrorEnabled ||
layout.textInputLayoutNewPassword.isErrorEnabled) {
true -> alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = false
false -> alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = true
}
}
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { /*Implement here*/ }
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { /*Implement here*/ }
})
layout.confirmNewPassword.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(p0: Editable?) {
/* to make PasswordToggle visible again, if made invisible
after empty field error
*/
if (!layout.textInputLayoutConfirmNewPassword.isEndIconVisible) {
layout.textInputLayoutConfirmNewPassword.isEndIconVisible = true
}
if (layout.confirmNewPassword.text.toString() == layout.newPassword.text.toString()) {
layout.textInputLayoutConfirmNewPassword.error = null
layout.textInputLayoutConfirmNewPassword.isErrorEnabled = false
} else {
layout.textInputLayoutConfirmNewPassword.error =
getString(R.string.invalid_confirm_password_message)
}
when (layout.textInputLayoutConfirmNewPassword.isErrorEnabled ||
layout.textInputLayoutNewPassword.isErrorEnabled) {
true -> alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = false
false -> alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = true
}
}
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { /*Implement here*/ }
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { /*Implement here*/ }
})
}
override fun doubleClick() = rootView.scrollView.smoothScrollTo(0, 0)
}
| apache-2.0 | e5a323e903a04c39c2c71fc54e74ef26 | 43.271357 | 117 | 0.664075 | 5.342632 | false | false | false | false |
Txuritan/mental | src/main/kotlin/com/github/txuritan/mental/core/common/Mental.kt | 1 | 2547 | /*
* MIT License
*
* Copyright (c) 2017 Ian Cronkright
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.txuritan.mental.core.common
import com.github.txuritan.mental.core.common.util.References
import net.minecraftforge.fml.common.Mod
import net.minecraftforge.fml.common.SidedProxy
import net.minecraftforge.fml.common.event.FMLInitializationEvent
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent
/**
* @author Ian 'Txuritan/Captain Daro'Ma'Sohni Tavia' Cronkright
*/
/*@Mod(
modid = References.MOD_ID,
version = References.VERSION,
name = References.MOD_NAME,
updateJSON = References.UPDATE_URL,
dependencies = "required-after:forgelin@[1.4.1,);",
modLanguageAdapter = "net.shadowfacts.forgelin.KotlinAdapter",
acceptedMinecraftVersions = "1.11.2"
)*/
object Mental {
@SidedProxy(
serverSide = References.COMMON_PROXY_CLASS,
clientSide = References.CLIENT_PROXY_CLASS,
modId = References.MOD_ID
)
lateinit var proxy : CommonProxy
@Mod.Instance(References.MOD_ID)
lateinit var instance : Mental
@Mod.EventHandler
fun preInit(event : FMLPreInitializationEvent) {
proxy.preInit(event)
}
@Mod.EventHandler
fun init(event : FMLInitializationEvent) {
proxy.init(event)
}
@Mod.EventHandler
fun postInit(event : FMLPostInitializationEvent) {
proxy.postInit(event)
}
}
| mit | 163e7f6f1af42a4c2f41787d2f4a0c83 | 33.890411 | 81 | 0.739694 | 4.196046 | false | false | false | false |
serorigundam/numeri3 | app/src/main/kotlin/net/ketc/numeri/domain/entity/TweetsDisplay.kt | 1 | 1536 | package net.ketc.numeri.domain.entity
import com.j256.ormlite.field.DatabaseField
import com.j256.ormlite.table.DatabaseTable
import net.ketc.numeri.util.ormlite.Entity
@DatabaseTable
data class TweetsDisplayGroup(@DatabaseField(generatedId = true)
override val id: Int = 0,
@DatabaseField(canBeNull = false)
var name: String = "") : Entity<Int>
data class TweetsDisplay(
@DatabaseField(generatedId = true)
override val id: Int = 0,
@DatabaseField(canBeNull = false, foreign = true, uniqueCombo = true)
val token: ClientToken = ClientToken(),
@DatabaseField(canBeNull = false, foreign = true, foreignAutoRefresh = true, uniqueCombo = true)
val group: TweetsDisplayGroup = TweetsDisplayGroup(),
@DatabaseField(canBeNull = false, uniqueCombo = true)
val foreignId: Long = -1,
@DatabaseField(canBeNull = false)
var name: String = "",
@DatabaseField(canBeNull = false, uniqueCombo = true)
val type: TweetsDisplayType = TweetsDisplayType.HOME,
@DatabaseField(canBeNull = false)
var order: Int = 0) : Entity<Int>
fun createTweetsDisplay(token: ClientToken, group: TweetsDisplayGroup, foreignId: Long, type: TweetsDisplayType, name: String = "")
= TweetsDisplay(token = token, group = group, foreignId = foreignId, type = type, name = name)
enum class TweetsDisplayType {
HOME, MENTIONS, USER_LIST, PUBLIC, FAVORITE, MEDIA
} | mit | 1fa56ec3cb85e3446eb032a84af7e579 | 44.205882 | 131 | 0.66276 | 4.117962 | false | false | false | false |
diareuse/mCache | mcache/src/main/java/wiki/depasquale/mcache/FileRW.kt | 1 | 3022 | package wiki.depasquale.mcache
import java.io.File
class FileRW(override val wrapper: FileWrapperInterface) : FileRWInterface {
override fun read(): String {
synchronized(lock) {
val file = findFile()
if (!file.exists() || file.length() <= 0L) {
return ""
}
return file.readText()
}
}
override fun write(wrappedFile: String) {
synchronized(lock) {
val file = findFile(true)
file.writeText(wrappedFile)
}
}
override fun delete(): Boolean {
synchronized(lock) {
val builder = wrapper.converter.builder
val index = builder.index
val classFolder = findClassFolder()
return when {
index.isNotEmpty() -> {
classFolder.listFiles()
.filter { it.nameWithoutExtension == index }
.map { it.deleteRecursively() }
.all { true }
}
builder.cls == Cache::class.java -> {
classFolder.parentFile?.deleteRecursively() == true
}
else -> {
classFolder.deleteRecursively()
}
}
}
}
override fun all(): List<String> {
synchronized(lock) {
val classFolder = findClassFolder()
return classFolder.listFiles().map { it.readText() }
}
}
private fun findFile(create: Boolean = false): File {
val classFolder = findClassFolder()
val classFile = File(classFolder, findFileName(classFolder))
if (create) {
if (!classFile.exists()) {
classFile.createNewFile()
}
if (!classFile.isFile) {
classFile.deleteRecursively()
classFile.createNewFile()
}
}
return classFile
}
private fun findClassFolder(): File {
val builder = wrapper.converter.builder
val folder = when (builder.mode) {
CacheMode.CACHE -> Cache.context.cacheDir
CacheMode.FILE -> Cache.context.filesDir
}
val name = builder.cls.simpleName
val homeFolder = File(folder, "mCache")
homeFolder.mkdirs()
val classFolder = File(homeFolder, name.base64())
classFolder.mkdirs()
return classFolder
}
private fun findFileName(classFolder: File): String {
removeUnwantedFiles(classFolder)
val index = wrapper.converter.builder.index
if (index.isNotEmpty())
return index.toString()
return "default".base64()
}
private fun removeUnwantedFiles(classFolder: File) {
classFolder.listFiles().forEach {
if (!it.isFile || it.length() == 0L) {
it.deleteRecursively()
}
}
}
companion object {
private val lock: Any = Any()
}
} | apache-2.0 | 7d4f78d2f8a91001d6c6942d126121c9 | 27.518868 | 76 | 0.524818 | 5.036667 | false | false | false | false |
TradeMe/MapMe | googlemaps/src/main/java/nz/co/trademe/mapme/googlemaps/GoogleMapMarkerAnnotation.kt | 1 | 1863 | package nz.co.trademe.mapme.googlemaps
import android.content.Context
import android.graphics.Bitmap
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.model.Marker
import com.google.android.gms.maps.model.MarkerOptions
import nz.co.trademe.mapme.LatLng
import nz.co.trademe.mapme.annotations.MarkerAnnotation
class GoogleMapMarkerAnnotation(latLng: LatLng,
title: String?,
icon: Bitmap? = null) : MarkerAnnotation(latLng, title, icon) {
override fun onUpdateIcon(icon: Bitmap?) {
nativeMarker?.setIcon(icon?.toBitmapDescriptor())
}
override fun onUpdateTitle(title: String?) {
nativeMarker?.title = title
}
override fun onUpdatePosition(position: LatLng) {
nativeMarker?.position = position.toGoogleMapsLatLng()
}
override fun onUpdateZIndex(index: Float) {
nativeMarker?.zIndex = index
}
override fun onUpdateAlpha(alpha: Float) {
nativeMarker?.alpha = alpha
}
override fun onUpdateAnchor(anchorUV: Pair<Float, Float>) {
nativeMarker?.setAnchor(anchorUV.first, anchorUV.second)
}
private var nativeMarker: Marker? = null
override fun annotatesObject(objec: Any): Boolean {
return nativeMarker?.equals(objec) ?: false
}
override fun removeFromMap(map: Any, context: Context) {
nativeMarker?.remove()
nativeMarker = null
}
override fun addToMap(map: Any, context: Context) {
val googleMap = map as GoogleMap
val options = MarkerOptions()
.position(latLng.toGoogleMapsLatLng())
.icon(icon?.toBitmapDescriptor())
.title(title)
.alpha(alpha)
.zIndex(zIndex)
nativeMarker = googleMap.addMarker(options)
}
}
| mit | a3ae6da2ea0c5329f390ac4b49650724 | 28.571429 | 95 | 0.651637 | 4.352804 | false | false | false | false |
AK-47-D/cms | src/main/kotlin/com/ak47/cms/cms/controller/SearchKeyWordController.kt | 1 | 2547 | package com.ak47.cms.cms.controller
import com.ak47.cms.cms.dao.SearchKeyWordRepository
import com.ak47.cms.cms.entity.SearchKeyWord
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.domain.Page
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Sort
import org.springframework.stereotype.Controller
import org.springframework.transaction.annotation.Transactional
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.servlet.ModelAndView
import javax.servlet.http.HttpServletRequest
/**
* Created by jack on 2017/7/22.
*/
@Controller
class SearchKeyWordController {
@Autowired lateinit var searchKeyWordRepository: SearchKeyWordRepository
@RequestMapping(value = "search_keyword_view", method = arrayOf(RequestMethod.GET))
fun sotuView(model: Model, request: HttpServletRequest): ModelAndView {
model.addAttribute("requestURI", request.requestURI)
return ModelAndView("search_keyword_view")
}
@RequestMapping(value = "searchKeyWordJson", method = arrayOf(RequestMethod.GET))
@ResponseBody
fun sotuSearchJson(@RequestParam(value = "page", defaultValue = "0") page: Int, @RequestParam(value = "size", defaultValue = "10") size: Int, @RequestParam(value = "searchText", defaultValue = "") searchText: String): Page<SearchKeyWord> {
return getPageResult(page, size, searchText)
}
private fun getPageResult(page: Int, size: Int, searchText: String): Page<SearchKeyWord> {
val sort = Sort(Sort.Direction.DESC, "id")
// 注意:PageRequest.of(page,size,sort) page 默认是从0开始
val pageable = PageRequest.of(page, size, sort)
if (searchText == "") {
return searchKeyWordRepository.findAll(pageable)
} else {
return searchKeyWordRepository.search(searchText, pageable)
}
}
@RequestMapping(value = "save_keyword", method = arrayOf(RequestMethod.GET, RequestMethod.POST))
@ResponseBody
@Transactional
fun save(@RequestParam(value = "keyWord") keyWord: String): String {
if (keyWord == "") {
return "0"
} else {
searchKeyWordRepository.saveOnNoDuplicateKey(keyWord)
return "1"
}
}
}
| apache-2.0 | a3a1f2e2c57eb810f74752b9aa053e30 | 38.515625 | 243 | 0.732305 | 4.35284 | false | false | false | false |
tangying91/profit | src/main/java/org/profit/server/handler/communication/data/ApiResponse.kt | 1 | 532 | package org.profit.server.handler.communication.data
import java.util.*
class ApiResponse<T> {
var isSuccess: Boolean
var event = 0
var msg: String? = null
var count: Long = 0
var items: List<T>
constructor(success: Boolean, msg: String?) {
isSuccess = success
this.msg = msg
items = ArrayList()
}
constructor(success: Boolean, count: Long, items: List<T>) {
isSuccess = success
this.count = count
this.items = items
}
} | apache-2.0 | fd20645f514002598322b4c7975a445b | 20.25 | 64 | 0.580827 | 4.15625 | false | false | false | false |
VerifAPS/verifaps-lib | geteta/src/main/kotlin/edu/kit/iti/formal/automation/testtables/print/text.kt | 1 | 8949 | package edu.kit.iti.formal.automation.testtables.print
import edu.kit.iti.formal.automation.testtables.grammar.TestTableLanguageParser
import edu.kit.iti.formal.automation.testtables.model.Duration
import edu.kit.iti.formal.automation.testtables.model.GeneralizedTestTable
import edu.kit.iti.formal.automation.testtables.model.ProgramVariable
import edu.kit.iti.formal.automation.testtables.model.TableRow
import edu.kit.iti.formal.util.CodeWriter
import edu.kit.iti.formal.util.center
import edu.kit.iti.formal.util.times
import java.io.StringWriter
import javax.swing.SwingConstants
/**
* ```
┌──┬──┐ ╔══╦══╗ ╒══╤══╕ ╓──╥──╖
│ │ │ ║ ║ ║ │ │ │ ║ ║ ║
├──┼──┤ ╠══╬══╣ ╞══╪══╡ ╟──╫──╢
│ │ │ ║ ║ ║ │ │ │ ║ ║ ║
└──┴──┘ ╚══╩══╝ ╘══╧══╛ ╙──╨──╜
* ```
* @author Alexander Weigl
* @version 1 (22.10.18)
*/
/**
* Class holds the characters for drawing the borders.
*/
data class AsciiBorderCharacters(
val TOP_LEFT: Char,
val TOP_MID: Char,
val TOP_RIGHT: Char,
val MID_LEFT: Char,
val MID_MID: Char,
val MID_RIGHT: Char,
val BOT_LEFT: Char,
val BOT_MID: Char,
val BOT_RIGHT: Char,
val HORIZONTAL: Char,
val VERTICAL: Char)
/**
* Single frame borders:
* ```
┌──┬──┐
│ │ │
├──┼──┤
│ │ │
└──┴──┘
* ```
* @author Alexander Weigl
* @version 1 (22.10.18)
*/
val SINGLE_BORDER = AsciiBorderCharacters('┌',
'┬', '┐', '├',
'┼', '┤', '└',
'┴', '┘', '─', '│')
/**
* Double frame borders:
* ```
╔══╦══╗
║ ║ ║
╠══╬══╣
║ ║ ║
╚══╩══╝
* ```
* @author Alexander Weigl
* @version 1 (22.10.18)
*/
val DOUBLE_BORDER = AsciiBorderCharacters('╔',
'╦', '╗', '╠',
'╬', '╣', '╚',
'╩', '╝', '═',
'║')
/**
* Options for Text printing.
*/
data class TextPrinterOptions(
var columnMinWidth: Int = 8,
var dontCareChar: String = "-",
var printEmptyCells: Boolean = false,
var emptyCellReplacement: String = "",
var border: AsciiBorderCharacters = SINGLE_BORDER,
val spacePadding: Int = 1 // spaces left and right
, val drawLinesBetweenRows: Boolean = false
)
/**
* Represents a text cell
*/
data class Cell(
var content: String,
var spanRows: Int = 1,
var spanColumns: Int = 1,
/**
* -1 for unset width, 0 for removal, otherwise contains width in characters
*/
var width: Int = -1,
/**
* Orientation of the cell.
* One of [SwingConstants.LEFT], [SwingConstants.CENTER] or
* [SwingConstants.RIGHT]
*/
var orientation: Int = SwingConstants.LEFT
)
class TextTablePrinter(gtt: GeneralizedTestTable,
stream: CodeWriter,
val options: TextPrinterOptions = TextPrinterOptions()) : AbstractTablePrinter(gtt, stream) {
lateinit var grid: Array<Array<Cell>>
var column = 0
init {
init()
}
override fun cellFormatter(c: TestTableLanguageParser.CellContext): String = c.text
override fun tableBegin() {
val columns = 1 + input.size + output.size + depth
val rows = 2 + gtt.region.flat().size
grid = Array(rows) { Array(columns) { Cell("") } }
grid[0][0].content = "#"
grid[0][0].orientation = SwingConstants.CENTER
grid[0][1].content = "INPUT"
grid[0][1].spanColumns = input.size
grid[0][1].orientation = SwingConstants.CENTER
grid[0][1 + input.size].content = "OUTPUT"
grid[0][1 + input.size].spanColumns = output.size
grid[0][1 + input.size].orientation = SwingConstants.CENTER
grid[0][1 + input.size + output.size].content = "DURATION"
grid[0][1 + input.size + output.size].spanColumns = depth
grid[0][1 + input.size + output.size].orientation = SwingConstants.CENTER
val variables = (input + output).map { it.name }
variables.forEachIndexed { i, it ->
grid[1][1 + i].content = it
}
}
override fun rowBegin() {
grid[currentRow + 2][0].content = (currentRow).toString()
column = 1
}
override fun printCell(v: ProgramVariable, row: TableRow) {
val cell = helper.columns[v.name]?.get(currentRow)!!
grid[currentRow + 2][column++].content = cell.content
}
override fun printRowDuration(duration: Duration) {
grid[currentRow + 2][column++].content = beautifyDuration(duration)
}
override fun printGroupDuration(dur: Duration, rowSpan: Int) {
grid[currentRow + 2][column].spanRows = rowSpan
grid[currentRow + 2][column++].content = beautifyDuration(dur)
}
private fun beautifyDuration(d: Duration): String {
val stream = StringWriter()
DSLTablePrinter(CodeWriter(stream)).print(d)
return stream.toString()
}
override fun print() {
super.print()
GridPrinter(grid, stream, options)
}
}
class GridPrinter(
val grid: Array<Array<Cell>>,
val stream: CodeWriter,
val options: TextPrinterOptions) {
init {
calculateWidth()
cleanUpGrid()
for (row in 0..grid.lastIndex) {
printRow(row)
}
printBorderHB(grid.last())
}
private fun printRow(row: Int) {
val cells = grid[row]
if (row == 0)
printBorderHT(grid[row])
if (row == 1 || row == 2)
printBorderHM(grid[row])
if (row > 2 && options.drawLinesBetweenRows)
printBorderHM(grid[row])
stream.print(options.border.VERTICAL)
cells.joinTo(stream, options.border.VERTICAL.toString()) {
when (it.orientation) {
SwingConstants.LEFT ->
String.format(" %${it.width - 2}s ", it.content)
SwingConstants.CENTER ->
it.content.center(it.width)
SwingConstants.RIGHT ->
String.format(" %-${it.width - 2}s ", it.content)
else -> throw IllegalStateException("Illegal orientation supplied")
}
}
stream.print(options.border.VERTICAL)
stream.nl()
}
private fun printBorderHT(cells: Array<Cell>) =
printBorderH(cells, options.border.TOP_LEFT,
options.border.TOP_MID, options.border.TOP_RIGHT,
options.border.HORIZONTAL)
private fun printBorderHM(cells: Array<Cell>) =
printBorderH(cells, options.border.MID_LEFT,
options.border.MID_MID, options.border.MID_RIGHT,
options.border.HORIZONTAL)
private fun printBorderHB(cells: Array<Cell>) =
printBorderH(cells, options.border.BOT_LEFT,
options.border.BOT_MID, options.border.BOT_RIGHT,
options.border.HORIZONTAL)
private fun printBorderH(cells: Array<Cell>,
startCorner: Char,
midCorner: Char,
stopCorner: Char,
horizontal: Char) {
stream.print(startCorner)
cells.joinTo(stream, midCorner.toString()) { (horizontal.toString() * (it.width)) }
stream.print(stopCorner)
stream.nl()
}
private fun calculateWidth() {
//add padding
val columns = grid[0].size
for (c in 0 until columns) {
val cells = grid.map { it[c] }
val width = cells.asSequence()
.map { options.spacePadding * 2 + if (it.width < 0) it.content.length else it.width }
.max() ?: options.columnMinWidth
cells.forEach { it.width = Math.max(options.columnMinWidth, width) }
}
}
private fun cleanUpGrid() {
grid.forEachIndexed { rowIdx, row ->
val seq = Array<Cell>(row.size) { row[it].copy() }
var idx = 0
while (idx < row.size) {
var cell = seq[idx]
if (cell.spanColumns > 1) {
val consumed = seq.slice(idx + 1 until idx + cell.spanColumns)
val w = consumed.sumBy { it.width + options.spacePadding }
cell.width += w
consumed.forEach { it.width = 0 }
idx += cell.spanColumns;
continue
}
idx++;
continue
}
grid[rowIdx] = seq.filter { it.width > 0 }.toTypedArray()
}
}
}
| gpl-3.0 | 6135597c24a6d5c167f0466b0434a28a | 29.756272 | 116 | 0.550169 | 3.495316 | false | false | false | false |
premnirmal/StockTicker | app/src/main/kotlin/com/github/premnirmal/ticker/ui/BottomNavigationBehavior.kt | 1 | 1096 | package com.github.premnirmal.ticker.ui
import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import androidx.coordinatorlayout.widget.CoordinatorLayout
import com.google.android.material.snackbar.Snackbar
class BottomNavigationBehavior<V : View>(
context: Context,
attrs: AttributeSet
) : CoordinatorLayout.Behavior<V>(context, attrs) {
override fun layoutDependsOn(
parent: CoordinatorLayout,
child: V,
dependency: View
): Boolean {
if (dependency is Snackbar.SnackbarLayout) {
updateSnackbar(child, dependency)
}
return super.layoutDependsOn(parent, child, dependency)
}
private fun updateSnackbar(
child: View,
snackbarLayout: Snackbar.SnackbarLayout
) {
if (snackbarLayout.layoutParams is CoordinatorLayout.LayoutParams) {
val params = snackbarLayout.layoutParams as CoordinatorLayout.LayoutParams
params.anchorId = child.id
params.anchorGravity = Gravity.TOP
params.gravity = Gravity.TOP
snackbarLayout.layoutParams = params
}
}
} | gpl-3.0 | 443dbea56af680338bfcf4b32bf42e40 | 27.128205 | 80 | 0.752737 | 4.605042 | false | false | false | false |
SimpleMobileTools/Simple-Flashlight | app/src/main/kotlin/com/simplemobiletools/flashlight/helpers/MyWidgetBrightDisplayProvider.kt | 1 | 2223 | package com.simplemobiletools.flashlight.helpers
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import android.widget.RemoteViews
import com.simplemobiletools.commons.extensions.getColoredDrawableWithColor
import com.simplemobiletools.flashlight.R
import com.simplemobiletools.flashlight.activities.BrightDisplayActivity
import com.simplemobiletools.flashlight.extensions.config
import com.simplemobiletools.flashlight.extensions.drawableToBitmap
class MyWidgetBrightDisplayProvider : AppWidgetProvider() {
private val OPEN_APP_INTENT_ID = 1
override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {
appWidgetManager.getAppWidgetIds(getComponentName(context)).forEach {
RemoteViews(context.packageName, R.layout.widget_bright_display).apply {
setupAppOpenIntent(context, this)
val selectedColor = context.config.widgetBgColor
val alpha = Color.alpha(selectedColor)
val bmp = getColoredIcon(context, selectedColor, alpha)
setImageViewBitmap(R.id.bright_display_btn, bmp)
appWidgetManager.updateAppWidget(it, this)
}
}
}
private fun getComponentName(context: Context) = ComponentName(context, MyWidgetBrightDisplayProvider::class.java)
private fun setupAppOpenIntent(context: Context, views: RemoteViews) {
Intent(context, BrightDisplayActivity::class.java).apply {
val pendingIntent = PendingIntent.getActivity(context, OPEN_APP_INTENT_ID, this, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
views.setOnClickPendingIntent(R.id.bright_display_btn, pendingIntent)
}
}
private fun getColoredIcon(context: Context, color: Int, alpha: Int): Bitmap {
val drawable = context.resources.getColoredDrawableWithColor(R.drawable.ic_bright_display, color, alpha)
return context.drawableToBitmap(drawable)
}
}
| gpl-3.0 | 51748f8f159d4c9583a1397468e9e6d0 | 43.46 | 159 | 0.758884 | 4.962054 | false | false | false | false |
duftler/orca | orca-kayenta/src/test/kotlin/com/netflix/spinnaker/orca/kayenta/tasks/PropagateDeployedServerGroupScopesTest.kt | 1 | 4958 | /*
* Copyright 2018 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.netflix.spinnaker.orca.kayenta.tasks
import com.fasterxml.jackson.module.kotlin.convertValue
import com.netflix.spinnaker.orca.clouddriver.MortService
import com.netflix.spinnaker.orca.clouddriver.pipeline.servergroup.CreateServerGroupStage
import com.netflix.spinnaker.orca.fixture.pipeline
import com.netflix.spinnaker.orca.fixture.stage
import com.netflix.spinnaker.orca.jackson.OrcaObjectMapper
import com.netflix.spinnaker.orca.kato.pipeline.ParallelDeployStage
import com.netflix.spinnaker.orca.kayenta.pipeline.DeployCanaryServerGroupsStage
import com.netflix.spinnaker.orca.kayenta.pipeline.DeployCanaryServerGroupsStage.Companion.DEPLOY_CONTROL_SERVER_GROUPS
import com.netflix.spinnaker.orca.kayenta.pipeline.DeployCanaryServerGroupsStage.Companion.DEPLOY_EXPERIMENT_SERVER_GROUPS
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.mock
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.fail
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
object PropagateDeployedServerGroupScopesTest : Spek({
val mort = mock<MortService> {
on { getAccountDetails("foo") } doReturn mapOf("accountId" to "abc123")
on { getAccountDetails("bar") } doReturn mapOf("accountId" to "def456")
}
val subject = PropagateDeployedServerGroupScopes(mort)
val objectMapper = OrcaObjectMapper.newInstance()
given("upstream experiment and control deploy stages") {
val pipeline = pipeline {
stage {
refId = "1"
type = DeployCanaryServerGroupsStage.STAGE_TYPE
name = "deployCanaryClusters"
stage {
type = ParallelDeployStage.PIPELINE_CONFIG_TYPE
name = DEPLOY_CONTROL_SERVER_GROUPS
stage {
type = CreateServerGroupStage.PIPELINE_CONFIG_TYPE
context["deploy.server.groups"] = mapOf(
"us-central1" to listOf("app-control-a-v000")
)
context["deploy.account.name"] = "foo"
}
stage {
type = CreateServerGroupStage.PIPELINE_CONFIG_TYPE
context["deploy.server.groups"] = mapOf(
"us-central1" to listOf("app-control-b-v000")
)
context["deploy.account.name"] = "bar"
}
}
stage {
type = ParallelDeployStage.PIPELINE_CONFIG_TYPE
name = DEPLOY_EXPERIMENT_SERVER_GROUPS
stage {
type = CreateServerGroupStage.PIPELINE_CONFIG_TYPE
context["deploy.server.groups"] = mapOf(
"us-central1" to listOf("app-experiment-a-v000")
)
context["deploy.account.name"] = "foo"
}
stage {
type = CreateServerGroupStage.PIPELINE_CONFIG_TYPE
context["deploy.server.groups"] = mapOf(
"us-central1" to listOf("app-experiment-b-v000")
)
context["deploy.account.name"] = "bar"
}
}
}
}
subject.execute(pipeline.stageByRef("1")).outputs["deployedServerGroups"]?.let { pairs ->
it("summarizes deployments, joining experiment and control pairs") {
objectMapper.convertValue<List<DeployedServerGroupPair>>(pairs).let {
assertThat(it).containsExactlyInAnyOrder(
DeployedServerGroupPair(
experimentAccountId = "abc123",
experimentScope = "app-experiment-a-v000",
experimentLocation = "us-central1",
controlAccountId = "abc123",
controlScope = "app-control-a-v000",
controlLocation = "us-central1"
),
DeployedServerGroupPair(
experimentAccountId = "def456",
experimentScope = "app-experiment-b-v000",
experimentLocation = "us-central1",
controlScope = "app-control-b-v000",
controlLocation = "us-central1",
controlAccountId = "def456"
)
)
}
}
} ?: fail("Task should output `deployedServerGroups`")
}
})
internal data class DeployedServerGroupPair(
val controlLocation: String,
val controlScope: String,
val controlAccountId: String?,
val experimentLocation: String,
val experimentScope: String,
val experimentAccountId: String?
)
| apache-2.0 | d5e4c908081c9f021ff9f955e7482df7 | 37.138462 | 122 | 0.670835 | 4.330131 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-locks-bukkit/src/main/kotlin/com/rpkit/locks/bukkit/listener/InventoryCloseListener.kt | 1 | 1994 | /*
* Copyright 2020 Ren Binden
*
* 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.rpkit.locks.bukkit.listener
import com.rpkit.characters.bukkit.character.RPKCharacterService
import com.rpkit.core.service.Services
import com.rpkit.locks.bukkit.RPKLocksBukkit
import com.rpkit.locks.bukkit.keyring.RPKKeyringService
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService
import org.bukkit.entity.Player
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.inventory.InventoryCloseEvent
class InventoryCloseListener(private val plugin: RPKLocksBukkit) : Listener {
@EventHandler
fun onInventoryClose(event: InventoryCloseEvent) {
if (!event.view.title.equals("Keyring", ignoreCase = true)) return
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return
val characterService = Services[RPKCharacterService::class.java] ?: return
val keyringService = Services[RPKKeyringService::class.java] ?: return
val bukkitPlayer = event.player
if (bukkitPlayer !is Player) return
val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(bukkitPlayer) ?: return
val character = characterService.getPreloadedActiveCharacter(minecraftProfile) ?: return
val contents = event.inventory.contents.filterNotNull()
keyringService.setKeyring(character, contents.toMutableList())
}
} | apache-2.0 | a26b07b9b447360197a461e7f16e3490 | 42.369565 | 107 | 0.770311 | 4.637209 | false | false | false | false |
newbieandroid/AppBase | app/src/main/java/com/fuyoul/sanwenseller/ui/web/WebViewActivity.kt | 1 | 7619 | package com.fuyoul.sanwenseller.ui.web
import android.content.Context
import android.content.Intent
import android.graphics.PixelFormat
import android.os.Bundle
import android.text.TextUtils
import android.view.*
import android.widget.FrameLayout
import com.fuyoul.sanwenseller.R
import com.fuyoul.sanwenseller.base.BaseActivity
import com.fuyoul.sanwenseller.configs.TopBarOption
import com.fuyoul.sanwenseller.structure.model.EmptyM
import com.fuyoul.sanwenseller.structure.presenter.EmptyP
import com.fuyoul.sanwenseller.structure.view.EmptyV
import com.fuyoul.sanwenseller.utils.NormalFunUtils
import com.tencent.smtt.export.external.interfaces.IX5WebChromeClient
import com.tencent.smtt.sdk.WebChromeClient
import com.tencent.smtt.sdk.WebSettings
import com.tencent.smtt.sdk.WebView
import com.tencent.smtt.sdk.WebViewClient
import kotlinx.android.synthetic.main.webview.*
/**
* @author: chen
* @CreatDate: 2017\10\28 0028
* @Desc:
*/
class WebViewActivity : BaseActivity<EmptyM, EmptyV, EmptyP>() {
private val COVER_SCREEN_PARAMS: ViewGroup.LayoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
private var customView: View? = null
private var fullscreenContainer: FrameLayout? = null
private var customViewCallback: IX5WebChromeClient.CustomViewCallback? = null
companion object {
fun startWebView(context: Context, title: String, urlPath: String) {
if (TextUtils.isEmpty(urlPath)) {
return
} else if (!urlPath.contains("http")) {
NormalFunUtils.showToast(context, "地址有误")
return
}
context.startActivity(Intent(context, WebViewActivity::class.java).putExtra("title", title).putExtra("urlPath", urlPath))
}
}
override fun setLayoutRes(): Int = R.layout.webview
override fun initData(savedInstanceState: Bundle?) {
normalWeb.setWebViewClient(object : WebViewClient() {
override fun shouldOverrideUrlLoading(p0: WebView?, p1: String?): Boolean {
p0!!.loadUrl(p1)
return false
}
})
normalWeb.setWebChromeClient(object : WebChromeClient() {
override fun getVideoLoadingProgressView(): View {
val frameLayout = FrameLayout(this@WebViewActivity)
frameLayout.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
return frameLayout
}
override fun onShowCustomView(view: View?, customViewCallback: IX5WebChromeClient.CustomViewCallback?) {
super.onShowCustomView(view, customViewCallback)
showCustomView(view!!, customViewCallback!!)
}
override fun onHideCustomView() {
super.onHideCustomView()
hideCustomView()
}
})
val webSetting = normalWeb.settings
webSetting.allowFileAccess = true
webSetting.layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS
webSetting.setSupportZoom(true)
webSetting.builtInZoomControls = true
webSetting.useWideViewPort = true
webSetting.setSupportMultipleWindows(false)
webSetting.setAppCacheEnabled(true)
webSetting.domStorageEnabled = true
webSetting.javaScriptEnabled = true
webSetting.setGeolocationEnabled(true)
webSetting.setAppCacheMaxSize(java.lang.Long.MAX_VALUE)
webSetting.setAppCachePath(this.getDir("appcache", 0).path)
webSetting.databasePath = this.getDir("databases", 0).path
webSetting.setGeolocationDatabasePath(this.getDir("geolocation", 0).path)
// webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
webSetting.pluginState = WebSettings.PluginState.ON_DEMAND
normalWeb.loadUrl(intent.getStringExtra("urlPath"))
}
override fun setListener() {
}
override fun getPresenter(): EmptyP = EmptyP(initViewImpl())
override fun initViewImpl(): EmptyV = EmptyV()
override fun initTopBar(): TopBarOption {
val op = TopBarOption()
if (TextUtils.isEmpty(intent.getStringExtra("title"))) {
return op
}
op.isShowBar = true
op.mainTitle = intent.getStringExtra("title")
return op
}
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (customView != null) {
hideCustomView()
return true
} else if (normalWeb != null && normalWeb.canGoBack()) {
normalWeb.goBack()
return true
} else {
finish()
}
}
return super.onKeyDown(keyCode, event)
}
override fun onDestroy() {
normalWeb.clearCache(true)
normalWeb.clearFormData()
normalWeb.clearHistory()
normalWeb.clearMatches()
normalWeb.clearSslPreferences()
normalWeb.destroy()
super.onDestroy()
}
override fun onCreate(savedInstanceState: Bundle?) {
window.setFormat(PixelFormat.TRANSLUCENT)
super.onCreate(savedInstanceState)
}
/** 视频播放全屏 */
private fun showCustomView(view: View, callback: IX5WebChromeClient.CustomViewCallback) {
// if a view already exists then immediately terminate the new one
if (customView != null) {
callback.onCustomViewHidden()
return
}
val decor = window.decorView as FrameLayout
fullscreenContainer = FullscreenHolder(this)
fullscreenContainer!!.addView(view, COVER_SCREEN_PARAMS)
decor.addView(fullscreenContainer, COVER_SCREEN_PARAMS)
customView = view
setStatusBarVisibility(false)
customViewCallback = callback
}
/** 隐藏视频全屏 */
private fun hideCustomView() {
if (customView == null) {
return
}
setStatusBarVisibility(true)
val decor = window.decorView as FrameLayout
decor.removeView(fullscreenContainer)
fullscreenContainer = null
customView = null
customViewCallback!!.onCustomViewHidden()
normalWeb.visibility = View.VISIBLE
}
/** 全屏容器界面 */
internal class FullscreenHolder(ctx: Context) : FrameLayout(ctx) {
init {
setBackgroundColor(ctx.resources.getColor(android.R.color.black))
}
override fun onTouchEvent(evt: MotionEvent): Boolean {
return true
}
}
private fun setStatusBarVisibility(visible: Boolean) {
//标题栏
val flag = if (visible) 0 else WindowManager.LayoutParams.FLAG_FULLSCREEN
window.setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN)
//虚拟按键
try {
if (visible) {
window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
} else {
window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_IMMERSIVE
}
} catch (e: Exception) {
e.printStackTrace()
}
}
} | apache-2.0 | 6b9b0b12c3a2493b3dbd337cf734c5ea | 31.878261 | 280 | 0.660627 | 4.773359 | false | false | false | false |
alexmonthy/lttng-scope | lttng-scope/src/main/kotlin/org/lttng/scope/project/tree/ProjectTreeItem.kt | 2 | 1812 | /*
* Copyright (C) 2017-2018 EfficiOS Inc., Alexandre Montplaisir <[email protected]>
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.lttng.scope.project.tree
import com.efficios.jabberwocky.context.ViewGroupContext
import com.efficios.jabberwocky.project.TraceProject
import javafx.scene.control.ContextMenu
import javafx.scene.control.Tooltip
import javafx.scene.control.TreeItem
import org.lttng.scope.views.context.ViewGroupContextManager
internal abstract class ProjectTreeItem(name: String) : TreeItem<String>(name) {
private val projectChangeListener = object : ViewGroupContext.ProjectChangeListener(this) {
override fun newProjectCb(newProject: TraceProject<*, *>?) {
if (newProject == null) {
clear()
} else {
initForProject(newProject)
}
}
}
init {
ViewGroupContextManager.getCurrent().registerProjectChangeListener(projectChangeListener)
isExpanded = true
}
// Note this doesn't need 'override' in Kotlin, weird
@Suppress("Unused")
protected fun finalize() {
// TODO Handle case where the Context we registered to might have changed
ViewGroupContextManager.getCurrent().deregisterProjectChangeListener(projectChangeListener)
}
protected fun getCurrentProject() = ViewGroupContextManager.getCurrent().traceProject
abstract fun initForProject(project: TraceProject<*, *>)
open fun clear() {
children.clear()
}
open val contextMenu: ContextMenu? = null
open val tooltip: Tooltip? = null
}
| epl-1.0 | a7add8d1cae435b4905bf53ba8cca446 | 33.188679 | 99 | 0.716336 | 4.768421 | false | false | false | false |
YiiGuxing/TranslationPlugin | src/main/kotlin/cn/yiiguxing/plugin/translate/util/LruCache.kt | 1 | 9180 | /*
* Copyright (C) 2011 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 cn.yiiguxing.plugin.translate.util
import java.util.*
/**
* LruCache
*
* @param [maxSize] for caches that do not override [.sizeOf][LruCache.sizeOf], this is
* the maximum number of entries in the cache. For all other caches,
* this is the maximum sum of the sizes of the entries in this cache.
*/
@Suppress("unused", "MemberVisibilityCanBePrivate")
open class LruCache<K, V>(maxSize: Int) {
private val map: LinkedHashMap<K, V>
/**
* Size of this cache in units. Not necessarily the number of elements.
*
* For caches that do not override [.sizeOf][sizeOf], this returns the number
* of entries in the cache. For all other caches, this returns the sum of
* the sizes of the entries in this cache.
*/
var size: Int = 0
private set
@Synchronized get
/**
* For caches that do not override [.sizeOf][sizeOf], this returns the maximum
* number of entries in the cache. For all other caches, this returns the
* maximum sum of the sizes of the entries in this cache.
*/
var maxSize = maxSize
private set
@Synchronized get
/**
* The number of times [.put][put] was called.
*/
var putCount: Int = 0
private set
@Synchronized get
/**
* The number of times [.create][create] returned a value.
*/
var createCount: Int = 0
private set
@Synchronized get
/**
* The number of values that have been evicted.
*/
var evictionCount: Int = 0
private set
@Synchronized get
/**
* The number of times [.get][get] returned a value that was already present in the cache.
*/
var hitCount: Int = 0
private set
@Synchronized get
/**
* The number of times [.get][get] returned null or required a new value to be created.
*/
var missCount: Int = 0
private set
@Synchronized get
/**
* A copy of the current contents of the cache, ordered from least
* recently accessed to most recently accessed.
*/
val snapshot: Map<K, V>
@Synchronized get() = LinkedHashMap(map)
init {
require(maxSize > 0) { "maxSize <= 0" }
this.map = LinkedHashMap(0, 0.75f, true)
}
/**
* Sets the size of the cache.
*
* @param maxSize The new maximum size.
*/
fun resize(maxSize: Int) {
require(maxSize > 0) { "maxSize <= 0" }
synchronized(this) {
this.maxSize = maxSize
}
trimToSize(maxSize)
}
/**
* Returns the value for `key` if it exists in the cache or can be
* created by `#create`. If a value was returned, it is moved to the
* head of the queue. This returns null if a value is not cached and cannot
* be created.
*/
operator fun get(key: K): V? {
synchronized(this) {
map[key]?.let {
hitCount++
return it
}
missCount++
}
/*
* Attempt to create a value. This may take a long time, and the map
* may be different when create() returns. If a conflicting value was
* added to the map while create() was working, we leave that value in
* the map and release the created value.
*/
val createdValue = create(key) ?: return null
val mapValue: V? = synchronized(this) {
createCount++
val previous = map.put(key, createdValue)
if (previous != null) {
// There was a conflict so undo that last put
map[key] = previous
} else {
size += safeSizeOf(key, createdValue)
}
previous
}
return if (mapValue != null) {
entryRemoved(false, key, createdValue, mapValue)
mapValue
} else {
trimToSize(maxSize)
createdValue
}
}
/**
* Caches `value` for `key`. The value is moved to the head of
* the queue.
*
* @return the previous value mapped by `key`.
*/
fun put(key: K, value: V): V? {
val previous: V? = synchronized(this) {
putCount++
size += safeSizeOf(key, value)
map.put(key, value)?.apply {
size -= safeSizeOf(key, this@apply)
}
}
previous?.let {
entryRemoved(false, key, it, value)
}
trimToSize(maxSize)
return previous
}
/**
* Remove the eldest entries until the total of remaining entries is at or
* below the requested size.
*
* @param maxSize the maximum size of the cache before returning. May be -1
* to evict even 0-sized elements.
*/
fun trimToSize(maxSize: Int) {
while (true) {
val toEvict = synchronized(this) {
check(!(size < 0 || map.isEmpty() && size != 0)) {
javaClass.name + ".sizeOf() is reporting inconsistent results!"
}
if (size <= maxSize || map.isEmpty()) {
return
}
val toEvict = map.entries.iterator().next()
map.remove(toEvict.key)
size -= safeSizeOf(toEvict.key, toEvict.value)
evictionCount++
toEvict
}
entryRemoved(true, toEvict.key, toEvict.value, null)
}
}
/**
* Removes the entry for `key` if it exists.
*
* @return the previous value mapped by `key`.
*/
fun remove(key: K): V? {
val previous: V? = synchronized(this) {
map.remove(key)?.apply {
size -= safeSizeOf(key, this@apply)
}
}
return previous?.apply {
entryRemoved(false, key, this@apply, null)
}
}
/**
* Called for entries that have been evicted or removed. This method is
* invoked when a value is evicted to make space, removed by a call to
* [.remove], or replaced by a call to [.put]. The default
* implementation does nothing.
*
* The method is called without synchronization: other threads may
* access the cache while this method is executing.
*
* @param evicted true if the entry is being removed to make space, false
* if the removal was caused by a [.put] or [.remove].
* @param newValue the new value for `key`, if it exists. If non-null,
* this removal was caused by a [.put]. Otherwise it was caused by
* an eviction or a [.remove].
*/
protected open fun entryRemoved(evicted: Boolean, key: K, oldValue: V, newValue: V?) {}
/**
* Called after a cache miss to compute a value for the corresponding key.
* Returns the computed value or null if no value can be computed. The
* default implementation returns null.
*
* The method is called without synchronization: other threads may
* access the cache while this method is executing.
*
* If a value for `key` exists in the cache when this method
* returns, the created value will be released with [.entryRemoved]
* and discarded. This can occur when multiple threads request the same key
* at the same time (causing multiple values to be created), or when one
* thread calls [.put] while another is creating a value for the same
* key.
*/
protected open fun create(key: K): V? {
return null
}
private fun safeSizeOf(key: K, value: V): Int {
val result = sizeOf(key, value)
check(result >= 0) { "Negative size: $key=$value" }
return result
}
/**
* Returns the size of the entry for `key` and `value` in
* user-defined units. The default implementation returns 1 so that size
* is the number of entries and max size is the maximum number of entries.
*
* An entry's size must not change while it is in the cache.
*/
protected open fun sizeOf(key: K, value: V): Int {
return 1
}
/**
* Clear the cache, calling [.entryRemoved] on each removed entry.
*/
fun evictAll() {
trimToSize(-1) // -1 will evict 0-sized elements
}
@Synchronized
override fun toString(): String {
val accesses = hitCount + missCount
val hitPercent = if (accesses != 0) 100 * hitCount / accesses else 0
return "LruCache[maxSize=$maxSize,hits=$hitCount,misses=$missCount,hitRate=$hitPercent%]"
}
}
| mit | c5490e1577b76b857629e82ac0af0509 | 30.438356 | 97 | 0.585294 | 4.390244 | false | false | false | false |
coil-kt/coil | coil-base/src/main/java/coil/decode/BitmapFactoryDecoder.kt | 1 | 8463 | package coil.decode
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Build.VERSION.SDK_INT
import coil.ImageLoader
import coil.fetch.SourceResult
import coil.request.Options
import coil.size.isOriginal
import coil.util.MIME_TYPE_JPEG
import coil.util.heightPx
import coil.util.toDrawable
import coil.util.toSoftware
import coil.util.widthPx
import kotlin.math.roundToInt
import kotlinx.coroutines.runInterruptible
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withPermit
import okio.Buffer
import okio.ForwardingSource
import okio.Source
import okio.buffer
/** The base [Decoder] that uses [BitmapFactory] to decode a given [ImageSource]. */
class BitmapFactoryDecoder(
private val source: ImageSource,
private val options: Options,
private val parallelismLock: Semaphore = Semaphore(Int.MAX_VALUE),
private val exifOrientationPolicy: ExifOrientationPolicy = ExifOrientationPolicy.RESPECT_PERFORMANCE
) : Decoder {
@Deprecated(message = "Kept for binary compatibility.", level = DeprecationLevel.HIDDEN)
constructor(
source: ImageSource,
options: Options
) : this(source, options)
@Deprecated(message = "Kept for binary compatibility.", level = DeprecationLevel.HIDDEN)
constructor(
source: ImageSource,
options: Options,
parallelismLock: Semaphore = Semaphore(Int.MAX_VALUE)
) : this(source, options, parallelismLock)
override suspend fun decode() = parallelismLock.withPermit {
runInterruptible { BitmapFactory.Options().decode() }
}
private fun BitmapFactory.Options.decode(): DecodeResult {
val safeSource = ExceptionCatchingSource(source.source())
val safeBufferedSource = safeSource.buffer()
// Read the image's dimensions.
inJustDecodeBounds = true
BitmapFactory.decodeStream(safeBufferedSource.peek().inputStream(), null, this)
safeSource.exception?.let { throw it }
inJustDecodeBounds = false
// Get the image's EXIF data.
val exifData = ExifUtils.getExifData(outMimeType, safeBufferedSource, exifOrientationPolicy)
safeSource.exception?.let { throw it }
// Always create immutable bitmaps as they have better performance.
inMutable = false
if (SDK_INT >= 26 && options.colorSpace != null) {
inPreferredColorSpace = options.colorSpace
}
inPremultiplied = options.premultipliedAlpha
configureConfig(exifData)
configureScale(exifData)
// Decode the bitmap.
val outBitmap: Bitmap? = safeBufferedSource.use {
BitmapFactory.decodeStream(it.inputStream(), null, this)
}
safeSource.exception?.let { throw it }
checkNotNull(outBitmap) {
"BitmapFactory returned a null bitmap. Often this means BitmapFactory could not " +
"decode the image data read from the input source (e.g. network, disk, or " +
"memory) as it's not encoded as a valid image format."
}
// Fix the incorrect density created by overloading inDensity/inTargetDensity.
outBitmap.density = options.context.resources.displayMetrics.densityDpi
// Reverse the EXIF transformations to get the original image.
val bitmap = ExifUtils.reverseTransformations(outBitmap, exifData)
return DecodeResult(
drawable = bitmap.toDrawable(options.context),
isSampled = inSampleSize > 1 || inScaled
)
}
/** Compute and set [BitmapFactory.Options.inPreferredConfig]. */
private fun BitmapFactory.Options.configureConfig(exifData: ExifData) {
var config = options.config
// Disable hardware bitmaps if we need to perform EXIF transformations.
if (exifData.isFlipped || exifData.isRotated) {
config = config.toSoftware()
}
// Decode the image as RGB_565 as an optimization if allowed.
if (options.allowRgb565 && config == Bitmap.Config.ARGB_8888 && outMimeType == MIME_TYPE_JPEG) {
config = Bitmap.Config.RGB_565
}
// High color depth images must be decoded as either RGBA_F16 or HARDWARE.
if (SDK_INT >= 26 && outConfig == Bitmap.Config.RGBA_F16 && config != Bitmap.Config.HARDWARE) {
config = Bitmap.Config.RGBA_F16
}
inPreferredConfig = config
}
/** Compute and set the scaling properties for [BitmapFactory.Options]. */
private fun BitmapFactory.Options.configureScale(exifData: ExifData) {
// Requests that request original size from a resource source need to be decoded with
// respect to their intrinsic density.
val metadata = source.metadata
if (metadata is ResourceMetadata && options.size.isOriginal) {
inSampleSize = 1
inScaled = true
inDensity = metadata.density
inTargetDensity = options.context.resources.displayMetrics.densityDpi
return
}
// This occurs if there was an error decoding the image's size.
if (outWidth <= 0 || outHeight <= 0) {
inSampleSize = 1
inScaled = false
return
}
// srcWidth and srcHeight are the original dimensions of the image after
// EXIF transformations (but before sampling).
val srcWidth = if (exifData.isSwapped) outHeight else outWidth
val srcHeight = if (exifData.isSwapped) outWidth else outHeight
val dstWidth = options.size.widthPx(options.scale) { srcWidth }
val dstHeight = options.size.heightPx(options.scale) { srcHeight }
// Calculate the image's sample size.
inSampleSize = DecodeUtils.calculateInSampleSize(
srcWidth = srcWidth,
srcHeight = srcHeight,
dstWidth = dstWidth,
dstHeight = dstHeight,
scale = options.scale
)
// Calculate the image's density scaling multiple.
var scale = DecodeUtils.computeSizeMultiplier(
srcWidth = srcWidth / inSampleSize.toDouble(),
srcHeight = srcHeight / inSampleSize.toDouble(),
dstWidth = dstWidth.toDouble(),
dstHeight = dstHeight.toDouble(),
scale = options.scale
)
// Only upscale the image if the options require an exact size.
if (options.allowInexactSize) {
scale = scale.coerceAtMost(1.0)
}
inScaled = scale != 1.0
if (inScaled) {
if (scale > 1) {
// Upscale
inDensity = (Int.MAX_VALUE / scale).roundToInt()
inTargetDensity = Int.MAX_VALUE
} else {
// Downscale
inDensity = Int.MAX_VALUE
inTargetDensity = (Int.MAX_VALUE * scale).roundToInt()
}
}
}
class Factory(
maxParallelism: Int = DEFAULT_MAX_PARALLELISM,
private val exifOrientationPolicy: ExifOrientationPolicy = ExifOrientationPolicy.RESPECT_PERFORMANCE
) : Decoder.Factory {
@Suppress("NEWER_VERSION_IN_SINCE_KOTLIN")
@SinceKotlin("999.9") // Only public in Java.
constructor() : this()
@Deprecated(message = "Kept for binary compatibility.", level = DeprecationLevel.HIDDEN)
constructor(maxParallelism: Int = DEFAULT_MAX_PARALLELISM) : this(maxParallelism)
private val parallelismLock = Semaphore(maxParallelism)
override fun create(result: SourceResult, options: Options, imageLoader: ImageLoader): Decoder {
return BitmapFactoryDecoder(result.source, options, parallelismLock, exifOrientationPolicy)
}
override fun equals(other: Any?) = other is Factory
override fun hashCode() = javaClass.hashCode()
}
/** Prevent [BitmapFactory.decodeStream] from swallowing [Exception]s. */
private class ExceptionCatchingSource(delegate: Source) : ForwardingSource(delegate) {
var exception: Exception? = null
private set
override fun read(sink: Buffer, byteCount: Long): Long {
try {
return super.read(sink, byteCount)
} catch (e: Exception) {
exception = e
throw e
}
}
}
internal companion object {
internal const val DEFAULT_MAX_PARALLELISM = 4
}
}
| apache-2.0 | 7a42c840fcdc09792adf2dfeecbb575e | 36.446903 | 108 | 0.651424 | 4.911782 | false | true | false | false |
dreamkas/start-utils | versions-utils/src/main/java/ru/dreamkas/semver/VersionBuilder.kt | 1 | 4268 | package ru.dreamkas.semver
import ru.dreamkas.semver.exceptions.VersionFormatException
import ru.dreamkas.semver.prerelease.PreRelease
import java.util.regex.Matcher
import java.util.regex.Pattern
object VersionBuilder {
private const val full = "full"
private const val base = "base"
private const val comparable = "comparable"
private const val major = "major"
private const val minor = "minor"
private const val patch = "patch"
private const val preRelease = "preRelease"
private const val metaData = "metaData"
private val PATTERN = Pattern.compile(
"""
(?<$full>
(?<$comparable>
(?<$base>
(?<$major>0|[1-9]+0*)
(?:
\.(?<$minor>0|[1-9]+0*)
(?:
\.(?<$patch>0|[0-9]+0*)
)?
)?
)
(?:-(?<$preRelease>[\da-z\-]+(?:\.[\da-z\-]+)*))?
)
(?:\+(?<$metaData>[\da-z\-\.]+))?
)
""".trimIndent(), Pattern.CASE_INSENSITIVE or Pattern.COMMENTS)
/**
* Build [Version][ru.dreamkas.semver.Version] from String template
* ## @param [fullVersion]: `<major>.<minor>.<patch>[-preRelease][+metaData]`
* * **_major_ ::** `0|[1-9]+0*`
* * **_minor_ ::** `0|[1-9]+0*`
* * **_patch_ ::** `0|[1-9]+0*`
* * **_preRelease_ ::** `[id](\.[id])*`
* * **_id_ ::** `[0-9a-zA-Z\-]+`
* * **_metaData_ ::** `[0-9a-zA-Z\-]+`
* @see <a href="http://semver.org/spec/v2.0.0.html">Semantic versioning details</a>
* @exception VersionFormatException when version isn't correct
*/
@JvmStatic
fun build(fullVersion: String): Version {
val matches = PATTERN.matcher(fullVersion)
if (matches.matches()) {
try {
return makeVersion(matches)
} catch (e: NumberFormatException) {
throw VersionFormatException(fullVersion, e)
}
}
throw VersionFormatException(fullVersion)
}
/**
* Build [Version][ru.dreamkas.semver.Version] from all elements
* @param [major]
* major version :: `0|[1-9]+0*`
* @param [minor]
* minor version :: `0|[1-9]+0*`
* @param [patch]
* patch version :: `0|[1-9]+0*`
* @param [preRelease]
* pre-release :: `[[0-9a-zA-Z\-]+](\.[[0-9a-zA-Z\-]+])*`
* @param [metaData]
* metadata :: `[0-9a-zA-Z\-]+`
* @see Version
* @see <a href="http://semver.org/spec/v2.0.0.html">Semantic versioning details</a>
* @exception VersionFormatException when version isn't correct
*/
@JvmStatic
@JvmOverloads
fun build(major: Int = 0, minor: Int = 0, patch: Int = 0, preRelease: String = "", metaData: String = ""): Version {
var version = "$major.$minor.$patch"
if (preRelease.isNotEmpty()) version += "-$preRelease"
if (metaData.isNotEmpty()) version += "+$metaData"
return build(version)
}
/**
* Build [Version][ru.dreamkas.semver.Version] from comparable and metadata elements
* @param [comparable]
* comparable part of version that consists of major, minor, patch and pre-release elements. For example: 1.5.8-beta.22
* @param [metaData]
* metadata part:: `[0-9a-zA-Z\-]+`
* @see Version
* @see <a href="http://semver.org/spec/v2.0.0.html">Semantic versioning details</a>
* @exception VersionFormatException when version isn't correct
*/
@JvmStatic
fun build(comparable: String, metaData: String = ""): Version {
var version = comparable
if (metaData.isNotEmpty()) version += "+$metaData"
return build(version)
}
@JvmStatic
fun matches(fullVersion: String) = PATTERN.matcher(fullVersion).matches()
private fun makeVersion(matches: Matcher): Version {
return Version(
matches.group(major).toInt(),
matches.group(minor)?.toInt() ?: 0,
matches.group(patch)?.toInt() ?: 0,
PreRelease(matches.group(preRelease)),
MetaData(matches.group(metaData))
)
}
}
| mit | 1e78ae222113c98e7f365679c466f63e | 34.865546 | 130 | 0.537723 | 3.803922 | false | false | false | false |
sugarmanz/Pandroid | app/src/main/java/com/jeremiahzucker/pandroid/ui/play/PlayPresenter.kt | 1 | 4608 | package com.jeremiahzucker.pandroid.ui.play
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import com.jeremiahzucker.pandroid.player.PlayerService
import com.jeremiahzucker.pandroid.request.Pandora
import com.jeremiahzucker.pandroid.request.json.v5.method.station.AddFeedback
import com.jeremiahzucker.pandroid.request.json.v5.method.station.DeleteFeedback
import com.jeremiahzucker.pandroid.request.json.v5.model.ResponseModel
/**
* Created by Jeremiah Zucker on 8/25/2017.
*/
object PlayPresenter : PlayContract.Presenter {
private val TAG = PlayPresenter::class.java.simpleName
private var view: PlayContract.View? = null
private var playerService: PlayerService? = null
private var serviceBound: Boolean = false
private val connection = object : ServiceConnection {
override fun onServiceConnected(className: ComponentName, service: IBinder) {
// This is called when the connection with the service has been
// established, giving us the service object we can use to
// interact with the service. Because we have bound to a explicit
// service that we know is running in our own process, we can
// cast its IBinder to a concrete class and directly access it.
playerService = (service as PlayerService.LocalBinder).service
view?.registerWithPlayerService(playerService!!)
view?.onTrackUpdated(playerService!!.currentTrack)
}
override fun onServiceDisconnected(className: ComponentName) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
// Because it is running in our same process, we should never
// see this happen.
playerService = null
view?.unregisterWithPlayerService()
}
}
override fun attach(view: PlayContract.View) {
this.view = view
bindPlayerService()
// TODO
if (playerService != null && playerService!!.isPlaying) {
view.onTrackUpdated(playerService!!.currentTrack)
} else {
// - load last play list/folder/song
}
}
override fun detach() {
view?.unregisterWithPlayerService()
unbindPlayerService()
view = null
}
override fun setTrackAsFavorite(stationToken: String, trackToken: String) {
Pandora.RequestBuilder(AddFeedback)
.body(AddFeedback.RequestBody(stationToken, trackToken, true))
.build<AddFeedback.ResponseBody>()
.subscribe(this::setTrackAsFavoriteSuccess, this::setTrackAsFavoriteError)
}
private fun setTrackAsFavoriteSuccess(response: AddFeedback.ResponseBody) {
view?.onTrackSetAsFavorite(true, response.feedbackId)
}
private fun setTrackAsFavoriteError(throwable: Throwable) {
throwable.printStackTrace()
}
override fun removeTrackAsFavorite(feedbackId: String) {
Pandora.RequestBuilder(DeleteFeedback)
.body(DeleteFeedback.RequestBody(feedbackId))
.build<ResponseModel>()
.subscribe(this::removeTrackAsFavoriteSuccess, this::removeTrackAsFavoriteError)
}
private fun removeTrackAsFavoriteSuccess(response: ResponseModel) {
view?.onTrackSetAsFavorite(false, null)
}
private fun removeTrackAsFavoriteError(throwable: Throwable) {
throwable.printStackTrace()
}
override fun bindPlayerService() {
// Establish a connection with the service. We use an explicit
// class name because we want a specific service implementation that
// we know will be running in our own process (and thus won't be
// supporting component replacement by other applications).
val intent = Intent(view?.getContextForService(), PlayerService::class.java)
// Calling startService here will prevent the service from being cleaned up when the app exits
// TODO: Figure out if this is what we want to do
view?.getContextForService()?.startService(intent)
view?.getContextForService()?.bindService(intent, connection, Context.BIND_AUTO_CREATE)
serviceBound = true
}
override fun unbindPlayerService() {
if (serviceBound) {
// Detach our existing connection.
view?.getContextForService()?.unbindService(connection)
serviceBound = false
}
}
}
| mit | 396f759e9817a40f9dd1cac61bc15cb8 | 39.069565 | 102 | 0.690972 | 4.917823 | false | false | false | false |
InnoFang/DesignPatterns | src/io/innofang/proxy/example/kotlin/client.kt | 1 | 955 | package io.innofang.proxy.example.kotlin
/**
* Created by Inno Fang on 2017/9/3.
*/
fun main(args: Array<String>) {
val picker: IPicker = RealPicker()
val proxy = ProxyPicker(picker)
proxy.receiveMessage()
proxy.takeCourier()
proxy.signatureAcceptance()
println("\n+-----Splitter-----+\n")
/* Dynamic Proxy */
//implement 1
/*
val dynamicProxy = DynamicProxy(picker)
val loader = picker.javaClass.classLoader
val dynamicPicker = Proxy.newProxyInstance(
loader, arrayOf(IPicker::class.java), dynamicProxy) as IPicker
*/
//implement 2
/*
val dynamicPicker = createProxy<IPicker>(InvocationHandler { _, method, args ->
method!!.invoke(picker, *(args ?: arrayOfNulls(0)))
})
*/
//implement 3
val dynamicPicker = createProxy<IPicker>(picker)
dynamicPicker.receiveMessage()
dynamicPicker.takeCourier()
dynamicPicker.signatureAcceptance()
} | gpl-3.0 | 5500532c2249787bd600c82f6b0f1bd5 | 23.512821 | 83 | 0.65445 | 4.188596 | false | false | false | false |
cketti/okhttp | mockwebserver/src/main/kotlin/okhttp3/mockwebserver/internal/duplex/MockDuplexResponseBody.kt | 1 | 3676 | /*
* Copyright (C) 2019 Square, 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 okhttp3.mockwebserver.internal.duplex
import java.io.IOException
import java.util.concurrent.CountDownLatch
import java.util.concurrent.FutureTask
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
import okhttp3.internal.http2.ErrorCode
import okhttp3.internal.http2.Http2Stream
import okhttp3.mockwebserver.RecordedRequest
import okio.BufferedSink
import okio.BufferedSource
import okio.buffer
import okio.utf8Size
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Assert.fail
private typealias Action = (RecordedRequest, BufferedSource, BufferedSink, Http2Stream) -> Unit
/**
* A scriptable request/response conversation. Create the script by calling methods like
* [receiveRequest] in the sequence they are run.
*/
class MockDuplexResponseBody : DuplexResponseBody {
private val actions = LinkedBlockingQueue<Action>()
private val results = LinkedBlockingQueue<FutureTask<Void>>()
fun receiveRequest(expected: String) = apply {
actions += { _, requestBody, _, _ ->
assertEquals(expected, requestBody.readUtf8(expected.utf8Size()))
}
}
fun exhaustRequest() = apply {
actions += { _, requestBody, _, _ -> assertTrue(requestBody.exhausted()) }
}
fun cancelStream(errorCode: ErrorCode) = apply {
actions += { _, _, _, stream -> stream.closeLater(errorCode) }
}
fun requestIOException() = apply {
actions += { _, requestBody, _, _ ->
try {
requestBody.exhausted()
fail()
} catch (expected: IOException) {
}
}
}
@JvmOverloads fun sendResponse(
s: String,
responseSent: CountDownLatch = CountDownLatch(0)
) = apply {
actions += { _, _, responseBody, _ ->
responseBody.writeUtf8(s)
responseBody.flush()
responseSent.countDown()
}
}
fun exhaustResponse() = apply {
actions += { _, _, responseBody, _ -> responseBody.close() }
}
fun sleep(duration: Long, unit: TimeUnit) = apply {
actions += { _, _, _, _ -> Thread.sleep(unit.toMillis(duration)) }
}
override fun onRequest(request: RecordedRequest, http2Stream: Http2Stream) {
val task = serviceStreamTask(request, http2Stream)
results.add(task)
task.run()
}
/** Returns a task that processes both request and response from [http2Stream]. */
private fun serviceStreamTask(
request: RecordedRequest,
http2Stream: Http2Stream
): FutureTask<Void> {
return FutureTask<Void> {
http2Stream.getSource().buffer().use { requestBody ->
http2Stream.getSink().buffer().use { responseBody ->
while (true) {
val action = actions.poll() ?: break
action(request, requestBody, responseBody, http2Stream)
}
}
}
return@FutureTask null
}
}
/** Returns once the duplex conversation completes successfully. */
fun awaitSuccess() {
val futureTask = results.poll(5, TimeUnit.SECONDS)
?: throw AssertionError("no onRequest call received")
futureTask.get(5, TimeUnit.SECONDS)
}
}
| apache-2.0 | 1ea8ecc1e22ab5f56cbb1f077d52ade8 | 30.418803 | 95 | 0.693689 | 4.294393 | false | false | false | false |
DataDozer/DataDozer | core/src/main/kotlin/org/datadozer/index/fields/SystemFields.kt | 1 | 4637 | package org.datadozer.index.fields
import org.datadozer.models.Similarity
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
/*
* Licensed to DataDozer under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. DataDozer licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* Used for representing the id of an index
*/
object IdField {
private val info = KeywordField.info.copy(
defaultFieldName = "__id"
)
val INSTANCE = FieldType(info)
val SCHEMA = FieldSchema(
fieldName = info.defaultFieldName!!,
schemaName = info.defaultFieldName!!,
docValues = false,
fieldType = INSTANCE,
similarity = Similarity.BM25,
analyzers = null,
fieldOrder = 0,
multiValued = false
)
}
/**
* This fields is used to add causal ordering to the events in
* the index. A document with lower modify index was created/updated before
* a document with the higher index.
* This is also used for concurrency updates.
*/
object ModifyIndex {
private val info = LongField.info.copy(
defaultFieldName = "__modifyindex"
)
val INSTANCE = FieldType(info)
val SCHEMA = FieldSchema(
fieldName = info.defaultFieldName!!,
schemaName = info.defaultFieldName!!,
docValues = true,
fieldType = INSTANCE,
similarity = Similarity.BM25,
analyzers = null,
fieldOrder = 1,
multiValued = false
)
}
/**
* Field to be used for time stamp. This fields is used by index to capture the modification
* time.
* It only supports a fixed yyyyMMddHHmmss format.
*/
object TimeStampField {
private val info = DateTimeField.info.copy(
defaultFieldName = "__timestamp",
autoPopulated = true,
toInternal = fun(_) = LocalDateTime.now().format(dateFormat).toLong()
)
private val dateFormat = DateTimeFormatter.ofPattern("yyyyMMddHHmmss")
val INSTANCE = FieldType(info)
val SCHEMA = FieldSchema(
fieldName = info.defaultFieldName!!,
schemaName = info.defaultFieldName!!,
docValues = true,
fieldType = INSTANCE,
similarity = Similarity.BM25,
analyzers = null,
fieldOrder = -1,
multiValued = false
)
}
/**
* Log fields is an internal fields which is used to maintain the transaction
* log. The advantage of saving the transaction log in the index is that it
* is straight forward to sync the replicas and slave from the index using the
* modify index. There is a minimal disk space overhead when saving the transaction
* log in the index.
*
* Complete documents are not saved in the log as they are already part of the
* Lucene document. we only save important metadata which helps us in identifying
* the transaction information.
*/
object LogField {
private val info = org.datadozer.index.fields.StoredField.info.copy(
defaultFieldName = "__log",
autoPopulated = true
)
val INSTANCE = FieldType(info)
val SCHEMA = FieldSchema(
fieldName = info.defaultFieldName!!,
schemaName = info.defaultFieldName!!,
docValues = false,
fieldType = INSTANCE,
similarity = Similarity.BM25,
analyzers = null,
fieldOrder = 2,
multiValued = false
)
}
/**
* Internal fields used to represent the type of transaction that was
* performed when the related document was added to the index. This
* can be broadly classified into document and index related operations.
* Index related operations deal with index schema changes while document
* related changes are related to creating/updating and deleting of the
* documents.
*
* This fields is also used to filter out the deleted and non document related
* results from the search query.
*/
object TransactionTypeField {
} | apache-2.0 | b4a1f9a308478a568b31ce5336656012 | 32.128571 | 92 | 0.669183 | 4.669688 | false | false | false | false |
ReactiveCircus/FlowBinding | flowbinding-android/src/main/java/reactivecircus/flowbinding/android/widget/AbsListViewScrollEventFlow.kt | 1 | 2459 | @file:Suppress("MatchingDeclarationName")
package reactivecircus.flowbinding.android.widget
import android.widget.AbsListView
import androidx.annotation.CheckResult
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.conflate
import reactivecircus.flowbinding.common.checkMainThread
/**
* Create a [Flow] of scroll events on the [AbsListView] instance.
*
* Note: Created flow keeps a strong reference to the [AbsListView] instance
* until the coroutine that launched the flow collector is cancelled.
*
* Example of usage:
*
* ```
* absListView.scrollEvents()
* .onEach { event ->
* // handle scroll event
* }
* .launchIn(uiScope)
* ```
*/
@CheckResult
@OptIn(ExperimentalCoroutinesApi::class)
public fun AbsListView.scrollEvents(): Flow<ScrollEvent> = callbackFlow {
checkMainThread()
val listener = object : AbsListView.OnScrollListener {
private var currentScrollState = AbsListView.OnScrollListener.SCROLL_STATE_IDLE
override fun onScrollStateChanged(absListView: AbsListView, scrollState: Int) {
currentScrollState = scrollState
trySend(
ScrollEvent(
view = this@scrollEvents,
scrollState = scrollState,
firstVisibleItem = firstVisiblePosition,
visibleItemCount = childCount,
totalItemCount = count
)
)
}
override fun onScroll(
absListView: AbsListView,
firstVisibleItem: Int,
visibleItemCount: Int,
totalItemCount: Int
) {
trySend(
ScrollEvent(
view = this@scrollEvents,
scrollState = currentScrollState,
firstVisibleItem = firstVisibleItem,
visibleItemCount = visibleItemCount,
totalItemCount = totalItemCount
)
)
}
}
setOnScrollListener(listener)
awaitClose { setOnScrollListener(null) }
}.conflate()
public data class ScrollEvent(
public val view: AbsListView,
public val scrollState: Int,
public val firstVisibleItem: Int,
public val visibleItemCount: Int,
public val totalItemCount: Int
)
| apache-2.0 | 3035ee1039cc9f4ee66a0f00636034bb | 30.525641 | 87 | 0.644571 | 5.665899 | false | false | false | false |
square/leakcanary | leakcanary-object-watcher-android-core/src/main/java/leakcanary/ServiceWatcher.kt | 2 | 6117 | package leakcanary
import android.annotation.SuppressLint
import android.app.Service
import android.os.Build
import android.os.Handler
import android.os.IBinder
import leakcanary.internal.friendly.checkMainThread
import shark.SharkLog
import java.lang.ref.WeakReference
import java.lang.reflect.InvocationTargetException
import java.lang.reflect.Proxy
import java.util.WeakHashMap
/**
* Expects services to become weakly reachable soon after they receive the [Service.onDestroy]
* callback.
*/
@SuppressLint("PrivateApi")
class ServiceWatcher(private val reachabilityWatcher: ReachabilityWatcher) : InstallableWatcher {
private val servicesToBeDestroyed = WeakHashMap<IBinder, WeakReference<Service>>()
private val activityThreadClass by lazy { Class.forName("android.app.ActivityThread") }
private val activityThreadInstance by lazy {
activityThreadClass.getDeclaredMethod("currentActivityThread").invoke(null)!!
}
private val activityThreadServices by lazy {
val mServicesField =
activityThreadClass.getDeclaredField("mServices").apply { isAccessible = true }
@Suppress("UNCHECKED_CAST")
mServicesField[activityThreadInstance] as Map<IBinder, Service>
}
private var uninstallActivityThreadHandlerCallback: (() -> Unit)? = null
private var uninstallActivityManager: (() -> Unit)? = null
override fun install() {
checkMainThread()
check(uninstallActivityThreadHandlerCallback == null) {
"ServiceWatcher already installed"
}
check(uninstallActivityManager == null) {
"ServiceWatcher already installed"
}
try {
swapActivityThreadHandlerCallback { mCallback ->
uninstallActivityThreadHandlerCallback = {
swapActivityThreadHandlerCallback {
mCallback
}
}
Handler.Callback { msg ->
// https://github.com/square/leakcanary/issues/2114
// On some Motorola devices (Moto E5 and G6), the msg.obj returns an ActivityClientRecord
// instead of an IBinder. This crashes on a ClassCastException. Adding a type check
// here to prevent the crash.
if (msg.obj !is IBinder) {
return@Callback false
}
if (msg.what == STOP_SERVICE) {
val key = msg.obj as IBinder
activityThreadServices[key]?.let {
onServicePreDestroy(key, it)
}
}
mCallback?.handleMessage(msg) ?: false
}
}
swapActivityManager { activityManagerInterface, activityManagerInstance ->
uninstallActivityManager = {
swapActivityManager { _, _ ->
activityManagerInstance
}
}
Proxy.newProxyInstance(
activityManagerInterface.classLoader, arrayOf(activityManagerInterface)
) { _, method, args ->
if (METHOD_SERVICE_DONE_EXECUTING == method.name) {
val token = args!![0] as IBinder
if (servicesToBeDestroyed.containsKey(token)) {
onServiceDestroyed(token)
}
}
try {
if (args == null) {
method.invoke(activityManagerInstance)
} else {
method.invoke(activityManagerInstance, *args)
}
} catch (invocationException: InvocationTargetException) {
throw invocationException.targetException
}
}
}
} catch (ignored: Throwable) {
SharkLog.d(ignored) { "Could not watch destroyed services" }
}
}
override fun uninstall() {
checkMainThread()
uninstallActivityManager?.invoke()
uninstallActivityThreadHandlerCallback?.invoke()
uninstallActivityManager = null
uninstallActivityThreadHandlerCallback = null
}
private fun onServicePreDestroy(
token: IBinder,
service: Service
) {
servicesToBeDestroyed[token] = WeakReference(service)
}
private fun onServiceDestroyed(token: IBinder) {
servicesToBeDestroyed.remove(token)?.also { serviceWeakReference ->
serviceWeakReference.get()?.let { service ->
reachabilityWatcher.expectWeaklyReachable(
service, "${service::class.java.name} received Service#onDestroy() callback"
)
}
}
}
private fun swapActivityThreadHandlerCallback(swap: (Handler.Callback?) -> Handler.Callback?) {
val mHField =
activityThreadClass.getDeclaredField("mH").apply { isAccessible = true }
val mH = mHField[activityThreadInstance] as Handler
val mCallbackField =
Handler::class.java.getDeclaredField("mCallback").apply { isAccessible = true }
val mCallback = mCallbackField[mH] as Handler.Callback?
mCallbackField[mH] = swap(mCallback)
}
@SuppressLint("PrivateApi")
private fun swapActivityManager(swap: (Class<*>, Any) -> Any) {
val singletonClass = Class.forName("android.util.Singleton")
val mInstanceField =
singletonClass.getDeclaredField("mInstance").apply { isAccessible = true }
val singletonGetMethod = singletonClass.getDeclaredMethod("get")
val (className, fieldName) = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
"android.app.ActivityManager" to "IActivityManagerSingleton"
} else {
"android.app.ActivityManagerNative" to "gDefault"
}
val activityManagerClass = Class.forName(className)
val activityManagerSingletonField =
activityManagerClass.getDeclaredField(fieldName).apply { isAccessible = true }
val activityManagerSingletonInstance = activityManagerSingletonField[activityManagerClass]
// Calling get() instead of reading from the field directly to ensure the singleton is
// created.
val activityManagerInstance = singletonGetMethod.invoke(activityManagerSingletonInstance)
val iActivityManagerInterface = Class.forName("android.app.IActivityManager")
mInstanceField[activityManagerSingletonInstance] =
swap(iActivityManagerInterface, activityManagerInstance!!)
}
companion object {
private const val STOP_SERVICE = 116
private const val METHOD_SERVICE_DONE_EXECUTING = "serviceDoneExecuting"
}
} | apache-2.0 | 6b84d9fafda4bd8097cc622e64f40b4a | 34.16092 | 99 | 0.692496 | 4.905373 | false | false | false | false |
owncloud/android | owncloudApp/src/main/java/com/owncloud/android/providers/FileContentProvider.kt | 2 | 73093 | /**
* ownCloud Android client application
*
* @author Bartek Przybylski
* @author David A. Velasco
* @author masensio
* @author David González Verdugo
* @author Christian Schabesberger
* @author Abel García de Prada
* Copyright (C) 2011 Bartek Przybylski
* Copyright (C) 2020 ownCloud GmbH.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* 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:></http:>//www.gnu.org/licenses/>.
*/
package com.owncloud.android.providers
import android.accounts.AccountManager
import android.content.ContentProvider
import android.content.ContentProviderOperation
import android.content.ContentProviderResult
import android.content.ContentUris
import android.content.ContentValues
import android.content.Context
import android.content.OperationApplicationException
import android.content.UriMatcher
import android.database.Cursor
import android.database.SQLException
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.database.sqlite.SQLiteQueryBuilder
import android.net.Uri
import android.os.CancellationSignal
import android.os.ParcelFileDescriptor
import android.provider.BaseColumns
import android.text.TextUtils
import androidx.sqlite.db.SupportSQLiteDatabase
import androidx.sqlite.db.SupportSQLiteQueryBuilder
import com.owncloud.android.MainApp
import com.owncloud.android.R
import com.owncloud.android.data.Executors
import com.owncloud.android.data.OwncloudDatabase
import com.owncloud.android.data.ProviderMeta
import com.owncloud.android.data.capabilities.datasources.implementation.OCLocalCapabilitiesDataSource
import com.owncloud.android.data.capabilities.datasources.implementation.OCLocalCapabilitiesDataSource.Companion.toModel
import com.owncloud.android.data.capabilities.db.OCCapabilityEntity
import com.owncloud.android.data.folderbackup.datasources.FolderBackupLocalDataSource
import com.owncloud.android.data.migrations.CameraUploadsMigrationToRoom
import com.owncloud.android.data.preferences.datasources.SharedPreferencesProvider
import com.owncloud.android.data.sharing.shares.db.OCShareEntity
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.datamodel.UploadsStorageManager
import com.owncloud.android.db.ProviderMeta.ProviderTableMeta
import com.owncloud.android.domain.files.LIST_MIME_DIR
import com.owncloud.android.extensions.getLongFromColumnOrThrow
import com.owncloud.android.extensions.getStringFromColumnOrThrow
import com.owncloud.android.lib.common.accounts.AccountUtils
import com.owncloud.android.utils.FileStorageUtils
import org.koin.android.ext.android.inject
import timber.log.Timber
import java.io.File
import java.io.FileNotFoundException
import java.util.ArrayList
import java.util.HashMap
/**
* The ContentProvider for the ownCloud App.
*/
class FileContentProvider(val executors: Executors = Executors()) : ContentProvider() {
private lateinit var dbHelper: DataBaseHelper
private lateinit var uriMatcher: UriMatcher
override fun delete(uri: Uri, where: String?, whereArgs: Array<String>?): Int {
val count: Int
val db = dbHelper.writableDatabase
db.beginTransaction()
try {
count = delete(db, uri, where, whereArgs)
db.setTransactionSuccessful()
} finally {
db.endTransaction()
}
context?.contentResolver?.notifyChange(
uri,
null
)
return count
}
private fun delete(db: SQLiteDatabase, uri: Uri, where: String?, whereArgs: Array<String>?): Int {
if (where != null && whereArgs == null) {
throw IllegalArgumentException("Selection not allowed, use parameterized queries")
}
var count = 0
when (uriMatcher.match(uri)) {
SINGLE_FILE -> {
val c = query(uri, null, where, whereArgs, null)
var remoteId: String? = ""
if (c.moveToFirst()) {
remoteId = c.getStringFromColumnOrThrow(ProviderTableMeta.FILE_REMOTE_ID)
c.close()
}
Timber.d("Removing FILE $remoteId")
count = db.delete(
ProviderTableMeta.FILE_TABLE_NAME,
ProviderTableMeta._ID +
"=" +
uri.pathSegments[1] +
if (!TextUtils.isEmpty(where))
" AND ($where)"
else
"", whereArgs
)
}
DIRECTORY -> {
// deletion of folder is recursive
val children = query(uri, null, null, null, null)
if (children.moveToFirst()) {
var childId: Long
var isDir: Boolean
while (!children.isAfterLast) {
childId = children.getLongFromColumnOrThrow(ProviderTableMeta._ID)
isDir = children.getStringFromColumnOrThrow(ProviderTableMeta.FILE_CONTENT_TYPE) in LIST_MIME_DIR
count += if (isDir) {
delete(
db,
ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_DIR, childId), null, null
)
} else {
delete(
db,
ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_FILE, childId), null, null
)
}
children.moveToNext()
}
children.close()
}
count += db.delete(
ProviderTableMeta.FILE_TABLE_NAME,
ProviderTableMeta._ID + "=" +
uri.pathSegments[1] +
if (!TextUtils.isEmpty(where))
" AND ($where)"
else
"", whereArgs
)
}
ROOT_DIRECTORY ->
count = db.delete(ProviderTableMeta.FILE_TABLE_NAME, where, whereArgs)
SHARES -> count =
OwncloudDatabase.getDatabase(MainApp.appContext).shareDao().deleteShare(uri.pathSegments[1])
CAPABILITIES -> count = db.delete(ProviderTableMeta.CAPABILITIES_TABLE_NAME, where, whereArgs)
UPLOADS -> count = db.delete(ProviderTableMeta.UPLOADS_TABLE_NAME, where, whereArgs)
CAMERA_UPLOADS_SYNC -> count = db.delete(ProviderTableMeta.CAMERA_UPLOADS_SYNC_TABLE_NAME, where, whereArgs)
QUOTAS -> count = db.delete(ProviderTableMeta.USER_QUOTAS_TABLE_NAME, where, whereArgs)
else -> throw IllegalArgumentException("Unknown uri: $uri")
}
return count
}
override fun getType(uri: Uri): String? {
return when (uriMatcher.match(uri)) {
ROOT_DIRECTORY -> ProviderTableMeta.CONTENT_TYPE
SINGLE_FILE -> ProviderTableMeta.CONTENT_TYPE_ITEM
else -> throw IllegalArgumentException("Unknown Uri id.$uri")
}
}
override fun insert(uri: Uri, values: ContentValues?): Uri? {
val newUri: Uri?
val db = dbHelper.writableDatabase
db.beginTransaction()
try {
newUri = insert(db, uri, values)
db.setTransactionSuccessful()
} finally {
db.endTransaction()
}
context?.contentResolver?.notifyChange(newUri!!, null)
return newUri
}
private fun insert(db: SQLiteDatabase, uri: Uri, values: ContentValues?): Uri {
when (uriMatcher.match(uri)) {
ROOT_DIRECTORY, SINGLE_FILE -> {
val remotePath = values?.getAsString(ProviderTableMeta.FILE_PATH)
val accountName = values?.getAsString(ProviderTableMeta.FILE_ACCOUNT_OWNER)
val projection =
arrayOf(ProviderTableMeta._ID, ProviderTableMeta.FILE_PATH, ProviderTableMeta.FILE_ACCOUNT_OWNER)
val where = "${ProviderTableMeta.FILE_PATH}=? AND ${ProviderTableMeta.FILE_ACCOUNT_OWNER}=?"
val whereArgs = arrayOf<String>()
arrayListOf<String>().apply {
remotePath?.let { add(it) }
accountName?.let { add(it) }
}.toArray(whereArgs)
val doubleCheck = query(uri, projection, where, whereArgs, null)
// ugly patch; serious refactorization is needed to reduce work in
// FileDataStorageManager and bring it to FileContentProvider
return if (!doubleCheck.moveToFirst()) {
doubleCheck.close()
val fileId = db.insert(ProviderTableMeta.FILE_TABLE_NAME, null, values)
if (fileId <= 0) throw SQLException("ERROR $uri")
ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_FILE, fileId)
} else {
// file is already inserted; race condition, let's avoid a duplicated entry
val insertedFileUri = ContentUris.withAppendedId(
ProviderTableMeta.CONTENT_URI_FILE,
doubleCheck.getLongFromColumnOrThrow(ProviderTableMeta._ID)
)
doubleCheck.close()
insertedFileUri
}
}
SHARES -> {
val shareId = values?.let {
OwncloudDatabase.getDatabase(MainApp.appContext).shareDao().insert(
OCShareEntity.fromContentValues(it)
)
} ?: 0
if (shareId <= 0) throw SQLException("ERROR $uri")
return ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_SHARE, shareId)
}
CAPABILITIES -> {
val capabilityId = db.insert(ProviderTableMeta.CAPABILITIES_TABLE_NAME, null, values)
if (capabilityId <= 0) throw SQLException("ERROR $uri")
return ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_CAPABILITIES, capabilityId)
}
UPLOADS -> {
val uploadId = db.insert(ProviderTableMeta.UPLOADS_TABLE_NAME, null, values)
if (uploadId <= 0) throw SQLException("ERROR $uri")
trimSuccessfulUploads(db)
return ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_UPLOADS, uploadId)
}
CAMERA_UPLOADS_SYNC -> {
val cameraUploadId = db.insert(
ProviderTableMeta.CAMERA_UPLOADS_SYNC_TABLE_NAME, null,
values
)
if (cameraUploadId <= 0) throw SQLException("ERROR $uri")
return ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_CAMERA_UPLOADS_SYNC, cameraUploadId)
}
QUOTAS -> {
val quotaId = db.insert(
ProviderTableMeta.USER_QUOTAS_TABLE_NAME, null,
values
)
if (quotaId <= 0) throw SQLException("ERROR $uri")
return ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_QUOTAS, quotaId)
}
else -> throw IllegalArgumentException("Unknown uri id: $uri")
}
}
override fun onCreate(): Boolean {
dbHelper = DataBaseHelper(context)
val authority = context?.resources?.getString(R.string.authority)
uriMatcher = UriMatcher(UriMatcher.NO_MATCH)
uriMatcher.addURI(authority, null, ROOT_DIRECTORY)
uriMatcher.addURI(authority, "file/", SINGLE_FILE)
uriMatcher.addURI(authority, "file/#", SINGLE_FILE)
uriMatcher.addURI(authority, "dir/", DIRECTORY)
uriMatcher.addURI(authority, "dir/#", DIRECTORY)
uriMatcher.addURI(authority, "shares/", SHARES)
uriMatcher.addURI(authority, "shares/#", SHARES)
uriMatcher.addURI(authority, "capabilities/", CAPABILITIES)
uriMatcher.addURI(authority, "capabilities/#", CAPABILITIES)
uriMatcher.addURI(authority, "uploads/", UPLOADS)
uriMatcher.addURI(authority, "uploads/#", UPLOADS)
uriMatcher.addURI(authority, "cameraUploadsSync/", CAMERA_UPLOADS_SYNC)
uriMatcher.addURI(authority, "cameraUploadsSync/#", CAMERA_UPLOADS_SYNC)
uriMatcher.addURI(authority, "quotas/", QUOTAS)
uriMatcher.addURI(authority, "quotas/#", QUOTAS)
return true
}
override fun query(
uri: Uri,
projection: Array<String>?,
selection: String?,
selectionArgs: Array<String>?,
sortOrder: String?
): Cursor {
if (selection != null && selectionArgs == null) {
throw IllegalArgumentException("Selection not allowed, use parameterized queries")
}
val db: SQLiteDatabase = dbHelper.writableDatabase
val sqlQuery = SQLiteQueryBuilder()
sqlQuery.isStrict = true
sqlQuery.tables = ProviderTableMeta.FILE_TABLE_NAME
when (uriMatcher.match(uri)) {
ROOT_DIRECTORY -> sqlQuery.projectionMap = fileProjectionMap
DIRECTORY -> {
val folderId = uri.pathSegments[1]
sqlQuery.appendWhere(
ProviderTableMeta.FILE_PARENT + "=" + folderId
)
sqlQuery.projectionMap = fileProjectionMap
}
SINGLE_FILE -> {
if (uri.pathSegments.size > 1) {
sqlQuery.appendWhere(ProviderTableMeta._ID + "=" + uri.pathSegments[1])
}
sqlQuery.projectionMap = fileProjectionMap
}
SHARES -> {
val supportSqlQuery = SupportSQLiteQueryBuilder
.builder(ProviderTableMeta.OCSHARES_TABLE_NAME)
.columns(computeProjection(projection))
.selection(selection, selectionArgs)
.orderBy(
if (TextUtils.isEmpty(sortOrder)) {
sortOrder
} else {
ProviderTableMeta.OCSHARES_DEFAULT_SORT_ORDER
}
).create()
// To use full SQL queries within Room
val newDb: SupportSQLiteDatabase =
OwncloudDatabase.getDatabase(MainApp.appContext).openHelper.writableDatabase
return newDb.query(supportSqlQuery)
}
CAPABILITIES -> {
sqlQuery.tables = ProviderTableMeta.CAPABILITIES_TABLE_NAME
if (uri.pathSegments.size > 1) {
sqlQuery.appendWhereEscapeString(ProviderTableMeta._ID + "=" + uri.pathSegments[1])
}
sqlQuery.projectionMap = capabilityProjectionMap
}
UPLOADS -> {
sqlQuery.tables = ProviderTableMeta.UPLOADS_TABLE_NAME
if (uri.pathSegments.size > 1) {
sqlQuery.appendWhere(ProviderTableMeta._ID + "=" + uri.pathSegments[1])
}
sqlQuery.projectionMap = uploadProjectionMap
}
CAMERA_UPLOADS_SYNC -> {
sqlQuery.tables = ProviderTableMeta.CAMERA_UPLOADS_SYNC_TABLE_NAME
if (uri.pathSegments.size > 1) {
sqlQuery.appendWhere(ProviderTableMeta._ID + "=" + uri.pathSegments[1])
}
sqlQuery.projectionMap = cameraUploadSyncProjectionMap
}
QUOTAS -> {
sqlQuery.tables = ProviderTableMeta.USER_QUOTAS_TABLE_NAME
if (uri.pathSegments.size > 1) {
sqlQuery.appendWhere(ProviderTableMeta._ID + "=" + uri.pathSegments[1])
}
sqlQuery.projectionMap = quotaProjectionMap
}
else -> throw IllegalArgumentException("Unknown uri id: $uri")
}
val order: String? = if (TextUtils.isEmpty(sortOrder)) {
when (uriMatcher.match(uri)) {
SHARES -> ProviderTableMeta.OCSHARES_DEFAULT_SORT_ORDER
CAPABILITIES -> ProviderTableMeta.CAPABILITIES_DEFAULT_SORT_ORDER
UPLOADS -> ProviderTableMeta.UPLOADS_DEFAULT_SORT_ORDER
CAMERA_UPLOADS_SYNC -> ProviderTableMeta.CAMERA_UPLOADS_SYNC_DEFAULT_SORT_ORDER
QUOTAS -> ProviderTableMeta.USER_QUOTAS_DEFAULT_SORT_ORDER
else // Files
-> ProviderTableMeta.FILE_DEFAULT_SORT_ORDER
}
} else {
sortOrder
}
// DB case_sensitive
db.execSQL("PRAGMA case_sensitive_like = true")
val c = sqlQuery.query(db, projection, selection, selectionArgs, null, null, order)
c.setNotificationUri(context?.contentResolver, uri)
return c
}
private fun computeProjection(projectionIn: Array<String>?): Array<String?> {
if (!projectionIn.isNullOrEmpty()) {
val projection = arrayOfNulls<String>(projectionIn.size)
val length = projectionIn.size
for (i in 0 until length) {
val userColumn = projectionIn[i]
val column = shareProjectionMap[userColumn]
if (column != null) {
projection[i] = column
continue
}
throw IllegalArgumentException("Invalid column " + projectionIn[i])
}
return projection
} else {
// Return all columns in projection map.
val entrySet = shareProjectionMap.entries
val projection = arrayOfNulls<String>(entrySet.size)
val entryIter = entrySet.iterator()
var i = 0
while (entryIter.hasNext()) {
val entry = entryIter.next()
// Don't include the _count column when people ask for no projectionIn.
if (entry.key == BaseColumns._COUNT) {
continue
}
projection[i++] = entry.value
}
return projection
}
}
override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int {
val count: Int
val db = dbHelper.writableDatabase
db.beginTransaction()
try {
count = update(db, uri, values, selection, selectionArgs)
db.setTransactionSuccessful()
} finally {
db.endTransaction()
}
context?.contentResolver?.notifyChange(uri, null)
return count
}
private fun update(
db: SQLiteDatabase,
uri: Uri,
values: ContentValues?,
selection: String?,
selectionArgs: Array<String>?
): Int {
if (selection != null && selectionArgs == null) {
throw IllegalArgumentException("Selection not allowed, use parameterized queries")
}
when (uriMatcher.match(uri)) {
DIRECTORY -> return 0 //updateFolderSize(db, selectionArgs[0]);
SHARES -> return values?.let {
OwncloudDatabase.getDatabase(context!!).shareDao()
.update(OCShareEntity.fromContentValues(it)).toInt()
} ?: 0
CAPABILITIES -> return db.update(ProviderTableMeta.CAPABILITIES_TABLE_NAME, values, selection, selectionArgs)
UPLOADS -> {
val ret = db.update(ProviderTableMeta.UPLOADS_TABLE_NAME, values, selection, selectionArgs)
trimSuccessfulUploads(db)
return ret
}
CAMERA_UPLOADS_SYNC -> return db.update(ProviderTableMeta.CAMERA_UPLOADS_SYNC_TABLE_NAME, values, selection, selectionArgs)
QUOTAS -> return db.update(ProviderTableMeta.USER_QUOTAS_TABLE_NAME, values, selection, selectionArgs)
else -> return db.update(
ProviderTableMeta.FILE_TABLE_NAME, values, selection, selectionArgs
)
}
}
@Throws(OperationApplicationException::class)
override fun applyBatch(operations: ArrayList<ContentProviderOperation>): Array<ContentProviderResult?> {
Timber.d("applying batch in provider $this (temporary: $isTemporary)")
val results = arrayOfNulls<ContentProviderResult>(operations.size)
var i = 0
val db = dbHelper.writableDatabase
db.beginTransaction() // it's supposed that transactions can be nested
try {
for (operation in operations) {
results[i] = operation.apply(this, results, i)
i++
}
db.setTransactionSuccessful()
} finally {
db.endTransaction()
}
Timber.d("applied batch in provider $this")
return results
}
private inner class DataBaseHelper internal constructor(context: Context?) :
SQLiteOpenHelper(
context,
ProviderMeta.DB_NAME,
null,
ProviderMeta.DB_VERSION
) {
override fun onCreate(db: SQLiteDatabase) {
// files table
Timber.i("SQL : Entering in onCreate")
createFilesTable(db)
// Create capabilities table
createCapabilitiesTable(db)
// Create uploads table
createUploadsTable(db)
// Create user avatar table
createUserAvatarsTable(db)
// Create user quota table
createUserQuotaTable(db)
// Create camera upload sync table
createCameraUploadsSyncTable(db)
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
Timber.i("SQL : Entering in onUpgrade")
var upgraded = false
if (oldVersion == 1 && newVersion >= 2) {
Timber.i("SQL : Entering in the #1 ADD in onUpgrade")
db.execSQL(
"ALTER TABLE " + ProviderTableMeta.FILE_TABLE_NAME +
" ADD COLUMN " + ProviderTableMeta.FILE_KEEP_IN_SYNC + " INTEGER " +
" DEFAULT 0"
)
upgraded = true
}
if (oldVersion < 3 && newVersion >= 3) {
Timber.i("SQL : Entering in the #2 ADD in onUpgrade")
db.beginTransaction()
try {
db.execSQL(
"ALTER TABLE " + ProviderTableMeta.FILE_TABLE_NAME +
" ADD COLUMN " + ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA +
" INTEGER " + " DEFAULT 0"
)
// assume there are not local changes pending to upload
db.execSQL(
"UPDATE " + ProviderTableMeta.FILE_TABLE_NAME +
" SET " + ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA + " = " + System.currentTimeMillis() +
" WHERE " + ProviderTableMeta.FILE_STORAGE_PATH + " IS NOT NULL"
)
db.setTransactionSuccessful()
upgraded = true
} finally {
db.endTransaction()
}
}
if (oldVersion < 4 && newVersion >= 4) {
Timber.i("SQL : Entering in the #3 ADD in onUpgrade")
db.beginTransaction()
try {
db.execSQL(
"ALTER TABLE " + ProviderTableMeta.FILE_TABLE_NAME +
" ADD COLUMN " + ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA + " INTEGER " + " DEFAULT 0"
)
db.execSQL(
"UPDATE " + ProviderTableMeta.FILE_TABLE_NAME +
" SET " + ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA + " = " + ProviderTableMeta.FILE_MODIFIED +
" WHERE " + ProviderTableMeta.FILE_STORAGE_PATH + " IS NOT NULL"
)
db.setTransactionSuccessful()
upgraded = true
} finally {
db.endTransaction()
}
}
if (oldVersion < 5 && newVersion >= 5) {
Timber.i("SQL : Entering in the #4 ADD in onUpgrade")
db.beginTransaction()
try {
db.execSQL(
"ALTER TABLE " + ProviderTableMeta.FILE_TABLE_NAME + " ADD COLUMN " + ProviderTableMeta.FILE_ETAG + " TEXT " + " DEFAULT NULL"
)
db.setTransactionSuccessful()
upgraded = true
} finally {
db.endTransaction()
}
}
if (oldVersion < 6 && newVersion >= 6) {
Timber.i("SQL : Entering in the #5 ADD in onUpgrade")
db.beginTransaction()
try {
db.execSQL(
"ALTER TABLE " + ProviderTableMeta.FILE_TABLE_NAME +
" ADD COLUMN " + ProviderTableMeta.FILE_SHARED_VIA_LINK + " INTEGER " + " DEFAULT 0"
)
db.execSQL(
"ALTER TABLE " + ProviderTableMeta.FILE_TABLE_NAME +
" ADD COLUMN " + ProviderTableMeta.FILE_PUBLIC_LINK + " TEXT " + " DEFAULT NULL"
)
// Create table ocshares
createOCSharesTable(db)
db.setTransactionSuccessful()
upgraded = true
} finally {
db.endTransaction()
}
}
if (oldVersion < 7 && newVersion >= 7) {
Timber.i("SQL : Entering in the #7 ADD in onUpgrade")
db.beginTransaction()
try {
db.execSQL(
"ALTER TABLE " + ProviderTableMeta.FILE_TABLE_NAME +
" ADD COLUMN " + ProviderTableMeta.FILE_PERMISSIONS + " TEXT " +
" DEFAULT NULL"
)
db.execSQL(
"ALTER TABLE " + ProviderTableMeta.FILE_TABLE_NAME +
" ADD COLUMN " + ProviderTableMeta.FILE_REMOTE_ID + " TEXT " +
" DEFAULT NULL"
)
db.setTransactionSuccessful()
upgraded = true
} finally {
db.endTransaction()
}
}
if (oldVersion < 8 && newVersion >= 8) {
Timber.i("SQL : Entering in the #8 ADD in onUpgrade")
db.beginTransaction()
try {
db.execSQL(
"ALTER TABLE " + ProviderTableMeta.FILE_TABLE_NAME +
" ADD COLUMN " + ProviderTableMeta.FILE_UPDATE_THUMBNAIL + " INTEGER " +
" DEFAULT 0"
)
db.setTransactionSuccessful()
upgraded = true
} finally {
db.endTransaction()
}
}
if (oldVersion < 9 && newVersion >= 9) {
Timber.i("SQL : Entering in the #9 ADD in onUpgrade")
db.beginTransaction()
try {
db.execSQL(
"ALTER TABLE " + ProviderTableMeta.FILE_TABLE_NAME +
" ADD COLUMN " + ProviderTableMeta.FILE_IS_DOWNLOADING + " INTEGER " +
" DEFAULT 0"
)
db.setTransactionSuccessful()
upgraded = true
} finally {
db.endTransaction()
}
}
if (oldVersion < 10 && newVersion >= 10) {
Timber.i("SQL : Entering in the #10 ADD in onUpgrade")
updateAccountName(db)
upgraded = true
}
if (oldVersion < 11 && newVersion >= 11) {
Timber.i("SQL : Entering in the #11 ADD in onUpgrade")
db.beginTransaction()
try {
db.execSQL(
"ALTER TABLE " + ProviderTableMeta.FILE_TABLE_NAME +
" ADD COLUMN " + ProviderTableMeta.FILE_ETAG_IN_CONFLICT + " TEXT " +
" DEFAULT NULL"
)
db.setTransactionSuccessful()
upgraded = true
} finally {
db.endTransaction()
}
}
if (oldVersion < 12 && newVersion >= 12) {
Timber.i("SQL : Entering in the #12 ADD in onUpgrade")
db.beginTransaction()
try {
db.execSQL(
"ALTER TABLE " + ProviderTableMeta.FILE_TABLE_NAME +
" ADD COLUMN " + ProviderTableMeta.FILE_SHARED_WITH_SHAREE + " INTEGER " +
" DEFAULT 0"
)
db.setTransactionSuccessful()
upgraded = true
} finally {
db.endTransaction()
}
}
if (oldVersion < 13 && newVersion >= 13) {
Timber.i("SQL : Entering in the #13 ADD in onUpgrade")
db.beginTransaction()
try {
// Create capabilities table
createCapabilitiesTable(db)
db.setTransactionSuccessful()
upgraded = true
} finally {
db.endTransaction()
}
}
if (oldVersion < 14 && newVersion >= 14) {
Timber.i("SQL : Entering in the #14 ADD in onUpgrade")
db.beginTransaction()
try {
// drop old instant_upload table
db.execSQL("DROP TABLE IF EXISTS " + "instant_upload" + ";")
// Create uploads table
createUploadsTable(db)
db.setTransactionSuccessful()
upgraded = true
} finally {
db.endTransaction()
}
}
if (oldVersion < 15 && newVersion >= 15) {
Timber.i("SQL : Entering in the #15 ADD in onUpgrade")
db.beginTransaction()
try {
// Create user profiles table
createUserAvatarsTable(db)
db.setTransactionSuccessful()
upgraded = true
} finally {
db.endTransaction()
}
}
if (oldVersion < 16 && newVersion >= 16) {
Timber.i("SQL : Entering in the #16 ADD in onUpgrade")
db.beginTransaction()
try {
db.execSQL(
"ALTER TABLE " + ProviderTableMeta.FILE_TABLE_NAME +
" ADD COLUMN " + ProviderTableMeta.FILE_TREE_ETAG + " TEXT " +
" DEFAULT NULL"
)
db.setTransactionSuccessful()
upgraded = true
} finally {
db.endTransaction()
}
}
if (oldVersion < 17 && newVersion >= 17) {
Timber.i("SQL : Entering in the #17 ADD in onUpgrade")
db.beginTransaction()
try {
db.execSQL(
"ALTER TABLE " + ProviderTableMeta.OCSHARES_TABLE_NAME +
" ADD COLUMN " + ProviderTableMeta.OCSHARES_NAME + " TEXT " +
" DEFAULT NULL"
)
db.setTransactionSuccessful()
upgraded = true
// SQLite does not allow to drop a columns; ftm, we'll not recreate
// the files table without the column FILE_PUBLIC_LINK, just forget about
} finally {
db.endTransaction()
}
}
if (oldVersion < 18 && newVersion >= 18) {
Timber.i("SQL : Entering in the #18 ADD in onUpgrade")
db.beginTransaction()
try {
db.execSQL(
"ALTER TABLE " + ProviderTableMeta.OCSHARES_TABLE_NAME +
" ADD COLUMN " + ProviderTableMeta.OCSHARES_URL + " TEXT " +
" DEFAULT NULL"
)
db.setTransactionSuccessful()
upgraded = true
} finally {
db.endTransaction()
}
}
if (oldVersion < 19 && newVersion >= 19) {
Timber.i("SQL : Entering in the #19 ADD in onUpgrade")
db.beginTransaction()
try {
db.execSQL(
"ALTER TABLE " + ProviderTableMeta.CAPABILITIES_TABLE_NAME +
" ADD COLUMN " + ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_MULTIPLE +
" INTEGER " + " DEFAULT -1"
)
db.setTransactionSuccessful()
upgraded = true
} finally {
db.endTransaction()
}
}
if (oldVersion < 20 && newVersion >= 20) {
Timber.i("SQL : Entering in the #20 ADD in onUpgrade")
db.beginTransaction()
try {
db.execSQL(
"ALTER TABLE " + ProviderTableMeta.CAPABILITIES_TABLE_NAME +
" ADD COLUMN " + ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_SUPPORTS_UPLOAD_ONLY + " INTEGER " +
" DEFAULT -1"
)
db.setTransactionSuccessful()
upgraded = true
} finally {
db.endTransaction()
}
}
if (oldVersion < 21 && newVersion >= 21) {
Timber.i("SQL : Entering in the #21 ADD in onUpgrade")
db.beginTransaction()
try {
db.execSQL(
"ALTER TABLE " + ProviderTableMeta.FILE_TABLE_NAME +
" ADD COLUMN " + ProviderTableMeta.FILE_PRIVATE_LINK + " TEXT " +
" DEFAULT NULL"
)
db.setTransactionSuccessful()
upgraded = true
} finally {
db.endTransaction()
}
}
if (oldVersion < 22 && newVersion >= 22) {
Timber.i("SQL : Entering in the #22 ADD in onUpgrade")
db.beginTransaction()
try {
createCameraUploadsSyncTable(db)
db.setTransactionSuccessful()
upgraded = true
} finally {
db.endTransaction()
}
}
if (oldVersion < 23 && newVersion >= 23) {
Timber.i("SQL : Entering in the #23 ADD in onUpgrade")
db.beginTransaction()
try {
createUserQuotaTable(db)
db.setTransactionSuccessful()
upgraded = true
} finally {
db.endTransaction()
}
}
if (oldVersion < 24 && newVersion >= 24) {
Timber.i("SQL : Entering in the #24 ADD in onUpgrade")
db.beginTransaction()
try {
db.execSQL(
"ALTER TABLE " + ProviderTableMeta.UPLOADS_TABLE_NAME +
" ADD COLUMN " + ProviderTableMeta.UPLOADS_TRANSFER_ID + " TEXT " +
" DEFAULT NULL"
)
db.setTransactionSuccessful()
upgraded = true
} finally {
db.endTransaction()
}
}
if (oldVersion < 25 && newVersion >= 25) {
Timber.i("SQL : Entering in the #25 ADD in onUpgrade")
db.beginTransaction()
try {
db.execSQL(
"ALTER TABLE " + ProviderTableMeta.CAPABILITIES_TABLE_NAME +
" ADD COLUMN " +
ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_READ_ONLY +
" INTEGER DEFAULT NULL"
)
db.execSQL(
"ALTER TABLE " + ProviderTableMeta.CAPABILITIES_TABLE_NAME +
" ADD COLUMN " +
ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_READ_WRITE +
" INTEGER DEFAULT NULL"
)
db.execSQL(
"ALTER TABLE " + ProviderTableMeta.CAPABILITIES_TABLE_NAME +
" ADD COLUMN " +
ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_UPLOAD_ONLY +
" INTEGER DEFAULT NULL"
)
db.execSQL(
"ALTER TABLE " + ProviderTableMeta.OCSHARES_TABLE_NAME +
" ADD COLUMN " + ProviderTableMeta.OCSHARES_SHARE_WITH_ADDITIONAL_INFO + " TEXT " +
" DEFAULT NULL"
)
db.setTransactionSuccessful()
upgraded = true
} finally {
db.endTransaction()
}
}
if (oldVersion < 26 && newVersion >= 26) {
Timber.i("SQL : Entering in #26 to migrate shares from SQLite to Room")
// Drop old shares table from old database
db.execSQL("DROP TABLE IF EXISTS " + ProviderTableMeta.OCSHARES_TABLE_NAME + ";")
}
if (oldVersion < 27 && newVersion >= 27) {
Timber.i("SQL : Entering in #27 to migrate capabilities from SQLite to Room")
val cursor = db.query(
ProviderTableMeta.CAPABILITIES_TABLE_NAME,
null,
null,
null,
null,
null,
null
)
if (cursor.moveToFirst()) {
val ocLocalCapabilitiesDataSource: OCLocalCapabilitiesDataSource by inject()
// Insert capability to the new capabilities table in new database
executors.diskIO().execute {
ocLocalCapabilitiesDataSource.insert(
listOf(OCCapabilityEntity.fromCursor(cursor)).map {
it.toModel()
}
)
}
}
}
if (oldVersion < 30 && newVersion >= 30) {
Timber.i("SQL : Entering in the #30 ADD chunking capability")
db.beginTransaction()
try {
db.execSQL(
"ALTER TABLE " + ProviderTableMeta.CAPABILITIES_TABLE_NAME +
" ADD COLUMN " + ProviderTableMeta.CAPABILITIES_DAV_CHUNKING_VERSION + " TEXT " +
" DEFAULT NULL"
)
db.setTransactionSuccessful()
upgraded = true
} finally {
db.endTransaction()
}
}
if (oldVersion < 32 && newVersion >= 32) {
Timber.i("SQL : Entering in the #32 DROP quotas and avatars table and use room database")
db.beginTransaction()
try {
// Drop quotas and avatars from old database
db.execSQL("DROP TABLE IF EXISTS " + ProviderTableMeta.USER_QUOTAS_TABLE_NAME + ";")
db.execSQL("DROP TABLE IF EXISTS " + ProviderTableMeta.USER_AVATARS__TABLE_NAME + ";")
db.setTransactionSuccessful()
upgraded = true
} finally {
db.endTransaction()
}
}
if (oldVersion < 34 && newVersion >= 34) {
Timber.i("SQL : Entering in the #34 Migrate old camera uploads configuration to room database")
db.beginTransaction()
var pictureUploadsTimestamp: Long = 0
var videoUploadsTimestamp: Long = 0
try {
val cursor = db.query(ProviderTableMeta.CAMERA_UPLOADS_SYNC_TABLE_NAME, null, null, null, null, null, null)
if (cursor.moveToFirst()) {
pictureUploadsTimestamp = cursor.getLongFromColumnOrThrow(ProviderTableMeta.PICTURES_LAST_SYNC_TIMESTAMP)
videoUploadsTimestamp = cursor.getLongFromColumnOrThrow(ProviderTableMeta.VIDEOS_LAST_SYNC_TIMESTAMP)
}
val sharedPreferencesProvider: SharedPreferencesProvider by inject()
val migrationToRoom = CameraUploadsMigrationToRoom(sharedPreferencesProvider)
val pictureUploadsConfiguration = migrationToRoom.getPictureUploadsConfigurationPreferences(pictureUploadsTimestamp)
val videoUploadsConfiguration = migrationToRoom.getVideoUploadsConfigurationPreferences(videoUploadsTimestamp)
val backupLocalDataSource: FolderBackupLocalDataSource by inject()
// Insert camera uploads configuration in new database
executors.diskIO().execute {
pictureUploadsConfiguration?.let { backupLocalDataSource.saveFolderBackupConfiguration(it) }
videoUploadsConfiguration?.let { backupLocalDataSource.saveFolderBackupConfiguration(it) }
if (pictureUploadsConfiguration != null || videoUploadsConfiguration != null) {
val workManagerProvider: WorkManagerProvider by inject()
workManagerProvider.enqueueCameraUploadsWorker()
}
}
cursor.close()
// Drop camera uploads timestamps from old database
db.execSQL("DROP TABLE IF EXISTS " + ProviderTableMeta.CAMERA_UPLOADS_SYNC_TABLE_NAME + ";")
db.setTransactionSuccessful()
upgraded = true
} finally {
db.endTransaction()
}
}
if (!upgraded) {
Timber.i("SQL : OUT of the ADD in onUpgrade; oldVersion == $oldVersion, newVersion == $newVersion")
}
}
}
private fun createFilesTable(db: SQLiteDatabase) {
db.execSQL(
"CREATE TABLE " + ProviderTableMeta.FILE_TABLE_NAME + "(" +
ProviderTableMeta._ID + " INTEGER PRIMARY KEY, " +
ProviderTableMeta.FILE_NAME + " TEXT, " +
ProviderTableMeta.FILE_PATH + " TEXT, " +
ProviderTableMeta.FILE_PARENT + " INTEGER, " +
ProviderTableMeta.FILE_CREATION + " INTEGER, " +
ProviderTableMeta.FILE_MODIFIED + " INTEGER, " +
ProviderTableMeta.FILE_CONTENT_TYPE + " TEXT, " +
ProviderTableMeta.FILE_CONTENT_LENGTH + " INTEGER, " +
ProviderTableMeta.FILE_STORAGE_PATH + " TEXT, " +
ProviderTableMeta.FILE_ACCOUNT_OWNER + " TEXT, " +
ProviderTableMeta.FILE_LAST_SYNC_DATE + " INTEGER, " +
ProviderTableMeta.FILE_KEEP_IN_SYNC + " INTEGER, " +
ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA + " INTEGER, " +
ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA + " INTEGER, " +
ProviderTableMeta.FILE_ETAG + " TEXT, " +
ProviderTableMeta.FILE_TREE_ETAG + " TEXT, " +
ProviderTableMeta.FILE_SHARED_VIA_LINK + " INTEGER, " +
ProviderTableMeta.FILE_PUBLIC_LINK + " TEXT, " +
ProviderTableMeta.FILE_PERMISSIONS + " TEXT null," +
ProviderTableMeta.FILE_REMOTE_ID + " TEXT null," +
ProviderTableMeta.FILE_UPDATE_THUMBNAIL + " INTEGER," + //boolean
ProviderTableMeta.FILE_IS_DOWNLOADING + " INTEGER," + //boolean
ProviderTableMeta.FILE_ETAG_IN_CONFLICT + " TEXT," +
ProviderTableMeta.FILE_SHARED_WITH_SHAREE + " INTEGER," +
ProviderTableMeta.FILE_PRIVATE_LINK + " TEXT );"
)
}
private fun createOCSharesTable(db: SQLiteDatabase) {
// Create ocshares table
db.execSQL(
"CREATE TABLE " + ProviderTableMeta.OCSHARES_TABLE_NAME + "(" +
ProviderTableMeta._ID + " INTEGER PRIMARY KEY, " +
"file_source" + " INTEGER, " +
"item_source" + " INTEGER, " +
ProviderTableMeta.OCSHARES_SHARE_TYPE + " INTEGER, " +
ProviderTableMeta.OCSHARES_SHARE_WITH + " TEXT, " +
ProviderTableMeta.OCSHARES_PATH + " TEXT, " +
ProviderTableMeta.OCSHARES_PERMISSIONS + " INTEGER, " +
ProviderTableMeta.OCSHARES_SHARED_DATE + " INTEGER, " +
ProviderTableMeta.OCSHARES_EXPIRATION_DATE + " INTEGER, " +
ProviderTableMeta.OCSHARES_TOKEN + " TEXT, " +
ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME + " TEXT, " +
ProviderTableMeta.OCSHARES_IS_DIRECTORY + " INTEGER, " + // boolean
"user_id" + " INTEGER, " +
ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED + " INTEGER," +
ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + " TEXT, " +
ProviderTableMeta.OCSHARES_URL + " TEXT, " +
ProviderTableMeta.OCSHARES_NAME + " TEXT );"
)
}
private fun createCapabilitiesTable(db: SQLiteDatabase) {
// Create capabilities table
db.execSQL(
"CREATE TABLE " + ProviderTableMeta.CAPABILITIES_TABLE_NAME + "(" +
ProviderTableMeta._ID + " INTEGER PRIMARY KEY, " +
ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME + " TEXT, " +
ProviderTableMeta.CAPABILITIES_VERSION_MAYOR + " INTEGER, " +
ProviderTableMeta.CAPABILITIES_VERSION_MINOR + " INTEGER, " +
ProviderTableMeta.CAPABILITIES_VERSION_MICRO + " INTEGER, " +
ProviderTableMeta.CAPABILITIES_VERSION_STRING + " TEXT, " +
ProviderTableMeta.CAPABILITIES_VERSION_EDITION + " TEXT, " +
ProviderTableMeta.CAPABILITIES_CORE_POLLINTERVAL + " INTEGER, " +
ProviderTableMeta.CAPABILITIES_DAV_CHUNKING_VERSION + " TEXT, " +
ProviderTableMeta.CAPABILITIES_SHARING_API_ENABLED + " INTEGER, " + // boolean
ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_ENABLED + " INTEGER, " + // boolean
ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED + " INTEGER, " + // boolean
ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_READ_ONLY + " INTEGER, " + // boolean
ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_READ_WRITE + " INTEGER, " + // boolean
ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_UPLOAD_ONLY + " INTEGER, " + // boolean
ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENABLED + " INTEGER, " + // boolean
ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_DAYS + " INTEGER, " +
ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENFORCED + " INTEGER, " + // boolean
ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_UPLOAD + " INTEGER, " + // boolean
ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_MULTIPLE + " INTEGER, " + // boolean
ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_SUPPORTS_UPLOAD_ONLY + " INTEGER, " + // boolean
ProviderTableMeta.CAPABILITIES_SHARING_RESHARING + " INTEGER, " + // boolean
ProviderTableMeta.CAPABILITIES_SHARING_FEDERATION_OUTGOING + " INTEGER, " + // boolean
ProviderTableMeta.CAPABILITIES_SHARING_FEDERATION_INCOMING + " INTEGER, " + // boolean
ProviderTableMeta.CAPABILITIES_FILES_BIGFILECHUNKING + " INTEGER, " + // boolean
ProviderTableMeta.CAPABILITIES_FILES_UNDELETE + " INTEGER, " + // boolean
ProviderTableMeta.CAPABILITIES_FILES_VERSIONING + " INTEGER );"
) // boolean
}
private fun createUploadsTable(db: SQLiteDatabase) {
// Create uploads table
db.execSQL(
"CREATE TABLE " + ProviderTableMeta.UPLOADS_TABLE_NAME + "(" +
ProviderTableMeta._ID + " INTEGER PRIMARY KEY, " +
ProviderTableMeta.UPLOADS_LOCAL_PATH + " TEXT, " +
ProviderTableMeta.UPLOADS_REMOTE_PATH + " TEXT, " +
ProviderTableMeta.UPLOADS_ACCOUNT_NAME + " TEXT, " +
ProviderTableMeta.UPLOADS_FILE_SIZE + " LONG, " +
ProviderTableMeta.UPLOADS_STATUS + " INTEGER, " + // UploadStatus
ProviderTableMeta.UPLOADS_LOCAL_BEHAVIOUR + " INTEGER, " + // Upload LocalBehaviour
ProviderTableMeta.UPLOADS_UPLOAD_TIME + " INTEGER, " +
ProviderTableMeta.UPLOADS_FORCE_OVERWRITE + " INTEGER, " + // boolean
ProviderTableMeta.UPLOADS_IS_CREATE_REMOTE_FOLDER + " INTEGER, " + // boolean
ProviderTableMeta.UPLOADS_UPLOAD_END_TIMESTAMP + " INTEGER, " +
ProviderTableMeta.UPLOADS_LAST_RESULT + " INTEGER, " + // Upload LastResult
ProviderTableMeta.UPLOADS_CREATED_BY + " INTEGER, " + // Upload createdBy
ProviderTableMeta.UPLOADS_TRANSFER_ID + " TEXT );" // Upload chunkedUploadId
)
}
private fun createUserAvatarsTable(db: SQLiteDatabase) {
db.execSQL(
"CREATE TABLE " + ProviderTableMeta.USER_AVATARS__TABLE_NAME + "(" +
ProviderTableMeta._ID + " INTEGER PRIMARY KEY, " +
ProviderTableMeta.USER_AVATARS__ACCOUNT_NAME + " TEXT, " +
ProviderTableMeta.USER_AVATARS__CACHE_KEY + " TEXT, " +
ProviderTableMeta.USER_AVATARS__MIME_TYPE + " TEXT, " +
ProviderTableMeta.USER_AVATARS__ETAG + " TEXT );"
)
}
private fun createUserQuotaTable(db: SQLiteDatabase) {
db.execSQL(
"CREATE TABLE " + ProviderTableMeta.USER_QUOTAS_TABLE_NAME + "(" +
ProviderTableMeta._ID + " INTEGER PRIMARY KEY, " +
ProviderTableMeta.USER_QUOTAS__ACCOUNT_NAME + " TEXT, " +
ProviderTableMeta.USER_QUOTAS__FREE + " LONG, " +
ProviderTableMeta.USER_QUOTAS__RELATIVE + " LONG, " +
ProviderTableMeta.USER_QUOTAS__TOTAL + " LONG, " +
ProviderTableMeta.USER_QUOTAS__USED + " LONG );"
)
}
private fun createCameraUploadsSyncTable(db: SQLiteDatabase) {
db.execSQL(
"CREATE TABLE " + ProviderTableMeta.CAMERA_UPLOADS_SYNC_TABLE_NAME + "(" +
ProviderTableMeta._ID + " INTEGER PRIMARY KEY, " +
ProviderTableMeta.PICTURES_LAST_SYNC_TIMESTAMP + " INTEGER," +
ProviderTableMeta.VIDEOS_LAST_SYNC_TIMESTAMP + " INTEGER);"
)
}
/**
* Version 10 of database does not modify its scheme. It coincides with the upgrade of the ownCloud account names
* structure to include in it the path to the server instance. Updating the account names and path to local files
* in the files table is a must to keep the existing account working and the database clean.
*
* See [com.owncloud.android.authentication.AccountUtils.updateAccountVersion]
*
* @param db Database where table of files is included.
*/
private fun updateAccountName(db: SQLiteDatabase) {
Timber.d("SQL : THREAD: ${Thread.currentThread().name}")
val ama = AccountManager.get(context)
try {
// get accounts from AccountManager ; we can't be sure if accounts in it are updated or not although
// we know the update was previously done in {link @FileActivity#onCreate} because the changes through
// AccountManager are not synchronous
val accounts = AccountManager.get(context).getAccountsByType(
MainApp.accountType
)
var serverUrl: String
var username: String?
var oldAccountName: String
var newAccountName: String
for (account in accounts) {
// build both old and new account name
serverUrl = ama.getUserData(account, AccountUtils.Constants.KEY_OC_BASE_URL)
username = AccountUtils.getUsernameForAccount(account)
oldAccountName = AccountUtils.buildAccountNameOld(Uri.parse(serverUrl), username)
newAccountName = AccountUtils.buildAccountName(Uri.parse(serverUrl), username)
// update values in database
db.beginTransaction()
try {
val cv = ContentValues()
cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, newAccountName)
val num = db.update(
ProviderTableMeta.FILE_TABLE_NAME,
cv,
ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
arrayOf(oldAccountName)
)
Timber.d("SQL : Updated account in database: old name == $oldAccountName, new name == $newAccountName ($num rows updated )")
// update path for downloaded files
updateDownloadedFiles(db, newAccountName, oldAccountName)
db.setTransactionSuccessful()
} catch (e: SQLException) {
Timber.e(e, "SQL Exception upgrading account names or paths in database")
} finally {
db.endTransaction()
}
}
} catch (e: Exception) {
Timber.e(e, "Exception upgrading account names or paths in database")
}
}
/**
* Rename the local ownCloud folder of one account to match the a rename of the account itself. Updates the
* table of files in database so that the paths to the local files keep being the same.
*
* @param db Database where table of files is included.
* @param newAccountName New name for the target OC account.
* @param oldAccountName Old name of the target OC account.
*/
private fun updateDownloadedFiles(
db: SQLiteDatabase, newAccountName: String,
oldAccountName: String
) {
val whereClause = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " +
ProviderTableMeta.FILE_STORAGE_PATH + " IS NOT NULL"
val c = db.query(
ProviderTableMeta.FILE_TABLE_NAME, null,
whereClause,
arrayOf(newAccountName), null, null, null
)
c.use {
if (it.moveToFirst()) {
// create storage path
val oldAccountPath = FileStorageUtils.getSavePath(oldAccountName)
val newAccountPath = FileStorageUtils.getSavePath(newAccountName)
// move files
val oldAccountFolder = File(oldAccountPath)
val newAccountFolder = File(newAccountPath)
oldAccountFolder.renameTo(newAccountFolder)
// update database
do {
// Update database
val oldPath = it.getStringFromColumnOrThrow(ProviderTableMeta.FILE_STORAGE_PATH)
val file = OCFile(it.getStringFromColumnOrThrow(ProviderTableMeta.FILE_PATH))
val newPath = FileStorageUtils.getDefaultSavePathFor(newAccountName, file)
val cv = ContentValues()
cv.put(ProviderTableMeta.FILE_STORAGE_PATH, newPath)
db.update(
ProviderTableMeta.FILE_TABLE_NAME,
cv,
ProviderTableMeta.FILE_STORAGE_PATH + "=?",
arrayOf(oldPath)
)
Timber.v("SQL : Updated path of downloaded file: old file name == $oldPath, new file name == $newPath")
} while (it.moveToNext())
}
}
}
@Throws(FileNotFoundException::class)
override fun openFile(uri: Uri, mode: String, signal: CancellationSignal?): ParcelFileDescriptor? {
return super.openFile(uri, mode, signal)
}
@Throws(FileNotFoundException::class)
override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor? {
return super.openFile(uri, mode)
}
/**
* Grants that total count of successful uploads stored is not greater than MAX_SUCCESSFUL_UPLOADS.
*
* Removes older uploads if needed.
*/
private fun trimSuccessfulUploads(db: SQLiteDatabase) {
var c: Cursor? = null
try {
c = db.rawQuery(
"delete from " + ProviderTableMeta.UPLOADS_TABLE_NAME +
" where " + ProviderTableMeta.UPLOADS_STATUS + " == " +
UploadsStorageManager.UploadStatus.UPLOAD_SUCCEEDED.value +
" and " + ProviderTableMeta._ID +
" not in (select " + ProviderTableMeta._ID +
" from " + ProviderTableMeta.UPLOADS_TABLE_NAME +
" where " + ProviderTableMeta.UPLOADS_STATUS + " == " +
UploadsStorageManager.UploadStatus.UPLOAD_SUCCEEDED.value +
" order by " + ProviderTableMeta.UPLOADS_UPLOAD_END_TIMESTAMP +
" desc limit " + MAX_SUCCESSFUL_UPLOADS +
")", null
)
c!!.moveToFirst() // do something with the cursor, or deletion doesn't happen; true story
} catch (e: Exception) {
Timber.e(e, "Something wrong trimming successful uploads, database could grow more than expected")
} finally {
c?.close()
}
}
companion object {
private const val SINGLE_FILE = 1
private const val DIRECTORY = 2
private const val ROOT_DIRECTORY = 3
private const val SHARES = 4
private const val CAPABILITIES = 5
private const val UPLOADS = 6
private const val CAMERA_UPLOADS_SYNC = 7
private const val QUOTAS = 8
private const val MAX_SUCCESSFUL_UPLOADS = "30"
private val fileProjectionMap = HashMap<String, String>()
init {
fileProjectionMap[ProviderTableMeta._ID] = ProviderTableMeta._ID
fileProjectionMap[ProviderTableMeta.FILE_PARENT] = ProviderTableMeta.FILE_PARENT
fileProjectionMap[ProviderTableMeta.FILE_NAME] = ProviderTableMeta.FILE_NAME
fileProjectionMap[ProviderTableMeta.FILE_CREATION] = ProviderTableMeta.FILE_CREATION
fileProjectionMap[ProviderTableMeta.FILE_MODIFIED] = ProviderTableMeta.FILE_MODIFIED
fileProjectionMap[ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA] =
ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA
fileProjectionMap[ProviderTableMeta.FILE_CONTENT_LENGTH] = ProviderTableMeta.FILE_CONTENT_LENGTH
fileProjectionMap[ProviderTableMeta.FILE_CONTENT_TYPE] = ProviderTableMeta.FILE_CONTENT_TYPE
fileProjectionMap[ProviderTableMeta.FILE_STORAGE_PATH] = ProviderTableMeta.FILE_STORAGE_PATH
fileProjectionMap[ProviderTableMeta.FILE_PATH] = ProviderTableMeta.FILE_PATH
fileProjectionMap[ProviderTableMeta.FILE_ACCOUNT_OWNER] = ProviderTableMeta.FILE_ACCOUNT_OWNER
fileProjectionMap[ProviderTableMeta.FILE_LAST_SYNC_DATE] = ProviderTableMeta.FILE_LAST_SYNC_DATE
fileProjectionMap[ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA] =
ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA
fileProjectionMap[ProviderTableMeta.FILE_KEEP_IN_SYNC] = ProviderTableMeta.FILE_KEEP_IN_SYNC
fileProjectionMap[ProviderTableMeta.FILE_ETAG] = ProviderTableMeta.FILE_ETAG
fileProjectionMap[ProviderTableMeta.FILE_TREE_ETAG] = ProviderTableMeta.FILE_TREE_ETAG
fileProjectionMap[ProviderTableMeta.FILE_SHARED_VIA_LINK] = ProviderTableMeta.FILE_SHARED_VIA_LINK
fileProjectionMap[ProviderTableMeta.FILE_SHARED_WITH_SHAREE] = ProviderTableMeta.FILE_SHARED_WITH_SHAREE
fileProjectionMap[ProviderTableMeta.FILE_PERMISSIONS] = ProviderTableMeta.FILE_PERMISSIONS
fileProjectionMap[ProviderTableMeta.FILE_REMOTE_ID] = ProviderTableMeta.FILE_REMOTE_ID
fileProjectionMap[ProviderTableMeta.FILE_UPDATE_THUMBNAIL] = ProviderTableMeta.FILE_UPDATE_THUMBNAIL
fileProjectionMap[ProviderTableMeta.FILE_IS_DOWNLOADING] = ProviderTableMeta.FILE_IS_DOWNLOADING
fileProjectionMap[ProviderTableMeta.FILE_ETAG_IN_CONFLICT] = ProviderTableMeta.FILE_ETAG_IN_CONFLICT
fileProjectionMap[ProviderTableMeta.FILE_PRIVATE_LINK] = ProviderTableMeta.FILE_PRIVATE_LINK
}
private val shareProjectionMap = HashMap<String, String>()
init {
shareProjectionMap[ProviderTableMeta.ID] = ProviderTableMeta.ID
shareProjectionMap[ProviderTableMeta.OCSHARES_SHARE_TYPE] = ProviderTableMeta.OCSHARES_SHARE_TYPE
shareProjectionMap[ProviderTableMeta.OCSHARES_SHARE_WITH] = ProviderTableMeta.OCSHARES_SHARE_WITH
shareProjectionMap[ProviderTableMeta.OCSHARES_PATH] = ProviderTableMeta.OCSHARES_PATH
shareProjectionMap[ProviderTableMeta.OCSHARES_PERMISSIONS] = ProviderTableMeta.OCSHARES_PERMISSIONS
shareProjectionMap[ProviderTableMeta.OCSHARES_SHARED_DATE] = ProviderTableMeta.OCSHARES_SHARED_DATE
shareProjectionMap[ProviderTableMeta.OCSHARES_EXPIRATION_DATE] = ProviderTableMeta.OCSHARES_EXPIRATION_DATE
shareProjectionMap[ProviderTableMeta.OCSHARES_TOKEN] = ProviderTableMeta.OCSHARES_TOKEN
shareProjectionMap[ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME] =
ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME
shareProjectionMap[ProviderTableMeta.OCSHARES_SHARE_WITH_ADDITIONAL_INFO] =
ProviderTableMeta.OCSHARES_SHARE_WITH_ADDITIONAL_INFO
shareProjectionMap[ProviderTableMeta.OCSHARES_IS_DIRECTORY] = ProviderTableMeta.OCSHARES_IS_DIRECTORY
shareProjectionMap[ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED] =
ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED
shareProjectionMap[ProviderTableMeta.OCSHARES_ACCOUNT_OWNER] = ProviderTableMeta.OCSHARES_ACCOUNT_OWNER
shareProjectionMap[ProviderTableMeta.OCSHARES_NAME] = ProviderTableMeta.OCSHARES_NAME
shareProjectionMap[ProviderTableMeta.OCSHARES_URL] = ProviderTableMeta.OCSHARES_URL
}
private val capabilityProjectionMap = HashMap<String, String>()
init {
capabilityProjectionMap[ProviderTableMeta._ID] = ProviderTableMeta._ID
capabilityProjectionMap[ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME] =
ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME
capabilityProjectionMap[ProviderTableMeta.CAPABILITIES_VERSION_MAYOR] =
ProviderTableMeta.CAPABILITIES_VERSION_MAYOR
capabilityProjectionMap[ProviderTableMeta.CAPABILITIES_VERSION_MINOR] =
ProviderTableMeta.CAPABILITIES_VERSION_MINOR
capabilityProjectionMap[ProviderTableMeta.CAPABILITIES_VERSION_MICRO] =
ProviderTableMeta.CAPABILITIES_VERSION_MICRO
capabilityProjectionMap[ProviderTableMeta.CAPABILITIES_VERSION_STRING] =
ProviderTableMeta.CAPABILITIES_VERSION_STRING
capabilityProjectionMap[ProviderTableMeta.CAPABILITIES_VERSION_EDITION] =
ProviderTableMeta.CAPABILITIES_VERSION_EDITION
capabilityProjectionMap[ProviderTableMeta.CAPABILITIES_CORE_POLLINTERVAL] =
ProviderTableMeta.CAPABILITIES_CORE_POLLINTERVAL
capabilityProjectionMap[ProviderTableMeta.CAPABILITIES_DAV_CHUNKING_VERSION] =
ProviderTableMeta.CAPABILITIES_DAV_CHUNKING_VERSION
capabilityProjectionMap[ProviderTableMeta.CAPABILITIES_SHARING_API_ENABLED] =
ProviderTableMeta.CAPABILITIES_SHARING_API_ENABLED
capabilityProjectionMap[ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_ENABLED] =
ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_ENABLED
capabilityProjectionMap[ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED] =
ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED
capabilityProjectionMap[ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_READ_ONLY] =
ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_READ_ONLY
capabilityProjectionMap[ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_READ_WRITE] =
ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_READ_WRITE
capabilityProjectionMap[ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_UPLOAD_ONLY] =
ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_UPLOAD_ONLY
capabilityProjectionMap[ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENABLED] =
ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENABLED
capabilityProjectionMap[ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_DAYS] =
ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_DAYS
capabilityProjectionMap[ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENFORCED] =
ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENFORCED
capabilityProjectionMap[ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_UPLOAD] =
ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_UPLOAD
capabilityProjectionMap[ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_MULTIPLE] =
ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_MULTIPLE
capabilityProjectionMap[ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_SUPPORTS_UPLOAD_ONLY] =
ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_SUPPORTS_UPLOAD_ONLY
capabilityProjectionMap[ProviderTableMeta.CAPABILITIES_SHARING_RESHARING] =
ProviderTableMeta.CAPABILITIES_SHARING_RESHARING
capabilityProjectionMap[ProviderTableMeta.CAPABILITIES_SHARING_FEDERATION_OUTGOING] =
ProviderTableMeta.CAPABILITIES_SHARING_FEDERATION_OUTGOING
capabilityProjectionMap[ProviderTableMeta.CAPABILITIES_SHARING_FEDERATION_INCOMING] =
ProviderTableMeta.CAPABILITIES_SHARING_FEDERATION_INCOMING
capabilityProjectionMap[ProviderTableMeta.CAPABILITIES_FILES_BIGFILECHUNKING] =
ProviderTableMeta.CAPABILITIES_FILES_BIGFILECHUNKING
capabilityProjectionMap[ProviderTableMeta.CAPABILITIES_FILES_UNDELETE] =
ProviderTableMeta.CAPABILITIES_FILES_UNDELETE
capabilityProjectionMap[ProviderTableMeta.CAPABILITIES_FILES_VERSIONING] =
ProviderTableMeta.CAPABILITIES_FILES_VERSIONING
}
private val uploadProjectionMap = HashMap<String, String>()
init {
uploadProjectionMap[ProviderTableMeta._ID] = ProviderTableMeta._ID
uploadProjectionMap[ProviderTableMeta.UPLOADS_LOCAL_PATH] = ProviderTableMeta.UPLOADS_LOCAL_PATH
uploadProjectionMap[ProviderTableMeta.UPLOADS_REMOTE_PATH] = ProviderTableMeta.UPLOADS_REMOTE_PATH
uploadProjectionMap[ProviderTableMeta.UPLOADS_ACCOUNT_NAME] = ProviderTableMeta.UPLOADS_ACCOUNT_NAME
uploadProjectionMap[ProviderTableMeta.UPLOADS_FILE_SIZE] = ProviderTableMeta.UPLOADS_FILE_SIZE
uploadProjectionMap[ProviderTableMeta.UPLOADS_STATUS] = ProviderTableMeta.UPLOADS_STATUS
uploadProjectionMap[ProviderTableMeta.UPLOADS_LOCAL_BEHAVIOUR] = ProviderTableMeta.UPLOADS_LOCAL_BEHAVIOUR
uploadProjectionMap[ProviderTableMeta.UPLOADS_UPLOAD_TIME] = ProviderTableMeta.UPLOADS_UPLOAD_TIME
uploadProjectionMap[ProviderTableMeta.UPLOADS_FORCE_OVERWRITE] = ProviderTableMeta.UPLOADS_FORCE_OVERWRITE
uploadProjectionMap[ProviderTableMeta.UPLOADS_IS_CREATE_REMOTE_FOLDER] =
ProviderTableMeta.UPLOADS_IS_CREATE_REMOTE_FOLDER
uploadProjectionMap[ProviderTableMeta.UPLOADS_UPLOAD_END_TIMESTAMP] =
ProviderTableMeta.UPLOADS_UPLOAD_END_TIMESTAMP
uploadProjectionMap[ProviderTableMeta.UPLOADS_LAST_RESULT] = ProviderTableMeta.UPLOADS_LAST_RESULT
uploadProjectionMap[ProviderTableMeta.UPLOADS_CREATED_BY] = ProviderTableMeta.UPLOADS_CREATED_BY
uploadProjectionMap[ProviderTableMeta.UPLOADS_TRANSFER_ID] = ProviderTableMeta.UPLOADS_TRANSFER_ID
}
private val cameraUploadSyncProjectionMap = HashMap<String, String>()
init {
cameraUploadSyncProjectionMap[ProviderTableMeta._ID] = ProviderTableMeta._ID
cameraUploadSyncProjectionMap[ProviderTableMeta.PICTURES_LAST_SYNC_TIMESTAMP] =
ProviderTableMeta.PICTURES_LAST_SYNC_TIMESTAMP
cameraUploadSyncProjectionMap[ProviderTableMeta.VIDEOS_LAST_SYNC_TIMESTAMP] =
ProviderTableMeta.VIDEOS_LAST_SYNC_TIMESTAMP
}
private val quotaProjectionMap = HashMap<String, String>()
init {
quotaProjectionMap[ProviderTableMeta._ID] = ProviderTableMeta._ID
quotaProjectionMap[ProviderTableMeta.USER_QUOTAS__ACCOUNT_NAME] =
ProviderTableMeta.USER_QUOTAS__ACCOUNT_NAME
quotaProjectionMap[ProviderTableMeta.USER_QUOTAS__FREE] = ProviderTableMeta.USER_QUOTAS__FREE
quotaProjectionMap[ProviderTableMeta.USER_QUOTAS__RELATIVE] = ProviderTableMeta.USER_QUOTAS__RELATIVE
quotaProjectionMap[ProviderTableMeta.USER_QUOTAS__TOTAL] = ProviderTableMeta.USER_QUOTAS__TOTAL
quotaProjectionMap[ProviderTableMeta.USER_QUOTAS__USED] = ProviderTableMeta.USER_QUOTAS__USED
}
}
}
| gpl-2.0 | 945a7657edf716d8f97b0da9730dd078 | 46.928525 | 150 | 0.564214 | 5.509649 | false | false | false | false |
matthewfrost/FYPRepo | PlantView/app/src/main/java/matthewfrost/co/plantview/Compass.kt | 1 | 2608 | package matthewfrost.co.plantview
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
/**
* Created by Matthew on 26/02/2017.
*/
class Compass : SensorEventListener
{
var sensorManager : SensorManager
var gsensor : Sensor
var msensor : Sensor
var mGravity : FloatArray = FloatArray(3)
var mMagnetic : FloatArray = FloatArray(3)
var azimuth : Double = 0.0
constructor(c : Context){
sensorManager = c.getSystemService(Context.SENSOR_SERVICE) as SensorManager
gsensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
msensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD)
}
fun start(){
sensorManager.registerListener(this, gsensor, SensorManager.SENSOR_DELAY_GAME)
sensorManager.registerListener(this, msensor, SensorManager.SENSOR_DELAY_GAME)
}
fun stop(){
sensorManager.unregisterListener(this)
}
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
//throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onSensorChanged(event: SensorEvent) {
var gravity : Float = 0.98f
synchronized(this){
if(event.sensor.type == Sensor.TYPE_ACCELEROMETER){
mGravity[0] = gravity * mGravity[0] + (1 - gravity) * event.values[0]
mGravity[1] = gravity * mGravity[1] + (1 - gravity) * event.values[1]
mGravity[2] = gravity * mGravity[2] + (1 - gravity) * event.values[2] //Low pass filter
}
if(event.sensor.type == Sensor.TYPE_MAGNETIC_FIELD){
mMagnetic[0] = gravity * mMagnetic[0] + (1 - gravity) * event.values[0]
mMagnetic[1] = gravity * mMagnetic[1] + (1 - gravity) * event.values[1]
mMagnetic[2] = gravity * mMagnetic[2] + (1 - gravity) * event.values[2]
}
var R : FloatArray = FloatArray(9)
var I : FloatArray = FloatArray(9)
var success = SensorManager.getRotationMatrix(R, I, mGravity, mMagnetic)
if(success){
var orientation : FloatArray = FloatArray(3)
SensorManager.getOrientation(R, orientation)
azimuth = Math.toDegrees(orientation[0].toDouble() + 45)
azimuth = ((azimuth + 360) % 360) //to account for device rotation
}
}
}
} | mit | 80bca3cf77525642e2d005b3ec0b8ffc | 35.746479 | 140 | 0.63727 | 4.29654 | false | false | false | false |
drmashu/dikon | buriteri/src/main/kotlin/io/github/drmashu/buri/template/PreCompiler.kt | 1 | 15103 | package io.github.drmashu.buri.template
import java.io.*
import java.util.*
import kotlin.text.Regex
/**
* テンプレートプリコンパイラ.
* @author NAGASAWA Takahiro<[email protected]>
*/
public class PreCompiler {
companion object {
private val blank = """[ \t\r\n]"""
private val NOT_BLANK = Regex("""[^ \t\r\n]""")
private val FIRST_LINE = Regex("""@\(([^)]*)\)""")
private val IF = Regex("$blank*if$blank*")
private val FOR = Regex("$blank*for$blank*")
private val ELSE = Regex("$blank*else$blank*")
private val ELSE_IF = Regex("$blank*else$blank+if$blank*")
private val at = '@'.toInt()
private val block_start = '{'.toInt()
private val block_end = '}'.toInt()
private val lineCommentMark = '/'.toInt()
private val cr = '\r'.toInt()
private val nl = '\n'.toInt()
private val blockCommentMark = '*'.toInt()
private val bracket_start = '('.toInt()
private val bracket_end = ')'.toInt()
/** ファイル種別ごとのレンダラースーパークラス定義 */
private val RENDERER_TYPE = mapOf(
Pair("html", "HtmlAction")
)
}
/**
* 指定されたファイルをプリコンパイルする。
* 対象のファイルが".kt.html"で終わっていない場合は、無視する。
* @param packageName パッケージ名
* @param srcFile 対象ファイル
* @param destDir 出力先ディレクトリ
*/
fun precompile(packageName:String, srcFile: File, destDir: File) {
val name = srcFile.name
for (rendererType in RENDERER_TYPE) {
if (name.endsWith(".kt." + rendererType.key, true)) {
if (!destDir.exists()) {
// 出力先がなければ作る
destDir.mkdirs()
}
val reader = FileReader(srcFile)
val distFile = File(destDir, name.substring(0, name.length() - 5))
val writer = FileWriter(distFile)
val className = name.substring(0, name.length() - 8)
precompile(reader, writer, packageName, className, rendererType.value)
writer.flush()
writer.close()
reader.close()
}
}
}
/**
* プリコンパイル処理
* @param _reader 入力元バッファ
* @param writer 出力先バッファ
* @param packageName パッケージ名
* @param className 出力クラス名
* @param typeName スーパークラス名
*/
fun precompile(_reader: Reader, writer: Writer, packageName:String, className: String, typeName: String) {
var reader = LineNumberReader(_reader)
val firstLine :String? = reader.readLine()
var lineIdx = 1
var charIdx = 1
//一行目専用処理
var param: String?
// 一行目の先頭が"@"で始まっていたら、このレンダラーのパラメータが指定されるということ
if (firstLine != null && firstLine.startsWith("@")) {
// カッコ内をとりだして、レンダラーメソッドのパラメータにする
val match = FIRST_LINE.match(firstLine)
param = match?.groups?.get(1)?.value
} else {
// 先頭行がパラメータ指定で始まっていないとエラー
throw BuriLexicalException("$lineIdx,$charIdx : 先頭行はパラメータ指定である必要があります")
}
if (param == null) {
//取り出せなければ、パラメータは空
param = ""
} else if (!param.isEmpty()) {
param = ", " + param
}
//先頭のコメント
writer.write("/** Generate source code by Buri Template PreCompiler at ${Date()} */\n")
writer.write("package $packageName\n")
writer.write("import java.util.*\n")
writer.write("import java.io.Writer\n")
writer.write("import javax.servlet.http.*\n")
writer.write("import io.github.drmashu.buri.*\n")
// クラス名
writer.write("class $className(request: HttpServletRequest, response: HttpServletResponse$param) : $typeName(request, response) {\n")
// GETメソッドに実装
writer.write("\tpublic override fun get() {\n")
val mode = Stack<Mode>()
// インサートモード
val insert = object : Mode(writer) {
override fun process(char: Int) {
when(char) {
block_end -> {
writer.write("}\"))\n")
// インサートモードから抜ける
mode.pop()
// マジックモードから抜ける
mode.pop()
}
else -> writer.write(char)
}
}
}
// 条件モード
val conditions = object : Mode(writer) {
override fun process(char: Int) {
writer.write(char)
when(char) {
bracket_end -> {
// モードから抜ける
mode.pop()
}
bracket_start -> {
mode.push(this)
}
}
}
}
// コマンドモード
val command = object : Mode(writer) {
var buf: StringBuffer? = null
// var needBlock = false
override fun process(char: Int) {
if (buf == null) {
buf = StringBuffer()
}
when(char) {
at -> {
if (buf != null && buf!!.length() > 0) {
buf = null
// コマンドのパラメータ/ブロック開始の前に @ があるとエラー
throw BuriLexicalException("$lineIdx,$charIdx: @ の出現位置が不正です")
}
// needBlock = false
// コマンドモードから抜ける
mode.pop()
// マジックモードから抜ける
mode.pop()
}
bracket_start -> {
val commandName = buf.toString()
buf = null
// needBlock = true
if (IF.matches(commandName)) {
writer.write("/* $lineIdx */if")
} else if (FOR.matches(commandName)) {
writer.write("/* $lineIdx */for")
} else {
// 提供されているコマンド以外の場合はエラー
throw BuriLexicalException("$lineIdx,$charIdx: 不正なコマンドです")
}
writer.write("(")
mode.push(conditions)
}
block_start -> {
if (buf != null && NOT_BLANK.matches(buf!!.toString())) {
throw BuriLexicalException("$lineIdx,$charIdx: ブロック開始の前に不正な文字があります")
}
writer.write(" {\n")
buf = null;
}
else -> {
buf?.append(char.toChar())
}
}
}
}
// ブロック終了モード
val blockEnd = object : Mode(writer) {
var buf: StringBuffer? = null
var elif = false
override fun process(char: Int) {
if (buf == null) {
buf = StringBuffer()
}
when(char) {
at -> {
if (elif) {
// else if の後 { の前に @ が出現してはダメ
throw BuriLexicalException("$lineIdx,$charIdx: @ の出現位置が不正です")
}
if (0 != buf?.length()) {
// なんらかのコマンドがあるのに@が出現している
throw BuriLexicalException("$lineIdx,$charIdx: @ の出現位置が不正です")
}
writer.write("/* $lineIdx */}\n")
// @で終了
buf = null
elif = false
// ブロック終了から抜ける
mode.pop()
// マジックモードから抜ける
mode.pop()
}
bracket_start -> {
val commandName = buf.toString()
if (!ELSE_IF.matches(commandName)) {
elif = false
// else if以外は許さない
throw BuriLexicalException("$lineIdx,$charIdx: 条件パラメータの出現位置が不正です")
}
writer.write("/* $lineIdx */} else if (")
mode.push(conditions)
buf = null
elif = true
}
block_start -> {
try {
val commandName = buf.toString()
val isElse = ELSE.matches(commandName)
if (!elif && !isElse) {
// else か else if 以外は許さない
throw BuriLexicalException("$lineIdx,$charIdx: 不正なコマンドです")
}
if (isElse) {
writer.write("/* $lineIdx */} else ")
}
writer.write("{\n")
if(reader.read() != at) {
// 次は at 以外は許さない
throw BuriLexicalException("$lineIdx,$charIdx: 不正な文字があります")
}
// ブロック終了から抜ける
mode.pop()
// マジックモードから抜ける
mode.pop()
} finally {
buf = null
elif = false
}
}
else -> {
buf?.append(char.toChar())
}
}
}
}
// 行コメントモード
val lineComment = object : Mode(writer) {
override fun process(char: Int) {
when(char) {
cr , nl -> {
if (char == cr) {
// CRの次はNLが来るので読み飛ばす
reader.read()
}
// 行コメントから抜ける
mode.pop()
// マジックモードから抜ける
mode.pop()
writer.write("/* $lineIdx */writer.write(\"\"\"")
}
}
}
}
// ブロックコメントモード
val blockComment = object : Mode(writer) {
var commentEnd = false
override fun process(char: Int) {
when(char) {
blockCommentMark -> commentEnd = true
at -> {
if (commentEnd) {
// ブロックコメントから抜ける
mode.pop()
// マジックモードから抜ける
mode.pop()
}
}
else -> commentEnd = false
}
}
}
// マジックモード
val magic = object : Mode(writer) {
override fun process(char: Int) {
when(char) {
block_start -> {
// インサート
mode.push(insert)
writer.write("/* $lineIdx */writer.write(encode(\"\${")
}
at -> {
// エスケープ
writer.write("/* $lineIdx */writer.write(\"@\")\n")
mode.pop()
}
lineCommentMark -> {
// 行コメント
mode.push(lineComment)
}
blockCommentMark -> {
// ブロックコメント
mode.push(blockComment)
}
block_end -> {
// ブロック終了
mode.push(blockEnd)
}
else -> {
// ID
mode.push(command)
command.process(char)
}
}
}
}
// ノーマルモード
val normal = object : Mode(writer) {
var inMode = false
override fun process(char: Int) {
when(char) {
at -> {
writer.write("\"\"\")\n")
mode.push(magic)
inMode = true
}
else -> {
if (inMode) {
writer.write("/* $lineIdx */writer.write(\"\"\"")
inMode = false
}
writer.write(char)
}
}
}
}
mode.push(normal)
writer.write("/* $lineIdx */writer.write(\"\"\"")
while(reader.ready()) {
var char = reader.read()
if (char == -1) {
break;
}
charIdx++
if (char == cr) {
char = reader.read()
}
if (char == nl) {
lineIdx++
charIdx = 1
}
mode.peek().process(char)
}
writer.write("\"\"\")\n")
writer.write("\t}\n")
writer.write("}\n")
}
abstract class Mode(val writer: Writer) {
abstract fun process(char: Int);
}
}
| apache-2.0 | 8b6d0981b96b152665e0ffa833c1ed44 | 35.103723 | 141 | 0.378858 | 4.677808 | false | false | false | false |
Ekito/koin | koin-projects/koin-core-ext/src/main/kotlin/org/koin/experimental/property/InjectProperties.kt | 1 | 1084 | @file:Suppress("UNCHECKED_CAST")
package org.koin.experimental.property
import org.koin.core.Koin
import org.koin.core.context.GlobalContext
import org.koin.core.scope.Scope
import kotlin.reflect.KClass
import kotlin.reflect.KMutableProperty0
fun <T : Any> T.inject(vararg properties: KMutableProperty0<*>) {
properties.forEach {
val prop = it as KMutableProperty0<Any>
val type = prop.returnType.classifier as KClass<*>
val value = GlobalContext.get().get(type)
prop.set(value)
}
}
fun <T : Any> T.inject(koin: Koin, vararg properties: KMutableProperty0<*>) {
properties.forEach {
val prop = it as KMutableProperty0<Any>
val type = prop.returnType.classifier as KClass<*>
val value = koin.get(type)
prop.set(value)
}
}
fun <T : Any> T.inject(scope: Scope, vararg properties: KMutableProperty0<*>) {
properties.forEach {
val prop = it as KMutableProperty0<Any>
val type = prop.returnType.classifier as KClass<*>
val value = scope.get(type)
prop.set(value)
}
} | apache-2.0 | a2f7d5d9851b5e95a2f5ec2d26df63b7 | 29.138889 | 79 | 0.674354 | 3.871429 | false | false | false | false |
herbeth1u/VNDB-Android | app/src/main/java/com/booboot/vndbandroid/ui/search/SearchFragment.kt | 1 | 2966 | package com.booboot.vndbandroid.ui.search
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import androidx.core.view.isVisible
import androidx.lifecycle.ViewModelProvider
import com.booboot.vndbandroid.R
import com.booboot.vndbandroid.extensions.fastScroll
import com.booboot.vndbandroid.extensions.home
import com.booboot.vndbandroid.extensions.observeNonNull
import com.booboot.vndbandroid.extensions.observeOnce
import com.booboot.vndbandroid.extensions.onSubmitListener
import com.booboot.vndbandroid.extensions.setupStatusBar
import com.booboot.vndbandroid.extensions.setupToolbar
import com.booboot.vndbandroid.model.vndbandroid.VnlistData
import com.booboot.vndbandroid.ui.base.BaseFragment
import com.booboot.vndbandroid.ui.vnlist.VNAdapter
import com.booboot.vndbandroid.util.GridAutofitLayoutManager
import com.booboot.vndbandroid.util.Pixels
import kotlinx.android.synthetic.main.floating_search_toolbar.*
import kotlinx.android.synthetic.main.search_fragment.*
class SearchFragment : BaseFragment<SearchViewModel>() {
override val layout = R.layout.search_fragment
private val adapter by lazy { VNAdapter(::onVnClicked) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val activity = home() ?: return
setupStatusBar(true, searchBarCardView)
setupToolbar()
activity.supportActionBar?.setDisplayShowTitleEnabled(false)
viewModel = ViewModelProvider(this).get(SearchViewModel::class.java)
viewModel.loadingData.observeNonNull(this, ::showLoading)
viewModel.errorData.observeOnce(this, ::showError)
viewModel.searchData.observeNonNull(this, ::showSearch)
floatingSearchBar.setupWithContainer(constraintLayout, vnList)
adapter.onUpdate = ::onAdapterUpdate
vnList.setHasFixedSize(true)
vnList.layoutManager = GridAutofitLayoutManager(activity, Pixels.px(300))
vnList.adapter = adapter
vnList.fastScroll()
searchBar.onSubmitListener {
searchBar?.clearFocus()
viewModel.search(searchBar?.text?.toString() ?: "")
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.search_fragment, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_advanced_search -> {
} // TODO
}
return super.onOptionsItemSelected(item)
}
private fun showSearch(searchData: VnlistData) {
vnList.isVisible = true
adapter.data = searchData
}
override fun onAdapterUpdate(empty: Boolean) {
super.onAdapterUpdate(empty)
vnList.isVisible = !empty
}
} | gpl-3.0 | a73343c1bd9d7424b61f992af93251c5 | 35.62963 | 81 | 0.74174 | 4.619938 | false | false | false | false |
uber/RIBs | android/demos/compose/src/main/kotlin/com/uber/rib/compose/root/main/logged_in/off_game/OffGameScope.kt | 1 | 1733 | /*
* Copyright (C) 2021. Uber Technologies
*
* 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.uber.rib.compose.root.main.logged_in.off_game
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import com.uber.rib.compose.root.main.AuthInfo
import com.uber.rib.compose.util.EventStream
import com.uber.rib.compose.util.StateStream
import com.uber.rib.core.ComposePresenter
@motif.Scope
interface OffGameScope {
fun router(): OffGameRouter
@motif.Objects
abstract class Objects {
abstract fun router(): OffGameRouter
abstract fun interactor(): OffGameInteractor
fun presenter(
stateStream: StateStream<OffGameViewModel>,
eventStream: EventStream<OffGameEvent>
): ComposePresenter {
return object : ComposePresenter() {
override val composable = @Composable {
OffGameView(stateStream.observe().collectAsState(initial = stateStream.current()), eventStream)
}
}
}
fun eventStream() = EventStream<OffGameEvent>()
fun stateStream(authInfo: AuthInfo) = StateStream(
OffGameViewModel(
playerOne = authInfo.playerOne,
playerTwo = authInfo.playerTwo
)
)
}
}
| apache-2.0 | b1d85fd9c389b36b14a8439ade37be9b | 30.509091 | 105 | 0.72764 | 4.175904 | false | true | false | false |
backpaper0/syobotsum | core/src/syobotsum/actor/Block.kt | 1 | 3187 | package syobotsum.actor
import syobotsum.action.fallTo
import syobotsum.action.FallAction
import com.badlogic.gdx.scenes.scene2d.Action
import com.badlogic.gdx.scenes.scene2d.InputEvent
import com.badlogic.gdx.scenes.scene2d.Stage
import com.badlogic.gdx.scenes.scene2d.actions.Actions
import com.badlogic.gdx.scenes.scene2d.ui.Image
import com.badlogic.gdx.scenes.scene2d.utils.Drawable
class Block(drawable: Drawable, val blockType: BlockType, val blocks: BlockField) : Image(drawable) {
var stacked = false
var under: Block? = null
var value = 0
fun start(event: InputEvent) {
/*
* ブロックの初期位置(x1, y1)とフリックした位置(x2, y2)から
* てっぺん(x3, y3)を求める
* x2 - x1 : y2 - y1 = x3 - x1 : y3 - y1 となるので計算する。
*
* さらに落下地点(x4, y4)を求める。
* 落下する際のx軸方向の移動距離は上昇の際の1/3となるようにする。
* これは奥へ落ちる事を表現するために大きさを1/3にしているため。
*/
//初期位置
val x1 = x + (width / 2f)
val y1 = y
//フリック位置
val x2 = event.stageX
val y2 = event.stageY
//てっぺん
val y3 = stage.height //てっぺんなのでy3はstageの高さとなる
val x3 = x1 + ((x2 - x1) * (y3 - y1) / (y2 - y1))
//落下地点
val x4 = x3 + ((x3 - x1) / 3f)
val y4 = 0f //落下地点なので0になる
val scale = 0.33f
val duration = blockType.fallingSpeed
//奥へ行く事を表現(徐々に小さくする)
val toBack = Actions.scaleTo(scale, scale, duration)
//昇る
val up = Actions.moveTo(x3, y3, duration)
//落ちつつ、積まれたら止まる
val fall = fallTo(x4, y4, duration)
addAction(Actions.sequence(Actions.parallel(toBack, up), fall))
}
fun stack(under: Block?) {
stacked = true
if (under != null) {
this.under = under
this.value = under.value + 1
} else {
this.value = 1
}
}
fun isStackedOn(other: Block): Boolean {
if (other == this) {
return false
}
//対象が積まれていなかったら、つまりまだ落下中なら積み判定しない
if (other.stacked == false) {
return false
}
//自分の底が対象の天辺に触れているなら積まれたとみなす
val selfBottom = y
val selfLeft = x
val selfRight = selfLeft + (width * scaleX)
val otherTop = other.y + (other.height * other.scaleY)
val otherLeft = other.x
val otherRight = otherLeft + (other.width * other.scaleX)
return selfBottom <= otherTop && selfLeft < otherRight && selfRight > otherLeft
}
fun findUnder(): Block? = blocks.findUnder(this)
enum class BlockType(val rate: Int, val fallingSpeed: Float) {
HEART(5, 0.8f), REDKING(2, 0.5f), OTHER(1, 0.4f);
fun calc(value: Int): Int = value * this.rate
}
}
| apache-2.0 | e2acdc92169574355fe434994a8c16a8 | 28.150538 | 101 | 0.58318 | 2.887114 | false | false | false | false |
msebire/intellij-community | uast/uast-common/src/org/jetbrains/uast/UastUtils.kt | 1 | 9451 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmMultifileClass
@file:JvmName("UastUtils")
package org.jetbrains.uast
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.psi.*
import com.intellij.psi.util.PsiTreeUtil
import java.io.File
inline fun <reified T : UElement> UElement.getParentOfType(strict: Boolean = true): T? = getParentOfType(T::class.java, strict)
@JvmOverloads
fun <T : UElement> UElement.getParentOfType(parentClass: Class<out UElement>, strict: Boolean = true): T? {
var element = (if (strict) uastParent else this) ?: return null
while (true) {
if (parentClass.isInstance(element)) {
@Suppress("UNCHECKED_CAST")
return element as T
}
element = element.uastParent ?: return null
}
}
fun UElement.skipParentOfType(strict: Boolean, vararg parentClasses: Class<out UElement>): UElement? {
var element = (if (strict) uastParent else this) ?: return null
while (true) {
if (!parentClasses.any { it.isInstance(element) }) {
return element
}
element = element.uastParent ?: return null
}
}
fun <T : UElement> UElement.getParentOfType(
parentClass: Class<out UElement>,
strict: Boolean = true,
vararg terminators: Class<out UElement>
): T? {
var element = (if (strict) uastParent else this) ?: return null
while (true) {
if (parentClass.isInstance(element)) {
@Suppress("UNCHECKED_CAST")
return element as T
}
if (terminators.any { it.isInstance(element) }) {
return null
}
element = element.uastParent ?: return null
}
}
fun <T : UElement> UElement.getParentOfType(
strict: Boolean = true,
firstParentClass: Class<out T>,
vararg parentClasses: Class<out T>
): T? {
var element = (if (strict) uastParent else this) ?: return null
while (true) {
if (firstParentClass.isInstance(element)) {
@Suppress("UNCHECKED_CAST")
return element as T
}
if (parentClasses.any { it.isInstance(element) }) {
@Suppress("UNCHECKED_CAST")
return element as T
}
element = element.uastParent ?: return null
}
}
@JvmOverloads
fun UElement?.getUCallExpression(searchLimit: Int = Int.MAX_VALUE): UCallExpression? =
this?.withContainingElements?.take(searchLimit)?.mapNotNull {
when (it) {
is UCallExpression -> it
is UQualifiedReferenceExpression -> it.selector as? UCallExpression
else -> null
}
}?.firstOrNull()
@Deprecated(message = "This function is deprecated, use getContainingUFile", replaceWith = ReplaceWith("getContainingUFile()"))
fun UElement.getContainingFile(): UFile? = getContainingUFile()
fun UElement.getContainingUFile(): UFile? = getParentOfType(UFile::class.java)
fun UElement.getContainingUClass(): UClass? = getParentOfType(UClass::class.java)
fun UElement.getContainingUMethod(): UMethod? = getParentOfType(UMethod::class.java)
fun UElement.getContainingUVariable(): UVariable? = getParentOfType(UVariable::class.java)
@Deprecated(message = "Useless function, will be removed in IDEA 2019.1", replaceWith = ReplaceWith("getContainingMethod()?.javaPsi"))
fun UElement.getContainingMethod(): PsiMethod? = getContainingUMethod()?.psi
@Deprecated(message = "Useless function, will be removed in IDEA 2019.1", replaceWith = ReplaceWith("getContainingUClass()?.javaPsi"))
fun UElement.getContainingClass(): PsiClass? = getContainingUClass()?.psi
@Deprecated(message = "Useless function, will be removed in IDEA 2019.1", replaceWith = ReplaceWith("getContainingUVariable()?.javaPsi"))
fun UElement.getContainingVariable(): PsiVariable? = getContainingUVariable()?.psi
@Deprecated(message = "Useless function, will be removed in IDEA 2019.1",
replaceWith = ReplaceWith("PsiTreeUtil.getParentOfType(this, PsiClass::class.java)"))
fun PsiElement?.getContainingClass(): PsiClass? = this?.let { PsiTreeUtil.getParentOfType(it, PsiClass::class.java) }
fun <T : UElement> PsiElement?.findContaining(clazz: Class<T>): T? {
var element = this
while (element != null && element !is PsiFileSystemItem) {
element.toUElement(clazz)?.let { return it }
element = element.parent
}
return null
}
fun UElement.isUastChildOf(probablyParent: UElement?, strict: Boolean = false): Boolean {
tailrec fun isChildOf(current: UElement?, probablyParent: UElement): Boolean {
return when (current) {
null -> false
probablyParent -> true
else -> isChildOf(current.uastParent, probablyParent)
}
}
if (probablyParent == null) return false
return isChildOf(if (strict) uastParent else this, probablyParent)
}
@Deprecated("contains a bug in negation of `strict` parameter", replaceWith = ReplaceWith("isUastChildOf(probablyElement, strict)"))
fun UElement.isChildOf(probablyParent: UElement?, strict: Boolean = false) = isUastChildOf(probablyParent, !strict)
/**
* Resolves the receiver element if it implements [UResolvable].
*
* @return the resolved element, or null if the element was not resolved, or if the receiver element is not an [UResolvable].
*/
fun UElement.tryResolve(): PsiElement? = (this as? UResolvable)?.resolve()
fun UElement.tryResolveNamed(): PsiNamedElement? = (this as? UResolvable)?.resolve() as? PsiNamedElement
fun UElement.tryResolveUDeclaration(context: UastContext): UDeclaration? {
return (this as? UResolvable)?.resolve()?.let { context.convertElementWithParent(it, null) as? UDeclaration }
}
fun UReferenceExpression?.getQualifiedName(): String? = (this?.resolve() as? PsiClass)?.qualifiedName
/**
* Returns the String expression value, or null if the value can't be calculated or if the calculated value is not a String.
*/
fun UExpression.evaluateString(): String? = evaluate() as? String
/**
* Get a physical [File] for this file, or null if there is no such file on disk.
*/
fun UFile.getIoFile(): File? = psi.virtualFile?.let { VfsUtilCore.virtualToIoFile(it) }
tailrec fun UElement.getUastContext(): UastContext {
val psi = this.psi
if (psi != null) {
return ServiceManager.getService(psi.project, UastContext::class.java) ?: error("UastContext not found")
}
return (uastParent ?: error("PsiElement should exist at least for UFile")).getUastContext()
}
tailrec fun UElement.getLanguagePlugin(): UastLanguagePlugin {
val psi = this.psi
if (psi != null) {
val uastContext = ServiceManager.getService(psi.project, UastContext::class.java) ?: error("UastContext not found")
return uastContext.findPlugin(psi) ?: error("Language plugin was not found for $this (${this.javaClass.name})")
}
return (uastParent ?: error("PsiElement should exist at least for UFile")).getLanguagePlugin()
}
fun Collection<UElement?>.toPsiElements(): List<PsiElement> = mapNotNull { it?.psi }
/**
* A helper function for getting parents for given [PsiElement] that could be considered as identifier.
* Useful for working with gutter according to recommendations in [com.intellij.codeInsight.daemon.LineMarkerProvider].
*
* @see [getUParentForAnnotationIdentifier] for working with annotations
*/
fun getUParentForIdentifier(identifier: PsiElement): UElement? {
val uIdentifier = identifier.toUElementOfType<UIdentifier>() ?: return null
return uIdentifier.uastParent
}
/**
* @param arg expression in call arguments list of [this]
* @return parameter that corresponds to the [arg] in declaration to which [this] resolves
*/
fun UCallExpression.getParameterForArgument(arg: UExpression): PsiParameter? {
val psiMethod = resolve() ?: return null
val parameters = psiMethod.parameterList.parameters
if (this is UCallExpressionEx)
return parameters.withIndex().find { (i, p) ->
val argumentForParameter = getArgumentForParameter(i) ?: return@find false
if (argumentForParameter == arg) return@find true
if (arg is ULambdaExpression && arg.sourcePsi?.parent == argumentForParameter.sourcePsi) return@find true // workaround for KT-25297
if (p.isVarArgs && argumentForParameter is UExpressionList) return@find argumentForParameter.expressions.contains(arg)
return@find false
}?.value
// not everyone implements UCallExpressionEx, lets try to guess
val indexInArguments = valueArguments.indexOf(arg)
if (parameters.size == valueArguments.count()) {
return parameters.getOrNull(indexInArguments)
}
// probably it is a kotlin extension method
if (parameters.size - 1 == valueArguments.count()) {
val parameter = parameters.firstOrNull() ?: return null
val receiverType = receiverType ?: return null
if (!parameter.type.isAssignableFrom(receiverType)) return null
if (!parameters.drop(1).zip(valueArguments)
.all { (param, arg) -> arg.getExpressionType()?.let { param.type.isAssignableFrom(it) } == true }) return null
return parameters.getOrNull(indexInArguments + 1)
}
//named parameters are not processed
return null
}
| apache-2.0 | e4029f29fbdd84dbe3b46dfb336c69e0 | 39.217021 | 138 | 0.731986 | 4.363343 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/visiblequests/QuestTypeOrderTable.kt | 1 | 592 | package de.westnordost.streetcomplete.data.visiblequests
object QuestTypeOrderTable {
const val NAME = "quest_order"
object Columns {
const val QUEST_PRESET_ID = "quest_preset_id"
const val BEFORE = "before"
const val AFTER = "after"
}
const val CREATE = """
CREATE TABLE $NAME (
${Columns.QUEST_PRESET_ID} INTEGER NOT NULL,
${Columns.BEFORE} TEXT NOT NULL,
${Columns.AFTER} TEXT NOT NULL
);"""
const val INDEX_CREATE = "CREATE INDEX quest_order_idx ON $NAME (${Columns.QUEST_PRESET_ID});"
}
| gpl-3.0 | 2205e8ae60997faef7f5a00b3277e0e7 | 28.6 | 98 | 0.611486 | 4.13986 | false | false | false | false |
songzhw/Hello-kotlin | KotlinPlayground/src/main/kotlin/ca/six/rxjava/SubjectDemo.kt | 1 | 1398 | package ca.six.rxjava
import io.reactivex.subjects.BehaviorSubject
import io.reactivex.subjects.PublishSubject
import io.reactivex.functions.Consumer
import io.reactivex.subjects.ReplaySubject
fun be() {
val s = BehaviorSubject.create<Int>()
s.onNext(0)
s.onNext(1)
s.onNext(2)
s.subscribe({ v -> println("Late: " + v!!) })
s.onNext(3)
} //=> Late 2, Late 3
fun be2() {
val s = BehaviorSubject.create<Int>()
s.onNext(0)
s.onNext(1)
s.onComplete()
s.subscribe(
{ v -> println("Late: " + v!!) },
{ err -> System.err.println("error $err") },
{ println("completed") })
} //=> completed
fun be3() {
val s = BehaviorSubject.create<Int>()
s.subscribe({ v -> println("Late: " + v!!) })
s.onNext(0)
s.onNext(1)
s.onNext(2)
s.onNext(3)
} //=> 0, 1, 2, 3
fun pu() {
val subject = PublishSubject.create<Int>()
subject.onNext(1)
subject.subscribe(Consumer<Int> { println(it) })
subject.onNext(2)
subject.onNext(3)
subject.onNext(4)
} //=> 2, 3, 4
fun re() {
val s = ReplaySubject.create<Int>()
s.subscribe { v -> println("Early:" + v!!) }
s.onNext(0)
s.onNext(1)
s.subscribe { v -> println("Late: " + v!!) }
s.onNext(2)
}
/*
Early:0
Early:1
Late: 0
Late: 1
Early:2
Late: 2
*/
fun main(args: Array<String>) {
pu()
println("= = = = = = = b1")
be()
println("= = = = = = = b2")
be2()
println("= = = = = = = b3 ")
be3()
println("= = = = = = = re")
re()
}
| apache-2.0 | e117af0b01d08f51ffcc6e8e4ac98e1e | 18.150685 | 49 | 0.596567 | 2.518919 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.