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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
holisticon/ranked | backend/command/src/main/kotlin/RestController.kt | 1 | 3866 | @file:Suppress("UNUSED", "PackageDirectoryMismatch")
package de.holisticon.ranked.command.rest
import de.holisticon.ranked.command.api.CreateMatch
import de.holisticon.ranked.command.api.CreatePlayer
import de.holisticon.ranked.command.api.CreateTeam
import de.holisticon.ranked.extension.send
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import io.swagger.annotations.ApiResponse
import io.swagger.annotations.ApiResponses
import mu.KLogging
import org.axonframework.commandhandling.gateway.CommandGateway
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping("/command")
@Api(tags = ["Command"])
class CommandApi(val commandGateway: CommandGateway) {
companion object : KLogging()
@ApiOperation(value = "Creates a new match.")
@ApiResponses(
ApiResponse(code = 204, message = "If the create match request has been successfully received."),
ApiResponse(code = 400, message = "If the create match request was not correct.")
)
@PostMapping(path = ["/match"])
fun createMatch(@RequestBody match: CreateMatch): ResponseEntity<String> {
var response: ResponseEntity<String> = ResponseEntity.noContent().build()
commandGateway.send(
command = match,
success = { _, _: Any -> logger.debug { "Successfully submitted a match" } },
failure = { _, cause: Throwable ->
logger.error { "Failure by submitting a match: ${cause.localizedMessage}" }
response = ResponseEntity.badRequest().build()
}
)
return response
}
@ApiOperation(value = "Creates a new player.")
@ApiResponses(
ApiResponse(code = 204, message = "If the create player request has been successfully received."),
ApiResponse(code = 400, message = "If the create player request was not correct.")
)
@PostMapping(path = ["/player"])
fun createPlayer(@RequestBody playerInfo: PlayerInfo): ResponseEntity<String> {
var response: ResponseEntity<String> = ResponseEntity.noContent().build()
commandGateway.send(
command = CreatePlayer(
displayName = playerInfo.displayName,
imageUrl = playerInfo.imageUrl
),
success = { _, _: Any -> logger.debug { "Successfully created a user ${playerInfo.displayName}" } },
failure = { _, cause: Throwable ->
logger.error { "Failure by submitting a user: ${cause.localizedMessage}" }
response = ResponseEntity.badRequest().build()
})
return response
}
data class PlayerInfo(
val displayName: String,
val imageUrl: String
)
@ApiOperation(value = "Creates a new team.")
@ApiResponses(
ApiResponse(code = 204, message = "If the create team request has been successfully received."),
ApiResponse(code = 400, message = "If the create team request was not correct.")
)
@PostMapping(path = ["/team"])
fun createTeam(@RequestBody teamInfo: TeamInfo): ResponseEntity<String> {
var response: ResponseEntity<String> = ResponseEntity.noContent().build()
commandGateway.send(
command = CreateTeam(name = teamInfo.name, imageUrl = teamInfo.imageUrl, player1Name = teamInfo.player1Name, player2Name = teamInfo.player2Name),
success = { _, _: Any -> logger.debug { "Successfully created a team ${teamInfo.name}" } },
failure = { _, cause: Throwable ->
logger.error { "Failure by submitting a team: ${cause.localizedMessage}" }
response = ResponseEntity.badRequest().build()
})
return response
}
data class TeamInfo(
val name: String,
val imageUrl: String,
val player1Name: String?,
val player2Name: String?
)
}
| bsd-3-clause | 42c848d224d37d31e86747826791f600 | 36.173077 | 151 | 0.715468 | 4.433486 | false | false | false | false |
androidx/androidx | wear/watchface/watchface-complications-data/src/test/java/android/support/wearable/complications/ComplicationTextTest.kt | 3 | 32344 | /*
* 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 android.support.wearable.complications
import android.content.Context
import android.os.Parcel
import android.support.wearable.complications.ComplicationText.TimeDifferenceBuilder
import android.support.wearable.complications.ComplicationText.TimeFormatBuilder
import androidx.test.core.app.ApplicationProvider
import androidx.wear.watchface.complications.data.StringExpression
import androidx.wear.watchface.complications.data.SharedRobolectricTestRunner
import com.google.common.truth.Truth
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import java.util.GregorianCalendar
import java.util.TimeZone
import java.util.concurrent.TimeUnit
@RunWith(SharedRobolectricTestRunner::class)
public class ComplicationTextTest {
private val mResources = ApplicationProvider.getApplicationContext<Context>().resources
@Test
public fun testPlainText() {
// GIVEN ComplicationText of the plain string type
val complicationText =
ComplicationText.plainText("hello")
// WHEN getText is called
// THEN the plain string is returned.
Assert.assertEquals(
"hello",
complicationText.getTextAt(mResources, 132456789).toString()
)
}
@Test
public fun testTimeDifferenceShortSingleUnitOnly() {
// GIVEN ComplicationText with short single unit time difference text only
val refTime: Long = 10000000
val complicationText =
TimeDifferenceBuilder()
.setReferencePeriodStartMillis(refTime - 156561)
.setReferencePeriodEndMillis(refTime)
.setStyle(ComplicationText.DIFFERENCE_STYLE_SHORT_SINGLE_UNIT)
.build()
// WHEN getText is called for a time after the ref period
// THEN the time difference text is returned and "2h 35m" should be rounded to "3h".
var testTime = refTime +
TimeUnit.MINUTES.toMillis(35) +
TimeUnit.HOURS.toMillis(2)
Assert.assertEquals(
"3h",
complicationText.getTextAt(mResources, testTime).toString()
)
// WHEN getText is called for a time after the ref period
// THEN the time difference text is returned and "23h 59m 10s" should be rounded to "1d".
testTime = refTime +
TimeUnit.SECONDS.toMillis(10) +
TimeUnit.MINUTES.toMillis(59) +
TimeUnit.HOURS.toMillis(23)
Assert.assertEquals(
"1d",
complicationText.getTextAt(mResources, testTime).toString()
)
// THEN the time difference text is returned, and "10m 10s" should be rounded to "11m".
testTime = refTime +
TimeUnit.SECONDS.toMillis(10) +
TimeUnit.MINUTES.toMillis(10)
Assert.assertEquals(
"11m",
complicationText.getTextAt(mResources, testTime).toString()
)
// WHEN getText is called for a time after the ref period
// THEN the time difference text is returned and "23h 15m" should be rounded to "1d".
testTime = refTime +
TimeUnit.MINUTES.toMillis(15) +
TimeUnit.HOURS.toMillis(23)
Assert.assertEquals(
"1d",
complicationText.getTextAt(mResources, testTime).toString()
)
// WHEN getText is called for a time after the ref period
// THEN the time difference text is returned and "23h 0m" should be round to "23h".
testTime = refTime + TimeUnit.HOURS.toMillis(23)
Assert.assertEquals(
"23h",
complicationText.getTextAt(mResources, testTime).toString()
)
// WHEN getText is called for a time after the ref period
// THEN the time difference text is returned and "23h 10m" should be round to "1d".
testTime = refTime +
TimeUnit.MINUTES.toMillis(10) +
TimeUnit.HOURS.toMillis(23)
Assert.assertEquals(
"1d",
complicationText.getTextAt(mResources, testTime).toString()
)
// WHEN getText is called for a time after the ref period
// THEN the time difference text is returned and "22h 10m" should be round to "23h".
testTime = refTime +
TimeUnit.MINUTES.toMillis(10) +
TimeUnit.HOURS.toMillis(22)
Assert.assertEquals(
"23h",
complicationText.getTextAt(mResources, testTime).toString()
)
// WHEN getText is called for a time after the ref period
// THEN the time difference text is returned and "1d 10h" should be round to "2d".
testTime = refTime +
TimeUnit.HOURS.toMillis(10) +
TimeUnit.DAYS.toMillis(1)
Assert.assertEquals(
"2d",
complicationText.getTextAt(mResources, testTime).toString()
)
// WHEN getText is called for a time after the ref period
// THEN the time difference text is returned and "22h 10m" should be round to "23h".
testTime = refTime +
TimeUnit.MINUTES.toMillis(10) +
TimeUnit.HOURS.toMillis(22)
Assert.assertEquals(
"23h",
complicationText.getTextAt(mResources, testTime).toString()
)
// WHEN getText is called for a time after the ref period
// THEN the time difference text is returned and "59m 30s" should be round to "1h".
testTime = refTime +
TimeUnit.SECONDS.toMillis(30) +
TimeUnit.MINUTES.toMillis(59)
Assert.assertEquals(
"1h",
complicationText.getTextAt(mResources, testTime).toString()
)
// WHEN getText is called for a time after the ref period
// THEN the time difference text is returned and "59m 00s" should be displayed as "59m".
testTime = refTime + TimeUnit.MINUTES.toMillis(59)
Assert.assertEquals(
"59m",
complicationText.getTextAt(mResources, testTime).toString()
)
}
@Test
public fun testTimeDifferenceShortDualUnitOnly() {
// GIVEN ComplicationText with short dual unit time difference text only
val refTime: Long = 10000000
val complicationText =
TimeDifferenceBuilder()
.setReferencePeriodStartMillis(refTime - 156561)
.setReferencePeriodEndMillis(refTime)
.setStyle(ComplicationText.DIFFERENCE_STYLE_SHORT_DUAL_UNIT)
.build()
// WHEN getText is called for a time after the ref period
// THEN the time difference text is returned and "2h 35m 10s" should be rounded to "2h 36m".
var testTime = refTime +
TimeUnit.SECONDS.toMillis(10) +
TimeUnit.MINUTES.toMillis(35) +
TimeUnit.HOURS.toMillis(
2
)
Assert.assertEquals(
"2h 36m",
complicationText.getTextAt(mResources, testTime).toString()
)
// WHEN getText is called for a time after the ref period
// THEN the time difference text is returned and "2h 35m" should be rounded to "2h 35m".
testTime = refTime +
TimeUnit.MINUTES.toMillis(35) +
TimeUnit.HOURS.toMillis(2)
Assert.assertEquals(
"2h 35m",
complicationText.getTextAt(mResources, testTime).toString()
)
// THEN the time difference text is returned
// and "9d 23h 58m 10s" should be rounded to "10d".
testTime = refTime +
TimeUnit.SECONDS.toMillis(10) +
TimeUnit.MINUTES.toMillis(58) +
TimeUnit.HOURS.toMillis(23) +
TimeUnit.DAYS.toMillis(9)
Assert.assertEquals(
"10d",
complicationText.getTextAt(mResources, testTime).toString()
)
// WHEN getText is called for a time after the ref period
// THEN the time difference text is returned and "23h 59m 10s" should be rounded to "1d".
testTime = refTime +
TimeUnit.SECONDS.toMillis(10) +
TimeUnit.MINUTES.toMillis(59) +
TimeUnit.HOURS.toMillis(
23
)
Assert.assertEquals(
"1d",
complicationText.getTextAt(mResources, testTime).toString()
)
// THEN the time difference text is returned
// and "23h 58m 10s" should be rounded to "23h 59m".
testTime = refTime +
TimeUnit.SECONDS.toMillis(10) +
TimeUnit.MINUTES.toMillis(58) +
TimeUnit.HOURS.toMillis(
23
)
Assert.assertEquals(
"23h 59m",
complicationText.getTextAt(mResources, testTime).toString()
)
}
@Test
public fun testStopwatchTextUnitOnly() {
// GIVEN ComplicationText with stop watch time difference text only
val refTime: Long = 10000000
val complicationText =
TimeDifferenceBuilder()
.setReferencePeriodStartMillis(refTime - 156561)
.setReferencePeriodEndMillis(refTime)
.setStyle(ComplicationText.DIFFERENCE_STYLE_STOPWATCH)
.build()
// WHEN getText is called for a time after the ref period
// THEN the time difference text is returned and "23h 59m 10s" should be rounded to "1d".
var testTime = refTime +
TimeUnit.SECONDS.toMillis(10) +
TimeUnit.MINUTES.toMillis(59) +
TimeUnit.HOURS.toMillis(
23
)
Assert.assertEquals(
"1d",
complicationText.getTextAt(mResources, testTime).toString()
)
// WHEN getText is called for a time after the ref period
// THEN the time difference text is returned in stopwatch style with no rounding.
testTime = refTime +
TimeUnit.MINUTES.toMillis(59) +
TimeUnit.HOURS.toMillis(23)
Assert.assertEquals(
"23:59",
complicationText.getTextAt(mResources, testTime).toString()
)
// WHEN getText is called for another time after the ref period
// THEN the time difference text is returned in stopwatch style with no rounding.
testTime = refTime +
TimeUnit.SECONDS.toMillis(59) +
TimeUnit.MINUTES.toMillis(1)
Assert.assertEquals(
"01:59",
complicationText.getTextAt(mResources, testTime).toString()
)
}
@Test
public fun testWordsSingleUnitWithSurroundingString() {
// GIVEN ComplicationText with stop watch time difference text only
val refTime: Long = 10000000
val complicationText =
TimeDifferenceBuilder()
.setReferencePeriodStartMillis(refTime - 156561)
.setReferencePeriodEndMillis(refTime)
.setStyle(ComplicationText.DIFFERENCE_STYLE_WORDS_SINGLE_UNIT)
.setSurroundingText("just ^1 left")
.build()
// WHEN getText is called for a time after the ref period
// THEN the time difference text is returned and "23h 59m 10s" should be rounded to one day.
var testTime = refTime +
TimeUnit.HOURS.toMillis(23) +
TimeUnit.MINUTES.toMillis(59) +
TimeUnit.SECONDS.toMillis(
10
)
Assert.assertEquals(
"just 1 day left",
complicationText.getTextAt(mResources, testTime).toString()
)
// WHEN getText is called for a time after the ref period
// THEN the time difference text is returned in words, showing the bigger unit only, and
// rounding up.
testTime = refTime +
TimeUnit.HOURS.toMillis(12) +
TimeUnit.MINUTES.toMillis(35)
Assert.assertEquals(
"just 13 hours left",
complicationText.getTextAt(mResources, testTime).toString()
)
// WHEN getText is called for another time after the ref period
// THEN the time difference text is returned in words, showing the bigger unit only, and
// rounding up.
testTime = refTime +
TimeUnit.MINUTES.toMillis(35) +
TimeUnit.SECONDS.toMillis(59)
Assert.assertEquals(
"just 36 mins left",
complicationText.getTextAt(mResources, testTime).toString()
)
}
@Test
public fun testSurroundingTextWithIgnoredPlaceholders() {
// WHEN ComplicationText with surrounding text that contains one of ^2..9 is created
val refTime: Long = 10000000
val complicationText =
TimeDifferenceBuilder()
.setReferencePeriodStartMillis(refTime - 156561)
.setReferencePeriodEndMillis(refTime)
.setStyle(ComplicationText.DIFFERENCE_STYLE_WORDS_SINGLE_UNIT)
.setSurroundingText("^1 ^^ ^ ^^1 ^2 ^3 ^4 ^5 ^6 ^7 ^8 ^9")
.build()
// THEN placeholders other than ^1 and ^^ are ignored
Assert.assertEquals(
"Now ^ ^ ^1 ^2 ^3 ^4 ^5 ^6 ^7 ^8 ^9",
complicationText.getTextAt(mResources, refTime).toString()
)
}
@Test
public fun testWordsSingleUnitWithSurroundingStringAndDayMinimumUnit() {
// GIVEN ComplicationText with stop watch time difference text only
val refTime: Long = 10000000
val complicationText =
TimeDifferenceBuilder()
.setReferencePeriodStartMillis(refTime - 156561)
.setReferencePeriodEndMillis(refTime)
.setStyle(ComplicationText.DIFFERENCE_STYLE_WORDS_SINGLE_UNIT)
.setSurroundingText("just ^1 left")
.setMinimumUnit(TimeUnit.DAYS)
.build()
// WHEN getText is called for a time after the ref period
// THEN the time difference text is returned with the time rounded up to the next day.
var testTime = refTime +
TimeUnit.DAYS.toMillis(7) +
TimeUnit.HOURS.toMillis(23) +
TimeUnit.MINUTES.toMillis(59)
Assert.assertEquals(
"just 8 days left",
complicationText.getTextAt(mResources, testTime).toString()
)
// WHEN getText is called for a time after the ref period
// THEN the time difference text is returned in words with the time rounded up to the next
// day.
testTime = refTime +
TimeUnit.HOURS.toMillis(12) +
TimeUnit.MINUTES.toMillis(35)
Assert.assertEquals(
"just 1 day left",
complicationText.getTextAt(mResources, testTime).toString()
)
// WHEN getText is called for another time after the ref period
// THEN the time difference text is returned in words with the time rounded up to the next
// day.
testTime = refTime +
TimeUnit.MINUTES.toMillis(35) +
TimeUnit.SECONDS.toMillis(59)
Assert.assertEquals(
"just 1 day left",
complicationText.getTextAt(mResources, testTime).toString()
)
}
@Test
public fun testShortWordsSingleUnit() {
// GIVEN ComplicationText with stop watch time difference text only
val refTime: Long = 10000000
val complicationText =
TimeDifferenceBuilder()
.setReferencePeriodStartMillis(refTime - 156561)
.setReferencePeriodEndMillis(refTime)
.setStyle(ComplicationText.DIFFERENCE_STYLE_SHORT_WORDS_SINGLE_UNIT)
.build()
// WHEN getText is called for a time after the ref period
// THEN the time difference text is returned and "23h 59m 10s" should be rounded to one day.
var testTime = refTime +
TimeUnit.HOURS.toMillis(23) +
TimeUnit.MINUTES.toMillis(59) +
TimeUnit.SECONDS.toMillis(10)
Assert.assertEquals(
"1 day",
complicationText.getTextAt(mResources, testTime).toString()
)
// WHEN getText is called for a time after the ref period
// THEN the time difference text is returned in words, showing the bigger unit only, and
// rounding up.
testTime = refTime +
TimeUnit.HOURS.toMillis(1) +
TimeUnit.MINUTES.toMillis(35)
Assert.assertEquals(
"2 hours",
complicationText.getTextAt(mResources, testTime).toString()
)
// WHEN getText is called for a double-digit number of hours after the ref period
// THEN the time difference text is returned using the short style.
testTime = refTime +
TimeUnit.HOURS.toMillis(12) +
TimeUnit.MINUTES.toMillis(35)
Assert.assertEquals(
"13h",
complicationText.getTextAt(mResources, testTime).toString()
)
// WHEN getText is called for another time many days the ref period, such that more than 7
// characters would be used if the unit was shown as a word
// THEN the time difference text is returned using the short style.
testTime = refTime + TimeUnit.DAYS.toMillis(120)
Assert.assertEquals(
"120d",
complicationText.getTextAt(mResources, testTime).toString()
)
}
@Test
public fun testStopwatchWithNowText() {
// GIVEN ComplicationText with stop watch time difference text only
val refTime: Long = 10000000
val complicationText =
TimeDifferenceBuilder()
.setReferencePeriodStartMillis(refTime - 156561)
.setReferencePeriodEndMillis(refTime)
.setStyle(ComplicationText.DIFFERENCE_STYLE_STOPWATCH)
.setShowNowText(true)
.build()
// WHEN getText is called for a time within the ref period
// THEN the time difference text is returned and "Now" is shown.
Assert.assertEquals(
"Now",
complicationText.getTextAt(mResources, refTime - 100).toString()
)
// WHEN getText is called for a time after the ref period
// THEN the time difference text is returned and the time difference is shown in stopwatch
// style.
val testTime = refTime + TimeUnit.SECONDS.toMillis(35)
Assert.assertEquals(
"00:35",
complicationText.getTextAt(mResources, testTime).toString()
)
}
@Test
public fun testSingleUnitWithoutNowText() {
// GIVEN ComplicationText with stop watch time difference text only
val refTime: Long = 10000000
val complicationText =
TimeDifferenceBuilder()
.setReferencePeriodStartMillis(refTime - 156561)
.setReferencePeriodEndMillis(refTime + 100)
.setStyle(ComplicationText.DIFFERENCE_STYLE_SHORT_SINGLE_UNIT)
.setShowNowText(false)
.build()
// WHEN getText is called for a time within the ref period
// THEN the time difference text is returned and "0m" is shown.
Assert.assertEquals(
"0m",
complicationText.getTextAt(mResources, refTime).toString()
)
}
@Test
public fun testTimeDifferenceShortSingleUnitAndFormatString() {
// GIVEN ComplicationText with short single unit time difference text and a format string
val refTime: Long = 10000000
val complicationText =
TimeDifferenceBuilder()
.setReferencePeriodStartMillis(refTime - 156561)
.setReferencePeriodEndMillis(refTime)
.setStyle(ComplicationText.DIFFERENCE_STYLE_SHORT_SINGLE_UNIT)
.setSurroundingText("hello ^1 time")
.build()
// WHEN getText is called for a time after the ref period
// THEN the time difference text is returned within the format string
val testTime = refTime +
TimeUnit.MINUTES.toMillis(35) +
TimeUnit.HOURS.toMillis(2)
Assert.assertEquals(
"hello 3h time",
complicationText.getTextAt(mResources, testTime).toString()
)
}
@Test
public fun testTimeDifferenceShortDualUnitAndFormatString() {
// GIVEN ComplicationText with short dual unit time difference text and a format string
val refTime: Long = 10000000
val complicationText =
TimeDifferenceBuilder()
.setReferencePeriodStartMillis(refTime - 156561)
.setReferencePeriodEndMillis(refTime)
.setStyle(ComplicationText.DIFFERENCE_STYLE_SHORT_DUAL_UNIT)
.setSurroundingText("sometext^1somemoretext")
.build()
// WHEN getText is called for a time after the ref period
// THEN the time difference text is returned within the format string
val testTime = refTime +
TimeUnit.MINUTES.toMillis(35) +
TimeUnit.HOURS.toMillis(2)
Assert.assertEquals(
"sometext2h 35msomemoretext",
complicationText.getTextAt(mResources, testTime).toString()
)
}
@Test
public fun testTimeFormatUpperCase() {
val complicationText =
TimeFormatBuilder()
.setFormat("EEE 'the' d LLL")
.setStyle(ComplicationText.FORMAT_STYLE_UPPER_CASE)
.build()
val result = complicationText.getTextAt(
mResources, GregorianCalendar(2016, 2, 4).timeInMillis
)
Assert.assertEquals("FRI THE 4 MAR", result.toString())
}
@Test
public fun testTimeFormatLowerCase() {
val complicationText =
TimeFormatBuilder()
.setFormat("EEE 'the' d LLL")
.setStyle(ComplicationText.FORMAT_STYLE_LOWER_CASE)
.build()
val result = complicationText.getTextAt(
mResources, GregorianCalendar(2016, 2, 4).timeInMillis
)
Assert.assertEquals("fri the 4 mar", result.toString())
}
@Test
public fun testTimeFormatNoStyle() {
val complicationText =
TimeFormatBuilder().setFormat("EEE 'the' d LLL").build()
val result = complicationText.getTextAt(
mResources, GregorianCalendar(2016, 2, 4).timeInMillis
)
Assert.assertEquals("Fri the 4 Mar", result.toString())
}
@Test
public fun testTimeFormatUpperCaseSurroundingString() {
val complicationText =
TimeFormatBuilder()
.setFormat("EEE 'the' d LLL")
.setStyle(ComplicationText.FORMAT_STYLE_UPPER_CASE)
.setSurroundingText("sometext^1somemoretext")
.build()
val result = complicationText.getTextAt(
mResources, GregorianCalendar(2016, 2, 4).timeInMillis
)
Assert.assertEquals("sometextFRI THE 4 MARsomemoretext", result.toString())
}
@Test
public fun testTimeFormatWithTimeZone() {
val complicationText =
TimeFormatBuilder()
.setFormat("HH:mm")
.setTimeZone(TimeZone.getTimeZone("Asia/Seoul"))
.build()
val calendar =
GregorianCalendar(TimeZone.getTimeZone("GMT+0"))
calendar[2016, 2, 4, 18, 52] = 58
val result =
complicationText.getTextAt(mResources, calendar.timeInMillis)
Assert.assertEquals("03:52", result.toString())
}
@Test
public fun testParcelPlainText() {
// GIVEN ComplicationText containing plain text
val originalText =
ComplicationText.plainText("hello how are you")
// WHEN the object is parcelled and unparcelled
val newText = originalText.roundTripParcelable()!!
// THEN the object behaves as expected.
Assert.assertEquals(
"hello how are you",
newText.getTextAt(mResources, 100000).toString()
)
}
@Test
public fun testParcelTimeDifferenceTextWithoutMinUnit() {
// GIVEN ComplicationText containing TimeDifferenceText
val refTime: Long = 10000000
val originalText =
TimeDifferenceBuilder()
.setReferencePeriodStartMillis(refTime - 156561)
.setReferencePeriodEndMillis(refTime)
.setStyle(ComplicationText.DIFFERENCE_STYLE_SHORT_SINGLE_UNIT)
.setSurroundingText("hello ^1 time")
.setShowNowText(false)
.build()
// WHEN the object is parcelled and unparcelled
val newText = originalText.roundTripParcelable()!!
// THEN the object behaves as expected.
val testTime = refTime +
TimeUnit.HOURS.toMillis(2) +
TimeUnit.MINUTES.toMillis(35)
Assert.assertEquals(
"hello 3h time",
newText.getTextAt(mResources, testTime).toString()
)
Assert.assertEquals(
"hello 0m time",
newText.getTextAt(mResources, refTime).toString()
)
}
@Test
public fun testParcelTimeDifferenceTextWithMinUnit() {
// GIVEN ComplicationText containing TimeDifferenceText with a minimum unit specified
val refTime: Long = 10000000
val originalText =
TimeDifferenceBuilder()
.setReferencePeriodStartMillis(refTime - 156561)
.setReferencePeriodEndMillis(refTime)
.setStyle(ComplicationText.DIFFERENCE_STYLE_SHORT_DUAL_UNIT)
.setMinimumUnit(TimeUnit.HOURS)
.build()
// WHEN the object is parcelled and unparcelled
val newText = originalText.roundTripParcelable()!!
// THEN the object behaves as expected.
val testTime = refTime +
TimeUnit.HOURS.toMillis(2) +
TimeUnit.MINUTES.toMillis(35)
Assert.assertEquals("3h", newText.getTextAt(mResources, testTime).toString())
}
@Test
public fun testParcelTimeDifferenceTextWithUnrecognizedMinUnit() {
// GIVEN a parcelled ComplicationText object containing TimeDifferenceText with an unknown
// minimum unit specified
val refTime: Long = 10000000
val originalText =
TimeDifferenceBuilder()
.setReferencePeriodStartMillis(refTime - 156561)
.setReferencePeriodEndMillis(refTime)
.setStyle(ComplicationText.DIFFERENCE_STYLE_SHORT_DUAL_UNIT)
.build()
val parcel = Parcel.obtain()
originalText.writeToParcel(parcel, 0)
parcel.setDataPosition(0)
val bundle = parcel.readBundle(javaClass.classLoader)
bundle!!.putString("minimum_unit", "XYZ")
val parcelWithBadMinUnit = Parcel.obtain()
parcelWithBadMinUnit.writeBundle(bundle)
parcelWithBadMinUnit.setDataPosition(0)
// WHEN the object is unparcelled
val newText =
ComplicationText.CREATOR.createFromParcel(
parcelWithBadMinUnit
)
// THEN the object is unparcelled successfully, and behaves as if no min unit was specified.
val testTime = refTime +
TimeUnit.HOURS.toMillis(2) +
TimeUnit.MINUTES.toMillis(35)
Assert.assertEquals("2h 35m", newText.getTextAt(mResources, testTime).toString())
}
@Test
public fun testParcelTimeFormatTextWithoutTimeZone() {
// GIVEN ComplicationText containing TimeFormatText with no time zone
val originalText =
TimeFormatBuilder()
.setFormat("EEE 'the' d LLL")
.setStyle(ComplicationText.FORMAT_STYLE_LOWER_CASE)
.build()
// WHEN the object is parcelled and unparcelled
val newText = originalText.roundTripParcelable()!!
// THEN the object behaves as expected.
val result =
newText.getTextAt(mResources, GregorianCalendar(2016, 2, 4).timeInMillis)
Assert.assertEquals("fri the 4 mar", result.toString())
}
@Test
public fun testParcelTimeFormatTextWithTimeZone() {
// GIVEN ComplicationText containing TimeFormatText with a time zone specified
val originalText =
TimeFormatBuilder()
.setFormat("EEE 'the' d LLL HH:mm")
.setStyle(ComplicationText.FORMAT_STYLE_LOWER_CASE)
.setTimeZone(TimeZone.getTimeZone("GMT+5"))
.build()
// WHEN the object is parcelled and unparcelled
val newText = originalText.roundTripParcelable()!!
// THEN the object behaves as expected.
val calendar =
GregorianCalendar(TimeZone.getTimeZone("GMT+0"))
calendar[2016, 2, 4, 18, 52] = 58
val result = newText.getTextAt(mResources, calendar.timeInMillis)
Assert.assertEquals("fri the 4 mar 23:52", result.toString())
}
@Test
public fun zeroWorksWhenNoRefPeriodStartTime() {
// GIVEN ComplicationText with time difference text with no ref period start time
val refTime: Long = 10000000
val complicationText =
TimeDifferenceBuilder()
.setReferencePeriodStartMillis(0)
.setReferencePeriodEndMillis(refTime + 100)
.setStyle(ComplicationText.DIFFERENCE_STYLE_SHORT_SINGLE_UNIT)
.build()
// WHEN getText is called for a zero time
// THEN the time difference text is returned and "Now" is shown, with no NPE
Assert.assertEquals("Now", complicationText.getTextAt(mResources, 0).toString())
}
@Test
public fun nextChangeTimeNotTimeDependent() {
val text =
ComplicationText.plainText("hello")
Truth.assertThat(text.getNextChangeTime(1000000))
.isEqualTo(Long.MAX_VALUE)
}
@Test
public fun nextChangeTimeTimeDifference() {
val text = TimeDifferenceBuilder()
.setReferencePeriodStartMillis(0)
.setReferencePeriodEndMillis(0)
.setStyle(ComplicationText.DIFFERENCE_STYLE_SHORT_SINGLE_UNIT)
.build()
// Time difference rounds up, so the next change is 1ms after the next minute boundary.
Truth.assertThat(text.getNextChangeTime(600000123))
.isEqualTo(600060001)
}
@Test
public fun nextChangeTimeTimeFormat() {
val text = TimeFormatBuilder()
.setFormat("EEE 'the' d LLL HH:mm")
.setStyle(ComplicationText.FORMAT_STYLE_LOWER_CASE)
.build()
// Time format rounds down, so the next change is at the next minute boundary.
Truth.assertThat(text.getNextChangeTime(600000123))
.isEqualTo(600060000)
}
@Test
public fun stringExpressionToParcelRoundTrip() {
val text = ComplicationText(StringExpression(byteArrayOf(1, 2, 3)))
Truth.assertThat(text.toParcelRoundTrip()).isEqualTo(text)
}
@Test
public fun getTextAt_ignoresStringExpressionIfSurroundingStringPresent() {
val text = ComplicationText(
"hello" as CharSequence,
/* timeDependentText = */ null,
StringExpression(byteArrayOf(1, 2, 3))
)
Truth.assertThat(text.getTextAt(mResources, 132456789).toString())
.isEqualTo("hello")
}
}
fun ComplicationText.toParcelRoundTrip(): ComplicationText {
val parcel = Parcel.obtain()
writeToParcel(parcel, /* flags = */ 0)
parcel.setDataPosition(0)
return ComplicationText.CREATOR.createFromParcel(parcel)
}
| apache-2.0 | 18a3e8e361bf6587e156c9350d93ea73 | 38.015682 | 100 | 0.620888 | 4.845543 | false | true | false | false |
androidx/androidx | wear/watchface/watchface/src/main/java/androidx/wear/watchface/IndentingPrintWriter.kt | 3 | 3354 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.watchface
import android.util.Printer
import java.io.PrintWriter
import java.io.Writer
/**
* Lightweight wrapper around [java.io.PrintWriter] that automatically indents newlines based
* on internal state.
*
* Delays writing indent until first actual write on a newline, enabling indent modification after
* newline.
*/
internal class IndentingPrintWriter(
writer: Writer,
private val singleIndent: String = "\t"
) : Printer {
internal val writer: PrintWriter = PrintWriter(writer)
/** Mutable version of current indent */
private val indentBuilder = StringBuilder()
/** Cache of current [indentBuilder] value */
private var currentIndent: CharArray? = null
/**
* Flag indicating if we're currently sitting on an empty line, and that next write should be
* prefixed with the current indent.
*/
private var emptyLine = true
/** Increases the indentation level for future lines. */
fun increaseIndent() {
indentBuilder.append(singleIndent)
currentIndent = null
}
/** Decreases the indentation level for future lines. */
fun decreaseIndent() {
indentBuilder.delete(0, singleIndent.length)
currentIndent = null
}
/** Prints `string`, followed by a newline. */
// Printer
override fun println(string: String) {
print(string)
print("\n")
}
/** Prints `string`, or `"null"` */
fun print(string: String?) {
val str = string ?: "null"
write(str, 0, str.length)
}
/** Ensures that all pending data is sent out to the target */
fun flush() {
writer.flush()
}
private fun write(string: String, offset: Int, count: Int) {
val bufferEnd = offset + count
var lineStart = offset
var lineEnd = offset
// March through incoming buffer looking for newlines
while (lineEnd < bufferEnd) {
val ch = string[lineEnd++]
if (ch == '\n') {
maybeWriteIndent()
writer.write(string, lineStart, lineEnd - lineStart)
lineStart = lineEnd
emptyLine = true
}
}
if (lineStart != lineEnd) {
maybeWriteIndent()
writer.write(string, lineStart, lineEnd - lineStart)
}
}
private fun maybeWriteIndent() {
if (emptyLine) {
emptyLine = false
if (indentBuilder.isNotEmpty()) {
if (currentIndent == null) {
currentIndent = indentBuilder.toString().toCharArray()
}
writer.write(currentIndent, 0, currentIndent!!.size)
}
}
}
}
| apache-2.0 | 315a1588a6240d59de8c854cd4845a02 | 29.490909 | 98 | 0.62254 | 4.600823 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinCallerUsages.kt | 4 | 2921 | // 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.refactoring.changeSignature.usages
import com.intellij.usageView.UsageInfo
import org.jetbrains.kotlin.idea.codeInsight.shorten.addToShorteningWaitSet
import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinChangeInfo
import org.jetbrains.kotlin.idea.refactoring.changeSignature.getAffectedCallables
import org.jetbrains.kotlin.idea.refactoring.changeSignature.isInsideOfCallerBody
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
class KotlinCallerUsage(element: KtNamedDeclaration) : KotlinUsageInfo<KtNamedDeclaration>(element) {
override fun processUsage(changeInfo: KotlinChangeInfo, element: KtNamedDeclaration, allUsages: Array<out UsageInfo>): Boolean {
// Do not process function twice
if (changeInfo.getAffectedCallables().any { it is KotlinCallableDefinitionUsage<*> && it.element == element }) return true
val parameterList = when (element) {
is KtFunction -> element.valueParameterList
is KtClass -> element.createPrimaryConstructorParameterListIfAbsent()
else -> null
} ?: return true
changeInfo.getNonReceiverParameters()
.asSequence()
.withIndex()
.filter { it.value.isNewParameter }
.toList()
.forEach {
val newParameter = it.value.getDeclarationSignature(it.index, changeInfo.methodDescriptor.originalPrimaryCallable)
parameterList.addParameter(newParameter).addToShorteningWaitSet()
}
return true
}
}
class KotlinCallerCallUsage(element: KtCallElement) : KotlinUsageInfo<KtCallElement>(element) {
override fun processUsage(changeInfo: KotlinChangeInfo, element: KtCallElement, allUsages: Array<out UsageInfo>): Boolean {
val argumentList = element.valueArgumentList ?: return true
val psiFactory = KtPsiFactory(project)
val isNamedCall = argumentList.arguments.any { it.isNamed() }
changeInfo.getNonReceiverParameters()
.filter { it.isNewParameter }
.forEach {
val parameterName = it.name
val argumentExpression = if (element.isInsideOfCallerBody(allUsages)) {
psiFactory.createExpression(parameterName)
} else {
it.defaultValueForCall ?: psiFactory.createExpression("_")
}
val argument = psiFactory.createArgument(
expression = argumentExpression,
name = if (isNamedCall) Name.identifier(parameterName) else null
)
argumentList.addArgument(argument).addToShorteningWaitSet()
}
return true
}
}
| apache-2.0 | d7137b42f305be7b0d12fb8e7825619b | 46.112903 | 158 | 0.686751 | 5.727451 | false | false | false | false |
GunoH/intellij-community | plugins/gradle/java/src/service/project/wizard/GradleNewProjectWizardStep.kt | 1 | 6127 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.gradle.service.project.wizard
import com.intellij.ide.JavaUiBundle
import com.intellij.ide.projectWizard.NewProjectWizardCollector.BuildSystem.logDslChanged
import com.intellij.ide.projectWizard.NewProjectWizardCollector.BuildSystem.logSdkChanged
import com.intellij.ide.projectWizard.NewProjectWizardCollector.BuildSystem.logSdkFinished
import com.intellij.ide.wizard.NewProjectWizardBaseData
import com.intellij.ide.wizard.NewProjectWizardStep
import com.intellij.openapi.externalSystem.model.project.ProjectData
import com.intellij.openapi.externalSystem.service.project.ProjectDataManager
import com.intellij.openapi.externalSystem.service.project.wizard.MavenizedNewProjectWizardStep
import com.intellij.openapi.externalSystem.util.ExternalSystemBundle
import com.intellij.openapi.externalSystem.util.ui.DataView
import com.intellij.openapi.module.StdModuleTypes
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.JavaSdkType
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.SdkTypeId
import com.intellij.openapi.projectRoots.impl.DependentSdkType
import com.intellij.openapi.roots.ui.configuration.sdkComboBox
import com.intellij.openapi.ui.MessageDialogBuilder
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.ui.dsl.builder.*
import com.intellij.ui.layout.*
import com.intellij.util.lang.JavaVersion
import icons.GradleIcons
import org.gradle.util.GradleVersion
import org.jetbrains.plugins.gradle.util.*
import javax.swing.Icon
abstract class GradleNewProjectWizardStep<ParentStep>(parent: ParentStep) :
MavenizedNewProjectWizardStep<ProjectData, ParentStep>(parent), GradleNewProjectWizardData
where ParentStep : NewProjectWizardStep,
ParentStep : NewProjectWizardBaseData {
final override val sdkProperty = propertyGraph.property<Sdk?>(null)
final override val useKotlinDslProperty = propertyGraph.property(false)
final override var sdk by sdkProperty
final override var useKotlinDsl by useKotlinDslProperty
override fun createView(data: ProjectData) = GradleDataView(data)
override fun setupUI(builder: Panel) {
with(builder) {
row(JavaUiBundle.message("label.project.wizard.new.project.jdk")) {
val sdkTypeFilter = { it: SdkTypeId -> it is JavaSdkType && it !is DependentSdkType }
sdkComboBox(context, sdkProperty, StdModuleTypes.JAVA.id, sdkTypeFilter)
.validationOnApply { validateGradleVersion() }
.columns(COLUMNS_MEDIUM)
.whenItemSelectedFromUi { logSdkChanged(sdk) }
}.bottomGap(BottomGap.SMALL)
row(GradleBundle.message("gradle.dsl.new.project.wizard")) {
val renderer: (Boolean) -> String = {
when (it) {
true -> GradleBundle.message("gradle.dsl.new.project.wizard.kotlin")
else -> GradleBundle.message("gradle.dsl.new.project.wizard.groovy")
}
}
segmentedButton(listOf(false, true), renderer)
.bind(useKotlinDslProperty)
.whenItemSelectedFromUi { logDslChanged(it) }
}.bottomGap(BottomGap.SMALL)
}
super.setupUI(builder)
}
override fun setupProject(project: Project) {
logSdkFinished(sdk)
}
override fun findAllParents(): List<ProjectData> {
val project = context.project ?: return emptyList()
return ProjectDataManager.getInstance()
.getExternalProjectsData(project, GradleConstants.SYSTEM_ID)
.mapNotNull { it.externalProjectStructure }
.map { it.data }
}
override fun ValidationInfoBuilder.validateArtifactId(): ValidationInfo? {
if (artifactId != parentStep.name) {
return error(ExternalSystemBundle.message("external.system.mavenized.structure.wizard.name.and.artifact.id.is.different.error",
if (context.isCreatingNewProject) 1 else 0))
}
return null
}
private fun ValidationInfoBuilder.validateGradleVersion(): ValidationInfo? {
val javaVersion = getJavaVersion() ?: return null
if (getGradleVersion() == null) {
val preferredGradleVersion = getPreferredGradleVersion()
val errorTitle = GradleBundle.message("gradle.settings.wizard.unsupported.jdk.title", if (context.isCreatingNewProject) 0 else 1)
val errorMessage = GradleBundle.message(
"gradle.settings.wizard.unsupported.jdk.message",
javaVersion.toFeatureString(),
suggestOldestCompatibleJavaVersion(preferredGradleVersion),
suggestJavaVersion(preferredGradleVersion),
preferredGradleVersion.version)
val dialog = MessageDialogBuilder.yesNo(errorTitle, errorMessage).asWarning()
if (!dialog.ask(component)) {
return error(errorTitle)
}
}
return null
}
private fun getJavaVersion(): JavaVersion? {
val jdk = sdk ?: return null
val versionString = jdk.versionString ?: return null
return JavaVersion.tryParse(versionString)
}
private fun getPreferredGradleVersion(): GradleVersion {
val project = context.project ?: return GradleVersion.current()
return findGradleVersion(project) ?: GradleVersion.current()
}
private fun getGradleVersion(): GradleVersion? {
val preferredGradleVersion = getPreferredGradleVersion()
val javaVersion = getJavaVersion() ?: return preferredGradleVersion
return when (isSupported(preferredGradleVersion, javaVersion)) {
true -> preferredGradleVersion
else -> suggestGradleVersion(javaVersion)
}
}
protected fun suggestGradleVersion(): GradleVersion {
return getGradleVersion() ?: getPreferredGradleVersion()
}
class GradleDataView(override val data: ProjectData) : DataView<ProjectData>() {
override val location: String = data.linkedExternalProjectPath
override val icon: Icon = GradleIcons.GradleFile
override val presentationName: String = data.externalName
override val groupId: String = data.group ?: ""
override val version: String = data.version ?: ""
}
} | apache-2.0 | aea3c31595f252cd9e719870e834011f | 43.086331 | 158 | 0.761547 | 4.933172 | false | false | false | false |
smmribeiro/intellij-community | plugins/git4idea/tests/git4idea/merge/GitMergeProviderTestCase.kt | 11 | 7469 | /*
* 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 git4idea.merge
import com.intellij.openapi.vcs.Executor.*
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.history.VcsRevisionNumber
import com.intellij.openapi.vcs.merge.MergeData
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.LineSeparator
import com.intellij.vcsUtil.VcsFileUtil
import git4idea.branch.GitRebaseParams
import git4idea.repo.GitRepository
import git4idea.test.*
import git4idea.util.GitFileUtils
import java.io.File
import java.io.FileNotFoundException
abstract class GitMergeProviderTestCase : GitPlatformTest() {
protected val FILE = "file.txt"
protected val FILE_RENAME = "file_rename.txt"
protected val FILE_CONTENT = "\nThis\nis\nsome\ncontent\nto\nmake\ngit\ntreat\nthis\nfile\nas\nrename\nrather\nthan\ninsertion\nand\ndeletion\n"
protected lateinit var repository: GitRepository
override fun runInDispatchThread(): Boolean = true
public override fun setUp() {
super.setUp()
repository = createRepository(projectPath)
cd(projectRoot)
git("commit --allow-empty -m initial")
touch(FILE, "original" + FILE_CONTENT)
git("add .")
git("commit -m Base")
}
protected fun `assert all revisions and paths loaded`(branchCurrent: String, branchLast: String) {
`assert all revisions loaded`(branchCurrent, branchLast)
`assert revision GOOD, path GOOD`(Side.ORIGINAL)
`assert revision GOOD, path GOOD`(Side.LAST)
`assert revision GOOD, path GOOD`(Side.CURRENT)
}
protected fun `assert all revisions loaded`(branchCurrent: String, branchLast: String) {
`assert merge conflict`()
`assert merge provider consistent`()
`assert revision`(Side.ORIGINAL, "master")
`assert revision`(Side.LAST, "branch-$branchLast")
`assert revision`(Side.CURRENT, "branch-$branchCurrent")
}
protected fun `invoke merge`(branchCurrent: String, branchLast: String) {
git("checkout branch-$branchCurrent")
git("merge branch-$branchLast", true)
repository.update()
}
protected fun `invoke rebase`(branchCurrent: String, branchLast: String) {
git("checkout branch-$branchCurrent")
git("rebase branch-$branchLast", true)
repository.update()
}
protected fun `invoke rebase interactive`(branchCurrent: String, branchLast: String) {
git("checkout branch-$branchCurrent")
doRebaseInteractive(branchLast)
repository.update()
}
//
// Impl
//
private fun doRebaseInteractive(onto: String) {
git.setInteractiveRebaseEditor (TestGitImpl.InteractiveRebaseEditor({
it.lines().mapIndexed { i, s ->
if (i != 0) s
else s.replace("pick", "reword")
}.joinToString(LineSeparator.getSystemLineSeparator().separatorString)
}, null))
val rebaseParams = GitRebaseParams(vcs.version, null, null, "branch-$onto", true, false)
git.rebase(repository, rebaseParams)
}
protected fun `init branch - change`(branch: String) {
doInitBranch(branch, {
overwrite(FILE, "modified: $branch" + FILE_CONTENT)
})
}
protected fun `init branch - rename`(branch: String, newFileName: String = FILE_RENAME) {
doInitBranch(branch, {
mv(FILE, newFileName)
})
}
protected fun `init branch - change and rename`(branch: String, newFileName: String = FILE_RENAME) {
doInitBranch(branch, {
overwrite(FILE, "modified: $branch" + FILE_CONTENT)
mv(FILE, newFileName)
})
}
protected fun `init branch - delete`(branch: String) {
doInitBranch(branch, {
rm(FILE)
})
}
private fun doInitBranch(branch: String, vararg changesToCommit: () -> Unit) {
cd(repository)
git("checkout master")
git("checkout -b branch-$branch")
changesToCommit.forEachIndexed { index, changes ->
changes()
git("add -A .")
git("commit -m $branch-$index")
}
git("checkout master")
}
protected fun `assert merge conflict`() {
val files = git("ls-files --unmerged -z")
assertTrue(files.isNotEmpty())
}
protected fun `assert merge provider consistent`() {
val provider = repository.vcs.mergeProvider
val files = getConflictedFiles()
files.forEach {
val mergeData = provider.loadRevisions(it.toVF())
Side.values().forEach {
val revision = mergeData.revision(it)
val path = mergeData.filePath(it)
val content = mergeData.content(it)
if (revision != null && path != null) {
val relativePath = VcsFileUtil.relativePath(projectRoot, path)
val hash = revision.asString()
val actualContent = GitFileUtils.getFileContent(project, projectRoot, hash, relativePath)
assertOrderedEquals(content, actualContent)
}
}
}
}
protected fun `assert revision`(side: Side, revision: String) {
val actualHash = getMergeData().revision(side)!!.asString()
val expectedHash = git("show-ref -s $revision")
assertEquals(expectedHash, actualHash)
}
protected fun `assert revision GOOD, path GOOD`(side: Side) {
val mergeData = getMergeData()
assertNotNull(mergeData.revision(side))
assertNotNull(mergeData.filePath(side))
}
protected fun `assert revision GOOD, path BAD `(side: Side) {
val mergeData = getMergeData()
assertNotNull(mergeData.revision(side))
assertNull(mergeData.filePath(side))
}
private fun getConflictedFiles(): List<File> {
val records = git("ls-files --unmerged -z").split('\u0000').filter { !it.isBlank() }
val files = records.map { it.split('\t').last() }.toSortedSet()
return files.map { File(projectPath, it) }.toList()
}
private fun getConflictFile(): File {
val files = getConflictedFiles()
if (files.size != 1) fail("More than one conflict: $files")
return files.first()
}
private fun getMergeData(): MergeData {
return getMergeData(getConflictFile())
}
private fun getMergeData(file: File): MergeData {
return repository.vcs.mergeProvider.loadRevisions(file.toVF())
}
private fun File.toVF(): VirtualFile {
return LocalFileSystem.getInstance().refreshAndFindFileByIoFile(this) ?: throw FileNotFoundException(this.path)
}
private fun MergeData.content(side: Side): ByteArray = when (side) {
Side.ORIGINAL -> this.ORIGINAL
Side.LAST -> this.LAST
Side.CURRENT -> this.CURRENT
}
private fun MergeData.revision(side: Side): VcsRevisionNumber? = when (side) {
Side.ORIGINAL -> this.ORIGINAL_REVISION_NUMBER
Side.LAST -> this.LAST_REVISION_NUMBER
Side.CURRENT -> this.CURRENT_REVISION_NUMBER
}
private fun MergeData.filePath(side: Side): FilePath? = when (side) {
Side.ORIGINAL -> this.ORIGINAL_FILE_PATH
Side.LAST -> this.LAST_FILE_PATH
Side.CURRENT -> this.CURRENT_FILE_PATH
}
protected enum class Side {
ORIGINAL, LAST, CURRENT;
}
}
| apache-2.0 | 19d8f97481546a6db9eb2d1a661cd62c | 30.782979 | 146 | 0.698755 | 4.217391 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/structuralsearch/property/varRefAssign.kt | 4 | 153 | val a = "Hello World"
<warning descr="SSR">var b = a</warning>
<warning descr="SSR">var c = (a)</warning>
<warning descr="SSR">var d = ((a))</warning> | apache-2.0 | 6e7c9bed12c5fe8f99793b1118736ff7 | 21 | 44 | 0.620915 | 2.833333 | false | false | false | false |
Cognifide/gradle-aem-plugin | src/main/kotlin/com/cognifide/gradle/aem/common/instance/service/groovy/GroovyConsole.kt | 1 | 5075 | package com.cognifide.gradle.aem.common.instance.service.groovy
import com.cognifide.gradle.aem.common.instance.InstanceService
import com.cognifide.gradle.aem.common.instance.InstanceSync
import com.cognifide.gradle.common.CommonException
import com.cognifide.gradle.common.utils.Formats
import java.io.File
/**
* Allows to execute Groovy code / scripts on AEM instance having Groovy Console CRX package installed.
*
* @see <https://github.com/icfnext/aem-groovy-console>
*/
class GroovyConsole(sync: InstanceSync) : InstanceService(sync) {
/**
* Controls throwing exception on script execution error.
*/
val verbose = aem.obj.boolean {
convention(aem.commonOptions.verbose)
aem.prop.boolean("instance.groovyConsole.verbose")?.let { set(it) }
}
/**
* Directory to search for scripts to be evaluated.
*/
val scriptDir = aem.obj.dir {
convention(aem.instanceManager.configDir.dir("groovyScript"))
aem.prop.file("instance.groovyConsole.scriptDir")?.let { set(it) }
}
/**
* Check if console is installed on instance.
*/
val available: Boolean get() = sync.osgiFramework.findBundle(SYMBOLIC_NAME)?.stable ?: false
/**
* Ensure by throwing exception that console is available on instance.
*/
fun requireAvailable() {
if (!available) {
throw GroovyConsoleException("Groovy console is not available on $instance!\n" +
"Ensure having correct URLs defined & credentials, granted access and networking in correct state (internet accessible, VPN on/off)")
}
}
/**
* Evaluate Groovy code snippet on AEM instance.
*/
fun evalCode(code: String, data: Map<String, Any?> = mapOf()): GroovyEvalResult {
val result = try {
aem.logger.info("Evaluating Groovy Code: $code")
evalCodeInternal(code, data)
} catch (e: CommonException) {
throw GroovyConsoleException("Cannot evaluate Groovy code properly on $instance, code:\n$code, cause: ${e.message}", e)
}
if (verbose.get() && result.exceptionStackTrace.isNotBlank()) {
aem.logger.debug(result.toString())
throw GroovyConsoleException("Evaluation of Groovy code on $instance ended with exception:\n${result.exceptionStackTrace}")
}
return result
}
private fun evalCodeInternal(code: String, data: Map<String, Any?>): GroovyEvalResult {
return sync.http.postMultipart(EVAL_PATH, mapOf(
"script" to code,
"data" to Formats.toJson(data)
)) { asObjectFromJson(it, GroovyEvalResult::class.java) }
}
/**
* Evaluate any Groovy script on AEM instance.
*/
fun evalScript(file: File, data: Map<String, Any?> = mapOf()): GroovyEvalResult {
val result = try {
aem.logger.info("Evaluating Groovy script '$file' on $instance")
evalCodeInternal(file.bufferedReader().use { it.readText() }, data)
} catch (e: CommonException) {
throw GroovyConsoleException("Cannot evaluate Groovy script '$file' properly on $instance. Cause: ${e.message}", e)
}
if (verbose.get() && result.exceptionStackTrace.isNotBlank()) {
aem.logger.debug(result.toString())
throw GroovyConsoleException("Evaluation of Groovy script '$file' on $instance ended with exception:\n${result.exceptionStackTrace}")
}
return result
}
/**
* Evaluate Groovy script found by its file name on AEM instance.
*/
fun evalScript(fileName: String, data: Map<String, Any?> = mapOf()): GroovyEvalResult {
val script = scriptDir.get().asFile.resolve(fileName)
if (!script.exists()) {
throw GroovyConsoleException("Groovy script '$fileName' not found in directory: $scriptDir")
}
return evalScript(script, data)
}
/**
* Find scripts matching file pattern in pre-configured directory.
*/
fun findScripts(pathPattern: String): List<File> = project.fileTree(scriptDir)
.matching { it.include(pathPattern) }
.sortedBy { it.absolutePath }
.toList()
/**
* Evaluate all Groovy scripts found by file name pattern on AEM instance in path-based alphabetical order.
*/
fun evalScripts(
pathPattern: String = "**/*.groovy",
data: Map<String, Any> = mapOf(),
resultConsumer: GroovyEvalResult.() -> Unit = {}
) {
evalScripts(findScripts(pathPattern), data, resultConsumer)
}
/**
* Evaluate any Groovy scripts on AEM instance in specified order.
*/
fun evalScripts(
scripts: Iterable<File>,
data: Map<String, Any?> = mapOf(),
resultConsumer: GroovyEvalResult.() -> Unit = {}
) {
scripts.forEach { resultConsumer(evalScript(it, data)) }
}
companion object {
const val EVAL_PATH = "/bin/groovyconsole/post.json"
const val SYMBOLIC_NAME = "aem-groovy-console"
}
}
| apache-2.0 | 0709f216afdd74d3279855d53e1f46a0 | 35.510791 | 153 | 0.639409 | 4.397747 | false | false | false | false |
mminke/pv-datalogger | pvdatavisualizer/src/main/kotlin/nl/kataru/pvdata/core/InverterResource.kt | 1 | 3978 | package nl.kataru.pvdata.core
import nl.kataru.pvdata.security.AccountPrincipal
import java.net.URI
import javax.inject.Inject
import javax.ws.rs.*
import javax.ws.rs.core.Context
import javax.ws.rs.core.MediaType
import javax.ws.rs.core.Response
import javax.ws.rs.core.SecurityContext
/**
*
*/
@Path("/inverters")
open class InverterResource {
@Inject
lateinit private var inverterService: InverterService
@Context
lateinit private var securityContext: SecurityContext
@GET
@Produces(MediaType.APPLICATION_JSON)
fun getInverters(): Set<Inverter> {
val accountPrincipal = securityContext.userPrincipal as AccountPrincipal
return inverterService.findAllUsingAccount(accountPrincipal.account)
}
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
fun getInverter(@PathParam("id") id: String): Response {
val accountPrincipal = securityContext.userPrincipal as AccountPrincipal
val inverter = inverterService.findByIdUsingAccount(id, accountPrincipal.account)
if (inverter.isPresent) {
return Response.ok(inverter.get()).build()
} else {
return Response.status(Response.Status.NOT_FOUND).build()
}
}
@DELETE
@Path("{id}")
fun deleteInverter(@PathParam("id") id: String): Response {
val accountPrincipal = securityContext.userPrincipal as AccountPrincipal
if (inverterService.deleteWithIdUsingAccount(id, accountPrincipal.account)) {
return Response.ok().build()
} else {
return Response.status(Response.Status.NOT_FOUND).build()
}
}
@PUT
@Path("{serialNumber}")
@Consumes(MediaType.APPLICATION_JSON)
fun updateInverter(@PathParam("serialNumber") serialNumber: String, inverter: Inverter): String {
val accountPrincipal = securityContext.userPrincipal as AccountPrincipal
return "updated inverter with serial#: ${inverter.serialNumber}"
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
fun addInverter(inverter: Inverter): Response {
val accountPrincipal = securityContext.userPrincipal as AccountPrincipal
try {
val createdInverter = inverterService.createUsingAccount(inverter, accountPrincipal.account)
return Response.created(URI.create("/inverters/${createdInverter.id}")).build()
} catch (exception: IllegalArgumentException) {
// An inverter with the given serialnumber already exists.
val error = nl.kataru.pvdata.core.Error(exception.message ?: "Unknown reason.")
return Response.status(Response.Status.CONFLICT).entity(error).build()
}
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}/measurements")
fun addMeasurement(@PathParam("id") id: String, inverterMeasurement: InverterMeasurement): Response {
val accountPrincipal = securityContext.userPrincipal as AccountPrincipal
try {
val createdMeasurement = inverterService.createMeasurementUsingAccount(inverterMeasurement, accountPrincipal.account)
return Response.created(URI.create("/inverters/${id}/measurements/${createdMeasurement.id}")).build()
} catch (exception: IllegalArgumentException) {
val error = nl.kataru.pvdata.core.Error(exception.message ?: "Unknown reason.")
return Response.status(Response.Status.CONFLICT).entity(error).build()
} catch(exception: SecurityException) {
return Response.status(Response.Status.FORBIDDEN).build()
}
}
}
//@ApplicationPath("api/v2/")
//class MyApplication : Application() {
// override fun getClasses(): MutableSet<Class<*>>? {
// val classes = HashSet<Class<*>>()
// classes.add(nl.kataru.pvdata.core.InverterResource::class.java)
// return classes
// }
//}
| agpl-3.0 | 3e890775d6a4f73f36c0b5c1518ce94f | 34.517857 | 129 | 0.690548 | 4.415094 | false | false | false | false |
simonnorberg/dmach | app/src/main/java/net/simno/dmach/patch/PatchStateReducer.kt | 1 | 1194 | package net.simno.dmach.patch
import net.simno.dmach.util.logError
object PatchStateReducer : (ViewState, Result) -> ViewState {
override fun invoke(previousState: ViewState, result: Result) = when (result) {
is ErrorResult -> {
logError("PatchStateReducer", "ErrorResult", result.error)
previousState
}
is LoadResult -> previousState.copy(
title = result.title
)
DismissResult -> previousState.copy(
showDelete = false,
showOverwrite = false
)
ConfirmOverwriteResult -> previousState.copy(
finish = true,
showOverwrite = false
)
ConfirmDeleteResult -> previousState.copy(
showDelete = false
)
is SavePatchResult -> previousState.copy(
finish = !result.showOverwrite,
showOverwrite = result.showOverwrite,
title = result.title
)
is DeletePatchResult -> previousState.copy(
showDelete = true,
deleteTitle = result.deleteTitle
)
SelectPatchResult -> previousState.copy(
finish = true
)
}
}
| gpl-3.0 | 4293d5494941daa0c34a5ec78b5e89e5 | 30.421053 | 83 | 0.579564 | 5.259912 | false | false | false | false |
vnesek/nmote-jwt-issuer | src/main/kotlin/com/nmote/jwti/web/TwitterLoginController.kt | 1 | 3199 | /*
* Copyright 2017. Vjekoslav Nesek
* 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.nmote.jwti.web
import com.fasterxml.jackson.databind.ObjectMapper
import com.github.scribejava.core.model.OAuth1AccessToken
import com.github.scribejava.core.model.OAuth1RequestToken
import com.github.scribejava.core.model.OAuthRequest
import com.github.scribejava.core.model.Verb
import com.github.scribejava.core.oauth.OAuth10aService
import com.nmote.jwti.repository.AppRepository
import com.nmote.jwti.model.SocialAccount
import com.nmote.jwti.model.TwitterAccount
import com.nmote.jwti.repository.UserRepository
import com.nmote.jwti.service.ScopeService
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.CookieValue
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import javax.servlet.http.HttpServletResponse
@ConditionalOnBean(name = arrayOf("twitterOAuthService"))
@Controller
@RequestMapping("/twitter")
class TwitterLoginController(
@Qualifier("twitterOAuthService") service: OAuth10aService,
objectMapper: ObjectMapper,
users: UserRepository,
apps: AppRepository,
tokens: TokenCache,
scopes: ScopeService
) : OAuthLoginController<OAuth10aService, OAuth1AccessToken>(service, objectMapper, users, apps, tokens, scopes) {
@RequestMapping("callback")
fun callback(
@RequestParam oauth_token: String,
@RequestParam oauth_verifier: String,
@CookieValue("authState") authState: String,
response: HttpServletResponse
): String {
val requestToken = OAuth1RequestToken(oauth_token, oauth_verifier)
val accessToken = service.getAccessToken(requestToken, oauth_verifier)
return callback(accessToken, authState, response)
}
override val authorizationUrl: String
get() {
val requestToken = service.requestToken
return service.getAuthorizationUrl(requestToken)
}
override fun getSocialAccount(accessToken: OAuth1AccessToken): SocialAccount<OAuth1AccessToken> {
val request = OAuthRequest(Verb.GET, "https://api.twitter.com/1.1/account/verify_credentials.json") //,service);
service.signRequest(accessToken, request)
val response = service.execute(request)
val body = response.body
val account = objectMapper.readValue(body, TwitterAccount::class.java)
account.accessToken = accessToken
return account
}
}
| apache-2.0 | b9e7fe7a5251dc9fa5ebc58abf015839 | 40.545455 | 120 | 0.761175 | 4.388203 | false | false | false | false |
fkorotkov/k8s-kotlin-dsl | DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/kubernetes/discovery/v1/ClassBuilders.kt | 1 | 1764 | // GENERATE
package com.fkorotkov.kubernetes.discovery.v1
import io.fabric8.kubernetes.api.model.discovery.v1.Endpoint as v1_Endpoint
import io.fabric8.kubernetes.api.model.discovery.v1.EndpointConditions as v1_EndpointConditions
import io.fabric8.kubernetes.api.model.discovery.v1.EndpointHints as v1_EndpointHints
import io.fabric8.kubernetes.api.model.discovery.v1.EndpointPort as v1_EndpointPort
import io.fabric8.kubernetes.api.model.discovery.v1.EndpointSlice as v1_EndpointSlice
import io.fabric8.kubernetes.api.model.discovery.v1.EndpointSliceList as v1_EndpointSliceList
import io.fabric8.kubernetes.api.model.discovery.v1.ForZone as v1_ForZone
fun newEndpoint(block : v1_Endpoint.() -> Unit = {}): v1_Endpoint {
val instance = v1_Endpoint()
instance.block()
return instance
}
fun newEndpointConditions(block : v1_EndpointConditions.() -> Unit = {}): v1_EndpointConditions {
val instance = v1_EndpointConditions()
instance.block()
return instance
}
fun newEndpointHints(block : v1_EndpointHints.() -> Unit = {}): v1_EndpointHints {
val instance = v1_EndpointHints()
instance.block()
return instance
}
fun newEndpointPort(block : v1_EndpointPort.() -> Unit = {}): v1_EndpointPort {
val instance = v1_EndpointPort()
instance.block()
return instance
}
fun newEndpointSlice(block : v1_EndpointSlice.() -> Unit = {}): v1_EndpointSlice {
val instance = v1_EndpointSlice()
instance.block()
return instance
}
fun newEndpointSliceList(block : v1_EndpointSliceList.() -> Unit = {}): v1_EndpointSliceList {
val instance = v1_EndpointSliceList()
instance.block()
return instance
}
fun newForZone(block : v1_ForZone.() -> Unit = {}): v1_ForZone {
val instance = v1_ForZone()
instance.block()
return instance
}
| mit | d5679df32e72fd1af2e74bc26d20f264 | 28.4 | 97 | 0.751134 | 3.438596 | false | false | false | false |
aosp-mirror/platform_frameworks_support | room/compiler/src/main/kotlin/androidx/room/writer/FieldReadWriteWriter.kt | 1 | 15755 | /*
* Copyright (C) 2017 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.writer
import androidx.room.ext.L
import androidx.room.ext.T
import androidx.room.ext.defaultValue
import androidx.room.ext.typeName
import androidx.room.solver.CodeGenScope
import androidx.room.vo.CallType
import androidx.room.vo.Constructor
import androidx.room.vo.EmbeddedField
import androidx.room.vo.Field
import androidx.room.vo.FieldWithIndex
import androidx.room.vo.Pojo
import androidx.room.vo.RelationCollector
import com.squareup.javapoet.TypeName
/**
* Handles writing a field into statement or reading it form statement.
*/
class FieldReadWriteWriter(fieldWithIndex: FieldWithIndex) {
val field = fieldWithIndex.field
val indexVar = fieldWithIndex.indexVar
val alwaysExists = fieldWithIndex.alwaysExists
companion object {
/*
* Get all parents including the ones which have grand children in this list but does not
* have any direct children in the list.
*/
fun getAllParents(fields: List<Field>): Set<EmbeddedField> {
val allParents = mutableSetOf<EmbeddedField>()
fun addAllParents(field: Field) {
var parent = field.parent
while (parent != null) {
if (allParents.add(parent)) {
parent = parent.parent
} else {
break
}
}
}
fields.forEach(::addAllParents)
return allParents
}
/**
* Convert the fields with indices into a Node tree so that we can recursively process
* them. This work is done here instead of parsing because the result may include arbitrary
* fields.
*/
private fun createNodeTree(
rootVar: String,
fieldsWithIndices: List<FieldWithIndex>,
scope: CodeGenScope): Node {
val allParents = getAllParents(fieldsWithIndices.map { it.field })
val rootNode = Node(rootVar, null)
rootNode.directFields = fieldsWithIndices.filter { it.field.parent == null }
val parentNodes = allParents.associate {
Pair(it, Node(
varName = scope.getTmpVar("_tmp${it.field.name.capitalize()}"),
fieldParent = it))
}
parentNodes.values.forEach { node ->
val fieldParent = node.fieldParent!!
val grandParent = fieldParent.parent
val grandParentNode = grandParent?.let {
parentNodes[it]
} ?: rootNode
node.directFields = fieldsWithIndices.filter { it.field.parent == fieldParent }
node.parentNode = grandParentNode
grandParentNode.subNodes.add(node)
}
return rootNode
}
fun bindToStatement(
ownerVar: String,
stmtParamVar: String,
fieldsWithIndices: List<FieldWithIndex>,
scope: CodeGenScope
) {
fun visitNode(node: Node) {
fun bindWithDescendants() {
node.directFields.forEach {
FieldReadWriteWriter(it).bindToStatement(
ownerVar = node.varName,
stmtParamVar = stmtParamVar,
scope = scope
)
}
node.subNodes.forEach(::visitNode)
}
val fieldParent = node.fieldParent
if (fieldParent != null) {
fieldParent.getter.writeGet(
ownerVar = node.parentNode!!.varName,
outVar = node.varName,
builder = scope.builder()
)
scope.builder().apply {
beginControlFlow("if($L != null)", node.varName).apply {
bindWithDescendants()
}
nextControlFlow("else").apply {
node.allFields().forEach {
addStatement("$L.bindNull($L)", stmtParamVar, it.indexVar)
}
}
endControlFlow()
}
} else {
bindWithDescendants()
}
}
visitNode(createNodeTree(ownerVar, fieldsWithIndices, scope))
}
/**
* Just constructs the given item, does NOT DECLARE. Declaration happens outside the
* reading statement since we may never read if the cursor does not have necessary
* columns.
*/
private fun construct(
outVar: String,
constructor: Constructor?,
typeName: TypeName,
localVariableNames: Map<String, FieldWithIndex>,
localEmbeddeds: List<Node>, scope: CodeGenScope
) {
if (constructor == null) {
// best hope code generation
scope.builder().apply {
addStatement("$L = new $T()", outVar, typeName)
}
return
}
val variableNames = constructor.params.map { param ->
when (param) {
is Constructor.FieldParam -> localVariableNames.entries.firstOrNull {
it.value.field === param.field
}?.key
is Constructor.EmbeddedParam -> localEmbeddeds.firstOrNull {
it.fieldParent === param.embedded
}?.varName
else -> null
}
}
val args = variableNames.joinToString(",") { it ?: "null" }
scope.builder().apply {
addStatement("$L = new $T($L)", outVar, typeName, args)
}
}
/**
* Reads the row into the given variable. It does not declare it but constructs it.
*/
fun readFromCursor(
outVar: String,
outPojo: Pojo,
cursorVar: String,
fieldsWithIndices: List<FieldWithIndex>,
scope: CodeGenScope,
relationCollectors: List<RelationCollector>
) {
fun visitNode(node: Node) {
val fieldParent = node.fieldParent
fun readNode() {
// read constructor parameters into local fields
val constructorFields = node.directFields.filter {
it.field.setter.callType == CallType.CONSTRUCTOR
}.associateBy { fwi ->
FieldReadWriteWriter(fwi).readIntoTmpVar(cursorVar, scope)
}
// read decomposed fields
node.subNodes.forEach(::visitNode)
// construct the object
if (fieldParent != null) {
construct(outVar = node.varName,
constructor = fieldParent.pojo.constructor,
typeName = fieldParent.field.typeName,
localEmbeddeds = node.subNodes,
localVariableNames = constructorFields,
scope = scope)
} else {
construct(outVar = node.varName,
constructor = outPojo.constructor,
typeName = outPojo.typeName,
localEmbeddeds = node.subNodes,
localVariableNames = constructorFields,
scope = scope)
}
// ready any field that was not part of the constructor
node.directFields.filterNot {
it.field.setter.callType == CallType.CONSTRUCTOR
}.forEach { fwi ->
FieldReadWriteWriter(fwi).readFromCursor(
ownerVar = node.varName,
cursorVar = cursorVar,
scope = scope)
}
// assign relationship fields which will be read later
relationCollectors.filter { (relation) ->
relation.field.parent === fieldParent
}.forEach {
it.writeReadParentKeyCode(
cursorVarName = cursorVar,
itemVar = node.varName,
fieldsWithIndices = fieldsWithIndices,
scope = scope)
}
// assign sub modes to fields if they were not part of the constructor.
node.subNodes.mapNotNull {
val setter = it.fieldParent?.setter
if (setter != null && setter.callType != CallType.CONSTRUCTOR) {
Pair(it.varName, setter)
} else {
null
}
}.forEach { (varName, setter) ->
setter.writeSet(
ownerVar = node.varName,
inVar = varName,
builder = scope.builder())
}
}
if (fieldParent == null) {
// root element
// always declared by the caller so we don't declare this
readNode()
} else {
// always declare, we'll set below
scope.builder().addStatement("final $T $L", fieldParent.pojo.typeName,
node.varName)
if (fieldParent.nonNull) {
readNode()
} else {
val myDescendants = node.allFields()
val allNullCheck = myDescendants.joinToString(" && ") {
if (it.alwaysExists) {
"$cursorVar.isNull(${it.indexVar})"
} else {
"( ${it.indexVar} == -1 || $cursorVar.isNull(${it.indexVar}))"
}
}
scope.builder().apply {
beginControlFlow("if (! ($L))", allNullCheck).apply {
readNode()
}
nextControlFlow(" else ").apply {
addStatement("$L = null", node.varName)
}
endControlFlow()
}
}
}
}
visitNode(createNodeTree(outVar, fieldsWithIndices, scope))
}
}
/**
* @param ownerVar The entity / pojo that owns this field. It must own this field! (not the
* container pojo)
* @param stmtParamVar The statement variable
* @param scope The code generation scope
*/
private fun bindToStatement(ownerVar: String, stmtParamVar: String, scope: CodeGenScope) {
field.statementBinder?.let { binder ->
val varName = if (field.getter.callType == CallType.FIELD) {
"$ownerVar.${field.name}"
} else {
"$ownerVar.${field.getter.name}()"
}
binder.bindToStmt(stmtParamVar, indexVar, varName, scope)
}
}
/**
* @param ownerVar The entity / pojo that owns this field. It must own this field (not the
* container pojo)
* @param cursorVar The cursor variable
* @param scope The code generation scope
*/
private fun readFromCursor(ownerVar: String, cursorVar: String, scope: CodeGenScope) {
fun toRead() {
field.cursorValueReader?.let { reader ->
scope.builder().apply {
when (field.setter.callType) {
CallType.FIELD -> {
reader.readFromCursor("$ownerVar.${field.getter.name}", cursorVar,
indexVar, scope)
}
CallType.METHOD -> {
val tmpField = scope.getTmpVar("_tmp${field.name.capitalize()}")
addStatement("final $T $L", field.getter.type.typeName(), tmpField)
reader.readFromCursor(tmpField, cursorVar, indexVar, scope)
addStatement("$L.$L($L)", ownerVar, field.setter.name, tmpField)
}
CallType.CONSTRUCTOR -> {
// no-op
}
}
}
}
}
if (alwaysExists) {
toRead()
} else {
scope.builder().apply {
beginControlFlow("if ($L != -1)", indexVar).apply {
toRead()
}
endControlFlow()
}
}
}
/**
* Reads the value into a temporary local variable.
*/
fun readIntoTmpVar(cursorVar: String, scope: CodeGenScope): String {
val tmpField = scope.getTmpVar("_tmp${field.name.capitalize()}")
val typeName = field.getter.type.typeName()
scope.builder().apply {
addStatement("final $T $L", typeName, tmpField)
if (alwaysExists) {
field.cursorValueReader?.readFromCursor(tmpField, cursorVar, indexVar, scope)
} else {
beginControlFlow("if ($L == -1)", indexVar).apply {
addStatement("$L = $L", tmpField, typeName.defaultValue())
}
nextControlFlow("else").apply {
field.cursorValueReader?.readFromCursor(tmpField, cursorVar, indexVar, scope)
}
endControlFlow()
}
}
return tmpField
}
/**
* On demand node which is created based on the fields that were passed into this class.
*/
private class Node(
// root for me
val varName: String,
// set if I'm a FieldParent
val fieldParent: EmbeddedField?
) {
// whom do i belong
var parentNode: Node? = null
// these fields are my direct fields
lateinit var directFields: List<FieldWithIndex>
// these nodes are under me
val subNodes = mutableListOf<Node>()
fun allFields(): List<FieldWithIndex> {
return directFields + subNodes.flatMap { it.allFields() }
}
}
}
| apache-2.0 | 45f10717ee786c3d071aa6d1ed9b74b1 | 40.679894 | 99 | 0.483021 | 5.693892 | false | false | false | false |
breadwallet/breadwallet-android | app-core/src/main/java/com/breadwallet/model/PriceAlert.kt | 1 | 15417 | /**
* BreadWallet
*
* Created by Drew Carlson <[email protected]> on 5/30/2019.
* 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.model
import kotlin.math.absoluteValue
/**
* This immutable model holds the data necessary to store
* and validate triggering of user defined price alerts.
*
* To create a new [PriceAlert], use one of the appropriate
* factory methods in [PriceAlert.Companion]. The constructor
* should only be used when deserializing a PriceAlert.
*/
data class PriceAlert(
/**
* The [Type] of trigger to fire this.
*/
val type: Type,
/**
* The [Direction] that will be used when validating a trigger is met.
*/
val direction: Direction,
/**
* The currency code for the asset we are tracking the value of.
*/
val forCurrencyCode: String,
/**
* The user defined value the trigger will match against.
* Depending on the [type], this could represent an exact
* value in [toCurrencyCode] or a percentage used when comparing
* [pinnedPrice] to the current asset price.
*/
val value: Float,
/**
* The user defined currency the trigger will match against.
*/
val toCurrencyCode: String,
/**
* An optional record of the time in milliseconds at which
* this alert was created.
*/
val startTime: Long = 0,
/**
* An optional record of the exchange rate at the time of
* alert creation. Used for updating [Type.PERCENTAGE_CHANGE]
* alerts with the current price after being triggered so
* the alert repeats indefinitely.
*/
val pinnedPrice: Float = 0f,
/**
* If an alert has been triggered, this will be true and
* future alerts should not be dispatched.
*
* When [hasBeenTriggered] is true, [isTriggerUnmet] should
* be called to reset this flag when needed.
*/
val hasBeenTriggered: Boolean = false
) {
enum class Type {
/**
* Triggered if the current price of [forCurrencyCode] is greater
* or less than [value] depending on [direction].
*/
PRICE_TARGET,
/**
* Triggered if the latest price of [forCurrencyCode] is greater
* or less than the user stored [value] as a percentage of [pinnedPrice].
*/
PERCENTAGE_CHANGE,
/**
* Triggered if the latest price of [forCurrencyCode] is greater
* or less than the user stored [value] as a percentage of [pinnedPrice]
* within one day.
*/
PERCENTAGE_CHANGE_DAY,
/**
* Triggered if the latest price of [forCurrencyCode] is greater
* or less than the user stored [value] as a percentage of [pinnedPrice]
* within one day and one week.
*/
PERCENTAGE_CHANGE_DAY_WEEK;
fun isPriceTarget() = this == PRICE_TARGET
fun isPercentageChange() = when (this) {
PERCENTAGE_CHANGE,
PERCENTAGE_CHANGE_DAY,
PERCENTAGE_CHANGE_DAY_WEEK -> true
else -> false
}
fun isPercentageChangeWithWindow() = when (this) {
PERCENTAGE_CHANGE_DAY,
PERCENTAGE_CHANGE_DAY_WEEK -> true
else -> false
}
}
enum class Direction {
/**
* Triggers will be satisfied when the current asset price is
* above or below the defined threshold.
*/
BOTH,
/**
* Triggers will only be satisfied when the current asset price
* is above the defined threshold.
*/
INCREASE,
/**
* Triggers to be satisfied when the current asset price is
* below the defined threshold.
*/
DECREASE
}
init {
require(value > 0) { "value must be a positive number" }
require(pinnedPrice >= 0) { "pinnedPrice must be a positive number" }
require(toCurrencyCode.isNotBlank()) { "toCurrencyCode must not be blank" }
require(forCurrencyCode.isNotBlank()) { "forCurrencyCode must not be blank" }
if (type.isPercentageChange()) {
require(pinnedPrice > 0f) {
"pinnedPrice must not be 0 when type is Type.PERCENTAGE_CHANGE_*"
}
if (type.isPercentageChangeWithWindow()) {
require(startTime > 0) {
"startTime must be greater than 0 for Type.PERCENTAGE_CHANGE_*"
}
}
}
}
/**
* Returns whether or not this alerts trigger is satisfied based on
* the [currentPrice].
*
* @param currentPrice The current price of [forCurrencyCode] in [toCurrencyCode].
*/
fun isTriggerMet(currentPrice: Float, currentTime: Long = 0): Boolean {
return when (type) {
Type.PRICE_TARGET -> isPriceTargetTriggered(currentPrice)
Type.PERCENTAGE_CHANGE -> isPercentageChangeTriggered(currentPrice)
Type.PERCENTAGE_CHANGE_DAY -> isPercentageChangeInDayTriggered(currentPrice, currentTime, false)
Type.PERCENTAGE_CHANGE_DAY_WEEK -> isPercentageChangeInDayTriggered(currentPrice, currentTime, true)
}
}
/**
* Returns whether or not this alert is still past its trigger threshold.
*
* For [Type.PRICE_TARGET] alerts where [hasBeenTriggered] is true, this
* function is used to reset [hasBeenTriggered] flag so the alert will
* be triggered again.
*
* For [Type.PERCENTAGE_CHANGE] alerts, this function is used to update
* the [pinnedPrice] with the current exchange rate so the alert's threshold
* will be relative to the actual exchange rate and not stale data.
*
* For [Type.PERCENTAGE_CHANGE_DAY] and [Type.PERCENTAGE_CHANGE_DAY_WEEK]
* alerts, this function is used to update the [startTime] and [pinnedPrice].
*
* @param currentPrice The current price of [forCurrencyCode] in [toCurrencyCode].
*/
fun isTriggerUnmet(currentPrice: Float, currentTime: Long = 0): Boolean {
return when (type) {
Type.PRICE_TARGET -> !isPriceTargetTriggered(currentPrice)
Type.PERCENTAGE_CHANGE -> !isPercentageChangeTriggered(currentPrice)
Type.PERCENTAGE_CHANGE_DAY -> !isInWindow(currentTime, DAY_IN_MS)
Type.PERCENTAGE_CHANGE_DAY_WEEK -> !isInWindow(currentTime, WEEK_IN_MS)
}
}
/**
* Returns whether or not this price target alert is triggered
* based on the [direction] and [value] compared to [currentPrice].
*/
private fun isPriceTargetTriggered(currentPrice: Float): Boolean {
check(type.isPriceTarget())
return when (direction) {
Direction.INCREASE -> currentPrice > value
Direction.DECREASE -> currentPrice < value
Direction.BOTH -> error("Direction.BOTH unsupported for Type.PRICE_TARGET")
}
}
/**
* Returns whether or not this percent change alert is triggered
* using the difference (as a %) of [pinnedPrice] and [currentPrice].
*/
private fun isPercentageChangeTriggered(currentPrice: Float): Boolean {
check(type.isPercentageChange())
val percentChanged = percentageChanged(currentPrice, pinnedPrice)
return when (direction) {
Direction.INCREASE -> {
if (percentChanged <= 0) false
else percentChanged >= value
}
Direction.DECREASE -> {
if (percentChanged >= 0) false
else percentChanged.absoluteValue >= value
}
Direction.BOTH -> {
percentChanged.absoluteValue >= value
}
}
}
/**
* Returns whether or not this percent change alert is triggered
* using the difference (as a %) of [pinnedPrice] and [currentPrice]
* within a day of [startTime]. Optionally checks within a week of
* [startTime] if [andWeek] is true.
*/
private fun isPercentageChangeInDayTriggered(currentPrice: Float, currentTime: Long, andWeek: Boolean): Boolean {
check(type.isPercentageChangeWithWindow())
require(currentTime > startTime) { "currentTime must be greater than startTime." }
val window = if (andWeek) WEEK_IN_MS else DAY_IN_MS
return if (!isInWindow(currentTime, window)) false
else isPercentageChangeTriggered(currentPrice)
}
/**
* Returns true if the time between [currentTime] and [startTime]
* is less than [window].
*/
private fun isInWindow(currentTime: Long, window: Long): Boolean {
check(type.isPercentageChangeWithWindow())
return currentTime - startTime <= window
}
/**
* Returns the whole number percentage difference between
* [currentPrice] and [originalPrice].
*/
private fun percentageChanged(currentPrice: Float, originalPrice: Float): Float {
val difference = currentPrice - originalPrice
return difference / originalPrice * 100
}
/**
* Inverse of [hasBeenTriggered] for functional composition.
*/
fun hasNotBeenTriggered() = !hasBeenTriggered
/**
* True if this alert is of type [Type.PRICE_TARGET].
*/
fun isPriceTargetType() = type.isPriceTarget()
/**
* True if this alert is of type [Type.PERCENTAGE_CHANGE],
* [Type.PERCENTAGE_CHANGE_DAY], or [Type.PERCENTAGE_CHANGE_DAY_WEEK].
*/
fun isPercentageChangeType() = type.isPercentageChange()
companion object {
/**
* 24 hours in milliseconds for time operations.
*
* hours in day * minutes * seconds * ms
*/
private const val DAY_IN_MS: Long = 24 * 60 * 60 * 1000
/**
* 7 days in milliseconds for time operations.
*/
private const val WEEK_IN_MS: Long = 7 * DAY_IN_MS
/**
* Create an alert of type [Type.PRICE_TARGET] with [Direction.INCREASE].
*/
fun priceTargetIncrease(forCurrencyCode: String, value: Float, currencyCode: String) =
PriceAlert(Type.PRICE_TARGET, Direction.INCREASE, forCurrencyCode, value, currencyCode)
/**
* Create an alert of type [Type.PRICE_TARGET] with [Direction.DECREASE].
*/
fun priceTargetDecrease(forCurrencyCode: String, value: Float, currencyCode: String) =
PriceAlert(Type.PRICE_TARGET, Direction.DECREASE, forCurrencyCode, value, currencyCode)
/**
* Create an alert of type [Type.PERCENTAGE_CHANGE] with [Direction.INCREASE].
*/
fun percentageIncreased(forCurrencyCode: String, value: Float, currencyCode: String, pinnedPrice: Float) =
percentageChangeTrigger(Direction.INCREASE, forCurrencyCode, value, currencyCode, pinnedPrice)
/**
* Create an alert of type [Type.PERCENTAGE_CHANGE] with [Direction.DECREASE].
*/
fun percentageDecreased(forCurrencyCode: String, value: Float, currencyCode: String, pinnedPrice: Float) =
percentageChangeTrigger(Direction.DECREASE, forCurrencyCode, value, currencyCode, pinnedPrice)
/**
* Create an alert of type [Type.PERCENTAGE_CHANGE] with [Direction.BOTH].
*/
fun percentageChanged(forCurrencyCode: String, value: Float, currencyCode: String, pinnedPrice: Float) =
percentageChangeTrigger(Direction.BOTH, forCurrencyCode, value, currencyCode, pinnedPrice)
private fun percentageChangeTrigger(direction: Direction, forCurrencyCode: String, value: Float, currencyCode: String, pinnedPrice: Float) =
PriceAlert(Type.PERCENTAGE_CHANGE, direction, forCurrencyCode, value, currencyCode, pinnedPrice = pinnedPrice)
/**
* Create an alert of type [Type.PERCENTAGE_CHANGE_DAY] with [Direction.INCREASE].
*/
fun percentageIncreasedInDay(forCurrencyCode: String, value: Float, currencyCode: String, startTime: Long, pinnedPrice: Float) =
PriceAlert(Type.PERCENTAGE_CHANGE_DAY, Direction.INCREASE, forCurrencyCode, value, currencyCode, startTime, pinnedPrice)
/**
* Create an alert of type [Type.PERCENTAGE_CHANGE_DAY] with [Direction.DECREASE].
*/
fun percentageDecreasedInDay(forCurrencyCode: String, value: Float, currencyCode: String, startTime: Long, pinnedPrice: Float) =
PriceAlert(Type.PERCENTAGE_CHANGE_DAY, Direction.DECREASE, forCurrencyCode, value, currencyCode, startTime, pinnedPrice)
/**
* Create an alert of type [Type.PERCENTAGE_CHANGE_DAY] with [Direction.BOTH].
*/
fun percentageChangedInDay(forCurrencyCode: String, value: Float, currencyCode: String, startTime: Long, pinnedPrice: Float) =
PriceAlert(Type.PERCENTAGE_CHANGE_DAY, Direction.BOTH, forCurrencyCode, value, currencyCode, startTime, pinnedPrice)
/**
* Create an alert of type [Type.PERCENTAGE_CHANGE_DAY_WEEK] with [Direction.INCREASE].
*/
fun percentageIncreasedInDayAndWeek(forCurrencyCode: String, value: Float, currencyCode: String, startTime: Long, pinnedPrice: Float) =
PriceAlert(Type.PERCENTAGE_CHANGE_DAY_WEEK, Direction.INCREASE, forCurrencyCode, value, currencyCode, startTime, pinnedPrice)
/**
* Create an alert of type [Type.PERCENTAGE_CHANGE_DAY_WEEK] with [Direction.DECREASE].
*/
fun percentageDecreasedInDayAndWeek(forCurrencyCode: String, value: Float, currencyCode: String, startTime: Long, pinnedPrice: Float) =
PriceAlert(Type.PERCENTAGE_CHANGE_DAY_WEEK, Direction.DECREASE, forCurrencyCode, value, currencyCode, startTime, pinnedPrice)
/**
* Create an alert of type [Type.PERCENTAGE_CHANGE_DAY_WEEK] with [Direction.BOTH].
*/
fun percentageChangedInDayAndWeek(forCurrencyCode: String, value: Float, currencyCode: String, startTime: Long, pinnedPrice: Float) =
PriceAlert(Type.PERCENTAGE_CHANGE_DAY_WEEK, Direction.BOTH, forCurrencyCode, value, currencyCode, startTime, pinnedPrice)
}
} | mit | f3b2c97bc73bb4e627cd959427c2c176 | 41.473829 | 148 | 0.643121 | 4.666162 | false | false | false | false |
breadwallet/breadwallet-android | app-core/src/main/java/com/breadwallet/ext/BigDecimal.kt | 1 | 1448 | /**
* BreadWallet
*
* Created by Drew Carlson <[email protected]> on 10/23/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.ext
import java.math.BigDecimal
fun BigDecimal.isPositive() = compareTo(BigDecimal.ZERO) > 0
fun BigDecimal.isZero() = compareTo(BigDecimal.ZERO) == 0
fun BigDecimal.isNegative() = compareTo(BigDecimal.ZERO) < 0
| mit | 4b5ee3ee883dc42f53d113fa6ca702d1 | 45.709677 | 80 | 0.76174 | 4.387879 | false | false | false | false |
Nicologies/Hedwig | hedwig-server/src/main/java/com/nicologis/teamcity/ServiceMessageHandler.kt | 2 | 4616 | package com.nicologis.teamcity
import com.nicologis.messenger.MessengerFactory
import com.nicologis.github.PullRequestInfo
import com.nicologis.messenger.Recipient
import com.nicologis.slack.StatusColor
import jetbrains.buildServer.messages.BuildMessage1
import jetbrains.buildServer.messages.serviceMessages.ServiceMessage
import jetbrains.buildServer.messages.serviceMessages.ServiceMessageTranslator
import jetbrains.buildServer.serverSide.SBuildServer
import jetbrains.buildServer.serverSide.SRunningBuild
import org.apache.commons.lang.StringUtils
import java.util.*
class ServiceMessageHandler(private val _server: SBuildServer) : ServiceMessageTranslator {
override fun translate(sRunningBuild: SRunningBuild, buildMessage1: BuildMessage1,
serviceMessage: ServiceMessage): List<BuildMessage1> {
val ret = Arrays.asList(buildMessage1)
val attributes = serviceMessage.attributes
val status = attributes["Status"]
if (StringUtils.isEmpty(status)) {
return ret
}
val messages = HashMap<String, String>()
for (i in 0..49) {
val msgName = attributes["MsgName" + i]
val msgValue = attributes["MsgValue" + i]
if (StringUtils.isEmpty(msgName) || StringUtils.isEmpty(msgValue)) {
continue
}
messages.put(msgName!!, msgValue!!)
}
val statusType = attributes["StatusType"]
var statusColor = StatusColor.info
if (StringUtils.isNotEmpty(statusType)) {
val lowerCaseStatus = statusType!!.toLowerCase()
if (lowerCaseStatus == "good" || lowerCaseStatus == "succeeded") {
statusColor = StatusColor.good
} else if (lowerCaseStatus == "danger") {
statusColor = StatusColor.danger
} else if (lowerCaseStatus == "warning") {
statusColor = StatusColor.warning
}
}
val rooms = getRecipients(attributes)
val prInfo = getPullRequestInfo(sRunningBuild, attributes)
val build = BuildInfo(sRunningBuild, status!!, statusColor, prInfo, messages, _server.rootUrl)
MessengerFactory.sendMsg(build, sRunningBuild.parametersProvider, rooms)
return ret
}
private fun getPullRequestInfo(sRunningBuild: SRunningBuild, attributes: Map<String, String>): PullRequestInfo {
val prInfo = PullRequestInfo(sRunningBuild)
val prAuthor = attributes["PrAuthor"]
if (StringUtils.isNotEmpty(prAuthor)) {
prInfo.setAuthor(prAuthor!!)
}
val prAssignee = attributes["PrAssignee"]
if (StringUtils.isNotEmpty(prAssignee)) {
prInfo.setAssignee(prAssignee!!)
}
val prUrl = attributes["PrUrl"]
if (StringUtils.isNotEmpty(prUrl)) {
prInfo.Url = prUrl
}
val branchName = attributes["Branch"]
if (StringUtils.isNotEmpty(branchName)) {
prInfo.Branch = branchName!!
}
return prInfo
}
private fun getRecipients(attributes: Map<String, String>): List<Recipient> {
val recipients = ArrayList<Recipient>()
getRooms(attributes, recipients, "Channels")
getRooms(attributes, recipients, "Rooms")
val usersStr = attributes["Users"]
if (StringUtils.isNotEmpty(usersStr)) {
for (user in usersStr!!.split(";".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()) {
if (StringUtils.isEmpty(user)) {
continue
}
var trimmedUser = user.trim { it <= ' ' }
if (trimmedUser.startsWith("@")) {
trimmedUser = trimmedUser.substring(1)
}
recipients.add(Recipient(trimmedUser, false))
}
}
return recipients
}
private fun getRooms(attributes: Map<String, String>, recipients: MutableList<Recipient>, rooms: String) {
val channelsStr = attributes[rooms]
if (StringUtils.isNotEmpty(channelsStr)) {
channelsStr!!.split(";".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
.asSequence()
.filterNot { StringUtils.isEmpty(it) }
.mapTo(recipients) { channel -> Recipient(channel.trim { it <= ' ' }, true) }
}
}
override fun getServiceMessageName(): String {
return "Hedwig"
}
}
| mit | e46ecae1623e9f3abfd66a631780ec0f | 37.452991 | 116 | 0.610269 | 4.900212 | false | false | false | false |
luhaoaimama1/JavaZone | JavaTest_Zone/src/算法/每日一题/字符串转换整数.kt | 1 | 1851 | package 算法.每日一题
//https://leetcode-cn.com/problems/string-to-integer-atoi/
fun main() {
// println(myAtoi("42"))
// println(myAtoi(" -42"))
// println(myAtoi("4193 with words"))
// println(myAtoi("words and 987"))
// println(myAtoi("-91283472332"))
// println(myAtoi("+1"))
// println(myAtoi(" +0 123"))
// println(myAtoi("2147483646"))
println(myAtoi("-2147483649"))
println(myAtoi("- 234")) //0
println(myAtoi("0-1")) //0
}
fun myAtoi(str: String): Int {
var sum = 0
var symbol = 1
var symbolCount = 0
var symbolInit = false
loop@ for (i in 0 until str.length) {
when (val c = str[i]) {
' ' -> {
//已经计算的话 碰到这个就不计算了
if (symbolInit) return sum
else continue@loop // 空格跳过
}
'+', '-' -> {
if (!symbolInit) symbolInit = true
else return sum
symbol = if (c == '-') -1 else 1
}
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9' -> {
if (!symbolInit) symbolInit = true
val right = c.toString().toInt() * symbol
val overIntMax = isOverIntMax(sum, right)
if (overIntMax != 0) return overIntMax
sum = sum * 10 + right
}
else -> { //其他字符 终止
break@loop
}
}
}
return sum
}
//left:代表 未*10的左边的数 right个位数
fun isOverIntMax(left: Int, right: Int): Int {
if (left > Int.MAX_VALUE / 10 || (left == Int.MAX_VALUE / 10 && right > Int.MAX_VALUE % 10)) return Int.MAX_VALUE
if (left < Int.MIN_VALUE / 10 || (left == Int.MIN_VALUE / 10 && right < Int.MIN_VALUE % 10)) return Int.MIN_VALUE
return 0
} | epl-1.0 | 6f91660092c38b86e394af7e71c95771 | 31.109091 | 117 | 0.491785 | 3.18018 | false | false | false | false |
YouriAckx/AdventOfCode | 2017/src/day05/part01.kt | 1 | 397 | package day05
import java.io.File
fun main(args: Array<String>) {
val offsets = File("src/day05/input.txt").bufferedReader().readLines().map { it.toInt() }.toMutableList()
var steps = 0
var index = 0
while (index >= 0 && index < offsets.size) {
val prevIndex = index
index += offsets[index]
offsets[prevIndex]++
steps++
}
println(steps)
}
| gpl-3.0 | 5fea6a7e25eb0e0ddc9703626e54192c | 23.8125 | 109 | 0.599496 | 3.780952 | false | false | false | false |
kpspemu/kpspemu | src/commonMain/kotlin/com/soywiz/kpspemu/hle/modules/sceHprm.kt | 1 | 2818 | package com.soywiz.kpspemu.hle.modules
import com.soywiz.kpspemu.*
import com.soywiz.kpspemu.cpu.*
import com.soywiz.kpspemu.hle.*
import com.soywiz.kpspemu.mem.*
class sceHprm(emulator: Emulator) :
SceModule(emulator, "sceHprm", 0x40010011, "hpremote_02g.prx", "sceHP_Remote_Driver") {
fun sceHprmPeekCurrentKey(ptr: Ptr): Int {
ptr.sw(0, 0)
return 0
}
fun sceHprmIsRemoteExist(cpu: CpuState): Unit = UNIMPLEMENTED(0x208DB1BD)
fun sceHprmIsMicrophoneExist(cpu: CpuState): Unit = UNIMPLEMENTED(0x219C58F1)
fun sceHprmPeekLatch(cpu: CpuState): Unit = UNIMPLEMENTED(0x2BCEC83E)
fun sceHprm_3953DE6B(cpu: CpuState): Unit = UNIMPLEMENTED(0x3953DE6B)
fun sceHprm_396FD885(cpu: CpuState): Unit = UNIMPLEMENTED(0x396FD885)
fun sceHprmReadLatch(cpu: CpuState): Unit = UNIMPLEMENTED(0x40D2F9F0)
fun sceHprmUnregitserCallback(cpu: CpuState): Unit = UNIMPLEMENTED(0x444ED0B7)
fun sceHprmGetHpDetect(cpu: CpuState): Unit = UNIMPLEMENTED(0x71B5FB67)
fun sceHprmIsHeadphoneExist(cpu: CpuState): Unit = UNIMPLEMENTED(0x7E69EDA4)
fun sceHprmRegisterCallback(cpu: CpuState): Unit = UNIMPLEMENTED(0xC7154136)
fun sceHprm_FD7DE6CD(cpu: CpuState): Unit = UNIMPLEMENTED(0xFD7DE6CD)
override fun registerModule() {
registerFunctionInt("sceHprmPeekCurrentKey", 0x1910B327, since = 150) { sceHprmPeekCurrentKey(ptr) }
registerFunctionRaw("sceHprmIsRemoteExist", 0x208DB1BD, since = 150) { sceHprmIsRemoteExist(it) }
registerFunctionRaw("sceHprmIsMicrophoneExist", 0x219C58F1, since = 150) { sceHprmIsMicrophoneExist(it) }
registerFunctionRaw("sceHprmPeekLatch", 0x2BCEC83E, since = 150) { sceHprmPeekLatch(it) }
registerFunctionRaw("sceHprm_3953DE6B", 0x3953DE6B, since = 150) { sceHprm_3953DE6B(it) }
registerFunctionRaw("sceHprm_396FD885", 0x396FD885, since = 150) { sceHprm_396FD885(it) }
registerFunctionRaw("sceHprmReadLatch", 0x40D2F9F0, since = 150) { sceHprmReadLatch(it) }
registerFunctionRaw("sceHprmUnregitserCallback", 0x444ED0B7, since = 150) { sceHprmUnregitserCallback(it) }
registerFunctionRaw("sceHprmGetHpDetect", 0x71B5FB67, since = 150) { sceHprmGetHpDetect(it) }
registerFunctionRaw("sceHprmIsHeadphoneExist", 0x7E69EDA4, since = 150) { sceHprmIsHeadphoneExist(it) }
registerFunctionRaw("sceHprmRegisterCallback", 0xC7154136, since = 150) { sceHprmRegisterCallback(it) }
registerFunctionRaw("sceHprm_FD7DE6CD", 0xFD7DE6CD, since = 150) { sceHprm_FD7DE6CD(it) }
}
companion object {
const val PSP_HPRM_PLAYPAUSE = 0x1
const val PSP_HPRM_FORWARD = 0x4
const val PSP_HPRM_BACK = 0x8
const val PSP_HPRM_VOL_UP = 0x10
const val PSP_HPRM_VOL_DOWN = 0x20
const val PSP_HPRM_HOLD = 0x8
}
}
| mit | 0dffbd61138e4d80cef01ad9dab9b590 | 53.192308 | 115 | 0.726757 | 2.969442 | false | false | false | false |
hwki/SimpleBitcoinWidget | bitcoin/src/fdroid/java/com/brentpanther/bitcoinwidget/ui/home/AdditionalGlobalSettings.kt | 1 | 1391 | package com.brentpanther.bitcoinwidget.ui.home
import android.content.ActivityNotFoundException
import android.content.Intent
import android.widget.Toast
import androidx.compose.material.Icon
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.core.content.ContextCompat
import androidx.core.net.toUri
import com.brentpanther.bitcoinwidget.R
import com.brentpanther.bitcoinwidget.ui.settings.SettingsButton
@Composable
fun AdditionalSettings() {
val context = LocalContext.current
val address = stringResource(R.string.btc_address).toUri()
val donateError = stringResource(R.string.error_donate)
SettingsButton(
icon = {
Icon(painterResource(R.drawable.ic_bitcoin), null)
},
title = {
Text(stringResource(id = R.string.title_donate))
},
subtitle = {
Text(stringResource(id = R.string.summary_donate))
},
onClick = {
try {
ContextCompat.startActivity(context, Intent(Intent.ACTION_VIEW, address), null)
} catch (e: ActivityNotFoundException) {
Toast.makeText(context, donateError, Toast.LENGTH_SHORT).show()
}
}
)
} | mit | c4e390ce5ff0fa02ec5faf9347c48be7 | 33.8 | 95 | 0.705248 | 4.319876 | false | false | false | false |
Alfresco/activiti-android-app | auth-library/src/main/kotlin/com/alfresco/common/BaseViewModel.kt | 1 | 549 | package com.alfresco.common
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
abstract class BaseViewModel : ViewModel() {
protected val _isLoading = MutableLiveData<Boolean>()
protected val _hasNavigation = MutableLiveData<Boolean>()
val isLoading: LiveData<Boolean> get() = _isLoading
val hasNavigation: LiveData<Boolean> get() = _hasNavigation
public fun setHasNavigation(enableNavigation: Boolean) {
_hasNavigation.value = enableNavigation
}
} | lgpl-3.0 | 7db5c38b1da9c615d3a772de11567c3e | 26.5 | 63 | 0.761384 | 4.945946 | false | false | false | false |
BenoitDuffez/AndroidCupsPrint | app/src/main/java/io/github/benoitduffez/cupsprint/app/AddPrintersActivity.kt | 1 | 5089 | package io.github.benoitduffez.cupsprint.app
import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.text.TextUtils
import android.view.View
import io.github.benoitduffez.cupsprint.AppExecutors
import io.github.benoitduffez.cupsprint.R
import kotlinx.android.synthetic.main.add_printers.*
import org.koin.android.ext.android.inject
import timber.log.Timber
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URI
import java.net.URL
import java.util.regex.Pattern
/**
* Called when the system needs to manually add a printer
*/
class AddPrintersActivity : Activity() {
private val executors: AppExecutors by inject()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.add_printers)
}
/**
* Called when the button will be clicked
*/
fun addPrinter(@Suppress("UNUSED_PARAMETER") button: View) {
val url = add_url.text.toString()
val name = add_name.text.toString()
if (TextUtils.isEmpty(name)) {
add_name.error = getString(R.string.err_add_printer_empty_name)
return
}
if (TextUtils.isEmpty(url)) {
add_url.error = getString(R.string.err_add_printer_empty_url)
return
}
try {
URI(url)
} catch (e: Exception) {
add_url.error = e.localizedMessage
return
}
val prefs = getSharedPreferences(SHARED_PREFS_MANUAL_PRINTERS, Context.MODE_PRIVATE)
val editor = prefs.edit()
val id = prefs.getInt(PREF_NUM_PRINTERS, 0)
Timber.d("saving printer from input: $url")
editor.putString(PREF_URL + id, url)
editor.putString(PREF_NAME + id, name)
editor.putInt(PREF_NUM_PRINTERS, id + 1)
editor.apply()
// TODO: inform user?
// Allow the system to process the new printer addition before we get back to the list of printers
Handler().postDelayed({ finish() }, 200)
}
fun searchPrinters(@Suppress("UNUSED_PARAMETER") button: View) {
executors.networkIO.execute {
searchPrinters("http")
searchPrinters("https")
}
}
/**
* Will search for printers at the scheme://xxx/printers/ URL
*
* @param scheme The target scheme, http or https
*/
private fun searchPrinters(scheme: String) {
var urlConnection: HttpURLConnection? = null
val sb = StringBuilder()
var server = add_server_ip.text.toString()
if (!server.contains(":")) {
server += ":631"
}
val baseHost = "$scheme://$server"
val baseUrl = "$baseHost/printers/"
try {
urlConnection = URL(baseUrl).openConnection() as HttpURLConnection
val isw = InputStreamReader(urlConnection.inputStream)
var data = isw.read()
while (data != -1) {
val current = data.toChar()
sb.append(current)
data = isw.read()
}
} catch (e: Exception) {
e.printStackTrace()
return
} finally {
urlConnection?.disconnect()
}
/*
* 1: URL
* 2: Name
* 3: Description
* 4: Location
* 5: Make and model
* 6: Current state
* pattern matching fields: 1 2 3 4 5 6
*/
val p = Pattern.compile("<TR><TD><A HREF=\"([^\"]+)\">([^<]*)</A></TD><TD>([^<]*)</TD><TD>([^<]*)</TD><TD>([^<]*)</TD><TD>([^<]*)</TD></TR>\n")
val matcher = p.matcher(sb)
var url: String
var name: String
val prefs = getSharedPreferences(SHARED_PREFS_MANUAL_PRINTERS, Context.MODE_PRIVATE)
val editor = prefs.edit()
var id = prefs.getInt(PREF_NUM_PRINTERS, 0)
while (matcher.find()) {
val path = matcher.group(1)
url = if (path.startsWith("/")) {
baseHost + path
} else {
baseUrl + path
}
Timber.d("saving printer from search on $scheme: $url")
name = matcher.group(3)
editor.putString(PREF_URL + id, url)
editor.putString(PREF_NAME + id, name)
id++
}
editor.putInt(PREF_NUM_PRINTERS, id)
editor.apply()
}
companion object {
/**
* Shared preferences file name
*/
const val SHARED_PREFS_MANUAL_PRINTERS = "printers"
/**
* Will store the number of printers manually added
*/
const val PREF_NUM_PRINTERS = "num"
/**
* Will be suffixed by the printer ID. Contains the URL.
*/
const val PREF_URL = "url"
/**
* Will be suffixed by the printer ID. Contains the name.
*/
const val PREF_NAME = "name"
}
}
| lgpl-3.0 | 0c2d8073065a1fd4de1f0b28eb224d0b | 31.006289 | 151 | 0.560621 | 4.320034 | false | false | false | false |
AdamLuisSean/Picasa-Gallery-Android | app/src/main/kotlin/io/shtanko/picasagallery/ui/base/BaseAdapter.kt | 1 | 1948 | /*
* Copyright 2017 Alexey Shtanko
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.shtanko.picasagallery.ui.base
import android.support.v4.util.SparseArrayCompat
import android.support.v7.widget.RecyclerView.Adapter
import android.support.v7.widget.RecyclerView.ViewHolder
import android.view.ViewGroup
import io.shtanko.picasagallery.ui.delegate.ViewType
import io.shtanko.picasagallery.ui.delegate.ViewTypeAdapterDelegate
import io.shtanko.picasagallery.ui.util.OnItemClickListener
import kotlin.properties.Delegates
abstract class BaseAdapter<T : ViewType> : Adapter<ViewHolder>() {
var onItemClickListener: OnItemClickListener? = null
var items: List<T> by Delegates.observable(
emptyList()
) { _, _, _ -> notifyDataSetChanged() }
override fun getItemCount() = items.size
protected var delegateAdapters = SparseArrayCompat<ViewTypeAdapterDelegate>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder =
delegateAdapters.get(viewType).onCreateViewHolder(parent)
override fun onBindViewHolder(
holder: ViewHolder,
position: Int
) {
val model = this.items[position]
holder.itemView.setOnClickListener {
onItemClickListener?.onItemClicked(model)
}
delegateAdapters.get(getItemViewType(position))
.onBindViewHolder(holder, model)
}
override fun getItemViewType(position: Int): Int = this.items[position].getViewType()
} | apache-2.0 | 83841b03f21432c7555f2f1953be566d | 33.192982 | 87 | 0.766427 | 4.562061 | false | false | false | false |
manami-project/manami | manami-gui/src/main/kotlin/io/github/manamiproject/manami/gui/main/MainWindowView.kt | 1 | 3680 | package io.github.manamiproject.manami.gui.main
import io.github.manamiproject.manami.app.versioning.SemanticVersion
import io.github.manamiproject.manami.gui.*
import io.github.manamiproject.manami.gui.events.FileOpenedGuiEvent
import io.github.manamiproject.manami.gui.events.FileSavedStatusChangedGuiEvent
import io.github.manamiproject.manami.gui.events.NewVersionAvailableGuiEvent
import io.github.manamiproject.manami.gui.events.SavedAsFileGuiEvent
import io.github.manamiproject.manami.gui.extensions.focus
import io.github.manamiproject.manami.gui.search.SearchBoxView
import io.github.manamiproject.modb.core.extensions.EMPTY
import javafx.beans.property.SimpleStringProperty
import javafx.event.EventHandler
import javafx.scene.control.Alert
import javafx.scene.control.Alert.AlertType.INFORMATION
import javafx.scene.control.ButtonBar
import javafx.scene.control.ButtonType
import javafx.scene.layout.Priority.ALWAYS
import tornadofx.*
class MainWindowView : View() {
private val manamiAccess: ManamiAccess by inject()
private val menuView: MenuView by inject()
private val searchBoxView: SearchBoxView by inject()
private val tabPaneView: TabPaneView by inject()
private val quitController: QuitController by inject()
private val customTitleProperty = SimpleStringProperty("Manami")
init {
primaryStage.titleProperty().unbind()
titleProperty.bindBidirectional(customTitleProperty)
manamiAccess.primaryStage.isMaximized = true
manamiAccess.primaryStage.onCloseRequest = EventHandler { event -> quitController.quit(); event.consume() }
subscribe<FileOpenedGuiEvent> { event ->
customTitleProperty.set(generateTitle(event.fileName))
}
subscribe<SavedAsFileGuiEvent> { event ->
customTitleProperty.set(generateTitle(event.fileName))
}
subscribe<FileSavedStatusChangedGuiEvent> {
handleUnsavedIndicator()
}
subscribe<NewVersionAvailableGuiEvent> { event ->
handleNewVersionAvailable(event.version)
}
}
override val root = vbox {
hgrow = ALWAYS
vgrow = ALWAYS
hbox {
hgrow = ALWAYS
add(menuView.root)
add(searchBoxView.root)
}
add(tabPaneView.root)
}.apply { focus() }
private fun generateTitle(fileName: String = EMPTY): String {
val titleBuilder = StringBuilder("Manami")
if (fileName.isNotBlank()) {
titleBuilder.append(" - $fileName")
}
if (manamiAccess.isUnsaved()) {
titleBuilder.append(FILE_SAVED_INDICATOR)
}
return titleBuilder.toString()
}
private fun handleUnsavedIndicator() {
val newTitle = when {
manamiAccess.isUnsaved() && !customTitleProperty.get().endsWith(FILE_SAVED_INDICATOR) -> "$title*"
manamiAccess.isSaved() && customTitleProperty.get().endsWith(FILE_SAVED_INDICATOR) -> title.dropLast(1)
else -> customTitleProperty.get()
}
customTitleProperty.set(newTitle)
}
private fun handleNewVersionAvailable(version: SemanticVersion) {
Alert(INFORMATION).apply {
title = "New version available"
headerText = "There is a new version available: $version"
contentText = "https://github.com/manami-project/manami/releases/latest"
buttonTypes.clear()
buttonTypes.addAll(
ButtonType("OK", ButtonBar.ButtonData.OK_DONE),
)
}.showAndWait().get()
}
companion object {
private const val FILE_SAVED_INDICATOR = "*"
}
} | agpl-3.0 | 6eaa618098063ccbb710fe4405f4769f | 35.445545 | 115 | 0.691576 | 4.652339 | false | false | false | false |
RP-Kit/RPKit | rpk-core/src/main/kotlin/com/rpkit/core/expression/RPKExpressionImpl.kt | 1 | 1965 | /*
* Copyright 2021 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.core.expression
import org.scijava.parsington.Variable
import kotlin.math.roundToInt
internal class RPKExpressionImpl(
private val expression: String,
private val functions: Map<String, RPKFunction>,
private val constants: Map<String, Any?>
) : RPKExpression {
override fun parse(variables: Map<String, Any?>): Any? {
val parsingtonEvaluator = RPKParsingtonEvaluator(functions)
constants.forEach { (key, value) -> parsingtonEvaluator.evaluate("$key=$value") }
variables.forEach { (key, value) -> parsingtonEvaluator.evaluate("$key=$value") }
return parsingtonEvaluator.evaluate(expression)
}
override fun parseDouble(variables: Map<String, Any?>): Double? {
val parsingtonEvaluator = RPKParsingtonEvaluator(functions)
constants.forEach { (key, value) -> parsingtonEvaluator.evaluate("$key=$value") }
variables.forEach { (key, value) -> parsingtonEvaluator.evaluate("$key=$value") }
var result = parsingtonEvaluator.evaluate(expression)
if (result is Variable) {
result = parsingtonEvaluator.get(result)
}
if (result is Number) {
return result.toDouble()
}
return null
}
override fun parseInt(variables: Map<String, Any?>): Int? {
return parseDouble(variables)?.roundToInt()
}
} | apache-2.0 | c9ec7b9b0b399c0a48eb9a8be76a23ef | 36.807692 | 89 | 0.693639 | 4.337748 | false | false | false | false |
manami-project/manami | manami-app/src/main/kotlin/io/github/manamiproject/manami/app/file/DefaultFileHandler.kt | 1 | 3194 | package io.github.manamiproject.manami.app.file
import io.github.manamiproject.manami.app.state.CurrentFile
import io.github.manamiproject.manami.app.state.InternalState
import io.github.manamiproject.manami.app.state.State
import io.github.manamiproject.manami.app.commands.history.CommandHistory
import io.github.manamiproject.manami.app.commands.history.DefaultCommandHistory
import io.github.manamiproject.manami.app.events.EventBus
import io.github.manamiproject.manami.app.events.SimpleEventBus
import io.github.manamiproject.modb.core.extensions.RegularFile
import io.github.manamiproject.modb.core.extensions.regularFileExists
import io.github.manamiproject.modb.core.logging.LoggerDelegate
import kotlin.io.path.createFile
internal class DefaultFileHandler(
private val state: State = InternalState,
private val commandHistory: CommandHistory = DefaultCommandHistory,
private val parser: Parser<ParsedManamiFile> = FileParser(),
private val fileWriter: FileWriter = DefaultFileWriter(),
private val eventBus: EventBus = SimpleEventBus,
) : FileHandler {
override fun newFile(ignoreUnsavedChanged: Boolean) {
log.info { "Creating new file using [ignoreUnsavedChanged=$ignoreUnsavedChanged]" }
if (!ignoreUnsavedChanged) {
check(commandHistory.isSaved()) { "Cannot create a new list, because there are unsaved changes." }
}
CmdNewFile(
state = state,
commandHistory = commandHistory,
).execute()
}
override fun open(file: RegularFile, ignoreUnsavedChanged: Boolean) {
log.info { "Opening file [$file] using [ignoreUnsavedChanged=$ignoreUnsavedChanged]" }
if (!ignoreUnsavedChanged) {
check(commandHistory.isSaved()) { "Cannot open file, because there are unsaved changes." }
}
val parsedFile = parser.parse(file)
CmdOpenFile(
state = state,
commandHistory = commandHistory,
parsedFile = parsedFile,
file = file,
).execute()
eventBus.post(FileOpenedEvent(file.fileName.toString()))
}
override fun isOpenFileSet(): Boolean = state.openedFile() is CurrentFile
override fun isSaved(): Boolean = commandHistory.isSaved()
override fun isUnsaved(): Boolean = commandHistory.isUnsaved()
override fun save() {
if (commandHistory.isSaved()) {
return
}
val file = state.openedFile()
check(file is CurrentFile) { "No file set" }
fileWriter.writeTo(file.regularFile)
commandHistory.save()
}
override fun saveAs(file: RegularFile) {
if (!file.regularFileExists()) {
file.createFile()
}
state.setOpenedFile(file)
eventBus.post(SavedAsFileEvent(file.fileName.toString()))
save()
}
override fun isUndoPossible(): Boolean = commandHistory.isUndoPossible()
override fun undo() = commandHistory.undo()
override fun isRedoPossible(): Boolean = commandHistory.isRedoPossible()
override fun redo() = commandHistory.redo()
private companion object {
private val log by LoggerDelegate()
}
} | agpl-3.0 | 0599ef7e5b7e0a3992ba279be0552edb | 33.354839 | 110 | 0.697245 | 4.556348 | false | false | false | false |
nickthecoder/tickle | tickle-editor/src/main/kotlin/uk/co/nickthecoder/tickle/editor/tabs/SceneTab.kt | 1 | 8337 | /*
Tickle
Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.tickle.editor.tabs
import javafx.event.EventHandler
import javafx.geometry.Side
import javafx.scene.control.Button
import javafx.scene.control.TabPane
import javafx.stage.Stage
import uk.co.nickthecoder.paratask.AbstractTask
import uk.co.nickthecoder.paratask.TaskDescription
import uk.co.nickthecoder.paratask.gui.MyTab
import uk.co.nickthecoder.paratask.gui.MyTabPane
import uk.co.nickthecoder.paratask.gui.TaskPrompter
import uk.co.nickthecoder.paratask.parameters.*
import uk.co.nickthecoder.paratask.parameters.fields.TaskForm
import uk.co.nickthecoder.tickle.Director
import uk.co.nickthecoder.tickle.NoDirector
import uk.co.nickthecoder.tickle.editor.MainWindow
import uk.co.nickthecoder.tickle.editor.resources.*
import uk.co.nickthecoder.tickle.editor.scene.SceneEditor
import uk.co.nickthecoder.tickle.editor.util.*
import uk.co.nickthecoder.tickle.resources.Resources
import uk.co.nickthecoder.tickle.resources.SceneResource
import uk.co.nickthecoder.tickle.resources.SceneStub
import uk.co.nickthecoder.tickle.scripts.ScriptManager
import java.io.File
class SceneTab(val sceneName: String, sceneStub: SceneStub)
: EditTab(sceneName, sceneStub, graphicName = "scene.png"),
HasExtras, SceneResourceListener {
val sceneResource = DesignJsonScene(sceneStub.file).sceneResource as DesignSceneResource
private val task = SceneDetailsTask(this, sceneName, sceneResource)
private val taskForm = TaskForm(task)
private val sceneEditor = SceneEditor(sceneResource)
private val minorTabs = MyTabPane<MyTab>()
private val detailsTab = MyTab("Details", taskForm.build())
private val editorTab = MyTab("Scene Editor", sceneEditor.build())
private val copyButton = Button("Copy")
private val renameButton = Button("Rename")
private val deleteButton = Button("Delete")
val sceneFile = sceneStub.file
init {
minorTabs.side = Side.BOTTOM
minorTabs.tabClosingPolicy = TabPane.TabClosingPolicy.UNAVAILABLE
minorTabs.add(detailsTab)
minorTabs.add(editorTab)
borderPane.center = minorTabs
editorTab.isSelected = true
applyButton.text = "Save"
rightButtons.children.remove(okButton)
leftButtons.children.addAll(copyButton, renameButton, deleteButton)
copyButton.onAction = EventHandler { onCopy() }
deleteButton.onAction = EventHandler { onDelete() }
renameButton.onAction = EventHandler { onRename() }
sceneResource.listeners.add(this)
}
override fun actorModified(sceneResource: DesignSceneResource, actorResource: DesignActorResource, type: ModificationType) {
needsSaving = true
}
override fun extraSidePanes() = sceneEditor.sidePanes
override fun extraButtons() = listOf(sceneEditor.editSnapsButton,
sceneEditor.toggleGridButton, sceneEditor.toggleGuidesButton, sceneEditor.toggleSnapToOThersButton, sceneEditor.toggleSnapRotationButton,
sceneEditor.layers.stageButton)
override fun extraShortcuts() = sceneEditor.shortcuts
override fun justSave(): Boolean {
if (taskForm.check()) {
task.run()
DesignJsonScene(sceneResource).save(sceneResource.file!!)
return true
}
return false
}
fun onCopy() {
TaskPrompter(CopySceneTask()).placeOnStage(Stage())
}
fun onDelete() {
val task = DeleteSceneTask(sceneFile)
task.taskRunner.listen { cancelled ->
if (!cancelled) {
close()
}
}
TaskPrompter(task).placeOnStage(Stage())
}
fun onRename() {
val task = RenameSceneTask(sceneFile)
task.taskRunner.listen { cancelled ->
if (!cancelled) {
close()
sceneResource.file = task.newFile()
MainWindow.instance.openTab(task.newNameP.value, sceneResource)
}
}
TaskPrompter(task).placeOnStage(Stage())
}
override fun removed() {
super.removed()
sceneEditor.cleanUp()
}
fun selectCostumeName(costumeName: String) {
sceneEditor.selectCostumeName(costumeName)
}
inner class CopySceneTask : AbstractTask(threaded = false) {
val newNameP = StringParameter("newName")
val directoryP = FileParameter("directory", mustExist = true, expectFile = false, value = sceneResource.file?.parentFile)
override val taskD = TaskDescription("copyScene")
.addParameters(newNameP, directoryP)
override fun run() {
val newFile = File(directoryP.value!!, "${newNameP.value}.scene")
sceneResource.file!!.copyTo(newFile)
Resources.instance.fireAdded(newFile, newFile.nameWithoutExtension)
}
}
}
class SceneDetailsTask(val sceneTab: SceneTab, val name: String, val sceneResource: SceneResource) : AbstractTask() {
val directorP = ClassParameter("director", Director::class.java, required = false, value = NoDirector::class.java)
val backgroundColorP = ColorParameter("backgroundColor")
val showMouseP = BooleanParameter("showMouse")
val layoutP = ChoiceParameter<String>("layout", value = "")
val infoP = InformationParameter("info",
information = "The Director has no fields with the '@Attribute' annotation, and therefore, this scene has no attributes.")
val includesP = MultipleParameter("includes") {
StringParameter("include")
}
val attributesP = SimpleGroupParameter("attributes")
override val taskD = TaskDescription("sceneDetails")
.addParameters(directorP, backgroundColorP, showMouseP, layoutP, includesP, attributesP)
init {
Resources.instance.layouts.items().forEach { name, _ ->
layoutP.choice(name, name, name)
}
try {
directorP.classValue = ScriptManager.classForName(sceneResource.directorString)
} catch (e: Exception) {
//
}
with(sceneResource) {
backgroundColorP.value = background.toJavaFX()
showMouseP.value = showMouse
layoutP.value = layoutName
includes.forEach { file ->
includesP.addValue(Resources.instance.sceneFileToPath(file))
}
}
updateAttributes()
directorP.listen {
updateAttributes()
}
taskD.root.listen { sceneTab.needsSaving = true }
}
override fun run() {
with(sceneResource) {
directorString = directorP.classValue!!.name
layoutName = layoutP.value!!
showMouse = showMouseP.value == true
background = backgroundColorP.value.toTickle()
includes.clear()
includesP.value.forEach { str ->
includes.add(File(str))
}
}
}
fun updateAttributes() {
sceneResource.directorAttributes.updateAttributesMetaData(directorP.classValue!!)
attributesP.children.toList().forEach {
attributesP.remove(it)
}
sceneResource.directorAttributes.data().forEach { data ->
data as DesignAttributeData
data.parameter?.let { it ->
val parameter = it.copyBounded()
attributesP.add(parameter)
try {
parameter.stringValue = data.value ?: ""
} catch (e: Exception) {
// Do nothing
}
}
}
if (attributesP.children.size == 0) {
attributesP.add(infoP)
}
}
}
| gpl-3.0 | 4fe0e91e727df27ccbec0e6359592b23 | 31.694118 | 149 | 0.668946 | 4.548282 | false | false | false | false |
ujpv/intellij-rust | src/main/kotlin/org/rust/ide/icons/RustIcons.kt | 1 | 2774 | package org.rust.ide.icons
import com.intellij.icons.AllIcons
import com.intellij.openapi.util.IconLoader
import com.intellij.ui.LayeredIcon
import com.intellij.ui.RowIcon
import com.intellij.util.PlatformIcons
import javax.swing.Icon
/**
* Icons that are used by various plugin components.
*
* The order of properties matters in this class. When conflating an icon from simple elements,
* make sure that all those elements are declared above to the icon.
*/
object RustIcons {
// Logos
val RUST = IconLoader.getIcon("/icons/rust.png")
val RUST_BIG = IconLoader.getIcon("/icons/rust-big.png")
// File types
val RUST_FILE = IconLoader.getIcon("/icons/rust-file.png")
// Marks
val FINAL_MARK = AllIcons.Nodes.FinalMark!!
val STATIC_MARK = AllIcons.Nodes.StaticMark!!
val TEST_MARK = AllIcons.Nodes.JunitTestMark!!
// Source code elements
val MODULE = AllIcons.Nodes.Package!!
val TRAIT = AllIcons.Nodes.Interface!!
val STRUCT = AllIcons.Nodes.Class!!
val TYPE = AllIcons.Nodes.Class!!
val IMPL = AllIcons.Nodes.AbstractClass!!
val ENUM = AllIcons.Nodes.Enum!!
val METHOD = AllIcons.Nodes.Method!!
val FUNCTION = IconLoader.getIcon("/icons/nodes/function.png")
val ASSOC_FUNCTION = FUNCTION.addStaticMark()
val ABSTRACT_METHOD = AllIcons.Nodes.AbstractMethod!!
val ABSTRACT_FUNCTION = IconLoader.getIcon("/icons/nodes/abstractFunction.png")
val ABSTRACT_ASSOC_FUNCTION = ABSTRACT_FUNCTION.addStaticMark()
val MUT_ARGUMENT = AllIcons.Nodes.Parameter!!
val ARGUMENT = MUT_ARGUMENT.addFinalMark()
val FIELD = AllIcons.Nodes.Field!!
val MUT_BINDING = AllIcons.Nodes.Variable!!
val BINDING = MUT_BINDING.addFinalMark()
val GLOBAL_BINDING = IconLoader.getIcon("/icons/nodes/globalBinding.png")
val CONSTANT = GLOBAL_BINDING.addFinalMark()
val MUT_STATIC = GLOBAL_BINDING.addStaticMark()
val STATIC = MUT_STATIC.addFinalMark()
val ENUM_VARIANT = FIELD.addFinalMark().addStaticMark()
// Gutter
val IMPLEMENTED = AllIcons.Gutter.ImplementedMethod!!
val IMPLEMENTING_METHOD = AllIcons.Gutter.ImplementingMethod!!
val OVERRIDING_METHOD = AllIcons.Gutter.OverridingMethod!!
val RECURSIVE_CALL = AllIcons.Gutter.RecursiveMethod!!
}
fun Icon.addFinalMark(): Icon = LayeredIcon(this, RustIcons.FINAL_MARK)
fun Icon.addStaticMark(): Icon = LayeredIcon(this, RustIcons.STATIC_MARK)
fun Icon.addTestMark(): Icon = LayeredIcon(this, RustIcons.TEST_MARK)
fun Icon.addVisibilityIcon(pub: Boolean): RowIcon =
RowIcon(this, if (pub) PlatformIcons.PUBLIC_ICON else PlatformIcons.PRIVATE_ICON)
| mit | 9f7c47d93c2c35c51897d6b60bfec988 | 35.5 | 95 | 0.69863 | 3.940341 | false | true | false | false |
LorittaBot/Loritta | pudding/client/src/main/kotlin/net/perfectdreams/loritta/cinnamon/pudding/tables/notifications/DailyTaxTaxedUserNotifications.kt | 1 | 710 | package net.perfectdreams.loritta.cinnamon.pudding.tables.notifications
import net.perfectdreams.exposedpowerutils.sql.javatime.timestampWithTimeZone
import org.jetbrains.exposed.dao.id.LongIdTable
object DailyTaxTaxedUserNotifications : LongIdTable() {
val timestampLog = reference("timestamp_log", UserNotifications).index()
val nextInactivityTaxTimeWillBeTriggeredAt = timestampWithTimeZone("next_inactivity_tax_time_will_be_triggered_at")
val currentSonhos = long("current_sonhos")
val howMuchWasRemoved = long("how_much_was_removed")
val maxDayThreshold = integer("max_day_threshold")
val minimumSonhosForTrigger = long("minimum_sonhos_for_trigger")
val tax = double("tax")
} | agpl-3.0 | f158c69fd8162504e5fb90887c769742 | 49.785714 | 119 | 0.792958 | 4.011299 | false | false | false | false |
TimePath/commons | src/main/kotlin/com/timepath/util/Cache.kt | 1 | 1297 | package com.timepath.util
public open class Cache<K : Any, V : Any>(
private val delegate: MutableMap<K, V> = hashMapOf(),
fill: (K) -> V? = { null }
) : MutableMap<K, V> by delegate {
public val backingMap: Map<K, V> get() = delegate
private val f = fill
/**
* Called in response to accessing an undefined key. Gives an opportunity to lazily initialize.
*
* @param key the key
* @return the value to fill
*/
protected open fun fill(key: K): V? = f(key)
/**
* Called in response to accessing a key to check if it has expired. The default implementation never expires.
*
* @param key the key
* @param value the current value
* @return null if the key has expired. If the value really is null, return it from [fill].
*/
protected open fun expire(key: K, value: V?): V? = value
override fun containsKey(key: K) = get(key) != null
@Synchronized override fun get(key: K): V? {
val got = delegate[key]
val expire = expire(key, got)
if (expire != null) return got
val fill = fill(key)
if (fill != null) {
delegate[key] = fill
return fill
} else {
delegate.remove(key)
return null
}
}
}
| artistic-2.0 | 938eee0f80c0060d624eae28618d4430 | 28.477273 | 114 | 0.576715 | 3.954268 | false | false | false | false |
spaceisstrange/ToListen | ToListen/app/src/main/java/io/spaceisstrange/tolisten/ui/fragments/artists/ArtistsFragment.kt | 1 | 2955 | /*
* Made with <3 by Fran González (@spaceisstrange)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package io.spaceisstrange.tolisten.ui.fragments.artists
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import io.realm.Realm
import io.realm.RealmChangeListener
import io.spaceisstrange.tolisten.R
import io.spaceisstrange.tolisten.data.database.Database
import io.spaceisstrange.tolisten.data.model.Artist
import io.spaceisstrange.tolisten.ui.adapters.ArtistsAdapter
import kotlinx.android.synthetic.main.fragment_base_list.*
/**
* Fragment showing the list of artists stored
*/
class ArtistsFragment : Fragment() {
/**
* Adapter used in the list
*/
var artistAdapter: ArtistsAdapter = ArtistsAdapter()
/**
* Listener of the Realm database
*/
lateinit var realmListener: RealmChangeListener<Realm>
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_base_list, container, false)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Setup the ReyclerView
artistAdapter.onClick = { artist ->
// TODO: Do something with the artist
}
savedList.adapter = artistAdapter
savedList.layoutManager = LinearLayoutManager(context)
// Load the data from the database
artistAdapter.updateArtists(loadData())
// Add a listener to the database so we update the data whenever we add new things
realmListener = RealmChangeListener { realm ->
artistAdapter.updateArtists(loadData())
}
Realm.getDefaultInstance().addChangeListener(realmListener)
}
override fun onDestroy() {
super.onDestroy()
// Remove the Realm listener
Realm.getDefaultInstance().removeChangeListener(realmListener)
}
/**
* Loads and returns the data from the database
*/
fun loadData(): List<Artist> {
return Database.getArtists()
}
} | gpl-3.0 | ce502d2c0ff518cf07b4663928ca4cb4 | 32.579545 | 116 | 0.720041 | 4.448795 | false | false | false | false |
danrien/projectBlue | projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/connection/selected/SelectedConnectionSettingsChangeReceiver.kt | 2 | 1315 | package com.lasthopesoftware.bluewater.client.connection.selected
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.lasthopesoftware.bluewater.client.browsing.library.access.session.ProvideSelectedLibraryId
import com.lasthopesoftware.bluewater.client.connection.settings.changes.ObservableConnectionSettingsLibraryStorage
import com.lasthopesoftware.bluewater.shared.MagicPropertyBuilder
import com.lasthopesoftware.bluewater.shared.android.messages.SendMessages
class SelectedConnectionSettingsChangeReceiver(
private val selectedLibraryIdProvider: ProvideSelectedLibraryId,
private val sendMessages: SendMessages
) : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
val updatedLibraryId =
intent?.getIntExtra(ObservableConnectionSettingsLibraryStorage.updatedConnectionSettingsLibraryId, -1)
?: return
selectedLibraryIdProvider.selectedLibraryId.then { l ->
if (l?.id == updatedLibraryId) sendMessages.sendBroadcast(Intent(connectionSettingsUpdated))
}
}
companion object {
private val magicPropertyBuilder = MagicPropertyBuilder(SelectedConnectionSettingsChangeReceiver::class.java)
val connectionSettingsUpdated = magicPropertyBuilder.buildProperty("connectionSettingsUpdated")
}
}
| lgpl-3.0 | 733b3c928485fa43fd3c215d88edfda9 | 42.833333 | 115 | 0.850951 | 4.925094 | false | false | false | false |
daring2/fms | zabbix/core/src/test/kotlin/com/gitlab/daring/fms/zabbix/sender/SendRequestTest.kt | 1 | 1701 | package com.gitlab.daring.fms.zabbix.sender
import com.fasterxml.jackson.databind.JsonNode
import com.gitlab.daring.fms.common.json.JsonUtils.JsonMapper
import com.gitlab.daring.fms.common.json.toMap
import com.gitlab.daring.fms.zabbix.model.ItemValue
import org.junit.Assert.assertEquals
import org.junit.Test
import java.time.Instant.ofEpochMilli
class SendRequestTest {
@Test
fun testBuildJson() {
val vs1 = listOf(
ItemValue("h1", "k1", "v1"),
ItemValue("h2", "k2", "").withError("v2")
)
val req1 = SendRequest(vs1, ofEpochMilli(1002))
val d1 = "data: [" +
"{host: 'h1', key: 'k1', value: 'v1', state: 0}," +
"{host: 'h2', key: 'k2', value: 'v2', state: 1}" +
"]"
val n1 = "{request: 'sender data', $d1, clock: 1, ns: 2000000}"
assertJsonEquals(n1, req1.buildJson())
val req2 = req1.copy(proxy = "p1")
val n2 = "{request: 'history data', host: 'p1', $d1, clock: 1, ns: 2000000}"
assertJsonEquals(n2, req2.buildJson())
}
fun assertJsonEquals(exp: String, n: JsonNode) {
val expNode = JsonMapper.readTree(exp)
assertEquals("" + expNode, "" + n)
}
@Test
fun testBuildValueJson() {
val req = SendRequest(emptyList())
val v1 = ItemValue("h1", "k1", "v1")
val m1 = hashMapOf("host" to "h1", "key" to "k1", "value" to "v1", "state" to 0)
assertEquals(m1, req.buildValueJson(v1, 4).toMap())
val v2 = v1.withTime(ofEpochMilli(2003))
val m2 = m1 + listOf("clock" to 2L, "ns" to 3000004)
assertEquals(m2, req.buildValueJson(v2, 4).toMap())
}
} | apache-2.0 | f3fa0b9e38c756f16d052a8f9c4f212f | 33.734694 | 88 | 0.586714 | 3.23384 | false | true | false | false |
wireapp/wire-android | app/src/test/kotlin/com/waz/zclient/core/backend/mapper/BackendMapperTest.kt | 1 | 3685 | package com.waz.zclient.core.backend.mapper
import com.waz.zclient.UnitTest
import com.waz.zclient.core.backend.BackendItem
import com.waz.zclient.core.backend.datasources.local.CustomBackendPrefEndpoints
import com.waz.zclient.core.backend.datasources.local.CustomBackendPreferences
import com.waz.zclient.core.backend.datasources.remote.CustomBackendResponse
import com.waz.zclient.core.backend.datasources.remote.CustomBackendResponseEndpoints
import org.amshove.kluent.shouldBe
import org.junit.Before
import org.junit.Test
class BackendMapperTest : UnitTest() {
private lateinit var backendMapper: BackendMapper
@Before
fun setUp() {
backendMapper = BackendMapper()
}
@Test
fun `given a backend api response, map it to backend item`() {
val backendItem = backendMapper.toBackendItem(customBackendResponse)
assertBackendItemValues(backendItem)
}
@Test
fun `given a backend pref response, map it to backend item`() {
val backendItem = backendMapper.toBackendItem(customPrefBackend)
assertBackendItemValues(backendItem)
}
private fun assertBackendItemValues(item: BackendItem) = with(item) {
environment shouldBe TITLE
baseUrl shouldBe BACKEND_URL
websocketUrl shouldBe BACKEND_WSURL
blacklistHost shouldBe BLACKLIST_URL
teamsUrl shouldBe TEAMS_URL
accountsUrl shouldBe ACCOUNTS_URL
websiteUrl shouldBe WEBSITE_URL
}
@Test
fun `given custom backend response, map it to custom backend pref`() {
val customPrefBackend = backendMapper.toPreference(backendItem)
with(customPrefBackend) {
title shouldBe TITLE
with(prefEndpoints) {
backendUrl shouldBe BACKEND_URL
websocketUrl shouldBe BACKEND_WSURL
blacklistUrl shouldBe BLACKLIST_URL
teamsUrl shouldBe TEAMS_URL
accountsUrl shouldBe ACCOUNTS_URL
websiteUrl shouldBe WEBSITE_URL
}
}
}
companion object {
private const val ACCOUNTS_URL = "https://accounts.wire.com"
private const val TITLE = "custom.environment.link.wire.com"
private const val BACKEND_URL = "https://www.wire.com"
private const val BACKEND_WSURL = "https://www.wire.com"
private const val BLACKLIST_URL = "https://blacklist.wire.com"
private const val TEAMS_URL = "https://teams.wire.com"
private const val WEBSITE_URL = "https://wire.com"
private val backendItem = BackendItem(
environment = TITLE,
baseUrl = BACKEND_URL,
websocketUrl = BACKEND_WSURL,
blacklistHost = BLACKLIST_URL,
teamsUrl = TEAMS_URL,
accountsUrl = ACCOUNTS_URL,
websiteUrl = WEBSITE_URL
)
private val customPrefBackend = CustomBackendPreferences(
TITLE,
CustomBackendPrefEndpoints(
backendUrl = BACKEND_URL,
websocketUrl = BACKEND_WSURL,
blacklistUrl = BLACKLIST_URL,
teamsUrl = TEAMS_URL,
accountsUrl = ACCOUNTS_URL,
websiteUrl = WEBSITE_URL
)
)
private val customBackendResponse = CustomBackendResponse(
TITLE,
CustomBackendResponseEndpoints(
backendUrl = BACKEND_URL,
backendWsUrl = BACKEND_WSURL,
blacklistUrl = BLACKLIST_URL,
teamsUrl = TEAMS_URL,
accountsUrl = ACCOUNTS_URL,
websiteUrl = WEBSITE_URL
)
)
}
}
| gpl-3.0 | ba2d1893ae861514d96fbcae308ca11a | 34.776699 | 85 | 0.641248 | 4.835958 | false | true | false | false |
robinverduijn/gradle | subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/accessors/AccessorsClassPath.kt | 1 | 17920 | /*
* Copyright 2017 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.
*/
package org.gradle.kotlin.dsl.accessors
import org.gradle.api.Project
import org.gradle.api.internal.project.ProjectInternal
import org.gradle.cache.internal.CacheKeyBuilder.CacheKeySpec
import org.gradle.internal.classanalysis.AsmConstants.ASM_LEVEL
import org.gradle.internal.classpath.ClassPath
import org.gradle.internal.classpath.DefaultClassPath
import org.gradle.internal.hash.HashCode
import org.gradle.internal.hash.Hasher
import org.gradle.internal.hash.Hashing
import org.gradle.kotlin.dsl.cache.ScriptCache
import org.gradle.kotlin.dsl.codegen.fileHeaderFor
import org.gradle.kotlin.dsl.codegen.kotlinDslPackageName
import org.gradle.kotlin.dsl.concurrent.IO
import org.gradle.kotlin.dsl.concurrent.withAsynchronousIO
import org.gradle.kotlin.dsl.support.ClassBytesRepository
import org.gradle.kotlin.dsl.support.appendReproducibleNewLine
import org.gradle.kotlin.dsl.support.serviceOf
import org.gradle.kotlin.dsl.support.useToRun
import org.jetbrains.kotlin.metadata.ProtoBuf
import org.jetbrains.kotlin.metadata.ProtoBuf.Visibility
import org.jetbrains.kotlin.metadata.deserialization.Flags
import org.jetbrains.kotlin.metadata.jvm.deserialization.JvmProtoBufUtil
import org.jetbrains.org.objectweb.asm.AnnotationVisitor
import org.jetbrains.org.objectweb.asm.ClassReader
import org.jetbrains.org.objectweb.asm.ClassVisitor
import org.jetbrains.org.objectweb.asm.Opcodes.ACC_PUBLIC
import org.jetbrains.org.objectweb.asm.Opcodes.ACC_SYNTHETIC
import org.jetbrains.org.objectweb.asm.signature.SignatureReader
import org.jetbrains.org.objectweb.asm.signature.SignatureVisitor
import java.io.Closeable
import java.io.File
fun projectAccessorsClassPath(project: Project, classPath: ClassPath): AccessorsClassPath =
project.getOrCreateProperty("gradleKotlinDsl.projectAccessorsClassPath") {
buildAccessorsClassPathFor(project, classPath)
?: AccessorsClassPath.empty
}
private
fun buildAccessorsClassPathFor(project: Project, classPath: ClassPath) =
configuredProjectSchemaOf(project)?.let { projectSchema ->
// TODO:accessors make cache key computation more efficient
cachedAccessorsClassPathFor(project, cacheKeyFor(projectSchema, classPath)) { srcDir, binDir ->
withAsynchronousIO(project) {
buildAccessorsFor(
projectSchema,
classPath,
srcDir = srcDir,
binDir = binDir
)
}
}
}
data class AccessorsClassPath(val bin: ClassPath, val src: ClassPath) {
companion object {
val empty = AccessorsClassPath(ClassPath.EMPTY, ClassPath.EMPTY)
}
operator fun plus(other: AccessorsClassPath) =
AccessorsClassPath(bin + other.bin, src + other.src)
}
internal
fun cachedAccessorsClassPathFor(
project: Project,
cacheKeySpec: CacheKeySpec,
builder: (File, File) -> Unit
): AccessorsClassPath {
val cacheDir =
scriptCacheOf(project)
.cacheDirFor(cacheKeySpec) { baseDir ->
builder(
accessorsSourceDir(baseDir),
accessorsClassesDir(baseDir)
)
}
return AccessorsClassPath(
DefaultClassPath.of(accessorsClassesDir(cacheDir)),
DefaultClassPath.of(accessorsSourceDir(cacheDir))
)
}
private
fun accessorsSourceDir(baseDir: File) = baseDir.resolve("src")
private
fun accessorsClassesDir(baseDir: File) = baseDir.resolve("classes")
private
fun configuredProjectSchemaOf(project: Project): TypedProjectSchema? =
if (enabledJitAccessors(project)) {
require(classLoaderScopeOf(project).isLocked) {
"project.classLoaderScope must be locked before querying the project schema"
}
schemaFor(project).takeIf { it.isNotEmpty() }
} else null
fun schemaFor(project: Project): TypedProjectSchema =
projectSchemaProviderOf(project).schemaFor(project)
private
fun projectSchemaProviderOf(project: Project) =
project.serviceOf<ProjectSchemaProvider>()
private
fun scriptCacheOf(project: Project) = project.serviceOf<ScriptCache>()
fun IO.buildAccessorsFor(
projectSchema: TypedProjectSchema,
classPath: ClassPath,
srcDir: File,
binDir: File?,
packageName: String = kotlinDslPackageName,
format: AccessorFormat = AccessorFormats.default
) {
val availableSchema = availableProjectSchemaFor(projectSchema, classPath)
emitAccessorsFor(
availableSchema,
srcDir,
binDir,
OutputPackage(packageName),
format
)
}
typealias AccessorFormat = (String) -> String
object AccessorFormats {
val default: AccessorFormat = { accessor ->
accessor.replaceIndent()
}
val `internal`: AccessorFormat = { accessor ->
accessor
.replaceIndent()
.let { valFunOrClass.matcher(it) }
.replaceAll("internal\n$1 ")
}
private
val valFunOrClass by lazy {
"^(val|fun|class) ".toRegex(RegexOption.MULTILINE).toPattern()
}
}
internal
fun importsRequiredBy(candidateTypes: List<TypeAccessibility>): List<String> =
defaultPackageTypesIn(
candidateTypes
.filterIsInstance<TypeAccessibility.Accessible>()
.map { it.type.kotlinString }
)
internal
fun defaultPackageTypesIn(typeStrings: List<String>): List<String> =
typeStrings
.flatMap { classNamesFromTypeString(it).all }
.filter { '.' !in it }
.distinct()
internal
fun availableProjectSchemaFor(projectSchema: TypedProjectSchema, classPath: ClassPath) =
TypeAccessibilityProvider(classPath).use { accessibilityProvider ->
projectSchema.map(accessibilityProvider::accessibilityForType)
}
sealed class TypeAccessibility {
data class Accessible(val type: SchemaType) : TypeAccessibility()
data class Inaccessible(val type: SchemaType, val reasons: List<InaccessibilityReason>) : TypeAccessibility()
}
sealed class InaccessibilityReason {
data class NonPublic(val type: String) : InaccessibilityReason()
data class NonAvailable(val type: String) : InaccessibilityReason()
data class Synthetic(val type: String) : InaccessibilityReason()
data class TypeErasure(val type: String) : InaccessibilityReason()
val explanation
get() = when (this) {
is NonPublic -> "`$type` is not public"
is NonAvailable -> "`$type` is not available"
is Synthetic -> "`$type` is synthetic"
is TypeErasure -> "`$type` parameter types are missing"
}
}
private
data class TypeAccessibilityInfo(
val inaccessibilityReasons: List<InaccessibilityReason>,
val hasTypeParameter: Boolean = false
)
internal
class TypeAccessibilityProvider(classPath: ClassPath) : Closeable {
private
val classBytesRepository = ClassBytesRepository(classPath)
private
val typeAccessibilityInfoPerClass = mutableMapOf<String, TypeAccessibilityInfo>()
fun accessibilityForType(type: SchemaType): TypeAccessibility =
// TODO:accessors cache per SchemaType
inaccessibilityReasonsFor(classNamesFromTypeString(type)).let { inaccessibilityReasons ->
if (inaccessibilityReasons.isNotEmpty()) inaccessible(type, inaccessibilityReasons)
else accessible(type)
}
private
fun inaccessibilityReasonsFor(classNames: ClassNamesFromTypeString): List<InaccessibilityReason> =
classNames.all.flatMap { inaccessibilityReasonsFor(it) }.let { inaccessibilityReasons ->
if (inaccessibilityReasons.isNotEmpty()) inaccessibilityReasons
else classNames.leaves.filter(::hasTypeParameter).map(::typeErasure)
}
private
fun inaccessibilityReasonsFor(className: String): List<InaccessibilityReason> =
accessibilityInfoFor(className).inaccessibilityReasons
private
fun hasTypeParameter(className: String) =
accessibilityInfoFor(className).hasTypeParameter
private
fun accessibilityInfoFor(className: String): TypeAccessibilityInfo =
typeAccessibilityInfoPerClass.computeIfAbsent(className) {
loadAccessibilityInfoFor(it)
}
private
fun loadAccessibilityInfoFor(className: String): TypeAccessibilityInfo {
val classBytes = classBytesRepository.classBytesFor(className)
?: return TypeAccessibilityInfo(listOf(nonAvailable(className)))
val classReader = ClassReader(classBytes)
val access = classReader.access
return TypeAccessibilityInfo(
listOfNotNull(
when {
ACC_PUBLIC !in access -> nonPublic(className)
ACC_SYNTHETIC in access -> synthetic(className)
isNonPublicKotlinType(classReader) -> nonPublic(className)
else -> null
}),
hasTypeParameters(classReader)
)
}
private
fun isNonPublicKotlinType(classReader: ClassReader) =
kotlinVisibilityFor(classReader)?.let { it != Visibility.PUBLIC } ?: false
private
fun kotlinVisibilityFor(classReader: ClassReader) =
classReader(KotlinVisibilityClassVisitor()).visibility
private
fun hasTypeParameters(classReader: ClassReader): Boolean =
classReader(HasTypeParameterClassVisitor()).hasTypeParameters
private
operator fun <T : ClassVisitor> ClassReader.invoke(visitor: T): T =
visitor.also {
accept(it, ClassReader.SKIP_CODE + ClassReader.SKIP_DEBUG + ClassReader.SKIP_FRAMES)
}
override fun close() {
classBytesRepository.close()
}
}
internal
class ClassNamesFromTypeString(
val all: List<String>,
val leaves: List<String>
)
internal
fun classNamesFromTypeString(type: SchemaType): ClassNamesFromTypeString =
classNamesFromTypeString(type.kotlinString)
internal
fun classNamesFromTypeString(typeString: String): ClassNamesFromTypeString {
val all = mutableListOf<String>()
val leafs = mutableListOf<String>()
var buffer = StringBuilder()
fun nonPrimitiveKotlinType(): String? =
if (buffer.isEmpty()) null
else buffer.toString().let {
if (it in primitiveKotlinTypeNames) null
else it
}
typeString.forEach { char ->
when (char) {
'<' -> {
nonPrimitiveKotlinType()?.also { all.add(it) }
buffer = StringBuilder()
}
in " ,>" -> {
nonPrimitiveKotlinType()?.also {
all.add(it)
leafs.add(it)
}
buffer = StringBuilder()
}
else -> buffer.append(char)
}
}
nonPrimitiveKotlinType()?.also {
all.add(it)
leafs.add(it)
}
return ClassNamesFromTypeString(all, leafs)
}
private
class HasTypeParameterClassVisitor : ClassVisitor(ASM_LEVEL) {
var hasTypeParameters = false
override fun visit(version: Int, access: Int, name: String, signature: String?, superName: String?, interfaces: Array<out String>?) {
if (signature != null) {
SignatureReader(signature).accept(object : SignatureVisitor(ASM_LEVEL) {
override fun visitFormalTypeParameter(name: String) {
hasTypeParameters = true
}
})
}
}
}
private
class KotlinVisibilityClassVisitor : ClassVisitor(ASM_LEVEL) {
var visibility: Visibility? = null
override fun visitAnnotation(desc: String?, visible: Boolean): AnnotationVisitor? =
when (desc) {
"Lkotlin/Metadata;" -> ClassDataFromKotlinMetadataAnnotationVisitor { classData ->
visibility = Flags.VISIBILITY[classData.flags]
}
else -> null
}
}
/**
* Reads the serialized [ProtoBuf.Class] information stored in the visited [kotlin.Metadata] annotation.
*/
private
class ClassDataFromKotlinMetadataAnnotationVisitor(
private val onClassData: (ProtoBuf.Class) -> Unit
) : AnnotationVisitor(ASM_LEVEL) {
/**
* @see kotlin.Metadata.data1
*/
private
var d1 = mutableListOf<String>()
/**
* @see kotlin.Metadata.data2
*/
private
var d2 = mutableListOf<String>()
override fun visitArray(name: String?): AnnotationVisitor? =
when (name) {
"d1" -> AnnotationValueCollector(d1)
"d2" -> AnnotationValueCollector(d2)
else -> null
}
override fun visitEnd() {
val (_, classData) = JvmProtoBufUtil.readClassDataFrom(d1.toTypedArray(), d2.toTypedArray())
onClassData(classData)
super.visitEnd()
}
}
private
class AnnotationValueCollector<T>(val output: MutableList<T>) : AnnotationVisitor(ASM_LEVEL) {
override fun visit(name: String?, value: Any?) {
@Suppress("unchecked_cast")
output.add(value as T)
}
}
internal
operator fun Int.contains(flag: Int) =
and(flag) == flag
internal
fun nonAvailable(type: String): InaccessibilityReason =
InaccessibilityReason.NonAvailable(type)
internal
fun nonPublic(type: String): InaccessibilityReason =
InaccessibilityReason.NonPublic(type)
internal
fun synthetic(type: String): InaccessibilityReason =
InaccessibilityReason.Synthetic(type)
internal
fun typeErasure(type: String): InaccessibilityReason =
InaccessibilityReason.TypeErasure(type)
internal
fun accessible(type: SchemaType): TypeAccessibility =
TypeAccessibility.Accessible(type)
internal
fun inaccessible(type: SchemaType, vararg reasons: InaccessibilityReason) =
inaccessible(type, reasons.toList())
internal
fun inaccessible(type: SchemaType, reasons: List<InaccessibilityReason>): TypeAccessibility =
TypeAccessibility.Inaccessible(type, reasons)
private
fun classLoaderScopeOf(project: Project) =
(project as ProjectInternal).classLoaderScope
internal
val accessorsCacheKeyPrefix = CacheKeySpec.withPrefix("gradle-kotlin-dsl-accessors")
private
fun cacheKeyFor(projectSchema: TypedProjectSchema, classPath: ClassPath): CacheKeySpec =
(accessorsCacheKeyPrefix
+ hashCodeFor(projectSchema)
+ classPath)
fun hashCodeFor(schema: TypedProjectSchema): HashCode = Hashing.newHasher().run {
putAll(schema.extensions)
putAll(schema.conventions)
putAll(schema.tasks)
putAll(schema.containerElements)
putAllSorted(schema.configurations)
hash()
}
private
fun Hasher.putAllSorted(strings: List<String>) {
putInt(strings.size)
strings.sorted().forEach(::putString)
}
private
fun Hasher.putAll(entries: List<ProjectSchemaEntry<SchemaType>>) {
putInt(entries.size)
entries.forEach { entry ->
putString(entry.target.kotlinString)
putString(entry.name)
putString(entry.type.kotlinString)
}
}
private
fun enabledJitAccessors(project: Project) =
project.findProperty("org.gradle.kotlin.dsl.accessors")?.let {
it != "false" && it != "off"
} ?: true
internal
fun IO.writeAccessorsTo(
outputFile: File,
accessors: Iterable<String>,
imports: List<String> = emptyList(),
packageName: String = kotlinDslPackageName
) = io {
outputFile.bufferedWriter().useToRun {
appendReproducibleNewLine(fileHeaderWithImportsFor(packageName))
if (imports.isNotEmpty()) {
imports.forEach {
appendReproducibleNewLine("import $it")
}
appendReproducibleNewLine()
}
accessors.forEach {
appendReproducibleNewLine(it)
appendReproducibleNewLine()
}
}
}
internal
fun fileHeaderWithImportsFor(accessorsPackage: String = kotlinDslPackageName) = """
${fileHeaderFor(accessorsPackage)}
import org.gradle.api.Action
import org.gradle.api.Incubating
import org.gradle.api.NamedDomainObjectProvider
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.artifacts.Configuration
import org.gradle.api.artifacts.ConfigurablePublishArtifact
import org.gradle.api.artifacts.ConfigurationContainer
import org.gradle.api.artifacts.Dependency
import org.gradle.api.artifacts.DependencyConstraint
import org.gradle.api.artifacts.ExternalModuleDependency
import org.gradle.api.artifacts.ModuleDependency
import org.gradle.api.artifacts.PublishArtifact
import org.gradle.api.artifacts.dsl.ArtifactHandler
import org.gradle.api.artifacts.dsl.DependencyConstraintHandler
import org.gradle.api.artifacts.dsl.DependencyHandler
import org.gradle.api.tasks.TaskContainer
import org.gradle.api.tasks.TaskProvider
import org.gradle.kotlin.dsl.*
import org.gradle.kotlin.dsl.accessors.runtime.*
"""
/**
* Location of the discontinued project schema snapshot, relative to the root project.
*/
const val projectSchemaResourcePath =
"gradle/project-schema.json"
const val projectSchemaResourceDiscontinuedWarning =
"Support for $projectSchemaResourcePath was removed in Gradle 5.0. The file is no longer used and it can be safely deleted."
fun Project.warnAboutDiscontinuedJsonProjectSchema() {
if (file(projectSchemaResourcePath).isFile) {
logger.warn(projectSchemaResourceDiscontinuedWarning)
}
}
| apache-2.0 | f66c2c71ae20aae892fdc1873c3dca64 | 28.377049 | 137 | 0.704799 | 4.562118 | false | false | false | false |
anton-okolelov/intellij-rust | src/main/kotlin/org/rust/lang/core/types/Extensions.kt | 1 | 3357 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.types
import com.intellij.openapi.util.Computable
import com.intellij.psi.PsiElement
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.psi.util.PsiModificationTracker
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.*
import org.rust.lang.core.types.infer.RsInferenceResult
import org.rust.lang.core.types.infer.inferTypeReferenceType
import org.rust.lang.core.types.infer.inferTypesIn
import org.rust.lang.core.types.ty.Ty
import org.rust.lang.core.types.ty.TyReference
import org.rust.lang.core.types.ty.TyTypeParameter
import org.rust.lang.core.types.ty.TyUnknown
import org.rust.openapiext.recursionGuard
val RsTypeReference.type: Ty
get() = recursionGuard(this, Computable { inferTypeReferenceType(this) })
?: TyUnknown
val RsTypeElement.lifetimeElidable: Boolean get() {
val typeOwner = owner.parent
return typeOwner !is RsFieldDecl && typeOwner !is RsTupleFieldDecl && typeOwner !is RsTypeAlias
}
val RsInferenceContextOwner.inference: RsInferenceResult
get() = CachedValuesManager.getCachedValue(this, {
CachedValueProvider.Result.create(inferTypesIn(this), PsiModificationTracker.MODIFICATION_COUNT)
})
val PsiElement.inference: RsInferenceResult?
get() = ancestorOrSelf<RsInferenceContextOwner>()?.inference
val RsPatBinding.type: Ty
get() = inference?.getBindingType(this) ?: TyUnknown
val RsExpr.type: Ty
get() = inference?.getExprType(this) ?: TyUnknown
val RsExpr.declaration: RsElement?
get() = when (this) {
is RsPathExpr -> path.reference.resolve()
is RsCallExpr -> expr.declaration
is RsStructLiteral -> path.reference.resolve()
else -> null
}
val RsTraitOrImpl.selfType: Ty get() {
return when (this) {
is RsImplItem -> typeReference?.type ?: return TyUnknown
is RsTraitItem -> TyTypeParameter.self(this)
else -> error("Unreachable")
}
}
private val DEFAULT_MUTABILITY = true
val RsExpr.isMutable: Boolean get() {
return when (this) {
is RsPathExpr -> {
val declaration = path.reference.resolve() ?: return DEFAULT_MUTABILITY
if (declaration is RsSelfParameter) return declaration.mutability.isMut
if (declaration is RsPatBinding && declaration.mutability.isMut) return true
if (declaration is RsConstant) return declaration.mutability.isMut
val type = this.type
if (type is TyReference) return type.mutability.isMut
val letExpr = declaration.ancestorStrict<RsLetDecl>()
if (letExpr != null && letExpr.eq == null) return true
if (type is TyUnknown) return DEFAULT_MUTABILITY
if (declaration is RsEnumVariant) return true
if (declaration is RsStructItem) return true
if (declaration is RsFunction) return true
false
}
// is RsFieldExpr -> (expr.type as? TyReference)?.mutable ?: DEFAULT_MUTABILITY // <- this one brings false positives without additional analysis
is RsUnaryExpr -> mul != null || (expr != null && expr?.isMutable ?: DEFAULT_MUTABILITY)
else -> DEFAULT_MUTABILITY
}
}
| mit | f438a5b35e94a4e2f97fb9e80cf88a75 | 36.3 | 149 | 0.710456 | 4.354086 | false | false | false | false |
Caellian/Math | src/main/kotlin/hr/caellian/math/vector/VectorD.kt | 1 | 8825 | package hr.caellian.math.vector
import hr.caellian.math.matrix.MatrixD
import hr.caellian.math.matrix.MatrixN
import java.nio.Buffer
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.DoubleBuffer
import kotlin.math.abs
import kotlin.math.sqrt
/**
* Vector class for double N-dimensional vectors.
*
* @param wrapped value array to create a new vector from.
*
* @author Caellian
*/
class VectorD(override var wrapped: Array<Double> = emptyArray()) : VectorN<Double>() {
/**
* Creates a new vector using given values.
*
* @param values values to create a new vector from.
* @return created vector.
*/
constructor(vararg values: Double) : this(values.toTypedArray())
/**
* Creates a new vector using given collection values.
*
* @param values collection values to create a new vector from.
* @return created vector.
*/
constructor(values: Collection<Double>) : this(values.toTypedArray())
/**
* Creates a new vector using buffer values.
*
* @param buffer buffer to create a new vector from.
* @return created vector.
*/
constructor(buffer: DoubleBuffer) : this((0 until buffer.capacity()).map { buffer.get() })
/**
* @return new vector with negated values.
*/
override operator fun unaryMinus(): VectorD = VectorD(Array(size) { -this[it] })
/**
* Adds two vectors together and returns resulting vector.
* In order to add to matrices together, they must be of same size.
*
* @return result of vector addition.
*/
override operator fun plus(other: VectorN<Double>): VectorD {
require(size == other.size) { "Invalid argument vector size: ${other.size}!" }
return VectorD(Array(size) { this[it] + other[it] })
}
/**
* Subtracts other vector from this one and returns resulting vector.
* In order to subtract one vector from another, both vectors must be of same size.
*
* @return result of vector subtraction.
*/
override operator fun minus(other: VectorN<Double>): VectorD {
require(size == other.size) { "Invalid argument vector size: ${other.size}!" }
return VectorD(Array(size) { this[it] - other[it] })
}
/**
* Multiplies two vectors together and returns resulting vector.
* In order to add to multiply vectors together, they must be of same size.
*
* @return result of vector multiplication.
*/
override operator fun times(other: VectorN<Double>): VectorD {
require(size == other.size) { "Invalid argument vector size: ${other.size}!" }
return VectorD(Array(size) { this[it] * other[it] })
}
/**
* Divides this vector with other and returns resulting vector.
* In order to divide one vector with another, both vectors must be of same size.
*
* @return result of vector division.
*/
override operator fun div(other: VectorN<Double>): VectorD {
require(size == other.size) { "Invalid argument vector size: ${other.size}!" }
return VectorD(Array(size) { this[it] / other[it] })
}
/**
* Performs scalar addition on this vector and returns resulting vector.
*
* @return result of vector scalar addition.
*/
override operator fun plus(value: Double): VectorD = VectorD(Array(size) { this[it] + value })
/**
* Performs scalar subtraction on this vector and returns resulting vector.
*
* @return result of scalar vector subtraction.
*/
override operator fun minus(value: Double): VectorD = VectorD(Array(size) { this[it] - value })
/**
* Performs scalar multiplication on this vector and returns resulting vector.
*
* @return result of scalar vector multiplication.
*/
override operator fun times(value: Double): VectorD = VectorD(Array(size) { this[it] * value })
/**
* Performs scalar division on this vector and returns resulting vector.
*
* @return result of scalar vector division.
*/
override operator fun div(value: Double): VectorD = VectorD(Array(size) { this[it] / value })
/**
* @return biggest value of a member of this vector.
*/
override fun max(): Double = wrapped.max() ?: 0.0
/**
* @return smalled value of a member of this vector.
*/
override fun min(): Double = wrapped.min() ?: 0.0
/**
* @return new vector containing absolute values of this vector.
*/
override fun absolute(): VectorD = VectorD(Array(size) { abs(this[it]) })
/**
* @return new vector with normalized values of this one.
*/
override fun normalized(): VectorD = this / magnitude()
/**
* @return magnitude of this vector.
*/
override fun magnitude(): Double = distanceTo(this)
/**
* Calculates distance from this to other vector.
*
* @return distance between this and other vector.
*/
override fun distanceTo(other: VectorN<Double>): Double = sqrt(this dot other)
/**
*
* @return dot product of two vectors.
*/
override fun dot(other: VectorN<Double>): Double {
require(size == other.size) { "Invalid argument vector size: ${other.size}!" }
return wrapped.zip(other.wrapped).sumByDouble { (a, b) -> a * b }
}
/**
* Returns cross product of this and other vector.
*
* @return cross product.
*/
override fun cross(other: VectorN<Double>): VectorD {
require(size == other.size) { "Invalid argument vector size: ${other.size}!" }
return when (size) {
3 -> VectorD(arrayOf(
this[1] * other[2] - this[2] * other[1],
this[2] * other[0] - this[0] * other[2],
this[0] * other[1] - this[1] * other[0]
))
7 -> VectorD(arrayOf(
this[1] * other[3] - this[3] * other[1] + this[2] * other[6] - this[6] * other[2] + this[4] * other[5] - this[5] * other[4],
this[2] * other[4] - this[4] * other[2] + this[3] * other[0] - this[0] * other[3] + this[5] * other[6] - this[6] * other[5],
this[3] * other[5] - this[5] * other[3] + this[4] * other[1] - this[1] * other[4] + this[6] * other[0] - this[0] * other[6],
this[4] * other[6] - this[6] * other[4] + this[5] * other[2] - this[2] * other[5] + this[0] * other[1] - this[1] * other[0],
this[5] * other[0] - this[0] * other[5] + this[6] * other[3] - this[3] * other[6] + this[1] * other[2] - this[2] * other[1],
this[6] * other[1] - this[1] * other[6] + this[0] * other[4] - this[4] * other[0] + this[2] * other[3] - this[3] * other[2],
this[0] * other[2] - this[2] * other[0] + this[1] * other[5] - this[5] * other[1] + this[3] * other[4] - this[4] * other[3]
))
else -> throw NotImplementedError("Cross product does not exist in $size-dimensional space!")
}
}
/**
* Rotates this vector using rotation matrix.
*
* @return rotated vector.
*/
override fun rotated(rotationMatrix: MatrixN<Double>): VectorD = (rotationMatrix * verticalMatrix).toVector() as VectorD
/**
* Linearly interpolates between two vectors.
*
* @return linear interpolation.
*/
override fun lerp(destination: VectorN<Double>, percent: Double): VectorD = this + (destination - this) * percent
/**
* Vertical matrix containing data of this vector.
*/
override val verticalMatrix: MatrixD by lazy { MatrixD(arrayOf(toArray()), true) }
/**
* Horizontal matrix containing data of this vector.
*/
override val horizontalMatrix: MatrixD by lazy { MatrixD(arrayOf(toArray())) }
/**
* Returns array containing vector data.
*
* @return array containing data of this vector.
*/
override fun toArray(): Array<Double> = Array(size) { wrapped[it] }
/**
* @return clone of this vector.
*/
override fun replicated(): VectorD = VectorD(toArray())
/**
* @return type supported by this class.
*/
override fun getTypeClass() = Double::class
/**
* Creates a new instance of wrapper containing given data.
*
* @param data data of new wrapper.
* @return new instance of wrapper containing argument data.
*/
override fun withData(wrapped: Array<Double>): VectorD = VectorD(wrapped)
/**
* @return [Buffer] containing data of represented object.
*/
override fun toBuffer(): Buffer {
val result = ByteBuffer.allocateDirect(wrapped.size shl 2).order(
ByteOrder.nativeOrder()).asDoubleBuffer()
wrapped.forEach { result.put(it) }
return result.flip()
}
}
| mit | a7ae6b25330dd03e2725cf2035f23907 | 34.728745 | 144 | 0.604193 | 3.966292 | false | false | false | false |
JavaEden/OrchidCore | plugins/OrchidPosts/src/main/kotlin/com/eden/orchid/posts/model/CategoryModel.kt | 1 | 2376 | package com.eden.orchid.posts.model
import com.eden.common.util.EdenUtils
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.options.OptionsHolder
import com.eden.orchid.api.options.annotations.Archetype
import com.eden.orchid.api.options.annotations.Archetypes
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.options.annotations.Option
import com.eden.orchid.api.options.annotations.StringDefault
import com.eden.orchid.api.options.archetypes.ConfigArchetype
import com.eden.orchid.posts.PostsGenerator
import com.eden.orchid.posts.pages.PostPage
import com.eden.orchid.utilities.OrchidUtils
import com.eden.orchid.utilities.camelCase
import com.eden.orchid.utilities.from
import com.eden.orchid.utilities.titleCase
import com.eden.orchid.utilities.to
import javax.inject.Inject
@Archetypes(
Archetype(value = ConfigArchetype::class, key = "${PostsGenerator.GENERATOR_KEY}.defaultConfig")
)
class CategoryModel
@Inject
constructor(val context: OrchidContext) : OptionsHolder {
var first: List<PostPage> = ArrayList()
@Option
var key: String? = null
var path: String = ""
@Option
@StringDefault(":category/:year/:month/:day/:slug")
@Description("The permalink structure to use for the blog posts in this category. Permalinks may be " +
"overridden on any individual post."
)
lateinit var permalink: String
@Option
@Description("The display title of the category. Defaults to the un-camelCased category key.")
lateinit var title: String
lateinit var allCategories: Array<String>
override fun onPostExtraction() {
key = OrchidUtils.normalizePath(key)
if (!EdenUtils.isEmpty(key)) {
val categoryPath = key!!.split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
key = categoryPath.last()
path = OrchidUtils.normalizePath(categoryPath.joinToString("/"))
}
else {
key = null
path = ""
}
allCategories = path.split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
title = if (!EdenUtils.isEmpty(title)) {
title
}
else if (!EdenUtils.isEmpty(key)) {
key!!.from { camelCase() } to { titleCase() }
}
else {
"Blog"
}
}
}
| mit | 81cd69761fef87580ad874ce31bce09d | 31.108108 | 107 | 0.688973 | 4.250447 | false | false | false | false |
inv3rse/ProxerTv | app/src/main/java/com/inverse/unofficial/proxertv/base/client/interceptors/SeriesCaptchaDetection.kt | 1 | 1415 | package com.inverse.unofficial.proxertv.base.client.interceptors
import okhttp3.CacheControl
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.ResponseBody
fun containsCaptcha(htmlBody: String): Boolean {
return htmlBody.contains("<div id=\"captcha\"")
}
/**
* Interceptor that makes sure that a captcha response is not loaded from cache.
*/
class NoCacheCaptchaInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response? {
val request = chain.request()
val response = chain.proceed(request)
if (request.url().toString().contains("proxer.me/watch") && response.cacheResponse() != null) {
// We have to check the response body.
// Because we can only read it once, the original response can not be returned
val mediaType = response.body().contentType()
val htmlBody = response.body().string()
if (containsCaptcha(htmlBody)) {
val noCacheRequest = request.newBuilder()
.cacheControl(CacheControl.FORCE_NETWORK)
.build()
return chain.proceed(noCacheRequest)
} else {
val newBody = ResponseBody.create(mediaType, htmlBody)
return response.newBuilder().body(newBody).build()
}
} else {
return response
}
}
} | mit | d142b330660d6366f6da957277540034 | 33.536585 | 103 | 0.628269 | 5 | false | false | false | false |
Shynixn/BlockBall | blockball-tools/src/main/kotlin/com/github/shynixn/blockballtools/logic/service/PublicBlockBallReleaseToDiscordServiceImpl.kt | 1 | 3753 | package com.github.shynixn.blockballtools.logic.service
import com.github.shynixn.blockballtools.contract.SonaTypeService
import com.github.shynixn.discordwebhook.contract.DiscordWebhookService
import com.github.shynixn.discordwebhook.entity.DiscordAuthor
import com.github.shynixn.discordwebhook.entity.DiscordEmbed
import com.github.shynixn.discordwebhook.entity.DiscordField
import com.github.shynixn.discordwebhook.entity.DiscordPayload
import com.github.shynixn.discordwebhook.extension.decimal
import com.github.shynixn.discordwebhook.extension.timestampIso8601
import com.github.shynixn.discordwebhook.impl.DiscordWebhookServiceImpl
import java.awt.Color
import java.util.*
/**
* Created by Shynixn 2019.
* <p>
* Version 1.2
* <p>
* MIT License
* <p>
* Copyright (c) 2019 by Shynixn
* <p>
* 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:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* 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.
*/
class PublicBlockBallReleaseToDiscordServiceImpl(
private val releaseService: SonaTypeService = ReleaseServiceImpl(),
private val discordWebHookService: DiscordWebhookService = DiscordWebhookServiceImpl()
) {
private val bukkitSnapshotRepo =
"https://oss.sonatype.org/content/repositories/public/com/github/shynixn/blockball/blockball-bukkit-plugin/"
private val blockBallImage = "https://raw.githubusercontent.com/Shynixn/travis-ci-discord-webhook/master/ball.png"
/**
* Sends the snapshot status to discord.
*/
fun publishReleaseToDiscord(webHookUrl: String) {
val releaseDownloadUrl = releaseService.findDownloadUrl(bukkitSnapshotRepo)
val releaseId = releaseService.findId(bukkitSnapshotRepo)
val payload = DiscordPayload("BlockBall", blockBallImage)
val embeddedMessage = DiscordEmbed(
"Downloads",
Color(251, 140, 0).decimal,
DiscordAuthor("BlockBall Releases - Shynixn/BlockBall - $releaseId", "", blockBallImage),
"Author Shynixn released a new version from BlockBall",
Date().timestampIso8601
)
embeddedMessage.fields.add(
DiscordField(
"Spigot/Bukkit",
"<:bukkit:493024859555627009> [`Download BlockBall`]($releaseDownloadUrl)"
)
)
embeddedMessage.fields.add(
DiscordField(
"Leave a Star",
value = "https://github.com/Shynixn/BlockBall"
)
)
embeddedMessage.fields.add(
DiscordField(
name = "Like or Review",
value = "https://www.spigotmc.org/resources/15320"
)
)
payload.embeds.add(embeddedMessage)
discordWebHookService.sendDiscordPayload(webHookUrl, payload)
}
} | apache-2.0 | b143880f1485e19c2c03641bd73655ee | 39.365591 | 118 | 0.715161 | 4.415294 | false | false | false | false |
ac-opensource/Matchmaking-App | app/src/main/java/com/youniversals/playupgo/flux/action/UserActionCreator.kt | 1 | 1824 | package com.youniversals.playupgo.flux.action
import android.support.annotation.StringDef
import com.youniversals.playupgo.flux.Action
import com.youniversals.playupgo.flux.Dispatcher
import com.youniversals.playupgo.flux.Utils
import com.youniversals.playupgo.flux.model.UserModel
/**
* @author Gian Darren Aquino
* *
* @createdAt 31/08/2016
*/
class UserActionCreator(private val mDispatcher: Dispatcher, private val mUserModel: UserModel, private val mUtils: Utils) {
companion object {
const val ACTION_INITIALIZE_USER = "ACTION_INITIALIZE_USER"
const val ACTION_LOGIN_SUCCESS = "ACTION_LOGIN_SUCCESS"
const val ACTION_LOGIN_FAILED = "ACTION_LOGIN_FAILED"
const val ACTION_GET_USER_PROFILE_S = "ACTION_GET_USER_PROFILE_S"
const val ACTION_GET_USER_PROFILE_F = "ACTION_GET_USER_PROFILE_F"
}
@StringDef(value = *arrayOf(ACTION_INITIALIZE_USER))
@kotlin.annotation.Retention(AnnotationRetention.SOURCE)
annotation class UserAction
init {
preload()
}
fun preload() {
mDispatcher.dispatch(Action(ACTION_INITIALIZE_USER, Unit))
}
fun login(accessToken: String) {
mUserModel.login(accessToken)
.subscribe({ user -> mDispatcher.dispatch(Action(ACTION_LOGIN_SUCCESS, user)) }, { throwable ->
mDispatcher.dispatch(
Action(ACTION_LOGIN_FAILED, mUtils.getError(throwable)))
})
}
fun getUserProfile(externalId: String) {
mUserModel.getUserProfile(externalId)
.subscribe({ userProfile -> mDispatcher.dispatch(Action(ACTION_GET_USER_PROFILE_S, userProfile)) }, {
throwable -> mDispatcher.dispatch(Action(ACTION_GET_USER_PROFILE_F, mUtils.getError(throwable)))
})
}
}
| agpl-3.0 | 48d3da403ef66e618fec5ab44c822387 | 35.48 | 124 | 0.674342 | 4.24186 | false | false | false | false |
wuseal/JsonToKotlinClass | api/src/main/kotlin/wu/seal/jsontokotlinclass/server/controllers/GenerateController.kt | 1 | 4893 | package wu.seal.jsontokotlinclass.server.controllers
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.bind.annotation.RestController
import wu.seal.jsontokotlin.DefaultValueStrategy
import wu.seal.jsontokotlin.PropertyTypeStrategy
import wu.seal.jsontokotlin.TargetJsonConverter
import wu.seal.jsontokotlin.library.JsonToKotlinBuilder
import wu.seal.jsontokotlinclass.server.data.entities.Hit
import wu.seal.jsontokotlinclass.server.data.repos.HitsRepo
import wu.seal.jsontokotlinclass.server.models.routes.generate.GenerateRequest
import wu.seal.jsontokotlinclass.server.models.routes.generate.GenerateResponse
import wu.seal.jsontokotlinclass.server.utils.toHit
@Api(description = "To generate Kotlin source code")
@RestController
class GenerateController {
@Autowired
var hitsRepo: HitsRepo? = null
@ApiOperation("To generate Kotlin source code from given input")
@PostMapping("/generate")
@ResponseBody
fun generate(@RequestBody request: GenerateRequest): GenerateResponse {
val builder = JsonToKotlinBuilder()
// Integrating REST request params with builder class
if (request.annotationLib != null) {
builder.setAnnotationLib(TargetJsonConverter.valueOf(request.annotationLib))
}
if (request.classSuffix != null) {
builder.setClassSuffix(request.classSuffix)
}
if (request.defaultValueStrategy != null) {
builder.setDefaultValueStrategy(DefaultValueStrategy.valueOf(request.defaultValueStrategy))
}
if (request.indent != null) {
builder.setIndent(request.indent)
}
if (request.commentsEnabled != null) {
builder.enableComments(request.commentsEnabled)
}
if (request.createAnnotationOnlyWhenNeededEnabled != null) {
builder.enableCreateAnnotationOnlyWhenNeeded(request.createAnnotationOnlyWhenNeededEnabled)
}
if (request.enableVarProperties != null) {
builder.enableVarProperties(request.enableVarProperties)
}
if (request.forceInitDefaultValueWithOriginJsonValueEnabled != null) {
builder.enableForceInitDefaultValueWithOriginJsonValue(request.forceInitDefaultValueWithOriginJsonValueEnabled)
}
if (request.forcePrimitiveTypeNonNullableEnabled != null) {
builder.enableForcePrimitiveTypeNonNullable(request.forcePrimitiveTypeNonNullableEnabled)
}
if (request.innerClassModelEnabled != null) {
builder.enableInnerClassModel(request.innerClassModelEnabled)
}
if (request.keepAnnotationOnClassAndroidXEnabled != null) {
builder.enableKeepAnnotationOnClassAndroidX(request.keepAnnotationOnClassAndroidXEnabled)
}
if (request.keepAnnotationOnClassEnabled != null) {
builder.enableKeepAnnotationOnClass(request.keepAnnotationOnClassEnabled)
}
if (request.mapTypeEnabled != null) {
builder.enableMapType(request.mapTypeEnabled)
}
if (request.orderByAlphabeticEnabled != null) {
builder.enableOrderByAlphabetic(request.orderByAlphabeticEnabled)
}
if (request.parcelableSupportEnabled != null) {
builder.enableParcelableSupport(request.parcelableSupportEnabled)
}
if (request.propertyAndAnnotationInSameLineEnabled != null) {
builder.enableAnnotationAndPropertyInSameLine(request.propertyAndAnnotationInSameLineEnabled)
}
if (request.packageName != null) {
builder.setPackageName(request.packageName)
}
if (request.parentClassTemplate != null) {
builder.setParentClassTemplate(request.parentClassTemplate)
}
if (request.propertyPrefix != null) {
builder.setPropertyPrefix(request.propertyPrefix)
}
if (request.propertySuffix != null) {
builder.setPropertySuffix(request.propertyPrefix)
}
if (request.propertyTypeStrategy != null) {
builder.setPropertyTypeStrategy(PropertyTypeStrategy.valueOf(request.propertyTypeStrategy))
}
if (hitsRepo != null) {
// Setting
val hit = request.toHit(Hit.CLIENT_API)
// Setting default values
hitsRepo!!.save(hit)
}
val json = builder.build(request.json, request.className)
return GenerateResponse(
GenerateResponse.Data(json),
false,
-1,
"OK"
)
}
} | gpl-3.0 | 4d2257dafd4698cd562486f1c619805c | 34.985294 | 123 | 0.700593 | 4.893 | false | false | false | false |
NordicSemiconductor/Android-nRF-Toolbox | profile_gls/src/main/java/no/nordicsemi/android/gls/data/DataMapper.kt | 1 | 3254 | /*
* Copyright (c) 2022, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package no.nordicsemi.android.gls.data
import no.nordicsemi.android.ble.common.callback.glucose.GlucoseMeasurementContextResponse
import no.nordicsemi.android.ble.common.callback.glucose.GlucoseMeasurementResponse
internal fun GlucoseMeasurementResponse.toRecord(): GLSRecord {
return this.let {
GLSRecord(
sequenceNumber = it.sequenceNumber,
time = it.time,
glucoseConcentration = it.glucoseConcentration ?: 0f,
unit = it.unit?.let { ConcentrationUnit.create(it) }
?: ConcentrationUnit.UNIT_KGPL,
type = RecordType.createOrNull(it.type),
sampleLocation = SampleLocation.createOrNull(it.sampleLocation),
status = it.status
)
}
}
internal fun GlucoseMeasurementContextResponse.toMeasurementContext(): MeasurementContext {
return this.let {
MeasurementContext(
sequenceNumber = it.sequenceNumber,
carbohydrate = it.carbohydrate,
carbohydrateAmount = it.carbohydrateAmount ?: 0f,
meal = it.meal,
tester = it.tester,
health = it.health,
exerciseDuration = it.exerciseDuration ?: 0,
exerciseIntensity = it.exerciseIntensity ?: 0,
medication = it.medication,
medicationQuantity = it.medicationAmount ?: 0f,
medicationUnit = it.medicationUnit?.let { MedicationUnit.create(it) }
?: MedicationUnit.UNIT_KG,
HbA1c = it.hbA1c ?: 0f
)
}
}
internal fun GLSRecord.copyWithNewContext(response: GlucoseMeasurementContextResponse): GLSRecord {
return copy(context = context)
}
| bsd-3-clause | b9e2cc8e2e7f8436097c62dc80ce6611 | 42.972973 | 99 | 0.711432 | 4.602546 | false | false | false | false |
pyamsoft/zaptorch | app/src/main/java/com/pyamsoft/zaptorch/main/HowToScreen.kt | 1 | 2494 | /*
* Copyright 2021 Peter Kenji Yamanaka
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pyamsoft.zaptorch.main
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
@Composable
internal fun HowToScreen(
modifier: Modifier = Modifier,
onClose: () -> Unit,
) {
Surface(
modifier = modifier,
) {
Column(modifier = Modifier.padding(16.dp).fillMaxWidth()) {
Box(
modifier = Modifier.padding(bottom = 8.dp),
) { Title() }
Box(
modifier = Modifier.padding(bottom = 8.dp),
) { Message() }
Actions(
onClose = onClose,
)
}
}
}
@Composable
private fun Title() {
Text(
text = "How to Use",
style = MaterialTheme.typography.h5,
)
}
@Composable
private fun Message() {
Text(
text =
"""
Commands:
Press the Volume keys in the following sequences
↓ ↓ - Toggle flash light
↑ ↑ - Pulse slowly
↓ ↑ - Strobe effect quickly
""".trimIndent(),
style = MaterialTheme.typography.body1,
)
}
@Composable
private fun Actions(
onClose: () -> Unit,
) {
Row {
Spacer(
modifier = Modifier.weight(1F),
)
TextButton(
onClick = onClose,
) {
Text(
text = "Got It",
)
}
}
}
@Preview
@Composable
private fun PreviewHowToScreen() {
HowToScreen(
onClose = {},
)
}
| apache-2.0 | 84ef042f4e289c86893f78d627eaf60b | 22.415094 | 75 | 0.677276 | 4.035772 | false | false | false | false |
googlearchive/android-AutofillFramework | kotlinApp/Application/src/main/java/com/example/android/autofillframework/app/StandardSignInActivity.kt | 3 | 2536 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.autofillframework.app
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
import com.example.android.autofillframework.R
import kotlinx.android.synthetic.main.login_activity.clear
import kotlinx.android.synthetic.main.login_activity.login
import kotlinx.android.synthetic.main.login_activity.passwordField
import kotlinx.android.synthetic.main.login_activity.usernameField
class StandardSignInActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.login_activity)
login.setOnClickListener { login() }
clear.setOnClickListener { resetFields() }
}
private fun resetFields() {
usernameField.setText("")
passwordField.setText("")
}
/**
* Emulates a login action.
*/
private fun login() {
val username = usernameField.text.toString()
val password = passwordField.text.toString()
val valid = isValidCredentials(username, password)
if (valid) {
val intent = WelcomeActivity.getStartActivityIntent(this@StandardSignInActivity)
startActivity(intent)
finish()
} else {
Toast.makeText(this, "Authentication failed.", Toast.LENGTH_SHORT).show()
}
}
/**
* Dummy implementation for demo purposes. A real service should use secure mechanisms to
* authenticate users.
*/
fun isValidCredentials(username: String, password: String): Boolean {
return username == password
}
companion object {
fun getStartActivityIntent(context: Context): Intent {
val intent = Intent(context, StandardSignInActivity::class.java)
return intent
}
}
} | apache-2.0 | 92a181edb1682a5521c5c579f1c68b60 | 32.381579 | 93 | 0.70347 | 4.678967 | false | false | false | false |
joan-domingo/Podcasts-RAC1-Android | app/src/main/java/cat/xojan/random1/feature/MediaPlayerBaseActivity.kt | 1 | 4577 | package cat.xojan.random1.feature
import android.content.ComponentName
import android.os.Bundle
import android.os.RemoteException
import android.support.v4.media.MediaBrowserCompat
import android.support.v4.media.MediaMetadataCompat
import android.support.v4.media.session.MediaControllerCompat
import android.support.v4.media.session.MediaSessionCompat
import android.support.v4.media.session.PlaybackStateCompat
import android.util.Log
import androidx.fragment.app.Fragment
import cat.xojan.random1.R
import cat.xojan.random1.feature.mediaplayback.MediaPlaybackControlsFragment
import cat.xojan.random1.feature.mediaplayback.MediaPlaybackService
abstract class MediaPlayerBaseActivity : BaseActivity(), MediaBrowserProvider {
private val TAG = BaseActivity::class.simpleName
lateinit var mMediaBrowser: MediaBrowserCompat
private lateinit var mediaControllerCallback: MediaControllerCompat.Callback
private var controlsFragment: MediaPlaybackControlsFragment? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mMediaBrowser = MediaBrowserCompat(
this,
ComponentName(this, MediaPlaybackService::class.java),
object : MediaBrowserCompat.ConnectionCallback() {
override fun onConnected() {
try {
connectToSession(mMediaBrowser.sessionToken)
} catch (e: RemoteException) {
Log.e(TAG, "could not connect media controller: " + e)
hidePlaybackControls()
}
}
},
null)
mediaControllerCallback = object : MediaControllerCompat.Callback() {
override fun onPlaybackStateChanged(state: PlaybackStateCompat?) {
if (shouldShowControls()) {
showPlaybackControls()
} else {
hidePlaybackControls()
}
}
override fun onMetadataChanged(metadata: MediaMetadataCompat?) {
if (shouldShowControls()) {
showPlaybackControls()
} else {
hidePlaybackControls()
}
}
}
}
override fun onStart() {
super.onStart()
try {
controlsFragment = supportFragmentManager
.findFragmentById(R.id.fragment_playback_controls)
as MediaPlaybackControlsFragment
} catch (t: Throwable) {
}
hidePlaybackControls()
mMediaBrowser.connect()
}
override fun onStop() {
super.onStop()
val controllerCompat = MediaControllerCompat.getMediaController(this)
controllerCompat?.unregisterCallback(mediaControllerCallback)
mMediaBrowser.disconnect()
}
private fun connectToSession(token: MediaSessionCompat.Token) {
val mediaController = MediaControllerCompat(this, token)
MediaControllerCompat.setMediaController(this, mediaController)
mediaController.registerCallback(mediaControllerCallback)
if (shouldShowControls()) {
showPlaybackControls()
} else {
hidePlaybackControls()
}
controlsFragment?.onConnected()
onMediaControllerConnected()
}
open fun onMediaControllerConnected() {}
override fun getMediaBrowser(): MediaBrowserCompat = mMediaBrowser
private fun hidePlaybackControls() {
controlsFragment?.let {
supportFragmentManager.beginTransaction()
.hide(controlsFragment as Fragment)
.commit()
}
}
private fun shouldShowControls(): Boolean {
val mediaController = MediaControllerCompat.getMediaController(this)
if (mediaController == null ||
mediaController.metadata == null ||
mediaController.playbackState == null) {
return false
}
return when (mediaController.playbackState.state) {
PlaybackStateCompat.STATE_ERROR, PlaybackStateCompat.STATE_NONE,
PlaybackStateCompat.STATE_STOPPED -> false
else -> true
}
}
private fun showPlaybackControls() {
controlsFragment?.let {
supportFragmentManager.beginTransaction()
.show(controlsFragment as Fragment)
.commitAllowingStateLoss()
}
}
} | mit | 72882e411915616c1d8258f1f686b307 | 34.765625 | 82 | 0.628796 | 5.983007 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/async/UndoActions.kt | 1 | 5204 | /****************************************************************************************
* Copyright (c) 2009 Daniel Svärd <[email protected]> *
* Copyright (c) 2009 Edu Zamora <[email protected]> *
* Copyright (c) 2011 Norbert Nagold <[email protected]> *
* Copyright (c) 2022 Divyansh Kushwaha <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.async
import com.ichi2.anki.CardUtils
import com.ichi2.anki.R
import com.ichi2.libanki.Card
import com.ichi2.libanki.Collection
import com.ichi2.libanki.Note
import com.ichi2.libanki.UndoAction
import com.ichi2.libanki.Utils
import timber.log.Timber
import java.util.ArrayList
/** @param hasUnsuspended whether there were any unsuspended card (in which card the action was "Suspend",
* otherwise the action was "Unsuspend")
*/
class UndoSuspendCardMulti(
private val cards: Array<Card>,
private val originalSuspended: BooleanArray,
hasUnsuspended: Boolean
) : UndoAction(if (hasUnsuspended) R.string.menu_suspend_card else R.string.card_browser_unsuspend_card) {
override fun undo(col: Collection): Card? {
Timber.i("Undo: Suspend multiple cards")
val nbOfCards = cards.size
val toSuspendIds: MutableList<Long> = ArrayList(nbOfCards)
val toUnsuspendIds: MutableList<Long> = ArrayList(nbOfCards)
for (i in 0 until nbOfCards) {
val card = cards[i]
if (originalSuspended[i]) {
toSuspendIds.add(card.id)
} else {
toUnsuspendIds.add(card.id)
}
}
// unboxing
val toSuspendIdsArray = LongArray(toSuspendIds.size)
val toUnsuspendIdsArray = LongArray(toUnsuspendIds.size)
for (i in toSuspendIds.indices) {
toSuspendIdsArray[i] = toSuspendIds[i]
}
for (i in toUnsuspendIds.indices) {
toUnsuspendIdsArray[i] = toUnsuspendIds[i]
}
col.sched.suspendCards(toSuspendIdsArray)
col.sched.unsuspendCards(toUnsuspendIdsArray)
return null // don't fetch new card
}
}
class UndoDeleteNoteMulti(private val notesArr: Array<Note>, private val allCards: List<Card>) : UndoAction(
R.string.card_browser_delete_card
) {
override fun undo(col: Collection): Card? {
Timber.i("Undo: Delete notes")
// undo all of these at once instead of one-by-one
val ids = ArrayList<Long>(notesArr.size + allCards.size)
for (n in notesArr) {
n.flush(n.mod, false)
ids.add(n.id)
}
for (c in allCards) {
c.flush(false)
ids.add(c.id)
}
col.db.execute("DELETE FROM graves WHERE oid IN " + Utils.ids2str(ids))
return null // don't fetch new card
}
}
class UndoChangeDeckMulti(private val cards: Array<Card>, private val originalDids: LongArray) : UndoAction(
R.string.undo_action_change_deck_multi
) {
override fun undo(col: Collection): Card? {
Timber.i("Undo: Change Decks")
// move cards to original deck
for (i in cards.indices) {
val card = cards[i]
card.load()
card.did = originalDids[i]
val note = card.note()
note.flush()
card.flush()
}
return null // don't fetch new card
}
}
/** @param hasUnmarked whether there were any unmarked card (in which card the action was "mark",
* otherwise the action was "Unmark")
*/
class UndoMarkNoteMulti
(private val originalMarked: List<Note>, private val originalUnmarked: List<Note>, hasUnmarked: Boolean) : UndoAction(if (hasUnmarked) R.string.card_browser_mark_card else R.string.card_browser_unmark_card) {
override fun undo(col: Collection): Card? {
Timber.i("Undo: Mark notes")
CardUtils.markAll(originalMarked, true)
CardUtils.markAll(originalUnmarked, false)
return null // don't fetch new card
}
}
| gpl-3.0 | 2243e8c5e51b3e18f3d3d4011f4e46c4 | 43.09322 | 208 | 0.572939 | 4.212955 | false | false | false | false |
BrianLusina/MovieReel | app/src/main/kotlin/com/moviereel/utils/toolbox/MovieReelDiffUtilCallback.kt | 1 | 948 | package com.moviereel.utils.toolbox
import android.support.v7.util.DiffUtil
/**
* @author lusinabrian on 27/07/17.
* @Notes Diff Util callback for managing data updates to adapters in the application
*/
class MovieReelDiffUtilCallback<T>(var oldItemList: ArrayList<T>, var newItemList: ArrayList<T>) : DiffUtil.Callback() {
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldItemList[oldItemPosition] == newItemList[newItemPosition]
}
override fun getOldListSize() = oldItemList.size
override fun getNewListSize() = newItemList.size
override fun getChangePayload(oldItemPosition: Int, newItemPosition: Int): Any? {
return super.getChangePayload(oldItemPosition, newItemPosition)
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return newItemList[newItemPosition] == oldItemList[oldItemPosition]
}
} | mit | 5b2ef3ac8cb7a38f6afb16cd7df06476 | 35.5 | 120 | 0.753165 | 4.911917 | false | false | false | false |
SchoolPower/SchoolPower-Android | app/src/main/java/com/carbonylgroup/schoolpower/activities/WechatIntroActivity.kt | 1 | 6978 | package com.carbonylgroup.schoolpower.activities
import android.Manifest
import android.app.AlertDialog
import android.content.Context
import android.content.DialogInterface
import android.content.pm.PackageManager
import android.didikee.donate.WeiXinDonate
import android.graphics.BitmapFactory
import android.os.Bundle
import android.os.Environment
import androidx.annotation.Nullable
import androidx.legacy.app.ActivityCompat
import androidx.fragment.app.Fragment
import androidx.core.content.ContextCompat
import android.view.WindowManager
import android.widget.Toast
import com.carbonylgroup.schoolpower.R
import com.carbonylgroup.schoolpower.utils.ContextWrapper
import com.carbonylgroup.schoolpower.utils.Utils
import com.github.paolorotolo.appintro.AppIntro
import com.github.paolorotolo.appintro.AppIntroFragment
import com.github.paolorotolo.appintro.model.SliderPage
import java.io.File
class WechatIntroActivity : AppIntro() {
val MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE = 233
val WECHAT_NOT_FOUND = 1
lateinit var utils: Utils
override fun attachBaseContext(newBase: Context?) {
utils = Utils(newBase!!)
val newLocale = utils.getPreferences().getString("list_preference_language", "0")!!.toInt()
val context = ContextWrapper.wrap(newBase, Utils.getLocaleSet()[newLocale])
super.attachBaseContext(context)
}
override fun onCreate(@Nullable savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val page1 = SliderPage()
val page2 = SliderPage()
val page3 = SliderPage()
val page4 = SliderPage()
val page5 = SliderPage()
page1.title = getString(R.string.wechat_instruction_page1_title)
page1.description = getString(R.string.wechat_instruction_page1_des)
page2.description = getString(R.string.wechat_instruction_page2_des)
page3.description = getString(R.string.wechat_instruction_page3_des)
page4.description = getString(R.string.wechat_instruction_page4_des)
page5.description = getString(R.string.wechat_instruction_page5_des)
page1.bgColor = ContextCompat.getColor(this, R.color.B_score_green)
page2.bgColor = ContextCompat.getColor(this, R.color.B_score_green)
page3.bgColor = ContextCompat.getColor(this, R.color.B_score_green)
page4.bgColor = ContextCompat.getColor(this, R.color.B_score_green)
page5.bgColor = ContextCompat.getColor(this, R.color.B_score_green)
page1.imageDrawable = R.drawable.ic_wechat_pay
page2.imageDrawable = R.drawable.page2
page3.imageDrawable = R.drawable.page3
page4.imageDrawable = R.drawable.page4
page5.imageDrawable = R.drawable.page5
addSlide(AppIntroFragment.newInstance(page1))
addSlide(AppIntroFragment.newInstance(page2))
addSlide(AppIntroFragment.newInstance(page3))
addSlide(AppIntroFragment.newInstance(page4))
addSlide(AppIntroFragment.newInstance(page5))
val window = this.window
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
window.statusBarColor = ContextCompat.getColor(this, R.color.B_score_green_dark)
window.navigationBarColor = ContextCompat.getColor(this, R.color.B_score_green)
setBarColor(ContextCompat.getColor(this, android.R.color.transparent))
setSeparatorColor(ContextCompat.getColor(this, R.color.white_0_10))
showSkipButton(true)
isProgressButtonEnabled = true
}
override fun onSkipPressed(currentFragment: Fragment) {
super.onSkipPressed(currentFragment)
checkStoragePermission()
}
override fun onDonePressed(currentFragment: Fragment) {
super.onDonePressed(currentFragment)
checkStoragePermission()
}
private fun checkStoragePermission() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Permission is not granted
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
val explanation = AlertDialog.Builder(this)
val listener = DialogInterface.OnClickListener { _, _ ->
ActivityCompat.requestPermissions(this,
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE) }
explanation.setTitle(R.string.storage_permission_exp_title)
explanation.setMessage(R.string.wechat_instruction_page1_des)
explanation.setPositiveButton(R.string.alright, listener)
explanation.show()
} else {
// No explanation needed
ActivityCompat.requestPermissions(this,
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE)
}
} else {
// Permission has already been granted
gotoWechatScan()
}
}
private fun gotoWechatScan() {
if (WeiXinDonate.hasInstalledWeiXinClient(this)) {
val weixinQrIs = resources.openRawResource(R.raw.sp_wechat)
val qrPath = Environment.getExternalStorageDirectory().absolutePath + File.separator + "SchoolPowerDonate" + File.separator +
"sp_wechat.png"
WeiXinDonate.saveDonateQrImage2SDCard(qrPath, BitmapFactory.decodeStream(weixinQrIs))
WeiXinDonate.donateViaWeiXin(this, qrPath)
setIsDonated(true)
this.finish()
} else {
setResult(WECHAT_NOT_FOUND)
this.finish()
}
}
private fun setIsDonated(donated: Boolean) {
utils.setPreference("Donated", donated, Utils.TmpData)
}
override fun onRequestPermissionsResult(requestCode: Int,
permissions: Array<String>, grantResults: IntArray) {
when (requestCode) {
MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE -> {
// If request is cancelled, the result arrays are empty.
if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
// permission was granted
gotoWechatScan()
} else {
// permission denied
Toast.makeText(this, R.string.storage_permission_denied, Toast.LENGTH_LONG).show()
this.finish()
}
return
}
else -> {
// Ignore all other requests.
}
}
}
}
| gpl-3.0 | d368fb92d27fd283cd1680e327f68ffc | 40.784431 | 137 | 0.663944 | 4.673811 | false | false | false | false |
world-federation-of-advertisers/cross-media-measurement | src/main/kotlin/org/wfanet/measurement/eventdataprovider/privacybudgetmanagement/PrivacyLandscape.kt | 1 | 1247 | /**
* Copyright 2022 The Cross-Media Measurement Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* ```
* http://www.apache.org/licenses/LICENSE-2.0
* ```
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.wfanet.measurement.eventdataprovider.privacybudgetmanagement
import java.time.LocalDate
object PrivacyLandscape {
const val PRIVACY_BUCKET_VID_SAMPLE_WIDTH = 1f / 300f
val dates: List<LocalDate> = (0..400).map { LocalDate.now().minusDays(it.toLong()) }
val ageGroups: Set<AgeGroup> = AgeGroup.values().toSet()
val genders = Gender.values().toSet()
// There are 300 Vid intervals in the range [0, 1). The last interval has a little smaller length
// - [0.99666667 1) all others have length 1/300
val vidsIntervalStartPoints: List<Float> = (0..299).map { it * PRIVACY_BUCKET_VID_SAMPLE_WIDTH }
}
| apache-2.0 | cd697e56ba815ff0cd0ce1e55abae944 | 43.535714 | 100 | 0.734563 | 3.860681 | false | false | false | false |
RoverPlatform/rover-android | notifications/src/main/kotlin/io/rover/sdk/notifications/ui/NotificationCenterListViewModel.kt | 1 | 5775 | package io.rover.sdk.notifications.ui
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import io.rover.sdk.core.logging.log
import io.rover.sdk.core.streams.PublishSubject
import io.rover.sdk.core.streams.Publishers
import io.rover.sdk.core.streams.doOnNext
import io.rover.sdk.core.streams.doOnRequest
import io.rover.sdk.core.streams.filterNulls
import io.rover.sdk.core.streams.map
import io.rover.sdk.core.streams.share
import io.rover.sdk.core.streams.shareHotAndReplay
import io.rover.sdk.core.tracking.SessionTrackerInterface
import io.rover.sdk.notifications.domain.Notification
import io.rover.sdk.notifications.ui.concerns.NotificationCenterListViewModelInterface
import io.rover.sdk.notifications.ui.concerns.NotificationsRepositoryInterface
import org.reactivestreams.Publisher
import java.util.Date
class NotificationCenterListViewModel(
private val notificationsRepository: NotificationsRepositoryInterface,
private val sessionTracker: SessionTrackerInterface,
activityLifecycle: Lifecycle
) : NotificationCenterListViewModelInterface {
override fun events(): Publisher<out NotificationCenterListViewModelInterface.Event> = epic.doOnRequest {
// Infer from a new subscriber that it's a newly displayed view, and, thus, an
// automatic refresh should be kicked off.
requestRefresh()
}
override fun notificationClicked(notification: Notification) {
actions.onNext(Action.NotificationClicked(notification))
}
override fun deleteNotification(notification: Notification) {
actions.onNext(Action.DeleteNotification(notification))
}
override fun requestRefresh() {
notificationsRepository.refresh()
}
// State: stable IDs mapping. Ensure that we have a 100% consistent stable ID for the lifetime
// of the view model (which will sufficiently match the lifetime of the recyclerview that
// requires the stableids).
private var highestStableId = 0
private val stableIds: MutableMap<String, Int> = mutableMapOf()
private val actions = PublishSubject<Action>()
private val epic: Publisher<NotificationCenterListViewModelInterface.Event> =
Publishers.merge(
actions.share().map { action ->
when (action) {
is Action.NotificationClicked -> {
// the delete operation is entirely asynchronous, as a side-effect.
notificationsRepository.markRead(action.notification)
NotificationCenterListViewModelInterface.Event.Navigate(
action.notification
)
}
is Action.DeleteNotification -> {
notificationsRepository.delete(action.notification)
null
}
}
}.filterNulls(),
notificationsRepository.updates().map { update ->
update
.notifications
.filter { !it.isDeleted }
.filter { it.isNotificationCenterEnabled }
.filter { it.expiresAt?.after(Date()) ?: true }
}.doOnNext { notificationsReadyForDisplay ->
// side-effect, update the stable ids list map:
updateStableIds(notificationsReadyForDisplay)
}.map { notificationsReadyForDisplay ->
NotificationCenterListViewModelInterface.Event.ListUpdated(
notificationsReadyForDisplay,
stableIds
)
}.doOnNext { updateStableIds(it.notifications) },
notificationsRepository
.events()
.map { repositoryEvent ->
log.v("Received event $repositoryEvent")
when (repositoryEvent) {
is NotificationsRepositoryInterface.Emission.Event.Refreshing -> {
NotificationCenterListViewModelInterface.Event.Refreshing(repositoryEvent.refreshing)
}
is NotificationsRepositoryInterface.Emission.Event.FetchFailure -> {
NotificationCenterListViewModelInterface.Event.DisplayProblemMessage()
}
}
}
).shareHotAndReplay(0)
private fun trackEnterNotificationCenter() {
sessionTracker.enterSession(
"NotificationCenter",
"Notification Center Presented",
"Notification Center Viewed",
hashMapOf()
)
}
private fun trackLeaveNotificationCenter() {
sessionTracker.leaveSession(
"NotificationCenter",
"Notification Center Dismissed",
hashMapOf()
)
}
private fun updateStableIds(notifications: List<Notification>) {
notifications.forEach { notification ->
if (!stableIds.containsKey(notification.id)) {
stableIds[notification.id] = ++highestStableId
}
}
}
init {
activityLifecycle.addObserver(object : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun presented() {
trackEnterNotificationCenter()
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun dismissed() {
trackLeaveNotificationCenter()
}
})
}
private sealed class Action {
data class NotificationClicked(val notification: Notification) : Action()
data class DeleteNotification(val notification: Notification) : Action()
}
}
| apache-2.0 | 84606e1a5f6f7f80830a70616b5ed24a | 38.827586 | 109 | 0.638095 | 5.606796 | false | false | false | false |
SimonVT/cathode | cathode-sync/src/main/java/net/simonvt/cathode/actions/movies/SyncMovieCredits.kt | 1 | 4530 | /*
* Copyright (C) 2014 Simon Vig Therkildsen
*
* 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 net.simonvt.cathode.actions.movies
import android.content.ContentProviderOperation
import android.content.Context
import net.simonvt.cathode.actions.CallAction
import net.simonvt.cathode.actions.movies.SyncMovieCredits.Params
import net.simonvt.cathode.api.entity.CrewMember
import net.simonvt.cathode.api.entity.People
import net.simonvt.cathode.api.enumeration.Department
import net.simonvt.cathode.api.enumeration.Extended
import net.simonvt.cathode.api.service.MoviesService
import net.simonvt.cathode.provider.DatabaseContract.MovieCastColumns
import net.simonvt.cathode.provider.DatabaseContract.MovieColumns
import net.simonvt.cathode.provider.DatabaseContract.MovieCrewColumns
import net.simonvt.cathode.provider.ProviderSchematic.MovieCast
import net.simonvt.cathode.provider.ProviderSchematic.MovieCrew
import net.simonvt.cathode.provider.ProviderSchematic.Movies
import net.simonvt.cathode.provider.batch
import net.simonvt.cathode.provider.helper.MovieDatabaseHelper
import net.simonvt.cathode.provider.helper.PersonDatabaseHelper
import retrofit2.Call
import java.util.ArrayList
import javax.inject.Inject
class SyncMovieCredits @Inject constructor(
private val context: Context,
private val movieHelper: MovieDatabaseHelper,
private val personHelper: PersonDatabaseHelper,
private val moviesService: MoviesService
) : CallAction<Params, People>() {
override fun key(params: Params): String = "SyncMovieCredits&traktId=${params.traktId}"
override fun getCall(params: Params): Call<People> =
moviesService.getPeople(params.traktId, Extended.FULL)
override suspend fun handleResponse(params: Params, response: People) {
val movieId = movieHelper.getId(params.traktId)
val ops = arrayListOf<ContentProviderOperation>()
var op = ContentProviderOperation.newDelete(MovieCast.fromMovie(movieId)).build()
ops.add(op)
op = ContentProviderOperation.newDelete(MovieCrew.fromMovie(movieId)).build()
ops.add(op)
val cast = response.cast
if (cast != null) {
for ((character, person) in cast) {
val personId = personHelper.partialUpdate(person)
op = ContentProviderOperation.newInsert(MovieCast.MOVIE_CAST)
.withValue(MovieCastColumns.MOVIE_ID, movieId)
.withValue(MovieCastColumns.PERSON_ID, personId)
.withValue(MovieCastColumns.CHARACTER, character)
.build()
ops.add(op)
}
}
val crew = response.crew
if (crew != null) {
insertCrew(ops, movieId, Department.PRODUCTION, crew.production)
insertCrew(ops, movieId, Department.ART, crew.art)
insertCrew(ops, movieId, Department.CREW, crew.crew)
insertCrew(ops, movieId, Department.COSTUME_AND_MAKEUP, crew.costume_and_make_up)
insertCrew(ops, movieId, Department.DIRECTING, crew.directing)
insertCrew(ops, movieId, Department.WRITING, crew.writing)
insertCrew(ops, movieId, Department.SOUND, crew.sound)
insertCrew(ops, movieId, Department.CAMERA, crew.camera)
}
ops.add(
ContentProviderOperation.newUpdate(Movies.withId(movieId)).withValue(
MovieColumns.LAST_CREDITS_SYNC,
System.currentTimeMillis()
).build()
)
context.contentResolver.batch(ops)
}
private fun insertCrew(
ops: ArrayList<ContentProviderOperation>,
movieId: Long,
department: Department,
crew: List<CrewMember>?
) {
if (crew == null) {
return
}
for ((job, person) in crew) {
val personId = personHelper.partialUpdate(person)
val op = ContentProviderOperation.newInsert(MovieCrew.MOVIE_CREW)
.withValue(MovieCrewColumns.MOVIE_ID, movieId)
.withValue(MovieCrewColumns.PERSON_ID, personId)
.withValue(MovieCrewColumns.CATEGORY, department.toString())
.withValue(MovieCrewColumns.JOB, job)
.build()
ops.add(op)
}
}
data class Params(val traktId: Long)
}
| apache-2.0 | 6ae0c2ce670f3166b73e186ff44e90d7 | 36.438017 | 89 | 0.746578 | 4.210037 | false | false | false | false |
zhufucdev/PCtoPE | app/src/main/java/com/zhufucdev/pctope/activities/MainActivity.kt | 1 | 27704 | package com.zhufucdev.pctope.activities
import android.Manifest
import android.app.ActivityOptions
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.content.Intent.ACTION_VIEW
import android.content.pm.ShortcutInfo
import android.content.pm.ShortcutManager
import android.graphics.BitmapFactory
import android.graphics.drawable.Icon
import android.net.Uri
import android.os.*
import android.preference.PreferenceManager
import android.provider.Settings
import android.util.Log
import android.view.*
import android.view.animation.*
import android.widget.*
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.ActionMenuView
import androidx.appcompat.widget.Toolbar
import androidx.core.app.ActivityCompat
import androidx.core.view.GravityCompat
import androidx.recyclerview.widget.*
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.snackbar.Snackbar
import com.zhufucdev.pctope.adapters.FileChooserAdapter
import com.zhufucdev.pctope.adapters.TextureItems
import com.zhufucdev.pctope.collectors.ActivityCollector
import com.zhufucdev.pctope.interf.DeletingCallback
import com.zhufucdev.pctope.interf.SpacesItemDecoration
import com.zhufucdev.pctope.R
import com.zhufucdev.pctope.utils.*
import java.io.File
import java.util.*
class MainActivity : BaseActivity() {
private fun makeErrorDialog(errorString: String) {
//make up a error dialog
val errorDialog = AlertDialog.Builder(this@MainActivity)
errorDialog.setTitle(R.string.error)
errorDialog.setMessage([email protected](R.string.error_dialog) + errorString)
errorDialog.setIcon(R.drawable.alert_octagram)
errorDialog.setCancelable(false)
errorDialog.setPositiveButton(R.string.close) { _, _ -> finish() }
errorDialog.setNegativeButton(R.string.copy) { _, _ ->
val copy = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
copy.setPrimaryClip(ClipData.newPlainText("Error", errorString))
finish()
}.show()
}
private var progressBar: ProgressBar? = null
private fun showLoading() {
progressBar!!.visibility = View.VISIBLE
}
private fun hideLoading() {
progressBar!!.visibility = View.INVISIBLE
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 0) {
val result = data!!.getBooleanExtra("Status_return", false)
if (result) {
loadList()
updatePinnedShortcut()
initShortcuts()
if (chooserRoot.visibility == View.VISIBLE)
Handler().postDelayed({ Choose() }, 1000)
}
} else if (requestCode == 2) {
if (data == null)
return
if (data.getBooleanExtra("isDataChanged", false)) {
loadList()
updatePinnedShortcut()
initShortcuts()
}
}
}
private fun initToolbar() {
toolbar = findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
val actionBar = supportActionBar ?: return
actionBar.setDisplayHomeAsUpEnabled(true)
actionBar.setHomeAsUpIndicator(R.drawable.menu)
toolbarFore = findViewById(R.id.toolbar_fore)
toolbarFore.title = getString(R.string.mulit_select)
toolbarFore.visibility = View.GONE
menuView = findViewById(R.id.menu_item_view)
menuView.menu.clear()
menuInflater.inflate(R.menu.toolbar_menu, menuView.menu)
}
private val permissions = arrayOf(
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS,
Manifest.permission.READ_EXTERNAL_STORAGE
)
private var swipeRefreshLayout: SwipeRefreshLayout? = null
private lateinit var fab: FloatingActionButton
private lateinit var recyclerView: RecyclerView
private lateinit var chooserRoot: FrameLayout
private lateinit var toolbar: Toolbar
private lateinit var toolbarFore: Toolbar
private lateinit var menuView: ActionMenuView
private var isFromShortcut: Boolean = false
override fun onCreate(bundle: Bundle?) {
setContentView(R.layout.activity_main)
progressBar = findViewById(R.id.progressbar_in_main)
fab = findViewById(R.id.fab)
levelUp = findViewById(R.id.fab_level_up)
levelUp!!.visibility = View.INVISIBLE
levelUp!!.rotation = -90f
recyclerView = findViewById(R.id.recycle_view)
chooserRoot = findViewById(R.id.chooser_in_main)
chooserRoot.visibility = View.INVISIBLE
isFromShortcut = intent.getBooleanExtra("isFromShortcut", true)
mLog.d("Permissions", isGranted.toString())
initToolbar()
//file choosing
fab.setOnClickListener { Choose() }
recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
if (newState > 0) {
fab.hide()
} else {
fab.show()
}
}
})
if (isGranted) {
initActivity()
} else {
Snackbar.make(fab, R.string.permissions_request, Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.ok) {
requirePermissions()
}.show()
}
val actionBar = supportActionBar
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true)
actionBar.setHomeAsUpIndicator(R.drawable.menu)
}
navigationView = findViewById(R.id.nav_view)
drawerLayout = findViewById(R.id.drawer_main)
navigationView!!.setNavigationItemSelectedListener { item ->
drawerLayout!!.closeDrawer(GravityCompat.START)
when (item.itemId) {
R.id.nav_settings -> {
val settings = Intent(this@MainActivity, SettingsActivity::class.java)
startActivity(settings)
}
R.id.nav_about -> {
val about = Intent(this@MainActivity, AboutActivity::class.java)
startActivity(about)
}
R.id.nav_log -> {
val log = Intent(this@MainActivity, ShowLogActivity::class.java)
startActivity(log)
}
}
true
}
super.onCreate(bundle)
}
private fun requirePermissions() {
ActivityCompat.requestPermissions(this@MainActivity, permissions, 1)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && !Environment.isExternalStorageManager()) {
try {
startActivityForResult(
Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION)
.addCategory("android.intent.category.DEFAULT")
.setData(Uri.parse("package:${applicationContext.packageName}")),
2
)
} catch (ignored: Exception) {
startActivityForResult(
Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION),
2
)
}
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
if (requestCode == 1) {
if (isGranted)
initActivity()
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
if (!::items.isInitialized || !items.isInSelectMode)
drawerLayout!!.openDrawer(GravityCompat.START)
else {
inSelectMode(inSelect = false, withLoadingList = false)
}
}
}
return super.onOptionsItemSelected(item)
}
private fun initShortcuts() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N_MR1)
return
val manager = getSystemService(ShortcutManager::class.java)
val max = manager.maxShortcutCountPerActivity - 1
val infos = ArrayList<ShortcutInfo>()
var i = 0
while (i < max && i < mTextures.size) {
val temp = mTextures[i]
if (!temp.ifIsResourcePack("PE")!!) {
i--
continue
}
val intent = Intent(ACTION_VIEW, null, this@MainActivity, DetailsActivity::class.java)
intent.putExtra("texture_name", temp.name)
intent.putExtra("texture_description", temp.description)
intent.putExtra("texture_icon", temp.icon)
intent.putExtra("texture_version", temp.getVersion())
intent.putExtra("texture_path", temp.path)
val info = ShortcutInfo.Builder(this, "pack $i")
.setShortLabel(
if (temp.name.isNullOrEmpty()) {
getString(R.string.unable_to_get_name)
} else {
temp.name
}
)
.setIcon(Icon.createWithBitmap(BitmapFactory.decodeFile(temp.icon)))
.setIntent(intent)
.build()
infos.add(info)
i++
}
manager.dynamicShortcuts = infos
}
private fun updatePinnedShortcut() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N_MR1)
return
val manager = getSystemService(ShortcutManager::class.java)
val pinned = manager.pinnedShortcuts
for (i in 0 until pinned.size) {
var isFound = false
if (pinned[i].id == "add") continue
for (j in 0 until mTextures.size) {
if (pinned[i].intent?.getStringExtra("texture_path") == mTextures[j].path) {
isFound = true
break
}
}
if (!isFound) {
manager.disableShortcuts(listOf(pinned[i].id))
}
}
}
private fun initActivity() {
//init for textures list
recyclerView = findViewById(R.id.recycle_view)
class FirstLoad : AsyncTask<Void, Int, Boolean>() {
override fun onPreExecute() {
showLoading()
}
override fun doInBackground(vararg voids: Void): Boolean? {
loadList()
loadFileChooser()
return null
}
override fun onPostExecute(result: Boolean?) {
hideLoading()
if (isFromShortcut)
Choose()
initShortcuts()
updatePinnedShortcut()
}
}
FirstLoad().execute()
recyclerView.addItemDecoration(SpacesItemDecoration(16))
recyclerView.setHasFixedSize(true)
menuView.setOnMenuItemClickListener { item ->
when (item!!.itemId) {
R.id.delete -> {
val paths = ArrayList<Textures>()
for ((hasBeenDeleted, it) in items.selectedItems.withIndex()) {
val position = it - hasBeenDeleted
val path = items.getItem(position)
paths.add(path)
mTextures.remove(path)
items.notifyItemRemoved(position)
}
setLayoutManager()
initShortcuts()
updatePinnedShortcut()
Snackbar.make(fab, R.string.deleted_completed, Snackbar.LENGTH_LONG)
.addCallback(DeletingCallback(paths.toList()))
.setAction(R.string.undo) {
paths.forEach {
if (File(it.path).exists()) {
mTextures.add(it.position, it)
recyclerView.visibility = View.VISIBLE
loadList()
setLayoutManager()
initShortcuts()
updatePinnedShortcut()
} else {
Snackbar.make(fab, R.string.failed, Snackbar.LENGTH_SHORT)
.show()
}
}
}.show()
inSelectMode(inSelect = false, withLoadingList = false)
}
R.id.select_all -> {
if (!items.isSelectAllButtonActive)
items.selectAll()
else
items.deselectAll()
}
R.id.select_inverse -> {
items.selectInverse()
}
}
true
}
//for swipe refresh layout
swipeRefreshLayout = findViewById(R.id.swipe_refresh)
swipeRefreshLayout!!.setColorSchemeColors(
resources.getColor(R.color.colorAccent),
resources.getColor(R.color.google_blue),
resources.getColor(R.color.google_red),
resources.getColor(R.color.google_green)
)
swipeRefreshLayout!!.setOnRefreshListener {
Thread(Runnable {
try {
Thread.sleep(500)
} catch (e: Throwable) {
e.printStackTrace()
}
runOnUiThread {
inSelectMode(false, true)
swipeRefreshLayout!!.isRefreshing = false
}
}).start()
}
}
var lastTime: Long = 0
var count = 0
override fun onBackPressed() {
if (drawerLayout!!.isDrawerOpen(GravityCompat.START)) {
drawerLayout!!.closeDrawer(GravityCompat.START)
} else if (!items.isInSelectMode) {
if (count == 0) {
lastTime = System.currentTimeMillis()
Snackbar.make(fab, R.string.double_back_exit, Snackbar.LENGTH_LONG)
.setCallback(object : Snackbar.Callback() {
override fun onDismissed(transientBottomBar: Snackbar?, event: Int) {
count = 0
super.onDismissed(transientBottomBar, event)
}
})
.show()
} else {
ActivityCollector.finishAll()
}
Log.d("DoubleBack", "Count = $count , Delay = ${System.currentTimeMillis() - lastTime}")
count++
} else {
inSelectMode(false, false)
}
}
var mTextures: ArrayList<Textures> = ArrayList()
lateinit var items: TextureItems
private fun loadList() {
mTextures = ArrayList()
val packsListDir = File(
Environment.getExternalStorageDirectory()
.toString() + "/games/com.mojang/resource_packs/"
)
val packsList: Array<File>
var make = true
if (!packsListDir.exists()) make = packsListDir.mkdirs()
if (make) {
packsList = packsListDir.listFiles()
items = TextureItems(mTextures)
recyclerView.adapter = items
for (aPacksList in packsList) {
if (aPacksList.exists())
if (aPacksList.isDirectory) {
val texture = Textures(aPacksList)
if (texture.ifIsResourcePack("ALL")!!) {
mTextures.add(texture)
}
}
}
items.setOnItemClickListener(object : TextureItems.OnItemClickListener {
override fun onLongPress(view: View, position: Int) {
inSelectMode(false)
}
override fun onItemClick(view: View, position: Int) {
if (!items.getIfIsAlertIconShown(view)) {
if (!items.isInSelectMode) {
val intent = Intent(this@MainActivity, DetailsActivity::class.java)
val temp = items.getItem(position)
intent.putExtra("texture_name", temp.name)
intent.putExtra("texture_description", temp.description)
intent.putExtra("texture_icon", temp.icon)
intent.putExtra("texture_version", temp.getVersion())
intent.putExtra("texture_path", temp.path)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val options = ActivityOptions.makeSceneTransitionAnimation(
this@MainActivity,
view.findViewById(R.id.card_texture_icon),
getString(R.string.pack_icon_transition)
)
ActivityCompat.startActivityForResult(
this@MainActivity,
intent,
2,
options.toBundle()
)
} else {
startActivityForResult(intent, 2)
}
}
}
}
})
runOnUiThread {
setLayoutManager()
items.notifyDataSetChanged()
}
} else
makeErrorDialog("Failed to make textures root directory.")
}
fun inSelectMode(withLoadingList: Boolean) {
if (items.isInSelectMode) {
val animation = AnimationUtils.loadAnimation(this, R.anim.cards_show)
toolbarFore.visibility = View.VISIBLE
toolbarFore.startAnimation(animation)
setSupportActionBar(toolbarFore)
} else {
if (withLoadingList)
loadList()
items.deselectAll()
val animation = AnimationUtils.loadAnimation(this, R.anim.cards_hide)
toolbarFore.startAnimation(animation)
animation.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationRepeat(animation: Animation?) {}
override fun onAnimationEnd(animation: Animation?) {
toolbarFore.visibility = View.GONE
setSupportActionBar(toolbar)
}
override fun onAnimationStart(animation: Animation?) {}
})
}
}
fun inSelectMode(inSelect: Boolean, withLoadingList: Boolean) {
items.isInSelectMode = inSelect
inSelectMode(withLoadingList)
}
private var adapter: FileChooserAdapter? = null
private var levelUp: FloatingActionButton? = null
private fun Choose() {
if (chooserRoot.visibility == View.INVISIBLE) {
fab.isEnabled = false
levelUp!!.show()
toolbar.setTitle(R.string.choosing_alert)
toolbar.subtitle = adapter!!.getPath()
chooserRoot.visibility = View.VISIBLE
if (!isFromShortcut) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val animator = ViewAnimationUtils.createCircularReveal(
chooserRoot,
fab.x.toInt() + fab.width / 2,
fab.y.toInt() - fab.height / 2,
0f,
Math.hypot(chooserRoot.width.toDouble(), chooserRoot.height.toDouble())
.toFloat()
)
animator.duration = 300
animator.start()
}
}
val first = RotateAnimation(
0.0f,
45.0f * 4 + 15,
Animation.RELATIVE_TO_SELF,
0.5f,
Animation.RELATIVE_TO_SELF,
0.5f
)
first.duration = 200
fab.startAnimation(first)
first.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation) {
}
override fun onAnimationEnd(animation: Animation) {
fab.rotation = 60.0f
val second = RotateAnimation(
15.0f,
0.0f,
Animation.RELATIVE_TO_SELF,
0.5f,
Animation.RELATIVE_TO_SELF,
0.5f
)
second.duration = 100
fab.startAnimation(second)
second.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation) {
}
override fun onAnimationEnd(animation: Animation) {
fab.rotation = 45.0f
fab.isEnabled = true
}
override fun onAnimationRepeat(animation: Animation) {
}
})
}
override fun onAnimationRepeat(animation: Animation) {
}
})
} else {
fab.isEnabled = false
levelUp!!.hide()
toolbar.setTitle(getString(R.string.app_name))
toolbar.subtitle = ""
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val animator = ViewAnimationUtils.createCircularReveal(
chooserRoot,
fab.x.toInt() + fab.width / 2,
fab.y.toInt() - fab.height / 2,
Math.hypot(chooserRoot.width.toDouble(), chooserRoot.height.toDouble())
.toFloat(),
0f
)
animator.duration = 400
animator.start()
} else chooserRoot.visibility = View.INVISIBLE
fab.rotation = 45.0f
val first = RotateAnimation(
0.0f,
-45.0f * 4 + 15,
Animation.RELATIVE_TO_SELF,
0.5f,
Animation.RELATIVE_TO_SELF,
0.5f
)
first.duration = 200
first.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation) {
}
override fun onAnimationEnd(animation: Animation) {
fab.rotation = -15.0f
val second = RotateAnimation(
0.0f,
15.0f,
Animation.RELATIVE_TO_SELF,
0.5f,
Animation.RELATIVE_TO_SELF,
0.5f
)
second.duration = 100
fab.startAnimation(second)
second.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation) {
}
override fun onAnimationEnd(animation: Animation) {
fab.rotation = 0.0f
fab.isEnabled = true
}
override fun onAnimationRepeat(animation: Animation) {
}
})
}
override fun onAnimationRepeat(animation: Animation) {
}
})
fab.startAnimation(first)
Handler().postDelayed({ chooserRoot.visibility = View.INVISIBLE }, 390)
}
isFromShortcut = false
}
var chooser: RecyclerView? = null
private fun loadFileChooser() {
chooser = findViewById(R.id.file_chooser_view)
chooser!!.layoutManager = StaggeredGridLayoutManager(2, OrientationHelper.VERTICAL)
adapter =
FileChooserAdapter(Environment.getExternalStorageDirectory().path, mutableListOf("zip"))
adapter?.setOnItemClickListener(object : FileChooserAdapter.OnItemClickListener {
override fun onClick(view: View, data: Intent) {
val path = data.getStringExtra("path")
if (File(path).isFile) {
val pref = PreferenceManager.getDefaultSharedPreferences(this@MainActivity)
val intent = if (pref.getString(
"pref_conversion_style",
"new"
) == "new"
) Intent(this@MainActivity, ConversionActivity::class.java)
else Intent(this@MainActivity, ConversionActivityOld::class.java)
intent.putExtra("filePath", path)
startActivityForResult(intent, 0)
} else {
toolbar.subtitle = path
}
}
})
levelUp!!.setOnClickListener {
if (adapter!!.upLevel(Environment.getExternalStorageDirectory().path))
toolbar.subtitle = adapter!!.getPath()
else
Snackbar.make(fab as View, R.string.non_upper_level, Snackbar.LENGTH_SHORT).show()
}
runOnUiThread { chooser!!.adapter = adapter }
}
fun setLayoutManager() {
if (items.itemCount == 0) {
recyclerView.visibility = View.GONE
(findViewById<LinearLayout>(R.id.android_nothing)).visibility = View.VISIBLE
} else {
recyclerView.visibility = View.VISIBLE
(findViewById<LinearLayout>(R.id.android_nothing)).visibility = View.GONE
}
var layoutManager = LinearLayoutManager(this@MainActivity)
val displayMetrics = resources.displayMetrics
val width = displayMetrics.widthPixels
val height = displayMetrics.heightPixels
val itemCount = items.itemCount
if (itemCount != 0) {
if (width >= height) {
var lineCount = Math.round(width / 512f)
if (lineCount >= itemCount && itemCount != 0)
lineCount = items.itemCount
mLog.i(
"Layout Manager",
"Layout manager set by Grid Layout Manager. Line count is $lineCount"
)
layoutManager = GridLayoutManager(this, lineCount)
}
}
recyclerView.layoutManager = layoutManager
}
} | gpl-3.0 | 7af048511fe9739d774d9594d0280a4a | 35.792829 | 104 | 0.52866 | 5.573124 | false | false | false | false |
crunchersaspire/worshipsongs-android | app/src/main/java/org/worshipsongs/task/HttpAsyncTask.kt | 2 | 5792 | package org.worshipsongs.task
import android.app.ProgressDialog
import android.content.SharedPreferences
import android.os.AsyncTask
import android.os.Bundle
import android.preference.PreferenceManager
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import org.worshipsongs.CommonConstants
import org.worshipsongs.R
import org.worshipsongs.fragment.AlertDialogFragment
import org.worshipsongs.parser.CommitMessageParser
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
/**
* Author : Madasamy
* Version : 3.x
*/
class HttpAsyncTask(private val context: AppCompatActivity) : AsyncTask<String, String, String>(), AlertDialogFragment.DialogListener
{
private val progressDialog: ProgressDialog?
private var sharedPreferences: SharedPreferences? = null
private val commitMessageParser = CommitMessageParser()
private val remoteUrl: String
get() = sharedPreferences!!.getString(CommonConstants.REMOTE_URL, context.getString(R.string.remoteUrl))!!
init
{
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
progressDialog = ProgressDialog(context)
}
override fun onPreExecute()
{
super.onPreExecute()
progressDialog!!.setMessage(context.getString(R.string.check_update_message))
progressDialog.isIndeterminate = true
progressDialog.setCancelable(false)
progressDialog.show()
}
override fun doInBackground(vararg params: String): String?
{
val stringUrl = params[0]
val result: String
var inputLine: String? = null
try
{
val myUrl = URL(stringUrl)
Log.i(CLASS_NAME, "Preparing to check download " + stringUrl + "")
val connection = myUrl.openConnection() as HttpURLConnection
connection.requestMethod = REQUEST_METHOD
connection.readTimeout = READ_TIMEOUT
connection.connectTimeout = CONNECTION_TIMEOUT
connection.connect()
val streamReader = InputStreamReader(connection.inputStream)
val reader = BufferedReader(streamReader)
val stringBuilder = StringBuilder()
while ({ inputLine = reader.readLine(); inputLine }() != null)
{
stringBuilder.append(inputLine)
}
//Close our InputStream and Buffered reader
reader.close()
streamReader.close()
//Set our result equal to our stringBuilder
result = stringBuilder.toString()
return result
} catch (e: Exception)
{
Log.e(CLASS_NAME, "Error", e)
return ""
}
}
override fun onPostExecute(jsonObject: String)
{
super.onPostExecute(jsonObject)
val shaKey = commitMessageParser.getShaKey(jsonObject)
val existingShaKey = sharedPreferences!!.getString(CommonConstants.COMMIT_SHA_KEY, "")
if (!context.isFinishing && progressDialog != null && progressDialog.isShowing)
{
progressDialog.dismiss()
}
displayAlertDialog(shaKey, existingShaKey!!)
}
private fun displayAlertDialog(shaKey: String?, existingShaKey: String)
{
val bundle = Bundle()
bundle.putString(CommonConstants.COMMIT_SHA_KEY, shaKey)
bundle.putString(CommonConstants.TITLE_KEY, context.getString(R.string.updates_title))
if (shaKey == null || shaKey.isEmpty())
{
bundle.putString(CommonConstants.TITLE_KEY, context.getString(R.string.warning))
bundle.putString(CommonConstants.MESSAGE_KEY, "Error occurred while checking song updates")
val alertDialogFragment = AlertDialogFragment.newInstance(bundle)
alertDialogFragment.isCancelable = false
alertDialogFragment.setVisibleNegativeButton(false)
alertDialogFragment.setDialogListener(this)
alertDialogFragment.show(context.supportFragmentManager, "MessageUpdateFragment")
} else if (existingShaKey.equals(shaKey, ignoreCase = true))
{
bundle.putString(CommonConstants.MESSAGE_KEY, context.getString(R.string.message_no_update))
val alertDialogFragment = AlertDialogFragment.newInstance(bundle)
alertDialogFragment.isCancelable = false
alertDialogFragment.setVisibleNegativeButton(false)
alertDialogFragment.setDialogListener(this)
alertDialogFragment.show(context.supportFragmentManager, "NoUpdateFragment")
} else
{
bundle.putString(CommonConstants.MESSAGE_KEY, context.getString(R.string.message_update_available))
val alertDialogFragment = AlertDialogFragment.newInstance(bundle)
alertDialogFragment.isCancelable = false
alertDialogFragment.setDialogListener(this)
alertDialogFragment.show(context.supportFragmentManager, "UpdateFragment")
}
}
override fun onClickPositiveButton(bundle: Bundle?, tag: String?)
{
if ("UpdateFragment".equals(tag!!, ignoreCase = true))
{
AsyncDownloadTask(context).execute(remoteUrl)
sharedPreferences!!.edit().putString(CommonConstants.COMMIT_SHA_KEY, bundle!!.getString(CommonConstants.COMMIT_SHA_KEY)).apply()
} else
{
[email protected]()
}
}
override fun onClickNegativeButton()
{
context.finish()
}
companion object
{
private val CLASS_NAME = HttpAsyncTask::class.java.simpleName
val REQUEST_METHOD = "GET"
val READ_TIMEOUT = 15000
val CONNECTION_TIMEOUT = 15000
}
}
| gpl-3.0 | f563852773f753546683bf322363cec4 | 37.105263 | 140 | 0.677486 | 5.270246 | false | false | false | false |
jeffersonvenancio/BarzingaNow | android/app/src/main/java/com/barzinga/view/ItemDetailFragment.kt | 1 | 1396 | package com.barzinga.view
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.barzinga.R
import com.barzinga.model.Item
/**
* Created by diego.santos on 18/10/17.
*/
class ItemDetailFragment : Fragment() {
private var item: Item? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
item = arguments.getSerializable("item") as Item
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val view = inflater!!.inflate(R.layout.fragment_item_detail,
container, false)
val tvTitle = view.findViewById<View>(R.id.tvTitle) as TextView
val tvBody = view.findViewById<View>(R.id.tvBody) as TextView
tvTitle.text = item!!.title
tvBody.text = item!!.body
return view
}
companion object {
// ItemDetailFragment.newInstance(item)
fun newInstance(item: Item): ItemDetailFragment {
val fragmentDemo = ItemDetailFragment()
val args = Bundle()
args.putSerializable("item", item)
fragmentDemo.arguments = args
return fragmentDemo
}
}
} | apache-2.0 | fa8e16eaabb35955595896cb1345fa04 | 30.044444 | 79 | 0.659026 | 4.562092 | false | false | false | false |
mopsalarm/Pr0 | app/src/main/java/com/pr0gramm/app/ui/fragments/post/CommentTreeController.kt | 1 | 3711 | package com.pr0gramm.app.ui.fragments.post
import com.pr0gramm.app.Logger
import com.pr0gramm.app.api.pr0gramm.Api
import com.pr0gramm.app.orm.Vote
import com.pr0gramm.app.ui.fragments.feed.update
import com.pr0gramm.app.util.LongSparseArray
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.dropWhile
import kotlinx.coroutines.flow.mapLatest
import kotlinx.coroutines.runInterruptible
/**
* Handles updates to comments ands performs tree calculation in the background.
*/
class CommentTreeController(op: String) {
private val logger = Logger("CommentTreeHelper")
private val inputState = MutableStateFlow(CommentTree.Input(isValid = false, op = op))
val comments = inputState
.dropWhile { state -> !state.isValid }
.mapLatest { state -> calculateVisibleComments(state) }
// update the currently selected comment
fun selectComment(id: Long) {
inputState.update { it.copy(selectedCommentId = id) }
}
fun updateUserInfo(selfUser: String?, isAdmin: Boolean) {
inputState.update { it.copy(self = selfUser, isAdmin = isAdmin) }
}
fun collapseComment(commentId: Long) {
inputState.update { it.copy(collapsed = it.collapsed + commentId) }
}
fun collapseComments(commentIds: Iterable<Long>) {
inputState.update { it.copy(collapsed = it.collapsed + commentIds) }
}
fun expandComment(commentId: Long) {
inputState.update { it.copy(collapsed = it.collapsed - commentId) }
}
fun updateVotes(currentVotes: LongSparseArray<Vote>) {
inputState.update { previousState ->
previousState.copy(
baseVotes = calculateBaseVotes(currentVotes),
currentVotes = currentVotes.clone(),
)
}
}
fun updateComments(comments: List<Api.Comment>, currentVotes: LongSparseArray<Vote>) {
inputState.update { previousState ->
previousState.copy(
isValid = true,
allComments = comments.toList(),
baseVotes = calculateBaseVotes(currentVotes),
currentVotes = currentVotes.clone(),
)
}
}
fun clearComments() {
inputState.update { previousState ->
previousState.copy(allComments = listOf())
}
}
private fun calculateBaseVotes(currentVotes: LongSparseArray<Vote>): LongSparseArray<Vote> {
// start with the current votes and reset the existing base votes
return currentVotes.clone().apply {
putAll(inputState.value.baseVotes)
}
}
private suspend fun calculateVisibleComments(inputState: CommentTree.Input): LinearizedComments {
logger.debug {
"Will run an update for current state ${System.identityHashCode(inputState)} " +
"(${inputState.allComments.size} comments, " +
"selected=${inputState.selectedCommentId})"
}
if (inputState.allComments.isEmpty()) {
// quickly return if there are no comments to display
return LinearizedComments(comments = listOf())
}
return runInterruptible(Dispatchers.Default) {
logger.debug { "Running update in thread ${Thread.currentThread().name}" }
LinearizedComments(
comments = CommentTree(inputState).visibleComments,
hasCollapsedComments = inputState.collapsed.isNotEmpty(),
)
}
}
class LinearizedComments(
val comments: List<CommentTree.Item>,
val hasCollapsedComments: Boolean = false,
)
} | mit | 8b78537ffccb690135f6ef3bf8b46d7d | 34.018868 | 101 | 0.648882 | 4.715375 | false | false | false | false |
colriot/anko | preview/idea-plugin/src/org/jetbrains/kotlin/android/dslpreview/RobowrapperDependencies.kt | 1 | 1794 | /*
* Copyright 2015 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.kotlin.android.dslpreview
import com.intellij.openapi.application.PathManager
import java.io.File
object RobowrapperDependencies {
internal val DEPENDENCIES_DIRECTORY: File = File(PathManager.getSystemPath(), "dsl-plugin/deps")
internal val ANDROID_ALL_DEPENDENCY = Dependency("org.robolectric", "android-all", "5.0.0_r2-robolectric-1")
internal val DEPENDENCIES: List<Dependency> = listOf(
ANDROID_ALL_DEPENDENCY,
Dependency("org.robolectric", "shadows-core", "3.0-rc3", postfix = "-21"),
Dependency("org.robolectric", "shadows-support-v4", "3.0-rc3", postfix = "-21"),
Dependency("org.json", "json", "20080701"),
Dependency("org.ccil.cowan.tagsoup", "tagsoup", "1.2")
)
}
class Dependency(
group: String,
artifact: String,
version: String,
extension: String = "jar",
postfix: String? = ""
) {
internal val downloadUrl = "http://central.maven.org/maven2/${group.replace('.', '/')}/" +
"$artifact/$version/$artifact-$version.$extension"
internal val file = File(RobowrapperDependencies.DEPENDENCIES_DIRECTORY, "$artifact-$version$postfix.$extension")
} | apache-2.0 | 59e7f7d0f4fb233530b3f7d2d85021f5 | 36.395833 | 117 | 0.692308 | 3.917031 | false | false | false | false |
Zephyrrus/ubb | YEAR 3/SEM 1/MOBILE/native/PhotoApp/app/src/main/java/com/example/zephy/photoapp/entity/LessonSubmissionCommentEntity.kt | 1 | 1093 | package com.example.zephy.photoapp.entity
import android.arch.persistence.room.ColumnInfo
import android.arch.persistence.room.Entity
import android.arch.persistence.room.Ignore
import android.arch.persistence.room.PrimaryKey
import com.example.zephy.photoapp.model.UserModel
import java.util.*
@Entity(tableName = "submission_comment_table")
class LessonSubmissionCommentEntity(
@ColumnInfo(name = "submissionId")
var submissionId: Int,
@ColumnInfo(name = "date")
var date: Date,
@ColumnInfo(name = "content")
var content: String,
@ColumnInfo(name = "userId")
var userId: Int,
@ColumnInfo(name = "parentId")
var parentId: String?,
@ColumnInfo(name = "syncId")
var syncId: String?
) {
@PrimaryKey(autoGenerate = true)
var id: Int = 0
@Ignore
var user: UserModel = UserModel(1, "Krisztian", "Kristo", "Zephy", "[email protected]", Calendar.getInstance().time)
}
//data class LessonSubmissionCommentModel(val id: Int, val submissionId: Int, val date: Date, val content: String, val user: UserModel, val parentId: Int?) | mit | e4078a172e75a0c87157f70946a17f0f | 27.789474 | 155 | 0.720952 | 3.730375 | false | false | false | false |
QuickBlox/quickblox-android-sdk | sample-conference-kotlin/app/src/main/java/com/quickblox/sample/conference/kotlin/presentation/screens/chat/ViewState.kt | 1 | 3177 | package com.quickblox.sample.conference.kotlin.presentation.screens.chat
import androidx.annotation.IntDef
import com.quickblox.sample.conference.kotlin.presentation.screens.chat.ViewState.Companion.ERROR
import com.quickblox.sample.conference.kotlin.presentation.screens.chat.ViewState.Companion.ERROR_LOAD_ATTACHMENT
import com.quickblox.sample.conference.kotlin.presentation.screens.chat.ViewState.Companion.ERROR_UPLOAD
import com.quickblox.sample.conference.kotlin.presentation.screens.chat.ViewState.Companion.FILE_DELETED
import com.quickblox.sample.conference.kotlin.presentation.screens.chat.ViewState.Companion.FILE_LOADED
import com.quickblox.sample.conference.kotlin.presentation.screens.chat.ViewState.Companion.FILE_SHOWED
import com.quickblox.sample.conference.kotlin.presentation.screens.chat.ViewState.Companion.LEAVE
import com.quickblox.sample.conference.kotlin.presentation.screens.chat.ViewState.Companion.LOADER_PROGRESS_UPDATED
import com.quickblox.sample.conference.kotlin.presentation.screens.chat.ViewState.Companion.MESSAGES_SHOWED
import com.quickblox.sample.conference.kotlin.presentation.screens.chat.ViewState.Companion.MESSAGES_UPDATED
import com.quickblox.sample.conference.kotlin.presentation.screens.chat.ViewState.Companion.MESSAGE_SENT
import com.quickblox.sample.conference.kotlin.presentation.screens.chat.ViewState.Companion.RECEIVED_MESSAGE
import com.quickblox.sample.conference.kotlin.presentation.screens.chat.ViewState.Companion.PROGRESS
import com.quickblox.sample.conference.kotlin.presentation.screens.chat.ViewState.Companion.SHOW_ATTACHMENT_SCREEN
import com.quickblox.sample.conference.kotlin.presentation.screens.chat.ViewState.Companion.SHOW_CALL_SCREEN
import com.quickblox.sample.conference.kotlin.presentation.screens.chat.ViewState.Companion.SHOW_INFO_SCREEN
import com.quickblox.sample.conference.kotlin.presentation.screens.chat.ViewState.Companion.SHOW_LOGIN_SCREEN
import com.quickblox.sample.conference.kotlin.presentation.screens.chat.ViewState.Companion.UPDATE_TOOLBAR
/*
* Created by Injoit in 2021-09-30.
* Copyright © 2021 Quickblox. All rights reserved.
*/
@IntDef(PROGRESS, ERROR, MESSAGES_SHOWED, RECEIVED_MESSAGE, LOADER_PROGRESS_UPDATED, MESSAGE_SENT, SHOW_ATTACHMENT_SCREEN,
ERROR_UPLOAD, LEAVE, FILE_SHOWED, FILE_DELETED, MESSAGES_UPDATED, SHOW_CALL_SCREEN, UPDATE_TOOLBAR, ERROR_LOAD_ATTACHMENT,
SHOW_LOGIN_SCREEN, SHOW_INFO_SCREEN, FILE_LOADED)
annotation class ViewState {
companion object {
const val PROGRESS = 0
const val ERROR = 1
const val MESSAGES_SHOWED = 2
const val RECEIVED_MESSAGE = 4
const val LOADER_PROGRESS_UPDATED = 5
const val MESSAGE_SENT = 6
const val SHOW_ATTACHMENT_SCREEN = 7
const val LEAVE = 8
const val FILE_SHOWED = 9
const val ERROR_UPLOAD = 10
const val FILE_DELETED = 11
const val MESSAGES_UPDATED = 12
const val SHOW_CALL_SCREEN = 13
const val UPDATE_TOOLBAR = 14
const val ERROR_LOAD_ATTACHMENT = 15
const val SHOW_LOGIN_SCREEN = 16
const val SHOW_INFO_SCREEN = 17
const val FILE_LOADED = 18
}
} | bsd-3-clause | 8b1d82e12abaae9661ac1c5c1ba00017 | 61.294118 | 130 | 0.795025 | 4.162516 | false | false | false | false |
ademar111190/goodreads | app/src/main/java/ademar/goodreads/core/model/Work.kt | 1 | 1099 | package ademar.goodreads.core.model
import org.simpleframework.xml.Element
import org.simpleframework.xml.Root
@Root(name = "work", strict = false)
class Work {
@field:Element(name = "id")
var id: Long = 0
@field:Element(name = "books_count")
var booksCount: Int = 0
@field:Element(name = "ratings_count")
var ratingsCount: Int = 0
@field:Element(name = "text_reviews_count")
var reviewsCount: Int = 0
@field:Element(name = "original_publication_day", required = false)
var publicationDay: Int? = null
@field:Element(name = "original_publication_month", required = false)
var publicationMonth: Int? = null
@field:Element(name = "original_publication_year", required = false)
var publicationYear: Int? = null
@field:Element(name = "average_rating")
var averageRating: Double = 0.0
@field:Element(name = "best_book")
lateinit var bestBook: Book
override fun equals(other: Any?): Boolean {
return other is Work && id == other.id
}
override fun hashCode(): Int {
return id.toInt()
}
}
| mit | 7c13a6e620c2a75dd88d8e4c18603a57 | 23.977273 | 73 | 0.656051 | 3.687919 | false | false | false | false |
soniccat/android-taskmanager | taskmanager_httptask/src/main/java/com/aglushkov/taskmanager_http/loader/http/TransportTask.kt | 1 | 2134 | package com.aglushkov.taskmanager_http.loader.http
import com.example.alexeyglushkov.streamlib.progress.ProgressUpdater
import com.aglushkov.taskmanager_http.loader.transport.TaskTransport
import com.example.alexeyglushkov.taskmanager.task.TaskImpl
open class TransportTask : TaskImpl, TaskTransport.Listener {
private var _transport: TaskTransport? = null
var transport: TaskTransport
get() {
return _transport!!
}
set(value) {
if (_transport != null && _transport?.listener === this) {
transport.listener = null
}
_transport = value
transport.listener = this
val transportId = transport.id
if (transportId != null) {
taskId = transportId
}
}
constructor() : super()
constructor(transport: TaskTransport) : super() {
this.transport = transport
}
override suspend fun startTask() {
transport.start()
if (needCancelTask) {
setIsCancelled()
} else {
val e = transport.error
val d = transport.data
if (e != null) {
setError(e)
} else {
taskResult = d
}
}
}
fun setError(error: Exception) {
private.taskError = error
}
override fun canBeCancelledImmediately(): Boolean {
return true
}
override fun clear() {
super.clear()
transport.clear()
}
override fun cancelTask(info: Any?) {
val progressUpdater = transport.progressUpdater
if (progressUpdater != null) {
transport.cancel()
progressUpdater.cancel(info) // cancel will call this method again
} else {
super.cancelTask(info)
}
}
// TaskTransport.Listener
override fun getProgressUpdater(transport: TaskTransport, size: Float): ProgressUpdater {
return createProgressUpdater(size)
}
override fun needCancel(transport: TaskTransport): Boolean {
return needCancelTask
}
}
| mit | 407bbbdca7ef74cced73a01339056de4 | 24.404762 | 93 | 0.583411 | 4.962791 | false | false | false | false |
rcgroot/open-gpstracker-ng | studio/features/src/main/java/nl/sogeti/android/gpstracker/ng/features/map/rendering/TrackPolylineProvider.kt | 1 | 3061 | /*------------------------------------------------------------------------------
** Ident: Sogeti Smart Mobile Solutions
** Author: rene
** Copyright: (c) 2016 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker 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 OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.ng.features.map.rendering
import android.graphics.Color
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.PolylineOptions
class TrackPolylineProvider(val waypoints: List<List<LatLng>>) {
val lineOptions by lazy { drawPolylines() }
private val LINE_SEGMENTS = 150
private fun drawPolylines(): List<PolylineOptions> {
val points = waypoints.filter { it.size >= 2 }
val distribution = distribute(points)
val lineOptions = mutableListOf<PolylineOptions>()
for (i in points.indices) {
val options = PolylineOptions()
.width(5f)
.color(Color.RED)
fillLine(points[i], options, distribution[i])
lineOptions.add(options)
}
return lineOptions
}
private fun distribute(points: List<List<LatLng>>): List<Int> {
val distribution = mutableListOf<Int>()
val total = points.fold(0, { count, list -> count + list.size })
points.forEach { distribution.add((LINE_SEGMENTS * it.size) / total) }
return distribution
}
private fun fillLine(points: List<LatLng>, options: PolylineOptions, goal: Int) {
options.add(points.first())
if (goal > 0) {
val initialStep = points.size / goal
val step = Math.max(1, initialStep)
for (i in step..points.size - 1 step step) {
options.add(points[i])
}
}
options.add(points.last())
}
}
| gpl-3.0 | ed0f3a1d2674864b7fbfeeb81d0b6951 | 39.813333 | 85 | 0.592617 | 4.596096 | false | false | false | false |
06needhamt/Neuroph-Intellij-Plugin | neuroph-plugin/src/com/thomas/needham/neurophidea/actions/ShowAboutFromAction.kt | 1 | 2085 | /*
The MIT License (MIT)
Copyright (c) 2016 Tom Needham
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.thomas.needham.neurophidea.actions
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.Project
import com.thomas.needham.neurophidea.forms.about.AboutForm
/**
* Created by thoma on 13/06/2016.
*/
class ShowAboutFromAction : AnAction() {
var form: AboutForm? = null
var itr: Long = 0L
companion object ProjectInfo {
var project: Project? = null
var projectDirectory: String? = ""
var isOpen: Boolean? = false
}
override fun actionPerformed(e: AnActionEvent) {
InitialisationAction.project = e.project
InitialisationAction.projectDirectory = InitialisationAction.project?.basePath
InitialisationAction.isOpen = InitialisationAction.project?.isOpen
form = AboutForm()
}
override fun update(e: AnActionEvent) {
super.update(e)
if (form != null) {
form?.repaint(itr, 0, 0, form?.width!!, form?.height!!)
itr++
}
e.presentation.isEnabledAndVisible = true
}
}
| mit | a51a8b88c093b5b78ebe8eaf11f9d14f | 34.338983 | 80 | 0.77506 | 4.195171 | false | false | false | false |
lindelea/lindale | app/src/main/java/org/lindelin/lindale/Application.kt | 1 | 2797 | package org.lindelin.lindale
import android.annotation.SuppressLint
import android.content.Context
import com.github.kittinunf.fuel.core.FuelManager
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import org.lindelin.lindale.models.Settings
import org.lindelin.lindale.supports.Keys
import org.lindelin.lindale.supports.Preferences
class Application : android.app.Application() {
private lateinit var clientUrl: String
private lateinit var clientId: String
private lateinit var clientSecret: String
fun getClientUrl() = clientUrl
fun getClientId() = clientId
fun getClientSecret() = clientSecret
companion object {
lateinit var instance: Context
}
override fun onCreate() {
super.onCreate()
instance = this
}
fun init() {
println("App init start...")
Preferences(this@Application).getString(Keys.CLIENT_URL)?.let {
FuelManager.instance.basePath = it
}
val db = FirebaseDatabase.getInstance()
val ref = db.getReference("system/oauth")
ref.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
dataSnapshot.value.let {
val oauthInfo = it as HashMap<*,*>
clientUrl = oauthInfo["client_url"].toString()
clientId = oauthInfo["client_id"].toString()
clientSecret = oauthInfo["client_secret"].toString()
Preferences(this@Application).transaction {
putString(Keys.CLIENT_URL, oauthInfo["client_url"].toString())
putString(Keys.CLIENT_ID, oauthInfo["client_id"].toString())
putString(Keys.CLIENT_SECRET, oauthInfo["client_secret"].toString())
}
FuelManager.instance.basePath = clientUrl
syncPreferences()
println("App init end...")
}
}
override fun onCancelled(error: DatabaseError) {
println(error)
}
})
}
fun syncPreferences() {
Settings.Locale.fetch(this) {
it?.let {
Preferences(this).transaction {
putString(Keys.USER_LANG, it.currentLanguage)
}
}
}
Settings.Notification.fetch(this) {
it?.let {
Preferences(this).transaction {
putBoolean(Keys.USER_NOTIFICATION_SLACK, it.getSlackConfig())
}
}
}
}
} | mit | 6dbf434e78b4507576c725b9b184a2d4 | 33.975 | 92 | 0.597426 | 5.122711 | false | false | false | false |
liceoArzignano/app_bold | app/src/main/kotlin/it/liceoarzignano/bold/firebase/BoldMessagingService.kt | 1 | 4125 | package it.liceoarzignano.bold.firebase
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import android.util.Log
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import it.liceoarzignano.bold.BuildConfig
import it.liceoarzignano.bold.R
import it.liceoarzignano.bold.news.News
import it.liceoarzignano.bold.news.NewsHandler
import it.liceoarzignano.bold.news.NewsListActivity
import it.liceoarzignano.bold.settings.AppPrefs
import org.json.JSONException
import org.json.JSONObject
import java.util.*
class BoldMessagingService : FirebaseMessagingService() {
private lateinit var mNews: News
override fun onMessageReceived(remoteMessage: RemoteMessage?) {
if (remoteMessage == null || remoteMessage.data.isEmpty()) {
return
}
try {
val json = JSONObject(remoteMessage.data.toString())
val title = json.getString(if (BuildConfig.DEBUG) "d_title" else "title")
var message: String? = json.getString(if (BuildConfig.DEBUG) "d_message" else "message")
val url = json.getString("url")
val isPrivate = json.getBoolean("isPrivate")
val intent: Intent
val prefs = AppPrefs(baseContext)
if (message.isNullOrBlank() || (isPrivate &&
!prefs.get(AppPrefs.KEY_IS_TEACHER, false))) {
return
}
if (isPrivate) {
message = getString(R.string.news_type_private, message)
}
mNews = News(title, System.currentTimeMillis(), message?: "", url)
saveNews()
if (prefs.get(AppPrefs.KEY_NOTIF_NEWS, true)) {
intent = Intent(applicationContext, NewsListActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
if (url.isNotBlank()) {
intent.putExtra("newsUrl", mNews.url)
}
publishNotification(intent)
}
} catch (e: JSONException) {
Log.e(TAG, e.message)
}
}
private fun publishNotification(intent: Intent) {
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
val pIntent = PendingIntent.getActivity(application, 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT)
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val builder = NotificationCompat.Builder(baseContext, CHANNEL)
.setSmallIcon(R.drawable.ic_notification)
.setAutoCancel(true)
.setContentTitle(mNews.title)
.setContentText(mNews.description + '\u2026')
.setContentIntent(pIntent)
.setGroup(CHANNEL)
.setColor(ContextCompat.getColor(baseContext, R.color.colorAccent))
.setStyle(NotificationCompat.BigTextStyle().bigText(mNews.description))
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
var channel: NotificationChannel? = manager.getNotificationChannel(CHANNEL)
if (channel == null) {
channel = NotificationChannel(CHANNEL, getString(R.string.channel_title_news),
NotificationManager.IMPORTANCE_DEFAULT)
channel.description = getString(R.string.channel_description_news)
channel.enableLights(true)
manager.createNotificationChannel(channel)
}
}
manager.notify(Calendar.getInstance().timeInMillis.toInt() * 1000, builder.build())
}
private fun saveNews() = NewsHandler.getInstance(this).add(mNews)
companion object {
private const val TAG = "BoldFireBase"
private const val CHANNEL = "channel_news"
}
}
| lgpl-3.0 | 201f692def554b512ec7f4b33a54d6f9 | 39.841584 | 100 | 0.651879 | 4.830211 | false | false | false | false |
nextcloud/android | app/src/androidTest/java/com/nextcloud/client/files/downloader/DownloaderServiceTest.kt | 1 | 1987 | /**
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* Copyright (C) 2020 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.files.downloader
import androidx.test.core.app.ApplicationProvider.getApplicationContext
import androidx.test.rule.ServiceTestRule
import com.nextcloud.client.account.MockUser
import io.mockk.MockKAnnotations
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
class DownloaderServiceTest {
@get:Rule
val service = ServiceTestRule.withTimeout(3, TimeUnit.SECONDS)
val user = MockUser()
@Before
fun setUp() {
MockKAnnotations.init(this, relaxed = true)
}
@Test(expected = TimeoutException::class)
fun cannot_bind_to_service_without_user() {
val intent = FileTransferService.createBindIntent(getApplicationContext(), user)
intent.removeExtra(FileTransferService.EXTRA_USER)
service.bindService(intent)
}
@Test
fun bind_with_user() {
val intent = FileTransferService.createBindIntent(getApplicationContext(), user)
val binder = service.bindService(intent)
assertTrue(binder is FileTransferService.Binder)
}
}
| gpl-2.0 | b7555d9de85c3581c1dc258ddcbf7829 | 33.258621 | 88 | 0.749371 | 4.376652 | false | true | false | false |
d9n/intellij-rust | src/main/kotlin/org/rust/ide/intentions/UnElideLifetimesIntention.kt | 1 | 3493 | package org.rust.ide.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.typeParameters
import org.rust.lang.core.psi.ext.isRef
import org.rust.lang.core.psi.ext.selfParameter
import org.rust.lang.core.psi.ext.valueParameters
import org.rust.lang.core.psi.ext.parentOfType
class UnElideLifetimesIntention : RsElementBaseIntentionAction<RsFunction>() {
override fun getText() = "Un-elide lifetimes"
override fun getFamilyName(): String = text
override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): RsFunction? {
val fn = element.parentOfType<RsFunction>(stopAt = RsBlock::class.java) ?: return null
if ((fn.retType?.typeReference as? RsRefLikeType)?.lifetime != null) return null
val args = fn.allRefArgs
if (args.isEmpty() || args.any { it.lifetime != null }) return null
return fn
}
override fun invoke(project: Project, editor: Editor, ctx: RsFunction) {
ctx.allRefArgs.asSequence().zip(nameGenerator).forEach {
it.first.replace(createParam(project, it.first, it.second))
}
// generic params
val genericParams = RsPsiFactory(project).createTypeParameterList(
ctx.allRefArgs.mapNotNull { it.lifetime?.text } + ctx.typeParameters.map { it.text }
)
ctx.typeParameterList?.replace(genericParams) ?: ctx.addAfter(genericParams, ctx.identifier)
// return type
val retType = ctx.retType?.typeReference as? RsRefLikeType ?: return
if ((ctx.selfParameter != null) || (ctx.allRefArgs.drop(1).none())) {
retType.replace(createRefType(project, retType, ctx.allRefArgs.first().lifetime!!.text))
} else {
val lifeTime = (retType.replace(createRefType(project, retType, "'unknown"))
as RsRefLikeType).lifetime ?: return
editor.selectionModel.setSelection(lifeTime.textRange.startOffset + 1, lifeTime.textRange.endOffset)
}
}
private val nameGenerator = generateSequence(0) { it + 1 }.map {
val abcSize = 'z' - 'a' + 1
// BACKCOMPAT: 2016.3
@Suppress("DEPRECATED_BINARY_MOD_AS_REM")
val letter = 'a' + it % abcSize
val index = it / abcSize
return@map if (index == 0) "'$letter" else "'$letter$index"
}
private fun createRefType(project: Project, origin: RsRefLikeType, lifeTimeName: String): RsRefLikeType =
RsPsiFactory(project).createType(origin.text.replaceFirst("&", "&$lifeTimeName ")) as RsRefLikeType
private fun createParam(project: Project, origin: PsiElement, lifeTimeName: String): PsiElement =
RsPsiFactory(project).createMethodParam(origin.text.replaceFirst("&", "&$lifeTimeName "))
private val RsFunction.allRefArgs: List<PsiElement> get() {
val selfAfg: List<PsiElement> = listOfNotNull(selfParameter)
val params: List<PsiElement> = valueParameters
.filter { param ->
val type = param.typeReference
type is RsRefLikeType && type.isRef
}
return (selfAfg + params).filterNotNull()
}
private val PsiElement.lifetime: RsLifetime? get() =
when (this) {
is RsSelfParameter -> lifetime
is RsValueParameter -> (typeReference as? RsRefLikeType)?.lifetime
else -> null
}
}
| mit | 4abeae52e75e3ba7f0002662a16451ad | 41.597561 | 112 | 0.671915 | 4.275398 | false | false | false | false |
DemonWav/IntelliJBukkitSupport | src/main/kotlin/nbt/filetype/NbtFileType.kt | 1 | 692 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.nbt.filetype
import com.demonwav.mcdev.asset.PlatformAssets
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.vfs.VirtualFile
object NbtFileType : FileType {
override fun getDefaultExtension() = "nbt"
override fun getIcon() = PlatformAssets.MINECRAFT_ICON
override fun getCharset(file: VirtualFile, content: ByteArray): String? = null
override fun getName() = "NBT"
override fun getDescription() = "Named Binary Tag"
override fun isBinary() = true
override fun isReadOnly() = false
}
| mit | 82234809eca0f4ee78f1bbbe9ed83e9f | 26.68 | 82 | 0.732659 | 4.168675 | false | false | false | false |
samtstern/quickstart-android | mlkit/app/src/main/java/com/google/firebase/samples/apps/mlkit/kotlin/facedetection/FaceContourGraphic.kt | 1 | 4764 | package com.google.firebase.samples.apps.mlkit.kotlin.facedetection
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import com.google.firebase.ml.vision.face.FirebaseVisionFace
import com.google.firebase.ml.vision.face.FirebaseVisionFaceContour
import com.google.firebase.ml.vision.face.FirebaseVisionFaceLandmark
import com.google.firebase.samples.apps.mlkit.common.GraphicOverlay
import com.google.firebase.samples.apps.mlkit.common.GraphicOverlay.Graphic
/** Graphic instance for rendering face contours graphic overlay view. */
class FaceContourGraphic(overlay: GraphicOverlay, private val firebaseVisionFace: FirebaseVisionFace?) :
Graphic(overlay) {
private val facePositionPaint: Paint
private val idPaint: Paint
private val boxPaint: Paint
init {
val selectedColor = Color.WHITE
facePositionPaint = Paint()
facePositionPaint.color = selectedColor
idPaint = Paint()
idPaint.color = selectedColor
idPaint.textSize = ID_TEXT_SIZE
boxPaint = Paint()
boxPaint.color = selectedColor
boxPaint.style = Paint.Style.STROKE
boxPaint.strokeWidth = BOX_STROKE_WIDTH
}
/** Draws the face annotations for position on the supplied canvas. */
override fun draw(canvas: Canvas) {
val face = firebaseVisionFace ?: return
// Draws a circle at the position of the detected face, with the face's track id below.
val x = translateX(face.boundingBox.centerX().toFloat())
val y = translateY(face.boundingBox.centerY().toFloat())
canvas.drawCircle(x, y, FACE_POSITION_RADIUS, facePositionPaint)
canvas.drawText("id: ${face.trackingId}", x + ID_X_OFFSET, y + ID_Y_OFFSET, idPaint)
// Draws a bounding box around the face.
val xOffset = scaleX(face.boundingBox.width() / 2.0f)
val yOffset = scaleY(face.boundingBox.height() / 2.0f)
val left = x - xOffset
val top = y - yOffset
val right = x + xOffset
val bottom = y + yOffset
canvas.drawRect(left, top, right, bottom, boxPaint)
val contour = face.getContour(FirebaseVisionFaceContour.ALL_POINTS)
for (point in contour.points) {
val px = translateX(point.x)
val py = translateY(point.y)
canvas.drawCircle(px, py, FACE_POSITION_RADIUS, facePositionPaint)
}
if (face.smilingProbability >= 0) {
canvas.drawText(
"happiness: ${String.format("%.2f", face.smilingProbability)}",
x + ID_X_OFFSET * 3,
y - ID_Y_OFFSET,
idPaint)
}
if (face.rightEyeOpenProbability >= 0) {
canvas.drawText(
"right eye: ${String.format("%.2f", face.rightEyeOpenProbability)}",
x - ID_X_OFFSET,
y,
idPaint)
}
if (face.leftEyeOpenProbability >= 0) {
canvas.drawText(
"left eye: ${String.format("%.2f", face.leftEyeOpenProbability)}",
x + ID_X_OFFSET * 6,
y,
idPaint)
}
val leftEye = face.getLandmark(FirebaseVisionFaceLandmark.LEFT_EYE)
leftEye?.position?.let {
canvas.drawCircle(
translateX(it.x),
translateY(it.y),
FACE_POSITION_RADIUS,
facePositionPaint)
}
val rightEye = face.getLandmark(FirebaseVisionFaceLandmark.RIGHT_EYE)
rightEye?.position?.let {
canvas.drawCircle(
translateX(it.x),
translateY(it.y),
FACE_POSITION_RADIUS,
facePositionPaint)
}
val leftCheek = face.getLandmark(FirebaseVisionFaceLandmark.LEFT_CHEEK)
leftCheek?.position?.let {
canvas.drawCircle(
translateX(it.x),
translateY(it.y),
FACE_POSITION_RADIUS,
facePositionPaint)
}
val rightCheek = face.getLandmark(FirebaseVisionFaceLandmark.RIGHT_CHEEK)
rightCheek?.position?.let {
canvas.drawCircle(
translateX(it.x),
translateY(it.y),
FACE_POSITION_RADIUS,
facePositionPaint)
}
}
companion object {
private const val FACE_POSITION_RADIUS = 4.0f
private const val ID_TEXT_SIZE = 30.0f
private const val ID_Y_OFFSET = 80.0f
private const val ID_X_OFFSET = -70.0f
private const val BOX_STROKE_WIDTH = 5.0f
}
}
| apache-2.0 | 40468e1a050a91b1f453d5ea819bf48c | 36.511811 | 104 | 0.59131 | 4.532826 | false | false | false | false |
rhdunn/marklogic-intellij-plugin | src/main/java/uk/co/reecedunn/intellij/plugin/marklogic/ui/log/MarkLogicLogViewToolbar.kt | 1 | 2361 | /*
* Copyright (C) 2017-2018 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.marklogic.ui.log
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.application.ApplicationManager
import uk.co.reecedunn.intellij.plugin.marklogic.ui.resources.MarkLogicBundle
import javax.swing.JComponent
interface LogViewActions {
fun refreshLog(): Runnable
var scrollToEnd: Boolean
}
private class RefreshAction(val actions: LogViewActions) : AnAction() {
init {
val message = MarkLogicBundle.message("action.refresh")
templatePresentation.description = message
templatePresentation.text = message
templatePresentation.icon = AllIcons.Actions.Refresh
}
override fun actionPerformed(e: AnActionEvent?) {
ApplicationManager.getApplication().executeOnPooledThread(actions.refreshLog())
}
}
private class ScrollToEndAction(val actions: LogViewActions) : ToggleAction() {
init {
val message = MarkLogicBundle.message("action.scroll-to-end")
templatePresentation.description = message
templatePresentation.text = message
templatePresentation.icon = AllIcons.RunConfigurations.Scroll_down
}
override fun isSelected(e: AnActionEvent?): Boolean =
actions.scrollToEnd
override fun setSelected(e: AnActionEvent?, state: Boolean) {
actions.scrollToEnd = state
}
}
class MarkLogicLogViewToolbar(actions: LogViewActions) {
private val group: ActionGroup = DefaultActionGroup(
RefreshAction(actions),
ScrollToEndAction(actions))
private val toolbar: ActionToolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.TOOLBAR, group, false)
val component get(): JComponent = toolbar.component
}
| apache-2.0 | f65a1cfa9e6a6b3c8284e735687c822d | 34.238806 | 124 | 0.7446 | 4.750503 | false | false | false | false |
cashapp/sqldelight | sqldelight-compiler/src/main/kotlin/app/cash/sqldelight/core/compiler/model/NamedQuery.kt | 1 | 8902 | /*
* Copyright (C) 2017 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 app.cash.sqldelight.core.compiler.model
import app.cash.sqldelight.core.capitalize
import app.cash.sqldelight.core.compiler.SqlDelightCompiler.allocateName
import app.cash.sqldelight.core.decapitalize
import app.cash.sqldelight.core.lang.SqlDelightQueriesFile
import app.cash.sqldelight.core.lang.cursorGetter
import app.cash.sqldelight.core.lang.parentAdapter
import app.cash.sqldelight.core.lang.psi.StmtIdentifierMixin
import app.cash.sqldelight.core.lang.util.TableNameElement
import app.cash.sqldelight.core.lang.util.name
import app.cash.sqldelight.core.lang.util.sqFile
import app.cash.sqldelight.core.lang.util.tablesObserved
import app.cash.sqldelight.core.lang.util.type
import app.cash.sqldelight.dialect.api.IntermediateType
import app.cash.sqldelight.dialect.api.PrimitiveType.ARGUMENT
import app.cash.sqldelight.dialect.api.PrimitiveType.BLOB
import app.cash.sqldelight.dialect.api.PrimitiveType.BOOLEAN
import app.cash.sqldelight.dialect.api.PrimitiveType.INTEGER
import app.cash.sqldelight.dialect.api.PrimitiveType.NULL
import app.cash.sqldelight.dialect.api.PrimitiveType.REAL
import app.cash.sqldelight.dialect.api.PrimitiveType.TEXT
import app.cash.sqldelight.dialect.api.QueryWithResults
import com.alecstrong.sql.psi.core.psi.NamedElement
import com.alecstrong.sql.psi.core.psi.QueryElement
import com.alecstrong.sql.psi.core.psi.SqlCompoundSelectStmt
import com.alecstrong.sql.psi.core.psi.SqlExpr
import com.alecstrong.sql.psi.core.psi.SqlPragmaName
import com.alecstrong.sql.psi.core.psi.SqlValuesExpression
import com.intellij.psi.PsiElement
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.PropertySpec
data class NamedQuery(
val name: String,
val queryable: QueryWithResults,
private val statementIdentifier: StmtIdentifierMixin? = null,
) : BindableQuery(statementIdentifier, queryable.statement) {
internal val select get() = queryable.statement
internal val pureTable get() = queryable.pureTable
/**
* Explodes the sqlite query into an ordered list (same order as the query) of types to be exposed
* by the generated api.
*/
val resultColumns: List<IntermediateType> by lazy {
if (queryable is SelectQueryable) resultColumns(queryable.select)
else queryable.select.typesExposed(LinkedHashSet())
}
private fun resultColumns(select: SqlCompoundSelectStmt): List<IntermediateType> {
val namesUsed = LinkedHashSet<String>()
return select.selectStmtList.fold(emptyList()) { results, select ->
val compoundSelect = if (select.valuesExpressionList.isNotEmpty()) {
resultColumns(select.valuesExpressionList)
} else {
select.typesExposed(namesUsed)
}
if (results.isEmpty()) {
return@fold compoundSelect
}
return@fold results.zip(compoundSelect, this::superType)
}
}
/**
* Explodes the sqlite query into an ordered list (same order as the query) of adapters required for
* the types to be exposed by the generated api.
*/
internal val resultColumnRequiredAdapters: List<PropertySpec> by lazy {
if (queryable is SelectQueryable) resultColumnRequiredAdapters(queryable.select)
else queryable.select.typesExposed(LinkedHashSet()).mapNotNull { it.parentAdapter() }
}
private fun resultColumnRequiredAdapters(select: SqlCompoundSelectStmt): List<PropertySpec> {
val namesUsed = LinkedHashSet<String>()
return select.selectStmtList.flatMap { select ->
if (select.valuesExpressionList.isNotEmpty()) {
resultColumns(select.valuesExpressionList)
} else {
select.typesExposed(namesUsed)
}.mapNotNull { it.parentAdapter() }
}
}
/**
* The name of the generated interface that this query references. The linked interface will have
* a default implementation subclass.
*/
internal val interfaceType: ClassName by lazy {
pureTable?.let {
return@lazy ClassName(it.sqFile().packageName!!, allocateName(it).capitalize())
}
var packageName = queryable.select.sqFile().packageName!!
if (queryable.select.sqFile().parent?.files
?.filterIsInstance<SqlDelightQueriesFile>()?.flatMap { it.namedQueries }
?.filter { it.needsInterface() && it != this }
?.any { it.name == name } == true
) {
packageName = "$packageName.${queryable.select.sqFile().virtualFile!!.nameWithoutExtension.decapitalize()}"
}
return@lazy ClassName(packageName, name.capitalize())
}
/**
* @return true if this query needs its own interface generated.
*/
internal fun needsInterface() = needsWrapper() && pureTable == null
internal fun needsWrapper() = (resultColumns.size > 1 || resultColumns[0].javaType.isNullable)
internal val tablesObserved: List<TableNameElement>? by lazy {
if (queryable is SelectQueryable && queryable.select == queryable.statement) {
queryable.select.tablesObserved()
} else {
null
}
}
internal val customQuerySubtype = "${name.capitalize()}Query"
private fun resultColumns(valuesList: List<SqlValuesExpression>): List<IntermediateType> {
return valuesList.fold(
emptyList(),
{ results, values ->
val exposedTypes = values.exprList.map { it.type() }
if (results.isEmpty()) return@fold exposedTypes
return@fold results.zip(exposedTypes, this::superType)
},
)
}
private fun superType(typeOne: IntermediateType, typeTwo: IntermediateType): IntermediateType {
// Arguments types always take the other type.
if (typeOne.dialectType == ARGUMENT) {
return typeTwo.copy(name = typeOne.name)
} else if (typeTwo.dialectType == ARGUMENT) {
return typeOne
}
// Nullable types take nullable version of the other type.
if (typeOne.dialectType == NULL) {
return typeTwo.asNullable().copy(name = typeOne.name)
} else if (typeTwo.dialectType == NULL) {
return typeOne.asNullable()
}
val nullable = typeOne.javaType.isNullable || typeTwo.javaType.isNullable
if (typeOne.dialectType != typeTwo.dialectType) {
// Incompatible dialect types. Prefer the type which can contain the other.
// NULL < INTEGER < REAL < TEXT < BLOB
val type = listOf(NULL, INTEGER, BOOLEAN, REAL, TEXT, BLOB)
.last { it == typeOne.dialectType || it == typeTwo.dialectType }
return IntermediateType(dialectType = type, name = typeOne.name).nullableIf(nullable)
}
if (typeOne.column !== typeTwo.column &&
typeOne.asNonNullable().cursorGetter(0) != typeTwo.asNonNullable().cursorGetter(0) &&
typeOne.column != null && typeTwo.column != null
) {
// Incompatible adapters. Revert to unadapted java type.
return if (typeOne.javaType.copy(nullable = false) == typeTwo.javaType.copy(nullable = false)) {
typeOne.copy(assumedCompatibleTypes = typeOne.assumedCompatibleTypes + typeTwo).nullableIf(nullable)
} else {
IntermediateType(dialectType = typeOne.dialectType, name = typeOne.name).nullableIf(nullable)
}
}
return typeOne.nullableIf(nullable)
}
private fun PsiElement.functionName() = when (this) {
is NamedElement -> allocateName(this)
is SqlExpr -> name
is SqlPragmaName -> text
else -> throw IllegalStateException("Cannot get name for type ${this.javaClass}")
}
private fun QueryElement.typesExposed(
namesUsed: LinkedHashSet<String>,
): List<IntermediateType> {
return queryExposed().flatMap {
val table = it.table?.name
return@flatMap it.columns.map { queryColumn ->
var name = queryColumn.element.functionName()
if (!namesUsed.add(name)) {
if (table != null) name = "${table}_$name"
while (!namesUsed.add(name)) name += "_"
}
return@map queryColumn.type().copy(name = name)
}
}
}
private fun QueryElement.QueryColumn.type(): IntermediateType {
var rootType = element.type()
nullable?.let { rootType = rootType.nullableIf(it) }
return compounded.fold(rootType) { type, column -> superType(type, column.type()) }
}
override val id: Int
// the sqlFile package name -> com.example.
// sqlFile.name -> test.sq
// name -> query name
get() = getUniqueQueryIdentifier(statement.sqFile().let { "${it.packageName}:${it.name}:$name" })
}
| apache-2.0 | 565c26e72e064b0583a271a8f252b580 | 38.564444 | 113 | 0.720288 | 4.136617 | false | false | false | false |
austinv11/OpenPlanner | Core/src/main/kotlin/com/austinv11/planner/core/plugins/PluginRepository.kt | 1 | 7894 | package com.austinv11.planner.core.plugins
import com.austinv11.planner.core.json.Plugin
import com.austinv11.planner.core.json.Repo
import com.austinv11.planner.core.json.RepoMetadata
import com.austinv11.planner.core.plugins.LocalPluginRepository.REPO_DIR
import com.github.kittinunf.fuel.httpDownload
import com.github.kittinunf.fuel.httpGet
import com.google.gson.Gson
import java.io.File
import java.io.IOException
import java.util.*
/**
* This represents a generic plugin repo.
*/
interface IPluginRepository {
/**
* This is the unix timestamp when this repo was last updated.
*/
val lastUpdated: Long
/**
* This is the plugins which are contained in this repo.
*/
val plugins: Array<Plugin>
/**
* This is the metadata about this repo.
*/
val metadata: RepoMetadata
/**
* This is called to updated the plugin repository listings.
*/
fun updateList()
/**
* This is used to find a plugin by its name.
* @param name The (exact) plugin name.
* @return The plugin (if found).
*/
fun findPluginByName(name: String): Plugin? {
try {
return plugins.first { it.metadata.name == name }
} catch (e: NoSuchElementException) {
return null
}
}
}
/**
* This represents the local cached plugin repository.
*/
object LocalPluginRepository : IPluginRepository {
override val lastUpdated: Long
get() = _lastUpdated
override val plugins: Array<Plugin>
get() {
updateList()
return _plugins.keys.toTypedArray()
}
override val metadata: RepoMetadata = RepoMetadata("localhost", "", "The internal local repository.")
val REPO_DIR = File("./plugins/")
private var _lastUpdated: Long = -1
private val _plugins = mutableMapOf<Plugin, File>()
private val GSON = Gson()
init {
if (!REPO_DIR.exists())
REPO_DIR.mkdir()
}
override fun updateList() {
synchronized(_plugins) {
_plugins.clear()
REPO_DIR.listFiles { pathname -> pathname?.isDirectory ?: false }.forEach {
it.listFiles { pathname -> pathname?.isDirectory ?: false }.forEach { //Each plugin directory has a subdirectory for each stored version
val index = File(it, "index.json")
if (index.exists()) {
val plugin = GSON.fromJson(index.readText(), Plugin::class.java)
_plugins.put(plugin, it)
}
}
}
_lastUpdated = System.currentTimeMillis()
}
}
}
/**
* This represents a remote plugin repository.
*/
open class RemotePluginRepository(private val url: String) : IPluginRepository {
override val lastUpdated: Long
get() = _lastUpdated
override val plugins: Array<Plugin>
get() = _plugins.keys.toTypedArray()
override val metadata: RepoMetadata
get() = _repo.metadata
private var _lastUpdated: Long = -1
private val _plugins = mutableMapOf<Plugin, String>()
private lateinit var _repo: Repo
private val GSON = Gson()
init {
updateList()
}
override fun updateList() {
synchronized(this) {
_plugins.clear()
val (request, response, result) = url.httpGet().responseString()
result.fold({
_repo = GSON.fromJson(it, Repo::class.java)
},{
throw IOException("Unable to retrieve repository listings for url: $url")
})
_repo.plugins.forEach {
val pluginUrl = normalizeUrl(url, it)
val (request, response, result) = pluginUrl.httpGet().responseString()
result.fold({
_plugins.put(GSON.fromJson(it, Plugin::class.java), pluginUrl.removeSuffix("index.json"))
},{
throw IOException("Unable to retrieve plugin index for url: $pluginUrl")
})
}
//All plugin listings retrieved
_lastUpdated = System.currentTimeMillis()
}
}
private fun normalizeUrl(parentUrl: String, startingUrl: String): String { //TODO: This is still prone to failure, let's hope in the meantime all plugin urls are absolute
var modifiedUrl: String = startingUrl
if (!startingUrl.contains("://")) { //Missing protocol, assuming that this is a subdirectory of the original repo url
val shouldAddForwardSlash = startingUrl.startsWith("/") or parentUrl.endsWith("/")
val slash = if (shouldAddForwardSlash) "/" else ""
modifiedUrl = (parentUrl + slash + startingUrl).replaceAfter("://", "//", "/")
}
if (!modifiedUrl.endsWith("/"))
modifiedUrl += "/"
if (!modifiedUrl.endsWith("index.json"))
modifiedUrl += "index.json"
return modifiedUrl
}
open fun downloadPlugin(plugin: Plugin) {
if (!managesPlugin(plugin))
throw IllegalArgumentException("Plugin $plugin is not hosted on this repo!")
val pluginDir = File(REPO_DIR, "${plugin.metadata.name}/${plugin.metadata.version}")
if (!pluginDir.exists()) { //Skip download if the plugin already exists
pluginDir.mkdirs()
File(pluginDir, "index.json").writeText(GSON.toJson(plugin)) //No need to download the index since it is already cached
val baseUrl = _plugins[plugin]
(plugin.resources + plugin.init_script).forEach {
val filepath = it.removePrefix(".").removePrefix("/")
val (request, response, result) = (baseUrl + filepath).httpDownload().destination { response, url ->
val file = File(pluginDir, filepath)
file.mkdirs()
file.delete()
return@destination file
}.responseString()
result.fold({
//Success
},{
throw IOException("Unable to download plugin resource from url ${request.url} (intended path: $filepath)")
})
}
LocalPluginRepository.updateList()
}
}
fun managesPlugin(plugin: Plugin): Boolean {
return _plugins.containsKey(plugin)
}
}
class CombinedRemotePluginRepository(private val initialRepos: Array<RemotePluginRepository>): RemotePluginRepository("") {
val repos: Array<RemotePluginRepository>
get() = _repos.toTypedArray()
override val lastUpdated: Long
get() = _lastUpdated
override val plugins: Array<Plugin>
get() {
var _plugins = arrayOf<Plugin>()
repos.forEach { _plugins += it.plugins }
return _plugins
}
override val metadata = RepoMetadata("Combined Repository [internal]", "null", "An internal implementation of a plugin repository which manages multiple remote plugin repositories.")
private val _repos = mutableListOf(*initialRepos)
private var _lastUpdated: Long = -1
override fun updateList() {
repos.forEach { it.updateList() }
_lastUpdated = System.currentTimeMillis()
}
override fun downloadPlugin(plugin: Plugin) {
_repos.find { it.managesPlugin(plugin) }?.downloadPlugin(plugin) ?: throw IllegalArgumentException("Plugin $plugin could not be found on any managed repo!")
}
fun addRepo(repo: RemotePluginRepository) {
_repos.add(repo)
}
fun removeRepo(repo: RemotePluginRepository) {
_repos.remove(repo)
}
}
| gpl-3.0 | badeb2b440d6c5132f25fd6b15241400 | 33.025862 | 186 | 0.586775 | 4.95543 | false | false | false | false |
lare96/luna | plugins/api/predef/PropertiesPredef.kt | 1 | 6626 | package api.predef
import io.luna.game.event.EventListener
import io.luna.game.event.EventMatcherListener
import io.luna.game.model.EntityType
import io.luna.game.model.item.Equipment
import io.luna.game.model.item.Item
import io.luna.game.model.mob.Player
import io.luna.game.model.mob.PlayerInteraction
import io.luna.game.model.mob.PlayerRights
import io.luna.game.model.mob.Skill
import io.luna.game.plugin.KotlinBindings
import io.luna.game.plugin.PluginBootstrap
import io.luna.util.Rational
import io.luna.util.ReflectionUtils
/**
* The Kotlin bindings. Not accessible to scripts.
*/
private val bindings: KotlinBindings = ReflectionUtils.getStaticField(
PluginBootstrap::class.java,
"bindings",
KotlinBindings::class.java)
/**
* The [LunaContext] instance.
*/
val ctx = bindings.ctx!!
/**
* The [Logger] instance.
*/
val logger = bindings.logger!!
/**
* The script event listeners.
*/
val scriptListeners: MutableList<EventListener<*>> = bindings.listeners!!
/**
* The script event listeners.
*/
val scriptMatchers: MutableList<EventMatcherListener<*>> = bindings.matchers!!
/**
* The [EventListenerPipelineSet] instance.
*/
val pipelines = bindings.pipelines!!
/**
* The [PluginManger] instance.
*/
val plugins = ctx.plugins!!
/**
* The [World] instance.
*/
val world = ctx.world!!
/**
* The [GameService] instance.
*/
val game = ctx.game!!
/*******************
* *
* Type aliases. *
* *
******************/
typealias TableEntry<R, C, V> = Pair<Pair<R, C>, V>
/**************************************
* *
* [PlayerRights] property aliases. *
* *
*************************************/
val RIGHTS_PLAYER = PlayerRights.PLAYER
val RIGHTS_MOD = PlayerRights.MODERATOR
val RIGHTS_ADMIN = PlayerRights.ADMINISTRATOR
val RIGHTS_DEV = PlayerRights.DEVELOPER
/*******************************************
* *
* [PlayerInteraction] property aliases. *
* *
******************************************/
val INTERACTION_TRADE = PlayerInteraction.TRADE!!
val INTERACTION_CHALLENGE = PlayerInteraction.CHALLENGE!!
val INTERACTION_ATTACK = PlayerInteraction.ATTACK!!
val INTERACTION_FOLLOW = PlayerInteraction.FOLLOW!!
/************************************
* *
* [EntityType] property aliases. *
* *
***********************************/
/* Aliases for 'EntityType'. */
val TYPE_PLAYER = EntityType.PLAYER
val TYPE_NPC = EntityType.NPC
val TYPE_OBJECT = EntityType.OBJECT
val TYPE_ITEM = EntityType.ITEM
/******************************************
* *
* [Skill] identifier property aliases. *
* *
*****************************************/
const val SKILL_ATTACK = Skill.ATTACK
const val SKILL_DEFENCE = Skill.DEFENCE
const val SKILL_STRENGTH = Skill.STRENGTH
const val SKILL_HITPOINTS = Skill.HITPOINTS
const val SKILL_RANGED = Skill.RANGED
const val SKILL_PRAYER = Skill.PRAYER
const val SKILL_MAGIC = Skill.MAGIC
const val SKILL_COOKING = Skill.COOKING
const val SKILL_WOODCUTTING = Skill.WOODCUTTING
const val SKILL_FLETCHING = Skill.FLETCHING
const val SKILL_FISHING = Skill.FISHING
const val SKILL_FIREMAKING = Skill.FIREMAKING
const val SKILL_CRAFTING = Skill.CRAFTING
const val SKILL_SMITHING = Skill.SMITHING
const val SKILL_MINING = Skill.MINING
const val SKILL_HERBLORE = Skill.HERBLORE
const val SKILL_AGILITY = Skill.AGILITY
const val SKILL_THIEVING = Skill.THIEVING
const val SKILL_SLAYER = Skill.SLAYER
const val SKILL_FARMING = Skill.FARMING
const val SKILL_RUNECRAFTING = Skill.RUNECRAFTING
/***********************************
* *
* [Skill] extension properties. *
* *
**********************************/
val Player.attack: Skill
get() = skill(SKILL_ATTACK)
val Player.strength: Skill
get() = skill(SKILL_STRENGTH)
val Player.defence: Skill
get() = skill(SKILL_DEFENCE)
val Player.hitpoints: Skill
get() = skill(SKILL_HITPOINTS)
val Player.ranged: Skill
get() = skill(SKILL_RANGED)
val Player.prayer: Skill
get() = skill(SKILL_PRAYER)
val Player.magic: Skill
get() = skill(SKILL_MAGIC)
val Player.cooking: Skill
get() = skill(SKILL_COOKING)
val Player.woodcutting: Skill
get() = skill(SKILL_WOODCUTTING)
val Player.fletching: Skill
get() = skill(SKILL_FLETCHING)
val Player.fishing: Skill
get() = skill(SKILL_FISHING)
val Player.firemaking: Skill
get() = skill(SKILL_FIREMAKING)
val Player.crafting: Skill
get() = skill(SKILL_CRAFTING)
val Player.smithing: Skill
get() = skill(SKILL_SMITHING)
val Player.mining: Skill
get() = skill(SKILL_MINING)
val Player.herblore: Skill
get() = skill(SKILL_HERBLORE)
val Player.agility: Skill
get() = skill(SKILL_AGILITY)
val Player.thieving: Skill
get() = skill(SKILL_THIEVING)
val Player.slayer: Skill
get() = skill(SKILL_SLAYER)
val Player.farming: Skill
get() = skill(SKILL_FARMING)
val Player.runecrafting: Skill
get() = skill(SKILL_RUNECRAFTING)
/***************************************
* *
* [Equipment] extension properties. *
* *
***************************************/
val Equipment.head: Item?
get() = this[Equipment.HEAD]
val Equipment.cape: Item?
get() = this[Equipment.CAPE]
val Equipment.amulet: Item?
get() = this[Equipment.AMULET]
val Equipment.weapon: Item?
get() = this[Equipment.WEAPON]
val Equipment.chest: Item?
get() = this[Equipment.CHEST]
val Equipment.shield: Item?
get() = this[Equipment.SHIELD]
val Equipment.legs: Item?
get() = this[Equipment.LEGS]
val Equipment.hands: Item?
get() = this[Equipment.HANDS]
val Equipment.feet: Item?
get() = this[Equipment.FEET]
val Equipment.ring: Item?
get() = this[Equipment.RING]
val Equipment.ammo: Item?
get() = this[Equipment.AMMUNITION]
/**********************************
* *
* [Rational] property aliases. *
* *
*********************************/
val ALWAYS = Rational.ALWAYS
val VERY_COMMON = Rational.VERY_COMMON
val COMMON = Rational.COMMON
val UNCOMMON = Rational.UNCOMMON
val VERY_UNCOMMON = Rational.VERY_UNCOMMON
val RARE = Rational.RARE
val VERY_RARE = Rational.VERY_RARE
val NEVER = Rational(0, 1) | mit | 8a08e9c4ecb65a6c2aa1978870bb4cbe | 24.293893 | 78 | 0.59674 | 3.668882 | false | false | false | false |
panpf/sketch | sketch-extensions/src/main/java/com/github/panpf/sketch/stateimage/SaveCellularTrafficExtensions.kt | 1 | 2871 | /*
* Copyright (C) 2022 panpf <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.panpf.sketch.stateimage
import android.graphics.drawable.Drawable
import com.github.panpf.sketch.Sketch
import com.github.panpf.sketch.request.ImageRequest
import com.github.panpf.sketch.request.isCausedBySaveCellularTraffic
import com.github.panpf.sketch.util.SketchException
/**
* Set the error image when the save cellular traffic
*/
fun ErrorStateImage.Builder.saveCellularTrafficError(): ErrorStateImage.Builder =
apply {
addMatcher(SaveCellularTrafficMatcher(null))
}
/**
* Set the error image when the save cellular traffic
*/
fun ErrorStateImage.Builder.saveCellularTrafficError(saveCellularTrafficImage: StateImage): ErrorStateImage.Builder =
apply {
addMatcher(SaveCellularTrafficMatcher(saveCellularTrafficImage))
}
/**
* Set the error image when the save cellular traffic
*/
fun ErrorStateImage.Builder.saveCellularTrafficError(saveCellularTrafficDrawable: Drawable): ErrorStateImage.Builder =
apply {
addMatcher(
SaveCellularTrafficMatcher(DrawableStateImage(saveCellularTrafficDrawable))
)
}
/**
* Set the error image when the save cellular traffic
*/
fun ErrorStateImage.Builder.saveCellularTrafficError(saveCellularTrafficImageResId: Int): ErrorStateImage.Builder =
apply {
addMatcher(
SaveCellularTrafficMatcher(DrawableStateImage(saveCellularTrafficImageResId))
)
}
class SaveCellularTrafficMatcher(val stateImage: StateImage?) :
ErrorStateImage.Matcher {
override fun match(request: ImageRequest, exception: SketchException?): Boolean =
isCausedBySaveCellularTraffic(request, exception)
override fun getDrawable(
sketch: Sketch, request: ImageRequest, throwable: SketchException?
): Drawable? = stateImage?.getDrawable(sketch, request, throwable)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is SaveCellularTrafficMatcher) return false
if (stateImage != other.stateImage) return false
return true
}
override fun hashCode(): Int {
return stateImage.hashCode()
}
override fun toString(): String {
return "SaveCellularTrafficMatcher($stateImage)"
}
} | apache-2.0 | 498030f5b21e3dbd274e14c810cbdaed | 32.788235 | 118 | 0.74016 | 4.801003 | false | false | false | false |
stripe/stripe-android | payments-core/src/main/java/com/stripe/android/PaymentConfiguration.kt | 1 | 3552 | package com.stripe.android
import android.content.Context
import android.content.SharedPreferences
import android.os.Parcelable
import androidx.annotation.RestrictTo
import com.stripe.android.core.ApiKeyValidator
import kotlinx.parcelize.Parcelize
@Parcelize
data class PaymentConfiguration
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
constructor(
val publishableKey: String,
val stripeAccountId: String? = null
) : Parcelable {
init {
ApiKeyValidator.get().requireValid(publishableKey)
}
/**
* Manages saving and loading [PaymentConfiguration] data to SharedPreferences.
*/
private class Store(context: Context) {
private val prefs: SharedPreferences =
context.applicationContext.getSharedPreferences(NAME, 0)
@JvmSynthetic
fun save(
publishableKey: String,
stripeAccountId: String?
) {
prefs.edit()
.putString(KEY_PUBLISHABLE_KEY, publishableKey)
.putString(KEY_ACCOUNT_ID, stripeAccountId)
.apply()
}
@JvmSynthetic
internal fun load(): PaymentConfiguration? {
return prefs.getString(KEY_PUBLISHABLE_KEY, null)?.let { publishableKey ->
PaymentConfiguration(
publishableKey = publishableKey,
stripeAccountId = prefs.getString(KEY_ACCOUNT_ID, null)
)
}
}
private companion object {
private val NAME = PaymentConfiguration::class.java.canonicalName
private const val KEY_PUBLISHABLE_KEY = "key_publishable_key"
private const val KEY_ACCOUNT_ID = "key_account_id"
}
}
companion object {
private var instance: PaymentConfiguration? = null
/**
* Attempts to load a [PaymentConfiguration] instance. First attempt to use the class's
* singleton instance. If unavailable, attempt to load from [Store].
*
* @param context application context
* @return a [PaymentConfiguration] instance, or throw an exception
*/
@JvmStatic
fun getInstance(context: Context): PaymentConfiguration {
return instance ?: loadInstance(context)
}
private fun loadInstance(context: Context): PaymentConfiguration {
return Store(context).load()?.let {
instance = it
it
}
?: throw IllegalStateException(
"PaymentConfiguration was not initialized. Call PaymentConfiguration.init()."
)
}
/**
* A publishable key from the Dashboard's [API keys](https://dashboard.stripe.com/apikeys) page.
*/
@JvmStatic
@JvmOverloads
fun init(
context: Context,
publishableKey: String,
stripeAccountId: String? = null
) {
instance = PaymentConfiguration(
publishableKey = publishableKey,
stripeAccountId = stripeAccountId
)
Store(context)
.save(
publishableKey = publishableKey,
stripeAccountId = stripeAccountId
)
DefaultFraudDetectionDataRepository(context).refresh()
}
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
// for paymentsheet
@JvmSynthetic
fun clearInstance() {
instance = null
}
}
}
| mit | 6520da4f32defbda3e27c5768ccfd4d4 | 30.433628 | 104 | 0.591779 | 5.729032 | false | true | false | false |
AndroidX/androidx | camera/camera-camera2-pipe-testing/src/test/java/androidx/camera/camera2/pipe/testing/CameraGraphSimulatorTest.kt | 3 | 12861 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.camera2.pipe.testing
import android.content.Context
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CaptureResult
import android.os.Build
import android.util.Size
import androidx.camera.camera2.pipe.CameraGraph
import androidx.camera.camera2.pipe.CameraStream
import androidx.camera.camera2.pipe.Request
import androidx.camera.camera2.pipe.StreamFormat
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.take
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import kotlinx.coroutines.withTimeoutOrNull
import androidx.test.core.app.ApplicationProvider
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import org.junit.Ignore
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.annotation.Config
@OptIn(ExperimentalCoroutinesApi::class)
@RunWith(RobolectricCameraPipeTestRunner::class)
@Config(minSdk = Build.VERSION_CODES.LOLLIPOP)
public class CameraGraphSimulatorTest {
private val metadata = FakeCameraMetadata(
mapOf(CameraCharacteristics.LENS_FACING to CameraCharacteristics.LENS_FACING_FRONT)
)
private val streamConfig = CameraStream.Config.create(
Size(640, 480),
StreamFormat.YUV_420_888
)
private val graphConfig = CameraGraph.Config(
camera = metadata.camera,
streams = listOf(streamConfig)
)
private val context = ApplicationProvider.getApplicationContext() as Context
@Ignore("b/188446185")
@Test
fun simulatorCanSimulateRepeatingFrames() = runTest {
val simulator = CameraGraphSimulator.create(
this,
context,
metadata,
graphConfig
)
val stream = simulator.cameraGraph.streams[streamConfig]!!
val listener = FakeRequestListener()
val request = Request(
streams = listOf(stream.id),
listeners = listOf(listener)
)
simulator.cameraGraph.acquireSession().use {
it.startRepeating(request)
}
simulator.cameraGraph.start()
simulator.simulateCameraStarted()
val frame = simulator.simulateNextFrame()
assertThat(frame.request).isSameInstanceAs(request)
assertThat(frame.frameNumber.value).isGreaterThan(0)
assertThat(frame.timestampNanos).isGreaterThan(0)
val startEvent = listener.onStartedFlow.first()
assertThat(startEvent.frameNumber).isNotNull()
assertThat(startEvent.frameNumber).isEqualTo(frame.frameNumber)
assertThat(startEvent.timestamp).isNotNull()
assertThat(startEvent.timestamp.value).isGreaterThan(0)
assertThat(startEvent.requestMetadata.repeating).isTrue()
assertThat(startEvent.requestMetadata.request.streams).contains(stream.id)
assertThat(startEvent.requestMetadata.template)
.isEqualTo(graphConfig.defaultTemplate)
val totalCaptureResultEvent = withContext(Dispatchers.IO) {
withTimeoutOrNull(timeMillis = 50) {
listener.onTotalCaptureResultFlow.first()
}
}
assertThat(totalCaptureResultEvent).isNull()
// Launch the callbacks in a coroutine job to test the behavior of the simulator.
val simulateCallbacks = launch {
val resultMetadata = mutableMapOf<CaptureResult.Key<*>, Any>()
// Simulate two partial capture results, and one total capture result.
resultMetadata[CaptureResult.LENS_STATE] = CaptureResult.LENS_STATE_MOVING
frame.simulatePartialCaptureResult(resultMetadata)
delay(10)
resultMetadata[CaptureResult.LENS_APERTURE] = 2.0f
frame.simulatePartialCaptureResult(resultMetadata)
delay(10)
resultMetadata[CaptureResult.FLASH_STATE] = CaptureResult.FLASH_STATE_FIRED
frame.simulateTotalCaptureResult(resultMetadata)
delay(10)
frame.simulateComplete(
resultMetadata,
extraMetadata = mapOf(
CaptureResult.LENS_APERTURE to 4.0f
)
)
}
val partialEvent1 = listener.onPartialCaptureResultFlow.first()
assertThat(partialEvent1.frameNumber).isEqualTo(frame.frameNumber)
assertThat(partialEvent1.frameMetadata.camera).isEqualTo(metadata.camera)
assertThat(partialEvent1.frameMetadata[CaptureResult.LENS_STATE]).isEqualTo(1)
assertThat(partialEvent1.frameMetadata[CaptureResult.LENS_APERTURE]).isNull()
assertThat(partialEvent1.frameMetadata[CaptureResult.FLASH_STATE]).isNull()
val partialEvent2 = listener.onPartialCaptureResultFlow.drop(1).first()
assertThat(partialEvent2.frameNumber).isEqualTo(frame.frameNumber)
assertThat(partialEvent2.frameMetadata.camera).isEqualTo(metadata.camera)
assertThat(partialEvent2.frameMetadata[CaptureResult.LENS_STATE]).isEqualTo(1)
assertThat(partialEvent2.frameMetadata[CaptureResult.LENS_APERTURE]).isEqualTo(2.0f)
assertThat(partialEvent2.frameMetadata[CaptureResult.FLASH_STATE]).isNull()
val totalEvent = listener.onTotalCaptureResultFlow.first()
assertThat(totalEvent.frameNumber).isEqualTo(frame.frameNumber)
assertThat(totalEvent.frameInfo.camera).isEqualTo(metadata.camera)
assertThat(totalEvent.frameInfo.metadata[CaptureResult.LENS_STATE]).isEqualTo(1)
assertThat(totalEvent.frameInfo.metadata[CaptureResult.LENS_APERTURE]).isEqualTo(2.0f)
assertThat(totalEvent.frameInfo.metadata[CaptureResult.FLASH_STATE]).isEqualTo(3)
val completedEvent = listener.onCompleteFlow.first()
assertThat(completedEvent.frameNumber).isEqualTo(frame.frameNumber)
assertThat(completedEvent.frameInfo.camera).isEqualTo(metadata.camera)
assertThat(completedEvent.frameInfo.metadata[CaptureResult.LENS_STATE]).isEqualTo(1)
assertThat(completedEvent.frameInfo.metadata[CaptureResult.LENS_APERTURE]).isEqualTo(
4.0f
)
assertThat(completedEvent.frameInfo.metadata[CaptureResult.FLASH_STATE]).isEqualTo(3)
simulateCallbacks.join()
}
@Test
fun simulatorAbortsRequests() = runTest {
val simulator = CameraGraphSimulator.create(
this,
context,
metadata,
graphConfig
)
val stream = simulator.cameraGraph.streams[streamConfig]!!
val listener = FakeRequestListener()
val request = Request(
streams = listOf(stream.id),
listeners = listOf(listener)
)
simulator.cameraGraph.acquireSession().use {
it.submit(request = request)
}
simulator.cameraGraph.close()
val abortedEvent = listener.onAbortedFlow.first()
assertThat(abortedEvent.request).isSameInstanceAs(request)
}
@Test
fun simulatorCanIssueBufferLoss() = runTest {
val simulator = CameraGraphSimulator.create(
this,
context,
metadata,
graphConfig
)
val stream = simulator.cameraGraph.streams[streamConfig]!!
val listener = FakeRequestListener()
val request = Request(
streams = listOf(stream.id),
listeners = listOf(listener)
)
simulator.cameraGraph.acquireSession().use {
it.submit(request = request)
}
simulator.cameraGraph.start()
simulator.simulateCameraStarted()
simulator.simulateFakeSurfaceConfiguration()
val frame = simulator.simulateNextFrame()
assertThat(frame.request).isSameInstanceAs(request)
frame.simulateBufferLoss(stream.id)
val lossEvent = listener.onBufferLostFlow.first()
assertThat(lossEvent.frameNumber).isEqualTo(frame.frameNumber)
assertThat(lossEvent.requestMetadata.request).isSameInstanceAs(request)
assertThat(lossEvent.streamId).isEqualTo(stream.id)
}
@Ignore("b/188446185")
@Test
fun simulatorCanIssueMultipleFrames() = runTest {
val simulator = CameraGraphSimulator.create(
this,
context,
metadata,
graphConfig
)
val stream = simulator.cameraGraph.streams[streamConfig]!!
val listener = FakeRequestListener()
val request = Request(
streams = listOf(stream.id),
listeners = listOf(listener)
)
simulator.cameraGraph.acquireSession().use {
it.startRepeating(request = request)
}
simulator.cameraGraph.start()
simulator.simulateCameraStarted()
val frame1 = simulator.simulateNextFrame()
val frame2 = simulator.simulateNextFrame()
val frame3 = simulator.simulateNextFrame()
assertThat(frame1).isNotEqualTo(frame2)
assertThat(frame2).isNotEqualTo(frame3)
assertThat(frame1.request).isSameInstanceAs(request)
assertThat(frame2.request).isSameInstanceAs(request)
assertThat(frame3.request).isSameInstanceAs(request)
val simulateCallbacks = launch {
val resultMetadata = mutableMapOf<CaptureResult.Key<*>, Any>()
resultMetadata[CaptureResult.LENS_STATE] = CaptureResult.LENS_STATE_MOVING
frame1.simulateTotalCaptureResult(resultMetadata)
frame1.simulateComplete(resultMetadata)
delay(15)
frame2.simulateTotalCaptureResult(resultMetadata)
frame2.simulateComplete(resultMetadata)
delay(15)
resultMetadata[CaptureResult.LENS_STATE] = CaptureResult.LENS_STATE_STATIONARY
frame3.simulateTotalCaptureResult(resultMetadata)
frame3.simulateComplete(resultMetadata)
}
val startEvents = withTimeout(timeMillis = 250) {
listener.onStartedFlow.take(3).toList()
}
assertThat(startEvents).hasSize(3)
val event1 = startEvents[0]
val event2 = startEvents[1]
val event3 = startEvents[2]
// Frame numbers are not equal
assertThat(event1.frameNumber).isNotEqualTo(event2.frameNumber)
assertThat(event2.frameNumber).isNotEqualTo(event3.frameNumber)
// Timestamps are in ascending order
assertThat(event3.timestamp.value).isGreaterThan(event2.timestamp.value)
assertThat(event2.timestamp.value).isGreaterThan(event1.timestamp.value)
// Metadata references the same request.
assertThat(event1.requestMetadata.repeating).isTrue()
assertThat(event2.requestMetadata.repeating).isTrue()
assertThat(event3.requestMetadata.repeating).isTrue()
assertThat(event1.requestMetadata.request).isSameInstanceAs(request)
assertThat(event2.requestMetadata.request).isSameInstanceAs(request)
assertThat(event3.requestMetadata.request).isSameInstanceAs(request)
val completeEvents = withTimeout(timeMillis = 250) {
listener.onCompleteFlow.take(3).toList()
}
assertThat(completeEvents).hasSize(3)
val completeEvent1 = completeEvents[0]
val completeEvent2 = completeEvents[1]
val completeEvent3 = completeEvents[2]
assertThat(completeEvent1.frameNumber).isEqualTo(event1.frameNumber)
assertThat(completeEvent2.frameNumber).isEqualTo(event2.frameNumber)
assertThat(completeEvent3.frameNumber).isEqualTo(event3.frameNumber)
assertThat(completeEvent1.frameInfo.metadata[CaptureResult.LENS_STATE])
.isEqualTo(CaptureResult.LENS_STATE_MOVING)
assertThat(completeEvent2.frameInfo.metadata[CaptureResult.LENS_STATE])
.isEqualTo(CaptureResult.LENS_STATE_MOVING)
assertThat(completeEvent3.frameInfo.metadata[CaptureResult.LENS_STATE])
.isEqualTo(CaptureResult.LENS_STATE_STATIONARY)
simulateCallbacks.join()
}
}
| apache-2.0 | 8788964f46f59c032d0ddfc7191d466e | 39.065421 | 94 | 0.700412 | 4.903164 | false | true | false | false |
charleskorn/batect | app/src/main/kotlin/batect/docker/client/DockerImagesClient.kt | 1 | 6298 | /*
Copyright 2017-2020 Charles Korn.
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 batect.docker.client
import batect.docker.DockerImage
import batect.docker.DockerRegistryCredentialsException
import batect.docker.ImageBuildFailedException
import batect.docker.ImagePullFailedException
import batect.docker.api.ImagesAPI
import batect.docker.build.DockerImageBuildContextFactory
import batect.docker.build.DockerfileParser
import batect.docker.data
import batect.docker.pull.DockerImageProgress
import batect.docker.pull.DockerImageProgressReporter
import batect.docker.pull.DockerRegistryCredentialsProvider
import batect.execution.CancellationContext
import batect.logging.Logger
import kotlinx.serialization.json.JsonObject
import okio.Sink
import java.nio.file.Files
import java.nio.file.LinkOption
import java.nio.file.Path
class DockerImagesClient(
private val api: ImagesAPI,
private val credentialsProvider: DockerRegistryCredentialsProvider,
private val imageBuildContextFactory: DockerImageBuildContextFactory,
private val dockerfileParser: DockerfileParser,
private val logger: Logger,
private val imageProgressReporterFactory: () -> DockerImageProgressReporter = ::DockerImageProgressReporter
) {
fun build(
buildDirectory: Path,
buildArgs: Map<String, String>,
dockerfilePath: String,
imageTags: Set<String>,
outputSink: Sink?,
cancellationContext: CancellationContext,
onStatusUpdate: (DockerImageBuildProgress) -> Unit
): DockerImage {
logger.info {
message("Building image.")
data("buildDirectory", buildDirectory)
data("buildArgs", buildArgs)
data("dockerfilePath", dockerfilePath)
data("imageTags", imageTags)
}
try {
val resolvedDockerfilePath = buildDirectory.resolve(dockerfilePath)
if (!Files.exists(resolvedDockerfilePath)) {
throw ImageBuildFailedException("Could not build image: the Dockerfile '$dockerfilePath' does not exist in '$buildDirectory'")
}
if (!resolvedDockerfilePath.toRealPath(LinkOption.NOFOLLOW_LINKS).startsWith(buildDirectory.toRealPath(LinkOption.NOFOLLOW_LINKS))) {
throw ImageBuildFailedException("Could not build image: the Dockerfile '$dockerfilePath' is not a child of '$buildDirectory'")
}
val context = imageBuildContextFactory.createFromDirectory(buildDirectory, dockerfilePath)
val baseImageNames = dockerfileParser.extractBaseImageNames(resolvedDockerfilePath)
val credentials = baseImageNames.mapNotNull { credentialsProvider.getCredentials(it) }.toSet()
val reporter = imageProgressReporterFactory()
var lastStepProgressUpdate: DockerImageBuildProgress? = null
val image = api.build(context, buildArgs, dockerfilePath, imageTags, credentials, outputSink, cancellationContext) { line ->
logger.debug {
message("Received output from Docker during image build.")
data("outputLine", line.toString())
}
val stepProgress = DockerImageBuildProgress.fromBuildOutput(line)
if (stepProgress != null) {
lastStepProgressUpdate = stepProgress
onStatusUpdate(lastStepProgressUpdate!!)
}
val pullProgress = reporter.processProgressUpdate(line)
if (pullProgress != null && lastStepProgressUpdate != null) {
lastStepProgressUpdate = lastStepProgressUpdate!!.copy(progress = pullProgress)
onStatusUpdate(lastStepProgressUpdate!!)
}
}
logger.info {
message("Image build succeeded.")
data("image", image)
}
return image
} catch (e: DockerRegistryCredentialsException) {
throw ImageBuildFailedException("Could not build image: ${e.message}", e)
}
}
fun pull(imageName: String, cancellationContext: CancellationContext, onProgressUpdate: (DockerImageProgress) -> Unit): DockerImage {
try {
if (!api.hasImage(imageName)) {
val credentials = credentialsProvider.getCredentials(imageName)
val reporter = imageProgressReporterFactory()
api.pull(imageName, credentials, cancellationContext) { progress ->
val progressUpdate = reporter.processProgressUpdate(progress)
if (progressUpdate != null) {
onProgressUpdate(progressUpdate)
}
}
}
return DockerImage(imageName)
} catch (e: DockerRegistryCredentialsException) {
throw ImagePullFailedException("Could not pull image '$imageName': ${e.message}", e)
}
}
}
data class DockerImageBuildProgress(val currentStep: Int, val totalSteps: Int, val message: String, val progress: DockerImageProgress?) {
companion object {
private val buildStepLineRegex = """^Step (\d+)/(\d+) : (.*)$""".toRegex()
fun fromBuildOutput(line: JsonObject): DockerImageBuildProgress? {
val output = line.getPrimitiveOrNull("stream")?.content
if (output == null) {
return null
}
val stepLineMatch = buildStepLineRegex.matchEntire(output)
if (stepLineMatch == null) {
return null
}
return DockerImageBuildProgress(stepLineMatch.groupValues[1].toInt(), stepLineMatch.groupValues[2].toInt(), stepLineMatch.groupValues[3], null)
}
}
}
| apache-2.0 | 4f4e6975ea888fe9dc4c8e09e98552ec | 39.371795 | 155 | 0.667672 | 5.378309 | false | false | false | false |
jorjoluiso/QuijoteLui | src/main/kotlin/com/quijotelui/electronico/comprobantes/factura/TotalImpuesto.kt | 1 | 616 | package comprobantes.factura
import java.math.BigDecimal
import javax.xml.bind.annotation.XmlElement
import javax.xml.bind.annotation.XmlRootElement
import javax.xml.bind.annotation.XmlType
@XmlRootElement
@XmlType(propOrder = arrayOf(
"codigo",
"codigoPorcentaje",
"baseImponible",
"tarifa",
"valor"))
class TotalImpuesto (
@XmlElement var codigo: String? = null,
@XmlElement var codigoPorcentaje: String? = null,
@XmlElement var baseImponible: BigDecimal? = null,
@XmlElement var tarifa: BigDecimal? = null,
@XmlElement var valor: BigDecimal? = null
) | gpl-3.0 | b98b90f9f5e84af68a90412a4ae772a1 | 27.045455 | 54 | 0.712662 | 3.802469 | false | false | false | false |
jorjoluiso/QuijoteLui | src/main/kotlin/com/quijotelui/electronico/comprobantes/retencion/InformacionRetencion.kt | 1 | 1011 | package com.quijotelui.electronico.comprobantes.retencion
import javax.xml.bind.annotation.XmlElement
import javax.xml.bind.annotation.XmlRootElement
import javax.xml.bind.annotation.XmlType
@XmlRootElement
@XmlType(propOrder = arrayOf(
"fechaEmision",
"dirEstablecimiento",
"contribuyenteEspecial",
"obligadoContabilidad",
"tipoIdentificacionSujetoRetenido",
"razonSocialSujetoRetenido",
"identificacionSujetoRetenido",
"periodoFiscal"
))
class InformacionRetencion (
@XmlElement var fechaEmision: String? = null,
@XmlElement var dirEstablecimiento: String? = null,
@XmlElement var contribuyenteEspecial: String? = null,
@XmlElement var obligadoContabilidad: String? = null,
@XmlElement var tipoIdentificacionSujetoRetenido: String? = null,
@XmlElement var razonSocialSujetoRetenido: String? = null,
@XmlElement var identificacionSujetoRetenido: String? = null,
@XmlElement var periodoFiscal: String? = null
) | gpl-3.0 | 8894b7ac458f71d8443975d505177f14 | 32.733333 | 69 | 0.742829 | 3.572438 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/facet/MinecraftFacet.kt | 1 | 9296 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.facet
import com.demonwav.mcdev.asset.PlatformAssets
import com.demonwav.mcdev.facet.MinecraftFacetType.Companion.TYPE_ID
import com.demonwav.mcdev.platform.AbstractModule
import com.demonwav.mcdev.platform.AbstractModuleType
import com.demonwav.mcdev.platform.PlatformType
import com.demonwav.mcdev.util.SourceType
import com.demonwav.mcdev.util.filterNotNull
import com.demonwav.mcdev.util.mapFirstNotNull
import com.google.common.collect.HashMultimap
import com.intellij.facet.Facet
import com.intellij.facet.FacetManager
import com.intellij.facet.FacetTypeId
import com.intellij.facet.FacetTypeRegistry
import com.intellij.ide.projectView.ProjectView
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleGrouper
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import java.util.concurrent.ConcurrentHashMap
import javax.swing.Icon
import kotlin.jvm.Throws
import org.jetbrains.jps.model.java.JavaResourceRootType
import org.jetbrains.jps.model.java.JavaSourceRootType
class MinecraftFacet(
module: Module,
name: String,
configuration: MinecraftFacetConfiguration,
underlyingFacet: Facet<*>?
) : Facet<MinecraftFacetConfiguration>(facetType, module, name, configuration, underlyingFacet) {
private val moduleMap = ConcurrentHashMap<AbstractModuleType<*>, AbstractModule>()
private val roots: HashMultimap<SourceType, VirtualFile?> = HashMultimap.create()
init {
configuration.facet = this
}
override fun initFacet() {
refresh()
}
override fun disposeFacet() {
moduleMap.forEach { (_, m) ->
m.dispose()
}
moduleMap.clear()
roots.clear()
}
fun refresh() {
if (module.isDisposed) {
return
}
// Don't allow parent types with child types in auto detected set
val allEnabled = configuration.state.run {
autoDetectTypes = PlatformType.removeParents(autoDetectTypes)
val userEnabled = userChosenTypes.entries.asSequence()
.filter { it.value }
.map { it.key }
val autoEnabled = autoDetectTypes.asSequence()
.filter { userChosenTypes[it] == null }
userEnabled + autoEnabled
}
// Remove modules that aren't registered anymore
val toBeRemoved = moduleMap.entries.asSequence()
.filter { !allEnabled.contains(it.key.platformType) }
.onEach { it.value.dispose() }
.map { it.key }
.toHashSet() // CME defense
toBeRemoved.forEach { moduleMap.remove(it) }
// Do this before we register the new modules
updateRoots()
// Add modules which are new
val newlyEnabled = mutableListOf<AbstractModule>()
allEnabled
.map { it.type }
.filter { !moduleMap.containsKey(it) }
.forEach {
newlyEnabled += register(it)
}
newlyEnabled.forEach(AbstractModule::init)
ProjectView.getInstance(module.project).refresh()
}
private fun updateRoots() {
roots.clear()
val rootManager = ModuleRootManager.getInstance(module)
rootManager.contentEntries.asSequence()
.flatMap { entry -> entry.sourceFolders.asSequence() }
.filterNotNull { it.file }
.forEach {
when (it.rootType) {
JavaSourceRootType.SOURCE -> roots.put(SourceType.SOURCE, it.file)
JavaSourceRootType.TEST_SOURCE -> roots.put(SourceType.TEST_SOURCE, it.file)
JavaResourceRootType.RESOURCE -> roots.put(SourceType.RESOURCE, it.file)
JavaResourceRootType.TEST_RESOURCE -> roots.put(SourceType.TEST_RESOURCE, it.file)
}
}
}
private fun register(type: AbstractModuleType<*>): AbstractModule {
type.performCreationSettingSetup(module.project)
val module = type.generateModule(this)
moduleMap[type] = module
return module
}
val modules get() = moduleMap.values
val types get() = moduleMap.keys
fun isOfType(type: AbstractModuleType<*>) = moduleMap.containsKey(type)
fun <T : AbstractModule> getModuleOfType(type: AbstractModuleType<T>): T? {
@Suppress("UNCHECKED_CAST")
return moduleMap[type] as? T
}
fun isEventClassValidForModule(eventClass: PsiClass?) =
eventClass != null && moduleMap.values.any { it.isEventClassValid(eventClass, null) }
fun isEventClassValid(eventClass: PsiClass, method: PsiMethod): Boolean {
return doIfGood(method) {
it.isEventClassValid(eventClass, method)
} == true
}
fun writeErrorMessageForEvent(eventClass: PsiClass, method: PsiMethod): String? {
return doIfGood(method) {
it.writeErrorMessageForEventParameter(eventClass, method)
}
}
fun isStaticListenerSupported(method: PsiMethod): Boolean {
return doIfGood(method) {
it.isStaticListenerSupported(method)
} == true
}
fun suppressStaticListener(method: PsiMethod): Boolean {
return doIfGood(method) {
!it.isStaticListenerSupported(method)
} == true
}
private inline fun <T> doIfGood(method: PsiMethod, action: (AbstractModule) -> T): T? {
for (abstractModule in moduleMap.values) {
val good = abstractModule.moduleType.listenerAnnotations.any {
method.modifierList.findAnnotation(it) != null
}
if (good) {
return action(abstractModule)
}
}
return null
}
val isEventGenAvailable get() = moduleMap.keys.any { it.isEventGenAvailable }
fun shouldShowPluginIcon(element: PsiElement?) = moduleMap.values.any { it.shouldShowPluginIcon(element) }
val icon: Icon?
get() {
val modulesWithIcon = moduleMap.keys.filter { it.hasIcon }
val candidateModules = modulesWithIcon.filter { !it.isIconSecondary }
.ifEmpty { modulesWithIcon }
return when (candidateModules.size) {
0 -> null
1 -> candidateModules.single().icon
else -> PlatformAssets.MINECRAFT_ICON
}
}
fun findFile(path: String, type: SourceType): VirtualFile? {
try {
return findFile0(path, type)
} catch (ignored: RefreshRootsException) {
}
updateRoots()
return try {
findFile0(path, type)
} catch (ignored: RefreshRootsException) {
// Well we tried our best
null
}
}
private class RefreshRootsException : Exception()
@Throws(RefreshRootsException::class)
private fun findFile0(path: String, type: SourceType): VirtualFile? {
val roots = roots[type]
for (root in roots) {
val r = root ?: continue
if (!r.isValid) {
throw RefreshRootsException()
}
return r.findFileByRelativePath(path) ?: continue
}
return null
}
companion object {
val ID = FacetTypeId<MinecraftFacet>(TYPE_ID)
val facetType: MinecraftFacetType
get() = FacetTypeRegistry.getInstance().findFacetType(ID) as MinecraftFacetType
val facetTypeOrNull: MinecraftFacetType?
get() = FacetTypeRegistry.getInstance().findFacetType(TYPE_ID) as? MinecraftFacetType
fun getInstance(module: Module) = FacetManager.getInstance(module).getFacetByType(ID)
fun getChildInstances(module: Module) = runReadAction run@{
val instance = getInstance(module)
if (instance != null) {
return@run setOf(instance)
}
val project = module.project
val manager = ModuleManager.getInstance(project)
val grouper = ModuleGrouper.instanceFor(project)
val result = mutableSetOf<MinecraftFacet>()
val modulePath = grouper.getModuleAsGroupPath(module) ?: return@run result
for (m in manager.modules) {
val path = grouper.getGroupPath(m)
if (modulePath != path) {
continue
}
val facet = getInstance(m) ?: continue
result.add(facet)
}
return@run result
}
fun <T : AbstractModule> getInstance(module: Module, type: AbstractModuleType<T>) =
getInstance(module)?.getModuleOfType(type)
fun <T : AbstractModule> getInstance(module: Module, vararg types: AbstractModuleType<T>): T? {
val instance = getInstance(module) ?: return null
return types.mapFirstNotNull { instance.getModuleOfType(it) }
}
}
}
| mit | c00d70df8b5a5b88f62e991e6e3f1a32 | 32.2 | 110 | 0.635865 | 4.819077 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/platform/mixin/folding/MixinObjectCastFoldingBuilder.kt | 1 | 2782 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.folding
import com.demonwav.mcdev.platform.mixin.MixinModuleType
import com.intellij.lang.ASTNode
import com.intellij.lang.folding.CustomFoldingBuilder
import com.intellij.lang.folding.FoldingDescriptor
import com.intellij.openapi.editor.Document
import com.intellij.openapi.util.TextRange
import com.intellij.psi.CommonClassNames
import com.intellij.psi.JavaRecursiveElementWalkingVisitor
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiJavaFile
import com.intellij.psi.PsiTypeCastExpression
import com.intellij.psi.impl.source.tree.ChildRole
import com.intellij.psi.impl.source.tree.CompositeElement
class MixinObjectCastFoldingBuilder : CustomFoldingBuilder() {
// I'm not dumb
override fun isDumbAware() = false
override fun isRegionCollapsedByDefault(node: ASTNode): Boolean =
MixinFoldingSettings.instance.state.foldObjectCasts
override fun getLanguagePlaceholderText(node: ASTNode, range: TextRange): String? {
val element = node.psi as? PsiTypeCastExpression ?: return null
return "(${element.castType?.text ?: return node.text})"
}
override fun buildLanguageFoldRegions(
descriptors: MutableList<FoldingDescriptor>,
root: PsiElement,
document: Document,
quick: Boolean
) {
if (root !is PsiJavaFile || !MixinModuleType.isInModule(root)) {
return
}
root.accept(Visitor(descriptors))
}
private class Visitor(private val descriptors: MutableList<FoldingDescriptor>) :
JavaRecursiveElementWalkingVisitor() {
val settings = MixinFoldingSettings.instance.state
override fun visitTypeCastExpression(expression: PsiTypeCastExpression) {
super.visitTypeCastExpression(expression)
if (!settings.foldObjectCasts) {
return
}
val innerCast = expression.operand as? PsiTypeCastExpression ?: return
if ((innerCast.type as? PsiClassType)?.resolve()?.qualifiedName == CommonClassNames.JAVA_LANG_OBJECT) {
// Fold the two casts
val start = (expression as? CompositeElement)?.findChildByRole(ChildRole.LPARENTH) ?: return
val end = (innerCast as? CompositeElement)?.findChildByRole(ChildRole.RPARENTH) ?: return
descriptors.add(
FoldingDescriptor(
expression.node,
TextRange(start.startOffset, end.startOffset + end.textLength)
)
)
}
}
}
}
| mit | 715d256f30bd00fa5ade6ae0bb8a1750 | 32.926829 | 115 | 0.685478 | 4.959002 | false | false | false | false |
kenrube/Fantlab-client | app/src/main/kotlin/ru/fantlab/android/data/dao/response/WorkResponse.kt | 2 | 4750 | package ru.fantlab.android.data.dao.response
import com.github.kittinunf.fuel.core.ResponseDeserializable
import com.google.gson.JsonNull
import com.google.gson.JsonParser
import ru.fantlab.android.data.dao.model.*
import ru.fantlab.android.provider.rest.DataManager
data class WorkResponse(
val work: Work,
val awards: Awards?,
val children: ArrayList<ChildWork>,
val classificatory: ArrayList<GenreGroup>,
val editionsBlocks: EditionsBlocks?,
val editionsInfo: EditionsInfo?,
val films: Films?,
val linguaProfile: ArrayList<String>,
val parents: ParentWorks?,
val rootSagas: ArrayList<WorkRootSaga>,
val statistics: Statistics?,
val translations: ArrayList<Translation>
) {
class Deserializer : ResponseDeserializable<WorkResponse> {
private lateinit var work: Work
private var awards: Awards? = null
private val children: ArrayList<ChildWork> = arrayListOf()
private val classificatory: ArrayList<GenreGroup> = arrayListOf()
private var editions: EditionsBlocks? = null
private var editionsInfo: EditionsInfo? = null
private var films: Films? = null
private val linguaProfile: ArrayList<String> = arrayListOf()
private var parents: ParentWorks? = null
private val rootSagas: ArrayList<WorkRootSaga> = arrayListOf()
private var statistics: Statistics? = null
private val translations: ArrayList<Translation> = arrayListOf()
override fun deserialize(content: String): WorkResponse {
val jsonObject = JsonParser().parse(content).asJsonObject
work = DataManager.gson.fromJson(jsonObject, Work::class.java)
if (jsonObject["awards"] != JsonNull.INSTANCE) {
val `object` = jsonObject.getAsJsonObject("awards")
awards = DataManager.gson.fromJson(`object`, Awards::class.java)
}
if (jsonObject["children"] != JsonNull.INSTANCE) {
val array = jsonObject.getAsJsonArray("children")
array.map {
children.add(DataManager.gson.fromJson(it.asJsonObject, ChildWork::class.java))
}
}
if (jsonObject["classificatory"] != JsonNull.INSTANCE) {
val array = jsonObject.getAsJsonObject("classificatory").getAsJsonArray("genre_group")
if (array != null) {
val recursiveClassificatory = arrayListOf<RecursiveGenreGroup>()
array.map {
recursiveClassificatory.add(DataManager.gson.fromJson(
it.asJsonObject,
RecursiveGenreGroup::class.java
))
}
recursiveClassificatory.map {
val genres = arrayListOf<Pair<Int, GenreGroup.Genre>>()
it.genre.map { genre ->
genres.add(0, genre)
}
classificatory.add(GenreGroup(genres, it.genreGroupId, it.label))
}
}
}
if (jsonObject["editions_blocks"] != JsonNull.INSTANCE) {
val `object` = jsonObject.getAsJsonObject("editions_blocks")
editions = EditionsBlocks.Deserializer().deserialize(`object`.toString())
}
if (jsonObject["editions_info"] != JsonNull.INSTANCE) {
val `object` = jsonObject.getAsJsonObject("editions_info")
editionsInfo = EditionsInfo.Deserializer().deserialize(`object`.toString())
}
if (jsonObject["films"] != JsonNull.INSTANCE) {
val `object` = jsonObject.getAsJsonObject("films")
films = DataManager.gson.fromJson(`object`, Films::class.java)
}
if (jsonObject["la_resume"] != JsonNull.INSTANCE) {
val array = jsonObject.getAsJsonArray("la_resume")
array.map {
linguaProfile.add(it.asJsonPrimitive.asString)
}
}
if (jsonObject["parents"] != JsonNull.INSTANCE) {
val `object` = jsonObject.getAsJsonObject("parents")
parents = DataManager.gson.fromJson(`object`, ParentWorks::class.java)
}
if (jsonObject["work_root_saga"] != JsonNull.INSTANCE) {
val array = jsonObject.getAsJsonArray("work_root_saga")
array.map {
rootSagas.add(DataManager.gson.fromJson(it.asJsonObject, WorkRootSaga::class.java))
}
}
if (jsonObject["stat"] != JsonNull.INSTANCE) {
val `object` = jsonObject.getAsJsonObject("stat")
statistics = DataManager.gson.fromJson(`object`, Statistics::class.java)
}
if (jsonObject["translations"] != JsonNull.INSTANCE) {
val array = jsonObject.getAsJsonArray("translations")
array.map {
translations.add(DataManager.gson.fromJson(it.asJsonObject, Translation::class.java))
}
}
return WorkResponse(
work,
awards,
children,
classificatory,
editions,
editionsInfo,
films,
linguaProfile,
parents,
rootSagas,
statistics,
translations
)
}
private fun ArrayList<Pair<Int, GenreGroup.Genre>>.add(
level: Int,
genreGroup: RecursiveGenreGroup.Genre
) {
add(level to GenreGroup.Genre(genreGroup.genreId, genreGroup.label, genreGroup.percent))
genreGroup.genre?.map { add(level + 1, it) }
}
}
} | gpl-3.0 | a6cabe96f4ca18478fae572a811c1d94 | 34.992424 | 91 | 0.708421 | 3.751975 | false | false | false | false |
anlun/haskell-idea-plugin | plugin/src/org/jetbrains/haskell/util/OSUtil.kt | 1 | 1393 | package org.jetbrains.haskell.util
import java.io.File
import kotlin.platform.platformStatic
public object OSUtil {
val newLine = System.getProperty("line.separator").toString();
val osName = System.getProperty("os.name")!!.toLowerCase();
public val isWindows: Boolean = (osName.indexOf("win") >= 0)
public val isMac: Boolean = (osName.indexOf("mac") >= 0) || (osName.indexOf("darwin") >= 0);
platformStatic
public fun getCabalData(): String {
return if (isWindows) {
joinPath(System.getenv("AppData")!!, "cabal")
} else if (isMac) {
joinPath(System.getProperty("user.home")!!, "Library", "Haskell")
} else {
joinPath(System.getProperty("user.home")!!, ".cabal")
}
}
platformStatic
public fun getDefaultCabalBin(): String = joinPath(getCabalData(), "bin")
fun getProgramDataFolder(name: String): String {
return if (isWindows) {
joinPath(System.getenv("AppData")!!, name);
} else if (isMac) {
joinPath(System.getProperty("user.home")!!, "Library", "Application Support", name);
} else {
joinPath(System.getProperty("user.home")!!, "." + name);
}
}
fun getExe(cmd : String) : String = if (isWindows) cmd + ".exe" else cmd
platformStatic
fun getExe() : String = if (isWindows) ".exe" else ""
} | apache-2.0 | 16db7f8cfad24905f5d4501c78b4defa | 31.418605 | 96 | 0.606604 | 4.273006 | false | false | false | false |
ligee/kotlin-jupyter | src/main/kotlin/org/jetbrains/kotlinx/jupyter/magics/CompletionMagicsProcessor.kt | 1 | 8537 | package org.jetbrains.kotlinx.jupyter.magics
import org.jetbrains.kotlinx.jupyter.common.ReplLineMagic
import org.jetbrains.kotlinx.jupyter.common.getHttp
import org.jetbrains.kotlinx.jupyter.common.text
import org.jetbrains.kotlinx.jupyter.config.catchAll
import org.jetbrains.kotlinx.jupyter.config.getLogger
import org.jetbrains.kotlinx.jupyter.createCachedFun
import org.jetbrains.kotlinx.jupyter.defaultRepositories
import org.jetbrains.kotlinx.jupyter.libraries.Brackets
import org.jetbrains.kotlinx.jupyter.libraries.libraryCommaRanges
import org.jetbrains.kotlinx.jupyter.libraries.parseLibraryArguments
import org.jetbrains.kotlinx.jupyter.libraryDescriptors
import org.jetbrains.kotlinx.jupyter.log
import org.w3c.dom.Document
import org.w3c.dom.Element
import org.w3c.dom.Node
import org.w3c.dom.NodeList
import org.xml.sax.InputSource
import java.io.File
import java.io.StringReader
import javax.xml.parsers.DocumentBuilder
import javax.xml.parsers.DocumentBuilderFactory
import kotlin.script.experimental.api.SourceCodeCompletionVariant
class CompletionMagicsProcessor(
private val homeDir: File?,
) : AbstractMagicsProcessor() {
fun process(code: String, cursor: Int): Result {
val magics = magicsIntervals(code)
var insideMagic = false
val handler = Handler()
for (magicRange in magics) {
if (cursor in (magicRange.from + 1)..magicRange.to) {
insideMagic = true
if (code[magicRange.from] != MAGICS_SIGN || cursor == magicRange.from) continue
val magicText = code.substring(magicRange.from + 1, magicRange.to)
log.catchAll(msg = "Handling completion of $magicText failed") {
handler.handle(magicText, cursor - magicRange.from - 1)
}
}
}
return Result(getCleanCode(code, magics), insideMagic, handler.completions)
}
class Result(
val code: String,
val cursorInsideMagic: Boolean,
val completions: List<SourceCodeCompletionVariant>
)
private inner class Handler {
private val _completions = mutableListOf<SourceCodeCompletionVariant>()
val completions: List<SourceCodeCompletionVariant> get() = _completions.distinctBy { it.text }
fun handle(magicText: String, cursor: Int) {
val firstSpaceIndex = magicText.indexOf(' ')
if (cursor <= firstSpaceIndex || firstSpaceIndex == -1) {
val magicPrefix = magicText.substring(0, cursor)
val suggestions = ReplLineMagic.codeInsightValues.filter { it.name.startsWith(magicPrefix) }
suggestions.mapTo(_completions) { mg ->
variant(mg.name, mg.type.name)
}
} else {
val magicName = magicText.substring(0, firstSpaceIndex)
val argument = magicText.substring(firstSpaceIndex)
val cursorToArgument = cursor - firstSpaceIndex
when (ReplLineMagic.valueOfOrNull(magicName)?.value) {
ReplLineMagic.USE -> {
for ((from, to) in libraryCommaRanges(argument)) {
if (cursorToArgument in (from + 1)..to) {
val libArgPart = argument.substring(from + 1, to)
handleLibrary(libArgPart, cursorToArgument - from - 1)
break
}
}
}
else -> {}
}
}
}
private fun handleLibrary(librarySubstring: String, cursor: Int) {
if (homeDir == null) return
val descriptors = libraryDescriptors(homeDir)!!
val firstBracketIndex = librarySubstring.indexOf('(')
if (cursor <= firstBracketIndex || firstBracketIndex == -1) {
val libNamePrefix = librarySubstring.substring(0, cursor).trimStart()
val sufficientNames = descriptors.keys.filter { it.startsWith(libNamePrefix) }
sufficientNames.mapTo(_completions) {
variant(it, "library")
}
} else {
val callArgs = parseLibraryArguments("$librarySubstring)", Brackets.ROUND, firstBracketIndex + 1).toList()
if (callArgs.isEmpty()) return
val argIndex = callArgs.indexOfFirst { cursor < it.end }
if (argIndex == -1) return
val argCallStart = if (argIndex == 0) firstBracketIndex + 1 else callArgs[argIndex - 1].end
val argCall = librarySubstring.substring(argCallStart, cursor)
val argName = callArgs[argIndex].variable.name
val argValuePrefix = if (argName.isNotEmpty()) {
if ('=' !in argCall) return
argCall.substringAfter('=').trimStart()
} else {
argCall
}
val libName = librarySubstring.substring(0, firstBracketIndex).trim()
val descriptor = descriptors[libName] ?: return
val paramNames = descriptor.variables.mapTo(mutableSetOf()) { it.name }
if (paramNames.isEmpty()) return
val paramName = argName.ifEmpty {
paramNames.singleOrNull() ?: return
}
for (dependencyStr in descriptor.dependencies) {
val match = MAVEN_DEP_REGEX.matchEntire(dependencyStr) ?: continue
val group = match.groups[1]!!.value
val artifact = match.groups[2]!!.value
val versionTemplate = match.groups[3]!!.value
if (!versionTemplate.startsWith("$")) continue
val dependencyParamName = versionTemplate.substring(1)
if (dependencyParamName != paramName) continue
val versions = (descriptor.repositories + defaultRepositories.map { it.string }).firstNotNullOfOrNull { repo ->
getVersions(ArtifactLocation(repo, group, artifact))
}.orEmpty()
val matchingVersions = versions.filter { it.startsWith(argValuePrefix) }.reversed()
matchingVersions.mapTo(_completions) {
variant(it, "version")
}
}
}
}
}
companion object {
private fun variant(text: String, icon: String) = SourceCodeCompletionVariant(text, text, icon, icon)
private val MAVEN_DEP_REGEX = "^([^:]+):([^:]+):([^:]+)$".toRegex()
private data class ArtifactLocation(val repository: String, val group: String, val artifact: String)
private fun metadataUrl(artifactLocation: ArtifactLocation): String {
val repo = with(artifactLocation.repository) { if (endsWith('/')) this else "$this/" }
return "$repo${artifactLocation.group.replace(".", "/")}/${artifactLocation.artifact}/maven-metadata.xml"
}
private val getVersions = createCachedFun { artifactLocation: ArtifactLocation ->
val response = getHttp(metadataUrl(artifactLocation))
if (!response.status.successful) {
getLogger("magics completion").warn("Magic completion request failed: ${response.status}")
return@createCachedFun null
}
val document = loadXML(response.text)
val versionsTag = document
.getElementsByTagName("versions")
.singleOrNull() ?: return@createCachedFun emptyList()
(versionsTag as? Element)?.getElementsByTagName("version")
?.toList()
?.map { it.textContent }
.orEmpty()
}
private fun loadXML(xml: String): Document {
val factory: DocumentBuilderFactory = DocumentBuilderFactory.newInstance()
val builder: DocumentBuilder = factory.newDocumentBuilder()
val inputSource = InputSource(StringReader(xml))
return builder.parse(inputSource)
}
private fun NodeList.toList(): List<Node> {
return object : AbstractList<Node>() {
override val size: Int get() = length
override fun get(index: Int) = item(index)
}
}
private fun NodeList.singleOrNull() = toList().singleOrNull()
}
}
| apache-2.0 | 9bf8d21905f9c9b4c509e3f54503e45d | 43.463542 | 131 | 0.596931 | 5.045508 | false | false | false | false |
felipebz/sonar-plsql | sonar-zpa-plugin/src/test/kotlin/org/sonar/plsqlopen/PlSqlChecksTest.kt | 1 | 5484 | /**
* Z PL/SQL Analyzer
* Copyright (C) 2015-2022 Felipe Zorzo
* mailto:felipe AT felipezorzo DOT com DOT br
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.plsqlopen
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.fail
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.sonar.api.batch.rule.internal.ActiveRulesBuilder
import org.sonar.api.batch.rule.internal.NewActiveRule
import org.sonar.api.rule.RuleKey
import org.sonar.api.server.rule.RulesDefinition
import org.sonar.check.Rule
import org.sonar.plsqlopen.rules.SonarQubeActiveRulesAdapter
import org.sonar.plsqlopen.rules.SonarQubeRuleKeyAdapter
import org.sonar.plsqlopen.rules.SonarQubeRuleMetadataLoader
import org.sonar.plugins.plsqlopen.api.CustomPlSqlRulesDefinition
import org.sonar.plugins.plsqlopen.api.checks.PlSqlCheck
import org.sonar.plugins.plsqlopen.api.checks.PlSqlVisitor
class PlSqlChecksTest {
private lateinit var activeRules: SonarQubeActiveRulesAdapter
private lateinit var customRulesDefinition: MyCustomPlSqlRulesDefinition
private val ruleMetadataLoader = SonarQubeRuleMetadataLoader()
@BeforeEach
fun setUp() {
activeRules = SonarQubeActiveRulesAdapter(ActiveRulesBuilder()
.addRule(NewActiveRule.Builder().setRuleKey(RuleKey.of(DEFAULT_REPOSITORY_KEY, DEFAULT_RULE_KEY)).build())
.addRule(NewActiveRule.Builder().setRuleKey(RuleKey.of(CUSTOM_REPOSITORY_KEY, CUSTOM_RULE_KEY)).build())
.build())
customRulesDefinition = MyCustomPlSqlRulesDefinition()
val context = RulesDefinition.Context()
customRulesDefinition.define(context)
}
@Test
fun shouldReturnDefaultChecks() {
val checks = PlSqlChecks.createPlSqlCheck(activeRules, ruleMetadataLoader)
checks.addChecks(DEFAULT_REPOSITORY_KEY, listOf(MyRule::class.java))
val defaultVisitor = visitor(checks, DEFAULT_REPOSITORY_KEY, DEFAULT_RULE_KEY)
assertThat(checks.all()).hasSize(1)
assertThat(checks.ruleKey(defaultVisitor)).isNotNull
assertThat(checks.ruleKey(defaultVisitor)?.rule).isEqualTo(DEFAULT_RULE_KEY)
assertThat(checks.ruleKey(defaultVisitor)?.repository).isEqualTo(DEFAULT_REPOSITORY_KEY)
}
@Test
fun shouldReturnCustomChecks() {
val checks = PlSqlChecks.createPlSqlCheck(activeRules, ruleMetadataLoader)
checks.addCustomChecks(arrayOf(customRulesDefinition))
val customVisitor = visitor(checks, CUSTOM_REPOSITORY_KEY, CUSTOM_RULE_KEY)
assertThat(checks.all()).hasSize(1)
assertThat(checks.ruleKey(customVisitor)).isNotNull
assertThat(checks.ruleKey(customVisitor)?.rule).isEqualTo(CUSTOM_RULE_KEY)
assertThat(checks.ruleKey(customVisitor)?.repository).isEqualTo(CUSTOM_REPOSITORY_KEY)
}
@Test
fun shouldWorkWithoutCustomChecks() {
val checks = PlSqlChecks.createPlSqlCheck(activeRules, ruleMetadataLoader)
checks.addCustomChecks(null)
assertThat(checks.all()).hasSize(0)
}
@Test
fun shouldNotReturnRuleKeyIfCheckDoesNotExists() {
val checks = PlSqlChecks.createPlSqlCheck(activeRules, ruleMetadataLoader)
checks.addChecks(DEFAULT_REPOSITORY_KEY, listOf(MyRule::class.java))
assertThat(checks.ruleKey(MyCustomRule())).isNull()
}
private fun visitor(plSqlChecks: PlSqlChecks, repository: String, rule: String): PlSqlVisitor {
val key = SonarQubeRuleKeyAdapter.of(repository, rule)
var visitor: PlSqlVisitor? = null
for (checks in plSqlChecks.checks) {
visitor = checks.of(key)
if (visitor != null) {
return visitor
}
}
return visitor ?: fail("Should return a visitor.")
}
@Rule(key = DEFAULT_RULE_KEY, name = "This is the default rules", description = "desc")
class MyRule : PlSqlCheck()
@Rule(key = CUSTOM_RULE_KEY, name = "This is a custom rules", description = "desc")
class MyCustomRule : PlSqlCheck()
class MyCustomPlSqlRulesDefinition : CustomPlSqlRulesDefinition() {
override fun repositoryName(): String {
return "Custom Rule Repository"
}
override fun repositoryKey(): String {
return CUSTOM_REPOSITORY_KEY
}
override fun checkClasses(): Array<Class<*>> {
return arrayOf(MyCustomRule::class.java)
}
}
companion object {
private const val DEFAULT_REPOSITORY_KEY = "DefaultRuleRepository"
private const val DEFAULT_RULE_KEY = "MyRule"
private const val CUSTOM_REPOSITORY_KEY = "CustomRuleRepository"
private const val CUSTOM_RULE_KEY = "MyCustomRule"
}
}
| lgpl-3.0 | 6e02b563ba1688e5dd5aaf175464c047 | 38.73913 | 122 | 0.71973 | 4.307934 | false | false | false | false |
TCA-Team/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/component/tumui/calendar/NextLectureCard.kt | 1 | 3217 | package de.tum.`in`.tumcampusapp.component.tumui.calendar
import android.content.Context
import android.content.SharedPreferences
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import de.tum.`in`.tumcampusapp.R
import de.tum.`in`.tumcampusapp.component.tumui.calendar.model.CalendarItem
import de.tum.`in`.tumcampusapp.component.ui.overview.CardInteractionListener
import de.tum.`in`.tumcampusapp.component.ui.overview.CardManager
import de.tum.`in`.tumcampusapp.component.ui.overview.card.Card
import de.tum.`in`.tumcampusapp.component.ui.overview.card.CardViewHolder
import org.joda.time.DateTime
import java.util.*
class NextLectureCard(context: Context) : Card(CardManager.CARD_NEXT_LECTURE, context, "card_next_lecture") {
private val calendarController: CalendarController = CalendarController(context)
private val lectures = ArrayList<CardCalendarItem>()
override val optionsMenuResId: Int
get() = R.menu.card_popup_menu
override fun updateViewHolder(viewHolder: RecyclerView.ViewHolder) {
if (viewHolder is NextLectureCardViewHolder) {
viewHolder.bind(lectures)
}
}
override fun discard(editor: SharedPreferences.Editor) {
val item = lectures.lastOrNull() ?: return
editor.putLong(NEXT_LECTURE_DATE, item.start.millis)
}
override fun shouldShow(prefs: SharedPreferences): Boolean {
val item = lectures.firstOrNull() ?: return false
val prevTime = prefs.getLong(NEXT_LECTURE_DATE, 0)
return item.start.millis > prevTime
}
override fun getId(): Int {
return 0
}
fun setLectures(calendarItems: List<CalendarItem>) {
calendarItems.mapTo(lectures) { calendarItem ->
CardCalendarItem(
id = calendarItem.nr,
start = calendarItem.dtstart,
end = calendarItem.dtend,
title = calendarItem.getFormattedTitle(),
locations = calendarController.getLocationsForEvent(calendarItem.nr)
)
}
}
data class CardCalendarItem(
val id: String,
val title: String,
val start: DateTime,
val end: DateTime,
val locations: List<String>?
) {
val locationString: String
get() {
val locationString = StringBuilder()
for (location in locations.orEmpty()) {
locationString.append(location)
locationString.append("\n")
}
// Remove the last new line character.
locationString.deleteCharAt(locationString.length - 1)
return locationString.toString()
}
}
companion object {
private const val NEXT_LECTURE_DATE = "next_date"
@JvmStatic
fun inflateViewHolder(parent: ViewGroup, interactionListener: CardInteractionListener): CardViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.card_next_lecture_item, parent, false)
return NextLectureCardViewHolder(view, interactionListener)
}
}
}
| gpl-3.0 | f2b5ef6494e828de64ae4f4444996a85 | 35.977011 | 114 | 0.662729 | 4.815868 | false | false | false | false |
ZieIony/Carbon | samples/src/main/java/tk/zielony/carbonsamples/widget/ButtonsActivity.kt | 1 | 8712 | package tk.zielony.carbonsamples.widget
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_buttons.*
import tk.zielony.carbonsamples.SampleAnnotation
import tk.zielony.carbonsamples.CodeActivity
import tk.zielony.carbonsamples.R
import tk.zielony.carbonsamples.ThemedActivity
@SampleAnnotation(layoutId = R.layout.activity_buttons, titleId = R.string.buttonsActivity_title)
class ButtonsActivity : ThemedActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initToolbar()
code_buttons.setOnClickListener { CodeActivity.start(this, CODE_BUTTONS) }
code_buttonsInversed.setOnClickListener { CodeActivity.start(this, CODE_BUTTONS_INVERSED) }
code_buttonsColored.setOnClickListener { CodeActivity.start(this, CODE_BUTTONS_COLORED) }
code_buttonsColoredInversed.setOnClickListener { CodeActivity.start(this, CODE_BUTTONS_COLORED_INVERSED) }
code_buttonsCustom.setOnClickListener { CodeActivity.start(this, CODE_BUTTONS_CUSTOM) }
}
companion object {
val CODE_BUTTONS = """
<carbon.widget.Button
style="@style/carbon_Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/carbon_padding"
android:text="Contained Button" />
<carbon.widget.Button
style="@style/carbon_Button.Outlined"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/carbon_padding"
android:text="Outlined button" />
<carbon.widget.Button
style="@style/carbon_Button.Flat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/carbon_padding"
android:text="Flat button" />
""".trimIndent()
val CODE_BUTTONS_INVERSED = """
<carbon.widget.Button
style="@style/carbon_Button.Inverse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/carbon_padding"
android:text="Contained Button" />
<carbon.widget.Button
style="@style/carbon_Button.Outlined.Inverse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/carbon_padding"
android:text="Outlined button" />
<carbon.widget.Button
style="@style/carbon_Button.Flat.Inverse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/carbon_padding"
android:text="Flat button" />
""".trimIndent()
val CODE_BUTTONS_COLORED = """
<carbon.widget.Button
style="@style/carbon_Button.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/carbon_padding"
android:tag="enable"
android:text="Contained Button" />
<carbon.widget.Button
style="@style/carbon_Button.Outlined.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/carbon_padding"
android:tag="enable"
android:text="Outlined button" />
<carbon.widget.Button
style="@style/carbon_Button.Flat.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/carbon_padding"
android:tag="enable"
android:text="flat button" />
""".trimIndent()
val CODE_BUTTONS_COLORED_INVERSED = """
<carbon.widget.Button
style="@style/carbon_Button.Colored.Inverse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/carbon_padding"
android:text="Contained Button" />
<carbon.widget.Button
style="@style/carbon_Button.Outlined.Colored.Inverse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/carbon_padding"
android:text="Outlined button" />
<carbon.widget.Button
style="@style/carbon_Button.Flat.Colored.Inverse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/carbon_padding"
android:text="flat button" />
""".trimIndent()
val CODE_BUTTONS_CUSTOM = """
<carbon.widget.Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/carbon_padding"
android:background="@drawable/buttonshape"
android:tag="enable"
android:text="Custom shape"
android:textColor="@color/carbon_textColorPrimary_dark"
app:carbon_backgroundTint="@null"
app:carbon_cornerRadius="0dp"
app:carbon_cornerRadiusTopStart="24dp" />
<carbon.widget.Button
style="@style/carbon_Button"
android:layout_width="wrap_content"
android:layout_height="36dp"
android:layout_margin="@dimen/carbon_padding"
android:background="#ffffffff"
android:paddingLeft="@dimen/carbon_padding"
android:paddingTop="0dp"
android:paddingRight="@dimen/carbon_padding"
android:paddingBottom="0dp"
android:tag="enable"
android:text="Inline Style"
android:textColor="#ff0000ff"
app:carbon_backgroundTint="@null"
app:carbon_cornerCut="4dp"
app:carbon_elevation="@dimen/carbon_elevationLow"
app:carbon_rippleColor="#40ff0000"
app:carbon_touchMarginBottom="6dp"
app:carbon_touchMarginLeft="100dp"
app:carbon_touchMarginRight="100dp"
app:carbon_touchMarginTop="6dp" />
<carbon.widget.Button
android:layout_width="wrap_content"
android:layout_height="36dp"
android:layout_margin="@dimen/carbon_padding"
android:background="@color/carbon_white"
android:tag="enable"
android:text="Rounded with ripple"
android:textColor="@color/carbon_amber_700"
app:carbon_cornerRadius="18dp"
app:carbon_rippleColor="#40ff0000"
app:carbon_stroke="@color/carbon_amber_700"
app:carbon_strokeWidth="2dp" />
<carbon.widget.Button
android:layout_width="wrap_content"
android:layout_height="56dp"
android:layout_margin="@dimen/carbon_padding"
android:background="@drawable/randomdata_background0"
android:tag="enable"
android:text="Custom"
android:textColor="@color/carbon_white"
android:textSize="@dimen/carbon_textSizeHeadline"
app:carbon_cornerCutBottomStart="16dp"
app:carbon_cornerCutTopEnd="16dp"
app:carbon_cornerRadiusBottomEnd="8dp"
app:carbon_cornerRadiusTopStart="8dp"
app:carbon_rippleColor="#4000ff00"
app:carbon_stroke="@color/carbon_green_700"
app:carbon_strokeWidth="2dp" />
""".trimIndent()
}
}
| apache-2.0 | da55f544863f1a26d08af982ae229842 | 45.588235 | 114 | 0.549587 | 5.056297 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/activities/GiftGemsActivity.kt | 1 | 4753 | package com.habitrpg.android.habitica.ui.activities
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.navArgs
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.google.android.material.tabs.TabLayoutMediator
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.SocialRepository
import com.habitrpg.android.habitica.databinding.ActivityGiftGemsBinding
import com.habitrpg.android.habitica.helpers.AppConfigManager
import com.habitrpg.android.habitica.helpers.ExceptionHandler
import com.habitrpg.android.habitica.helpers.PurchaseHandler
import com.habitrpg.android.habitica.models.members.Member
import com.habitrpg.android.habitica.ui.fragments.purchases.GiftBalanceGemsFragment
import com.habitrpg.android.habitica.ui.fragments.purchases.GiftPurchaseGemsFragment
import com.habitrpg.android.habitica.ui.views.CurrencyView
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.launch
import javax.inject.Inject
class GiftGemsActivity : PurchaseActivity() {
private lateinit var binding: ActivityGiftGemsBinding
internal val currencyView: CurrencyView by lazy {
val view = CurrencyView(this, "gems", true)
view
}
@Inject
lateinit var socialRepository: SocialRepository
@Inject
lateinit var appConfigManager: AppConfigManager
@Inject
lateinit var purchaseHandler: PurchaseHandler
private var giftedUsername: String? = null
private var giftedUserID: String? = null
private var giftedMember: Member? = null
private var purchaseFragment: GiftPurchaseGemsFragment? = null
private var balanceFragment: GiftBalanceGemsFragment? = null
override fun getLayoutResId(): Int {
return R.layout.activity_gift_gems
}
override fun getContentView(): View {
binding = ActivityGiftGemsBinding.inflate(layoutInflater)
return binding.root
}
override fun injectActivity(component: UserComponent?) {
component?.inject(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setTitle(R.string.gift_gems)
setSupportActionBar(binding.toolbar)
binding.toolbarAccessoryContainer.addView(currencyView)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)
giftedUserID = intent.getStringExtra("userID")
giftedUsername = intent.getStringExtra("username")
if (giftedUserID == null && giftedUsername == null) {
giftedUserID = navArgs<GiftGemsActivityArgs>().value.userID
giftedUsername = navArgs<GiftGemsActivityArgs>().value.username
}
setViewPagerAdapter()
lifecycleScope.launch(ExceptionHandler.coroutine()) {
val member = socialRepository.retrieveMember(giftedUsername ?: giftedUserID) ?: return@launch
giftedMember = member
giftedUserID = member.id
giftedUsername = member.username
purchaseFragment?.giftedMember = member
balanceFragment?.giftedMember = member
val user = userRepository.getUser().firstOrNull()
currencyView.value = user?.gemCount?.toDouble() ?: 0.0
}
}
private fun setViewPagerAdapter() {
val statePagerAdapter = object : FragmentStateAdapter(supportFragmentManager, lifecycle) {
override fun createFragment(position: Int): Fragment {
return if (position == 0) {
val fragment = GiftPurchaseGemsFragment()
fragment.setPurchaseHandler(purchaseHandler)
fragment.setupCheckout()
purchaseFragment = fragment
purchaseFragment?.giftedMember = giftedMember
fragment
} else {
val fragment = GiftBalanceGemsFragment()
balanceFragment = fragment
balanceFragment?.giftedMember = giftedMember
fragment
}
}
override fun getItemCount(): Int {
return 2
}
}
binding.viewPager.adapter = statePagerAdapter
TabLayoutMediator(binding.tabLayout, binding.viewPager) { tab, position ->
tab.text = when (position) {
0 -> getString(R.string.purchase)
1 -> getString(R.string.from_balance)
else -> ""
}
}.attach()
statePagerAdapter.notifyDataSetChanged()
}
}
| gpl-3.0 | 8e9e1f68c425f2880129e22e5813a929 | 37.024 | 105 | 0.688407 | 5.263566 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/presentation/course_purchase/reducer/CoursePurchaseReducer.kt | 1 | 4841 | package org.stepik.android.presentation.course_purchase.reducer
import org.stepik.android.domain.course_payments.model.PromoCodeSku
import org.stepik.android.domain.wishlist.model.WishlistOperationData
import org.stepik.android.presentation.course_purchase.CoursePurchaseFeature.State
import org.stepik.android.presentation.course_purchase.CoursePurchaseFeature.Message
import org.stepik.android.presentation.course_purchase.CoursePurchaseFeature.Action
import org.stepik.android.presentation.course_purchase.CoursePurchaseFeature
import org.stepik.android.presentation.wishlist.model.WishlistAction
import ru.nobird.android.core.model.mutate
import ru.nobird.android.presentation.redux.reducer.StateReducer
import javax.inject.Inject
class CoursePurchaseReducer
@Inject
constructor() : StateReducer<State, Message, Action> {
override fun reduce(state: State, message: Message): Pair<State, Set<Action>> =
when (message) {
is Message.InitMessage -> {
if (state is State.Idle) {
val promoCodeState = if (message.coursePurchaseData.promoCodeSku != PromoCodeSku.EMPTY) {
CoursePurchaseFeature.PromoCodeState.Valid(message.coursePurchaseData.promoCodeSku.name, message.coursePurchaseData.promoCodeSku)
} else {
CoursePurchaseFeature.PromoCodeState.Idle
}
val wishlistState = if (message.coursePurchaseData.isWishlisted) {
CoursePurchaseFeature.WishlistState.Wishlisted
} else {
CoursePurchaseFeature.WishlistState.Idle
}
State.Content(message.coursePurchaseData, promoCodeState, wishlistState) to emptySet()
} else {
null
}
}
is Message.WishlistAddMessage -> {
if (state is State.Content) {
val wishlistEntity = state.coursePurchaseData.wishlistEntity.copy(courses = state.coursePurchaseData.wishlistEntity.courses.mutate { add(0, state.coursePurchaseData.course.id) })
val wishlistOperationData = WishlistOperationData(state.coursePurchaseData.course.id, WishlistAction.ADD)
state.copy(wishlistState = CoursePurchaseFeature.WishlistState.Adding)to setOf(Action.AddToWishlist(state.coursePurchaseData.course, wishlistEntity, wishlistOperationData))
} else {
null
}
}
is Message.WishlistAddSuccess -> {
if (state is State.Content) {
val updatedCoursePurchaseData = state.coursePurchaseData.copy(wishlistEntity = message.wishlistEntity, isWishlisted = true)
state.copy(coursePurchaseData = updatedCoursePurchaseData, wishlistState = CoursePurchaseFeature.WishlistState.Wishlisted) to emptySet()
} else {
null
}
}
is Message.WishlistAddFailure -> {
if (state is State.Content) {
state.copy(wishlistState = CoursePurchaseFeature.WishlistState.Idle) to emptySet()
} else {
null
}
}
is Message.PromoCodeEditingMessage -> {
if (state is State.Content) {
state.copy(promoCodeState = CoursePurchaseFeature.PromoCodeState.Editing) to emptySet()
} else {
null
}
}
is Message.PromoCodeCheckMessage -> {
if (state is State.Content && state.promoCodeState is CoursePurchaseFeature.PromoCodeState.Editing) {
state.copy(promoCodeState = CoursePurchaseFeature.PromoCodeState.Checking(message.text)) to setOf(Action.CheckPromoCode(state.coursePurchaseData.course.id, message.text))
} else {
null
}
}
is Message.PromoCodeValidMessage -> {
if (state is State.Content && state.promoCodeState is CoursePurchaseFeature.PromoCodeState.Checking) {
state.copy(promoCodeState = CoursePurchaseFeature.PromoCodeState.Valid(state.promoCodeState.text, message.promoCodeSku)) to emptySet()
} else {
null
}
}
is Message.PromoCodeInvalidMessage -> {
if (state is State.Content && state.promoCodeState is CoursePurchaseFeature.PromoCodeState.Checking) {
state.copy(promoCodeState = CoursePurchaseFeature.PromoCodeState.Invalid) to emptySet()
} else {
null
}
}
} ?: state to emptySet()
} | apache-2.0 | 742f0264af1fd3872d00eab443618bf2 | 53.404494 | 198 | 0.619913 | 5.133616 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/ui/reader/setting/ReaderPreferences.kt | 1 | 4654 | package eu.kanade.tachiyomi.ui.reader.setting
import eu.kanade.tachiyomi.core.preference.PreferenceStore
import eu.kanade.tachiyomi.core.preference.getEnum
import eu.kanade.tachiyomi.data.preference.PreferenceValues
import eu.kanade.tachiyomi.util.system.isReleaseBuildType
class ReaderPreferences(
private val preferenceStore: PreferenceStore,
) {
// region General
fun pageTransitions() = preferenceStore.getBoolean("pref_enable_transitions_key", true)
fun doubleTapAnimSpeed() = preferenceStore.getInt("pref_double_tap_anim_speed", 500)
fun showPageNumber() = preferenceStore.getBoolean("pref_show_page_number_key", true)
fun showReadingMode() = preferenceStore.getBoolean("pref_show_reading_mode", true)
fun trueColor() = preferenceStore.getBoolean("pref_true_color_key", false)
fun fullscreen() = preferenceStore.getBoolean("fullscreen", true)
fun cutoutShort() = preferenceStore.getBoolean("cutout_short", true)
fun keepScreenOn() = preferenceStore.getBoolean("pref_keep_screen_on_key", true)
fun defaultReadingMode() = preferenceStore.getInt("pref_default_reading_mode_key", ReadingModeType.RIGHT_TO_LEFT.flagValue)
fun defaultOrientationType() = preferenceStore.getInt("pref_default_orientation_type_key", OrientationType.FREE.flagValue)
// TODO: Enable in release build when the feature is stable
fun longStripSplitWebtoon() = preferenceStore.getBoolean("pref_long_strip_split_webtoon", !isReleaseBuildType)
fun imageScaleType() = preferenceStore.getInt("pref_image_scale_type_key", 1)
fun zoomStart() = preferenceStore.getInt("pref_zoom_start_key", 1)
fun readerTheme() = preferenceStore.getInt("pref_reader_theme_key", 1)
fun alwaysShowChapterTransition() = preferenceStore.getBoolean("always_show_chapter_transition", true)
fun cropBorders() = preferenceStore.getBoolean("crop_borders", false)
fun navigateToPan() = preferenceStore.getBoolean("navigate_pan", true)
fun landscapeZoom() = preferenceStore.getBoolean("landscape_zoom", true)
fun cropBordersWebtoon() = preferenceStore.getBoolean("crop_borders_webtoon", false)
fun webtoonSidePadding() = preferenceStore.getInt("webtoon_side_padding", 0)
fun readerHideThreshold() = preferenceStore.getEnum("reader_hide_threshold", PreferenceValues.ReaderHideThreshold.LOW)
fun folderPerManga() = preferenceStore.getBoolean("create_folder_per_manga", false)
fun skipRead() = preferenceStore.getBoolean("skip_read", false)
fun skipFiltered() = preferenceStore.getBoolean("skip_filtered", true)
// endregion
// region Split two page spread
fun dualPageSplitPaged() = preferenceStore.getBoolean("pref_dual_page_split", false)
fun dualPageInvertPaged() = preferenceStore.getBoolean("pref_dual_page_invert", false)
fun dualPageSplitWebtoon() = preferenceStore.getBoolean("pref_dual_page_split_webtoon", false)
fun dualPageInvertWebtoon() = preferenceStore.getBoolean("pref_dual_page_invert_webtoon", false)
// endregion
// region Color filter
fun customBrightness() = preferenceStore.getBoolean("pref_custom_brightness_key", false)
fun customBrightnessValue() = preferenceStore.getInt("custom_brightness_value", 0)
fun colorFilter() = preferenceStore.getBoolean("pref_color_filter_key", false)
fun colorFilterValue() = preferenceStore.getInt("color_filter_value", 0)
fun colorFilterMode() = preferenceStore.getInt("color_filter_mode", 0)
fun grayscale() = preferenceStore.getBoolean("pref_grayscale", false)
fun invertedColors() = preferenceStore.getBoolean("pref_inverted_colors", false)
// endregion
// region Controls
fun readWithLongTap() = preferenceStore.getBoolean("reader_long_tap", true)
fun readWithVolumeKeys() = preferenceStore.getBoolean("reader_volume_keys", false)
fun readWithVolumeKeysInverted() = preferenceStore.getBoolean("reader_volume_keys_inverted", false)
fun navigationModePager() = preferenceStore.getInt("reader_navigation_mode_pager", 0)
fun navigationModeWebtoon() = preferenceStore.getInt("reader_navigation_mode_webtoon", 0)
fun pagerNavInverted() = preferenceStore.getEnum("reader_tapping_inverted", PreferenceValues.TappingInvertMode.NONE)
fun webtoonNavInverted() = preferenceStore.getEnum("reader_tapping_inverted_webtoon", PreferenceValues.TappingInvertMode.NONE)
fun showNavigationOverlayNewUser() = preferenceStore.getBoolean("reader_navigation_overlay_new_user", true)
fun showNavigationOverlayOnStart() = preferenceStore.getBoolean("reader_navigation_overlay_on_start", false)
// endregion
}
| apache-2.0 | e9eb293400510212fe34c01fedc4988a | 39.12069 | 130 | 0.759562 | 4.309259 | false | false | false | false |
GKZX-HN/MyGithub | app/src/main/java/com/gkzxhn/mygithub/ui/adapter/IvTvAdapter.kt | 1 | 2149 | package com.gkzxhn.mygithub.ui.adapter
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.RelativeLayout
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.gkzxhn.mygithub.R
import com.gkzxhn.mygithub.bean.entity.IvTvItemBean
import com.gkzxhn.mygithub.extension.dp2px
/**
* Created by 方 on 2017/12/13.
*/
class IvTvAdapter(var datas : List<IvTvItemBean>?) : BaseQuickAdapter<IvTvItemBean, BaseViewHolder>(R.layout.item_iv_tv, datas) {
override fun convert(helper: BaseViewHolder?, item: IvTvItemBean?) {
val baseView = helper!!.getView<RelativeLayout>(R.id.rl_base)
val layoutParams = baseView.layoutParams as RecyclerView.LayoutParams
var group2 = 4
if ("USER" == type){
group2 = 4
}else if("Organization" == type) {
group2 = 1
}
if (helper.layoutPosition == 0 || helper.layoutPosition == group2) {
layoutParams.topMargin = 20f.dp2px().toInt()
baseView.layoutParams = layoutParams
helper.setVisible(R.id.top_line, true)
}else {
helper.setVisible(R.id.top_line, false)
}
val bottom_line = helper.getView<View>(R.id.bottom_line)
val lineLayoutParams = bottom_line.layoutParams as RelativeLayout.LayoutParams
if (helper.layoutPosition == group2 - 1 || helper.layoutPosition == datas?.let { it.size - 1 }) {
lineLayoutParams.leftMargin = 0
bottom_line.layoutParams = lineLayoutParams
}
baseView.isClickable = item!!.clickable
helper.setImageResource(R.id.iv_left, item.ivResource)
helper.setText(R.id.tv_title, item.tvTitle)
if(item.tvRight is String) {
helper.setText(R.id.tv_right, item.tvRight.let { it })
helper.setBackgroundRes(R.id.tv_right, R.color.white)
}else if(item.tvRight is Int) {
helper.setBackgroundRes(R.id.tv_right, item.tvRight.let { it })
}
helper.setVisible(R.id.tv_right, item.clickable)
}
var type = "USER"
} | gpl-3.0 | 2ec8ee7d701ed7c772438f044a33e0bb | 40.307692 | 129 | 0.661388 | 3.875451 | false | false | false | false |
Heiner1/AndroidAPS | wear/src/main/java/info/nightscout/androidaps/complications/WallpaperComplication.kt | 1 | 1992 | @file:Suppress("DEPRECATION")
package info.nightscout.androidaps.complications
import android.app.PendingIntent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.Icon
import android.support.wearable.complications.ComplicationData
import android.util.DisplayMetrics
import android.view.WindowManager
import info.nightscout.androidaps.data.RawDisplayData
import info.nightscout.shared.logging.LTag
import java.io.IOException
/*
* Created by dlvoy on 2019-11-12
*/
abstract class WallpaperComplication : BaseComplicationProviderService() {
abstract val wallpaperAssetsFileName: String
override fun buildComplicationData(dataType: Int, raw: RawDisplayData, complicationPendingIntent: PendingIntent): ComplicationData? {
var complicationData: ComplicationData? = null
if (dataType == ComplicationData.TYPE_LARGE_IMAGE) {
val metrics = DisplayMetrics()
val windowManager = applicationContext.getSystemService(WINDOW_SERVICE) as WindowManager
windowManager.defaultDisplay.getMetrics(metrics)
val width = metrics.widthPixels
val height = metrics.heightPixels
val builder = ComplicationData.Builder(ComplicationData.TYPE_LARGE_IMAGE)
val assetManager = assets
try {
assetManager.open(wallpaperAssetsFileName).use { iStr ->
val bitmap = BitmapFactory.decodeStream(iStr)
val scaled = Bitmap.createScaledBitmap(bitmap, width, height, true)
builder.setLargeImage(Icon.createWithBitmap(scaled))
}
} catch (e: IOException) {
aapsLogger.error(LTag.WEAR, "Cannot read wallpaper asset: " + e.message, e)
}
complicationData = builder.build()
} else {
aapsLogger.warn(LTag.WEAR, "Unexpected complication type $dataType")
}
return complicationData
}
} | agpl-3.0 | d11511db42aa980b9feecd8502ceb4b7 | 41.404255 | 137 | 0.698795 | 5.21466 | false | false | false | false |
Adventech/sabbath-school-android-2 | features/lessons/src/main/java/com/cryart/sabbathschool/lessons/ui/lessons/intro/LessonIntroFragment.kt | 1 | 2807 | /*
* Copyright (c) 2021. Adventech <[email protected]>
*
* 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.cryart.sabbathschool.lessons.ui.lessons.intro
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.fragment.app.FragmentManager
import com.cryart.sabbathschool.core.extensions.view.viewBinding
import com.cryart.sabbathschool.lessons.R
import com.cryart.sabbathschool.lessons.databinding.SsFragmentLessonIntroBinding
import com.cryart.sabbathschool.lessons.ui.base.SsBottomSheetDialogFragment
import io.noties.markwon.Markwon
class LessonIntroFragment : SsBottomSheetDialogFragment() {
private val binding by viewBinding(SsFragmentLessonIntroBinding::bind)
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.ss_fragment_lesson_intro, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val model = arguments?.getParcelable<LessonIntroModel>(ARG_MODEL) ?: return
binding.toolbar.apply {
title = model.title
setNavigationOnClickListener { dismiss() }
}
Markwon.create(requireContext()).setMarkdown(
binding.txtContent,
model.introduction
)
}
}
private const val ARG_MODEL = "arg:model"
internal fun FragmentManager.showLessonIntro(model: LessonIntroModel) {
val fragment = LessonIntroFragment().apply {
arguments = bundleOf(ARG_MODEL to model)
}
fragment.show(this, "LessonDescription")
}
| mit | a0c25fb9db16bc02f4dea0b5f641e4bf | 37.986111 | 84 | 0.748486 | 4.601639 | false | false | false | false |
sirixdb/sirix | bundles/sirix-kotlin-cli/src/main/kotlin/org/sirix/cli/commands/Query.kt | 1 | 12780 | package org.sirix.cli.commands
import org.brackit.xquery.XQuery
import org.brackit.xquery.util.serialize.Serializer
import org.sirix.access.DatabaseType
import org.sirix.api.Database
import org.sirix.api.ResourceSession
import org.sirix.api.json.JsonResourceSession
import org.sirix.api.xml.XmlResourceSession
import org.sirix.cli.CliOptions
import org.sirix.cli.commands.RevisionsHelper.Companion.getRevisionsToSerialize
import org.sirix.exception.SirixException
import org.sirix.xquery.JsonDBSerializer
import org.sirix.xquery.SirixCompileChain
import org.sirix.xquery.SirixQueryContext
import org.sirix.xquery.XmlDBSerializer
import org.sirix.xquery.json.*
import org.sirix.xquery.node.BasicXmlDBStore
import org.sirix.xquery.node.XmlDBCollection
import org.sirix.xquery.node.XmlDBNode
import java.io.ByteArrayOutputStream
import java.io.PrintStream
class Query(options: CliOptions, private val queryOptions: QueryOptions) : CliCommand(options) {
override fun execute() {
val startMillis: Long = System.currentTimeMillis()
cliPrinter.prnLnV("Execute Query. Result is:")
val result = if (queryOptions.hasQueryStr()) {
xQuery()
} else {
serializeResource()
}
cliPrinter.prnLn(result)
cliPrinter.prnLnV("Query executed (${System.currentTimeMillis() - startMillis}ms)")
}
private fun xQuery(): String {
return when (databaseType()) {
DatabaseType.XML -> xQueryXml()
DatabaseType.JSON -> xQueryJson()
else -> throw IllegalArgumentException("Unknown Database Type!")
}
}
private fun xQueryXml(): String {
val database = openXmlDatabase(queryOptions.user)
database.use {
val manager = database.beginResourceSession(queryOptions.resource)
manager.use {
val dbCollection =
XmlDBCollection(options.location, database)
dbCollection.use {
val revisionNumber = RevisionsHelper.getRevisionNumber(
queryOptions.revision,
queryOptions.revisionTimestamp,
manager
)
val trx = manager.beginNodeReadOnlyTrx(revisionNumber[0])
trx.use {
if (queryOptions.nodeId == null)
trx.moveToFirstChild()
else
trx.moveTo(queryOptions.nodeId)
val dbStore = BasicXmlDBStore.newBuilder().build()
dbStore.use {
val queryCtx = SirixQueryContext.createWithNodeStore(dbStore)
val node = XmlDBNode(trx, dbCollection)
node.let { queryCtx.contextItem = node }
val out = ByteArrayOutputStream()
PrintStream(out).use { printStream ->
SirixCompileChain.createWithNodeStore(dbStore).use { sirixCompileChain ->
if (queryOptions.startResultSeqIndex == null) {
XQuery(sirixCompileChain, queryOptions.queryStr).prettyPrint().serialize(
queryCtx,
XmlDBSerializer(printStream, false, true)
)
} else {
serializePaginated(
sirixCompileChain,
queryCtx,
XmlDBSerializer(printStream, false, true)
)
}
}
return out.toString()
}
}
}
}
}
}
}
private fun xQueryJson(): String {
val database = openJsonDatabase(queryOptions.user)
database.use {
val manager = database.beginResourceSession(queryOptions.resource)
manager.use {
val dbCollection = JsonDBCollection(options.location, database)
dbCollection.use {
val revisionNumber = RevisionsHelper.getRevisionNumber(
queryOptions.revision,
queryOptions.revisionTimestamp,
manager
)
val trx = manager.beginNodeReadOnlyTrx(revisionNumber[0])
trx.use {
if (queryOptions.nodeId == null)
trx.moveToFirstChild()
else
trx.moveTo(queryOptions.nodeId.toLong())
val jsonDBStore = BasicJsonDBStore.newBuilder().build()
val xmlDBStore = BasicXmlDBStore.newBuilder().build()
val queryCtx = SirixQueryContext.createWithJsonStoreAndNodeStoreAndCommitStrategy(
xmlDBStore,
jsonDBStore,
SirixQueryContext.CommitStrategy.AUTO
)
queryCtx.use {
val jsonItem = JsonItemFactory().getSequence(trx, dbCollection)
if (jsonItem != null) {
queryCtx.contextItem = jsonItem
when (jsonItem) {
is AbstractJsonDBArray<*> -> {
jsonItem.collection.setJsonDBStore(jsonDBStore)
jsonDBStore.addDatabase(
jsonItem.collection,
jsonItem.collection.database
)
}
is JsonDBObject -> {
jsonItem.collection.setJsonDBStore(jsonDBStore)
jsonDBStore.addDatabase(
jsonItem.collection,
jsonItem.collection.database
)
}
is AtomicBooleanJsonDBItem -> {
jsonItem.collection.setJsonDBStore(jsonDBStore)
jsonDBStore.addDatabase(
jsonItem.collection,
jsonItem.collection.database
)
}
is AtomicStrJsonDBItem -> {
jsonItem.collection.setJsonDBStore(jsonDBStore)
jsonDBStore.addDatabase(
jsonItem.collection,
jsonItem.collection.database
)
}
is AtomicNullJsonDBItem -> {
jsonItem.collection.setJsonDBStore(jsonDBStore)
jsonDBStore.addDatabase(
jsonItem.collection,
jsonItem.collection.database
)
}
is NumericJsonDBItem -> {
jsonItem.collection.setJsonDBStore(jsonDBStore)
jsonDBStore.addDatabase(
jsonItem.collection,
jsonItem.collection.database
)
}
else -> throw IllegalStateException("Node type not known.")
}
}
val out = StringBuilder()
SirixCompileChain.createWithNodeAndJsonStore(xmlDBStore, jsonDBStore)
.use { sirixCompileChain ->
if (queryOptions.startResultSeqIndex == null) {
XQuery(sirixCompileChain, queryOptions.queryStr).prettyPrint()
.serialize(
queryCtx,
JsonDBSerializer(out, queryOptions.prettyPrint)
)
} else {
serializePaginated(
sirixCompileChain,
queryCtx,
JsonDBSerializer(out, false)
)
}
}
return out.toString()
}
}
}
}
}
}
private fun serializePaginated(
sirixCompileChain: SirixCompileChain,
queryCtx: SirixQueryContext?,
serializer: Serializer
) {
if (queryOptions.startResultSeqIndex == null) {
throw SirixException("startResultSeqIndex can't be null!")
}
serializer.use {
val sequence = XQuery(sirixCompileChain, queryOptions.queryStr).execute(queryCtx)
if (sequence != null) {
val itemIterator = sequence.iterate()
for (i in 0 until queryOptions.startResultSeqIndex) {
itemIterator.next()
}
if (queryOptions.endResultSeqIndex == null) {
while (true) {
val item = itemIterator.next()
if (item == null)
break
else
serializer.serialize(item)
}
} else {
for (i in queryOptions.startResultSeqIndex..queryOptions.endResultSeqIndex) {
val item = itemIterator.next()
if (item == null)
break
else
serializer.serialize(item)
}
}
}
}
}
private fun serializeResource(): String {
val database: Database<*> = openDatabase(queryOptions.user)
database.use {
val manager = database.beginResourceSession(queryOptions.resource)
manager.use {
val revisions: Array<Int> = getRevisions(manager)
with(queryOptions) {
val serializerAdapter =
SerializerAdapter(manager, nextTopLevelNodes).revisions(revisions.toIntArray())
.startNodeKey(nodeId)
.metadata(metaData).maxLevel(maxLevel).prettyPrint(prettyPrint)
return serializerAdapter.serialize()
}
}
}
}
private fun getRevisions(manager: ResourceSession<*, *>): Array<Int> {
return when (manager) {
is JsonResourceSession -> getRevisionsToSerialize(
queryOptions.startRevision,
queryOptions.endRevision,
queryOptions.startRevisionTimestamp,
queryOptions.endRevisionTimestamp,
manager,
queryOptions.revision,
queryOptions.revisionTimestamp
)
is XmlResourceSession -> getRevisionsToSerialize(
queryOptions.startRevision,
queryOptions.endRevision,
queryOptions.startRevisionTimestamp,
queryOptions.endRevisionTimestamp,
manager,
queryOptions.revision,
queryOptions.revisionTimestamp
)
else -> throw IllegalStateException("Unknown ResourceManager Type!")
}
}
}
| bsd-3-clause | 626fcc5333b9bcf977e63d81138246d6 | 42.175676 | 113 | 0.44687 | 6.503817 | false | false | false | false |
PolymerLabs/arcs | javatests/arcs/core/data/InformationFlowLabelTest.kt | 1 | 3776 | /*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.data
import arcs.core.data.InformationFlowLabel.Predicate
import arcs.core.data.InformationFlowLabel.SemanticTag
import com.google.common.truth.Truth.assertThat
import kotlin.test.assertFailsWith
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class InformationFlowLabelTest {
enum class Labels {
A, B, C, D;
val asPredicate: Predicate.Label
get() = Predicate.Label(SemanticTag(name))
}
private val labels = enumValues<Labels>().map { it.name }
private val indicesMap: Map<InformationFlowLabel, Int> = enumValues<Labels>().map {
it.asPredicate.label to it.ordinal
}.toMap()
@Test
fun prettyPrintSemanticTag() {
assertThat("${SemanticTag("packageName")}").isEqualTo("packageName")
assertThat("${SemanticTag("coarseLocation")}").isEqualTo("coarseLocation")
}
@Test
fun andConstructor() {
assertThat(Labels.A.asPredicate and Labels.B.asPredicate)
.isEqualTo(Predicate.And(Labels.A.asPredicate, Labels.B.asPredicate))
}
@Test
fun orConstructor() {
assertThat(Labels.A.asPredicate or Labels.B.asPredicate)
.isEqualTo(Predicate.Or(Labels.A.asPredicate, Labels.B.asPredicate))
}
@Test
fun notConstructor() {
assertThat(Labels.A.asPredicate.not())
.isEqualTo(Predicate.Not(Labels.A.asPredicate))
assertThat((Labels.A.asPredicate and Labels.B.asPredicate).not())
.isEqualTo(Predicate.Not(Predicate.And(Labels.A.asPredicate, Labels.B.asPredicate)))
}
@Test
fun andSequence() {
assertThat(
Predicate.and(Labels.A.asPredicate, Labels.B.asPredicate, Labels.C.asPredicate)
).isEqualTo((Labels.A.asPredicate and Labels.B.asPredicate) and Labels.C.asPredicate)
}
@Test
fun andSequence_tooShort() {
assertFailsWith<IllegalArgumentException> { Predicate.and(Labels.A.asPredicate) }
}
@Test
fun orSequence() {
assertThat(
Predicate.or(Labels.A.asPredicate, Labels.B.asPredicate, Labels.C.asPredicate)
).isEqualTo((Labels.A.asPredicate or Labels.B.asPredicate) or Labels.C.asPredicate)
}
@Test
fun orSequence_tooShort() {
assertFailsWith<IllegalArgumentException> { Predicate.or(Labels.A.asPredicate) }
}
@Test
fun prettyPrintLabelPredicate() {
assertThat("${Labels.A.asPredicate}").isEqualTo("A")
assertThat("${Labels.B.asPredicate}").isEqualTo("B")
}
@Test
fun prettyPrintNotPredicate() {
assertThat("${Labels.A.asPredicate.not()}").isEqualTo("not A")
assertThat("${Labels.D.asPredicate.not()}").isEqualTo("not D")
}
@Test
fun prettyPrintAndPredicate() {
val AandB = Labels.A.asPredicate and Labels.B.asPredicate
assertThat("$AandB").isEqualTo("(A and B)")
val AandBandNotC = AandB and Labels.C.asPredicate.not()
assertThat("$AandBandNotC").isEqualTo("((A and B) and not C)")
val AandBandNotCandD = AandB and (Labels.C.asPredicate.not() and Labels.D.asPredicate)
assertThat("$AandBandNotCandD").isEqualTo("((A and B) and (not C and D))")
}
@Test
fun prettyPrintOrPredicate() {
val AorB = Labels.A.asPredicate or Labels.B.asPredicate
assertThat("$AorB").isEqualTo("(A or B)")
val AorBorNotC = AorB or Labels.C.asPredicate.not()
assertThat("$AorBorNotC").isEqualTo("((A or B) or not C)")
val AorBorNotCorD = AorB or (Labels.C.asPredicate.not() or Labels.D.asPredicate)
assertThat("$AorBorNotCorD").isEqualTo("((A or B) or (not C or D))")
}
}
| bsd-3-clause | b86ce4f41597f0aa056eeb157abb9415 | 30.206612 | 96 | 0.710805 | 3.817998 | false | true | false | false |
Maccimo/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveFilesOrDirectories/KotlinMoveDirectoryWithClassesHelper.kt | 2 | 5795 | // 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.refactoring.move.moveFilesOrDirectories
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.refactoring.listeners.RefactoringElementListener
import com.intellij.refactoring.move.moveClassesOrPackages.MoveDirectoryWithClassesHelper
import com.intellij.refactoring.move.moveFilesOrDirectories.MoveFilesOrDirectoriesUtil
import com.intellij.usageView.UsageInfo
import com.intellij.util.Function
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.idea.base.util.quoteIfNeeded
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.core.getFqNameWithImplicitPrefix
import org.jetbrains.kotlin.idea.core.getPackage
import org.jetbrains.kotlin.idea.refactoring.invokeOnceOnCommandFinish
import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.KotlinDirectoryMoveTarget
import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.MoveKotlinDeclarationsProcessor
import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.analyzeConflictsInFile
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtFile
class KotlinMoveDirectoryWithClassesHelper : MoveDirectoryWithClassesHelper() {
private data class FileUsagesWrapper(
val psiFile: KtFile,
val usages: List<UsageInfo>,
val moveDeclarationsProcessor: MoveKotlinDeclarationsProcessor?
) : UsageInfo(psiFile)
private class MoveContext(
val newParent: PsiDirectory,
val moveDeclarationsProcessor: MoveKotlinDeclarationsProcessor?
)
private val fileHandler = MoveKotlinFileHandler()
private var fileToMoveContext: MutableMap<PsiFile, MoveContext>? = null
private fun getOrCreateMoveContextMap(): MutableMap<PsiFile, MoveContext> {
return fileToMoveContext ?: HashMap<PsiFile, MoveContext>().apply {
fileToMoveContext = this
invokeOnceOnCommandFinish { fileToMoveContext = null }
}
}
override fun findUsages(
filesToMove: MutableCollection<PsiFile>,
directoriesToMove: Array<out PsiDirectory>,
result: MutableCollection<UsageInfo>,
searchInComments: Boolean,
searchInNonJavaFiles: Boolean,
project: Project
) {
filesToMove
.filterIsInstance<KtFile>()
.mapTo(result) { FileUsagesWrapper(it, fileHandler.findUsages(it, null, false), null) }
}
override fun preprocessUsages(
project: Project,
files: MutableSet<PsiFile>,
infos: Array<UsageInfo>,
directory: PsiDirectory?,
conflicts: MultiMap<PsiElement, String>
) {
val psiPackage = directory?.getPackage() ?: return
val moveTarget = KotlinDirectoryMoveTarget(FqName(psiPackage.qualifiedName), directory.virtualFile)
for ((index, usageInfo) in infos.withIndex()) {
if (usageInfo !is FileUsagesWrapper) continue
ProgressManager.getInstance().progressIndicator?.text2 = KotlinBundle.message("text.processing.file.0", usageInfo.psiFile.name)
runReadAction {
analyzeConflictsInFile(usageInfo.psiFile, usageInfo.usages, moveTarget, files, conflicts) {
infos[index] = usageInfo.copy(usages = it)
}
}
}
}
override fun beforeMove(psiFile: PsiFile) {
}
// Actual move logic is implemented in postProcessUsages since usages are not available here
override fun move(
file: PsiFile,
moveDestination: PsiDirectory,
oldToNewElementsMapping: MutableMap<PsiElement, PsiElement>,
movedFiles: MutableList<PsiFile>,
listener: RefactoringElementListener?
): Boolean {
if (file !is KtFile) return false
val moveDeclarationsProcessor = fileHandler.initMoveProcessor(file, moveDestination, false)
val moveContextMap = getOrCreateMoveContextMap()
moveContextMap[file] = MoveContext(moveDestination, moveDeclarationsProcessor)
if (moveDeclarationsProcessor != null) {
moveDestination.getFqNameWithImplicitPrefix()?.quoteIfNeeded()?.let {
file.packageDirective?.fqName = it
}
}
return true
}
override fun afterMove(newElement: PsiElement) {
}
override fun postProcessUsages(usages: Array<out UsageInfo>, newDirMapper: Function<in PsiDirectory, out PsiDirectory>) {
val fileToMoveContext = fileToMoveContext ?: return
try {
val usagesToProcess = ArrayList<FileUsagesWrapper>()
usages
.filterIsInstance<FileUsagesWrapper>()
.forEach body@{
val file = it.psiFile
val moveContext = fileToMoveContext[file] ?: return@body
MoveFilesOrDirectoriesUtil.doMoveFile(file, moveContext.newParent)
val moveDeclarationsProcessor = moveContext.moveDeclarationsProcessor ?: return@body
val movedFile = moveContext.newParent.findFile(file.name) ?: return@body
usagesToProcess += FileUsagesWrapper(movedFile as KtFile, it.usages, moveDeclarationsProcessor)
}
usagesToProcess.forEach { fileHandler.retargetUsages(it.usages, it.moveDeclarationsProcessor!!) }
} finally {
this.fileToMoveContext = null
}
}
} | apache-2.0 | 445f57c236d1b7602044967d107f3810 | 41.306569 | 158 | 0.713891 | 5.534862 | false | false | false | false |
k9mail/k-9 | app/ui/legacy/src/main/java/com/fsck/k9/ui/settings/export/SettingsExportUiModel.kt | 2 | 2496 | package com.fsck.k9.ui.settings.export
class SettingsExportUiModel {
var settingsList: List<SettingsListItem> = emptyList()
var isSettingsListEnabled = true
var exportButton: ButtonState = ButtonState.DISABLED
var isShareButtonVisible = false
var isProgressVisible = false
var statusText = StatusText.HIDDEN
fun enableExportButton() {
exportButton = ButtonState.ENABLED
isShareButtonVisible = false
isProgressVisible = false
isSettingsListEnabled = true
}
fun disableExportButton() {
exportButton = ButtonState.DISABLED
isShareButtonVisible = false
isProgressVisible = false
}
fun showProgress() {
isProgressVisible = true
exportButton = ButtonState.INVISIBLE
isShareButtonVisible = false
statusText = StatusText.PROGRESS
isSettingsListEnabled = false
}
fun showSuccessText() {
exportButton = ButtonState.GONE
isProgressVisible = false
isShareButtonVisible = true
isSettingsListEnabled = true
statusText = StatusText.EXPORT_SUCCESS
}
fun showFailureText() {
exportButton = ButtonState.GONE
isShareButtonVisible = false
isProgressVisible = false
isSettingsListEnabled = true
statusText = StatusText.EXPORT_FAILURE
}
fun initializeSettingsList(list: List<SettingsListItem>) {
settingsList = list
updateExportButtonFromSelection()
}
fun setSettingsListItemSelection(position: Int, select: Boolean) {
settingsList[position].selected = select
statusText = StatusText.HIDDEN
isShareButtonVisible = false
updateExportButtonFromSelection()
}
private fun updateExportButtonFromSelection() {
if (isProgressVisible || isShareButtonVisible) return
val atLeastOnceSelected = settingsList.any { it.selected }
if (atLeastOnceSelected) {
enableExportButton()
} else {
disableExportButton()
}
}
}
sealed class SettingsListItem {
var selected: Boolean = true
object GeneralSettings : SettingsListItem()
data class Account(
val accountNumber: Int,
val displayName: String,
val email: String
) : SettingsListItem()
}
enum class ButtonState {
DISABLED,
ENABLED,
INVISIBLE,
GONE
}
enum class StatusText {
HIDDEN,
PROGRESS,
EXPORT_SUCCESS,
EXPORT_FAILURE
}
| apache-2.0 | 81513be75ee2d3ef1e9eeece305fe07a | 25.273684 | 70 | 0.667468 | 5.104294 | false | false | false | false |
hpost/kommon | app/src/main/java/cc/femto/kommon/util/TransitionUtils.kt | 1 | 2492 | package cc.femto.kommon.util
import android.support.annotation.IdRes
import android.transition.Transition
import android.transition.TransitionSet
import android.view.View
import android.view.ViewGroup
import java.util.*
/**
* Utility methods for working with transitions
* See https://github.com/nickbutcher/plaid/blob/master/app/src/main/java/io/plaidapp/util/TransitionUtils.java
*/
object TransitionUtils {
fun findTransition(
set: TransitionSet, clazz: Class<out Transition>): Transition? {
for (i in 0..set.transitionCount - 1) {
val transition = set.getTransitionAt(i)
if (transition.javaClass == clazz) {
return transition
}
if (transition is TransitionSet) {
val child = findTransition(transition, clazz)
if (child != null) return child
}
}
return null
}
fun findTransition(
set: TransitionSet,
clazz: Class<out Transition>,
@IdRes targetId: Int): Transition? {
for (i in 0..set.transitionCount - 1) {
val transition = set.getTransitionAt(i)
if (transition.javaClass == clazz) {
if (transition.targetIds.contains(targetId)) {
return transition
}
}
if (transition is TransitionSet) {
val child = findTransition(transition, clazz, targetId)
if (child != null) return child
}
}
return null
}
fun setAncestralClipping(view: View, clipChildren: Boolean): List<Boolean> {
return setAncestralClipping(view, clipChildren, ArrayList<Boolean>())
}
private fun setAncestralClipping(
view: View, clipChildren: Boolean, was: MutableList<Boolean>): List<Boolean> {
if (view is ViewGroup) {
was.add(view.clipChildren)
view.clipChildren = clipChildren
}
val parent = view.parent
if (parent != null && parent is ViewGroup) {
setAncestralClipping(parent, clipChildren, was)
}
return was
}
fun restoreAncestralClipping(view: View, was: MutableList<Boolean>) {
if (view is ViewGroup) {
view.clipChildren = was.removeAt(0)
}
val parent = view.parent
if (parent != null && parent is ViewGroup) {
restoreAncestralClipping(parent, was)
}
}
}
| apache-2.0 | 403f39e736bc23bed15cc142ccbbf89d | 31.789474 | 111 | 0.593499 | 4.589319 | false | false | false | false |
qoncept/TensorKotlin | test/jp/co/qoncept/tensorkotlin/TensorTest.kt | 1 | 7844 | package jp.co.qoncept.tensorkotlin
import org.testng.Assert.*
import org.testng.annotations.Test
class TensorTest {
@Test
fun testIndex() {
run {
val a = Tensor(Shape())
assertEquals(0, a.index(intArrayOf()))
}
run {
val a = Tensor(Shape(7))
assertEquals(3, a.index(intArrayOf(3)))
}
run {
val a = Tensor(Shape(5, 7))
assertEquals(9, a.index(intArrayOf(1, 2)))
}
run {
val a = Tensor(Shape(5, 7, 11))
assertEquals(244, a.index(intArrayOf(3, 1, 2)))
}
}
@Test
fun testGetByRanges() {
run {
val a = Tensor(Shape(5, 5, 5), (1..125).map { it.toFloat() }.toFloatArray())
val b = a[1..3, 2..4, 1..2]
assertEquals(Tensor(Shape(3, 3, 2), floatArrayOf(37, 38, 42, 43, 47, 48, 62, 63, 67, 68, 72, 73, 87, 88, 92, 93, 97, 98)), b)
}
}
@Test
fun testPlus() {
run {
val a = Tensor(Shape(2, 3), floatArrayOf(1, 2, 3, 4, 5, 6))
val b = Tensor(Shape(2, 3), floatArrayOf(7, 8, 9, 10, 11, 12))
assertEquals(Tensor(Shape(2, 3), floatArrayOf(8, 10, 12, 14, 16, 18)), a + b)
assertEquals(Tensor(Shape(2, 3), floatArrayOf(8, 10, 12, 14, 16, 18)), b + a)
}
run {
val a = Tensor(Shape(2, 3, 2), floatArrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))
val b = Tensor(Shape(2), floatArrayOf(100, 200))
assertEquals(Tensor(Shape(2, 3, 2), floatArrayOf(101, 202, 103, 204, 105, 206, 107, 208, 109, 210, 111, 212)), a + b)
assertEquals(Tensor(Shape(2, 3, 2), floatArrayOf(101, 202, 103, 204, 105, 206, 107, 208, 109, 210, 111, 212)), b + a)
}
run {
val a = Tensor(Shape(2, 1, 3, 2), floatArrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))
val b = Tensor(Shape(3, 2), floatArrayOf(100, 200, 300, 400, 500, 600))
assertEquals(Tensor(Shape(2, 1, 3, 2), floatArrayOf(101, 202, 303, 404, 505, 606, 107, 208, 309, 410, 511, 612)), a + b)
assertEquals(Tensor(Shape(2, 1, 3, 2), floatArrayOf(101, 202, 303, 404, 505, 606, 107, 208, 309, 410, 511, 612)), b + a)
}
}
@Test
fun testMinus() {
run {
val a = Tensor(Shape(2, 3), floatArrayOf(1, 2, 3, 4, 5, 6))
val b = Tensor(Shape(2, 3), floatArrayOf(12, 11, 10, 9, 8, 7))
assertEquals(Tensor(Shape(2, 3), floatArrayOf(-11, -9, -7, -5, -3, -1)), a - b)
assertEquals(Tensor(Shape(2, 3), floatArrayOf(11, 9, 7, 5, 3, 1)), b - a)
}
run {
val a = Tensor(Shape(2, 3, 2), floatArrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))
val b = Tensor(Shape(2), floatArrayOf(100, 200))
assertEquals(Tensor(Shape(2, 3, 2), floatArrayOf(-99, -198, -97, -196, -95, -194, -93, -192, -91, -190, -89, -188)), a - b)
assertEquals(Tensor(Shape(2, 3, 2), floatArrayOf(99, 198, 97, 196, 95, 194, 93, 192, 91, 190, 89, 188)), b - a)
}
run {
val a = Tensor(Shape(2, 1, 3, 2), floatArrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))
val b = Tensor(Shape(3, 2), floatArrayOf(100, 200, 300, 400, 500, 600))
assertEquals(Tensor(Shape(2, 1, 3, 2), floatArrayOf(-99, -198, -297, -396, -495, -594, -93, -192, -291, -390, -489, -588)), a - b)
assertEquals(Tensor(Shape(2, 1, 3, 2), floatArrayOf(99, 198, 297, 396, 495, 594, 93, 192, 291, 390, 489, 588)), b - a)
}
}
@Test
fun testTimes() {
run {
val a = Tensor(Shape(2, 3), floatArrayOf(1, 2, 3, 4, 5, 6))
val b = Tensor(Shape(2, 3), floatArrayOf(7, 8, 9, 10, 11, 12))
val r = a * b
assertEquals(Tensor(Shape(2, 3), floatArrayOf(7, 16, 27, 40, 55, 72)), r)
}
run {
val a = Tensor(Shape(2, 3, 2), floatArrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))
val b = Tensor(Shape(2), floatArrayOf(10, 100))
assertEquals(Tensor(Shape(2, 3, 2), floatArrayOf(10, 200, 30, 400, 50, 600, 70, 800, 90, 1000, 110, 1200)), a * b)
assertEquals(Tensor(Shape(2, 3, 2), floatArrayOf(10, 200, 30, 400, 50, 600, 70, 800, 90, 1000, 110, 1200)), b * a)
}
run {
val a = Tensor(Shape(2, 1, 3, 2), floatArrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))
val b = Tensor(Shape(3, 2), floatArrayOf(10, 100, 1000, -10, -100, -1000))
assertEquals(Tensor(Shape(2, 1, 3, 2), floatArrayOf(10, 200, 3000, -40, -500, -6000, 70, 800, 9000, -100, -1100, -12000)), a * b)
assertEquals(Tensor(Shape(2, 1, 3, 2), floatArrayOf(10, 200, 3000, -40, -500, -6000, 70, 800, 9000, -100, -1100, -12000)), b * a)
}
}
@Test
fun testDiv() {
run {
val a = Tensor(Shape(2, 3), floatArrayOf(1, 2, 3, 4, 5, 6))
val b = Tensor(Shape(2, 3), floatArrayOf(2, 4, 8, 16, 32, 64))
val r = a / b
assertEquals(Tensor(Shape(2, 3), floatArrayOf(0.5f, 0.5f, 0.375f, 0.25f, 0.15625f, 0.09375f)), r)
}
run {
val a = Tensor(Shape(2, 3, 2), floatArrayOf(2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096))
val b = Tensor(Shape(2), floatArrayOf(8, 2))
assertEquals(Tensor(Shape(2, 3, 2), floatArrayOf(0.25f, 2.0f, 1.0f, 8.0f, 4.0f, 32.0f, 16.0f, 128.0f, 64.0f, 512.0f, 256.0f, 2048.0f)), a / b)
assertEquals(Tensor(Shape(2, 3, 2), floatArrayOf(4.0f, 0.5f, 1.0f, 0.125f, 0.25f, 0.03125f, 0.0625f, 0.0078125f, 0.015625f, 0.001953125f, 0.00390625f, 0.00048828125f)), b / a)
}
run {
val a = Tensor(Shape(3, 1, 2, 2), floatArrayOf(2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096))
val b = Tensor(Shape(2, 2), floatArrayOf(8, 2, -8, -2))
assertEquals(Tensor(Shape(3, 1, 2, 2), floatArrayOf(0.25f, 2.0f, -1.0f, -8.0f, 4.0f, 32.0f, -16.0f, -128.0f, 64.0f, 512.0f, -256.0f, -2048.0f)), a / b)
assertEquals(Tensor(Shape(3, 1, 2, 2), floatArrayOf(4.0f, 0.5f, -1.0f, -0.125f, 0.25f, 0.03125f, -0.0625f, -0.0078125f, 0.015625f, 0.001953125f, -0.00390625f, -0.00048828125f)), b / a)
}
}
@Test
fun testMatmul() {
run {
val a = Tensor(Shape(2, 3), floatArrayOf(1, 2, 3, 4, 5, 6))
val b = Tensor(Shape(3, 4), floatArrayOf(7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18))
val r = a.matmul(b)
assertEquals(Tensor(Shape(2, 4), floatArrayOf(74, 80, 86, 92, 173, 188, 203, 218)), r)
}
}
@Test
fun testEquals() {
run {
val a = Tensor(Shape(2, 3), floatArrayOf(2, 3, 5, 7, 11, 13))
val b = Tensor(Shape(2, 3), floatArrayOf(2, 3, 5, 7, 11, 13))
assertTrue(a == b)
}
run {
val a = Tensor(Shape(2, 3), floatArrayOf(2, 3, 5, 7, 11, 13))
val b = Tensor(Shape(2, 3), floatArrayOf(2, 3, 5, 7, 11, 17))
assertFalse(a == b)
}
run {
val a = Tensor(Shape(2, 3), floatArrayOf(2, 3, 5, 7, 11, 13))
val b = Tensor(Shape(3, 2), floatArrayOf(2, 3, 5, 7, 11, 17))
assertFalse(a == b)
}
run {
val a = Tensor(Shape(2, 3), floatArrayOf(2, 3, 5, 7, 11, 13))
val b = Tensor(Shape(2, 2), floatArrayOf(2, 3, 5, 7))
assertFalse(a == b)
}
run {
val a = Tensor(Shape(2, 3), floatArrayOf(2, 3, 5, 7, 11, 13))
val b = Tensor(Shape(), floatArrayOf())
assertFalse(a == b)
}
run {
val a = Tensor(Shape(), floatArrayOf())
val b = Tensor(Shape(), floatArrayOf())
assertTrue(a == b)
}
}
}
| mit | a8a7b1aa3d91fce517d643acf618496c | 41.863388 | 196 | 0.49745 | 2.921415 | false | true | false | false |
mdaniel/intellij-community | platform/configuration-store-impl/src/schemeManager/schemeLoader.kt | 7 | 12346 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.configurationStore.schemeManager
import com.intellij.configurationStore.*
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.options.NonLazySchemeProcessor
import com.intellij.openapi.options.Scheme
import com.intellij.openapi.project.ProjectBundle
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.vfs.CharsetToolkit
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.io.createDirectories
import com.intellij.util.io.systemIndependentPath
import com.intellij.util.xml.dom.createXmlStreamReader
import org.jdom.Element
import org.jetbrains.annotations.NonNls
import java.io.IOException
import java.io.InputStream
import java.nio.file.Path
import java.security.MessageDigest
import java.util.*
import java.util.concurrent.atomic.AtomicBoolean
import java.util.function.Function
import javax.xml.stream.XMLStreamConstants
import javax.xml.stream.XMLStreamReader
internal class SchemeLoader<T: Scheme, MUTABLE_SCHEME : T>(private val schemeManager: SchemeManagerImpl<T, MUTABLE_SCHEME>,
private val oldSchemes: List<T>,
private val preScheduledFilesToDelete: MutableSet<String>,
private val isDuringLoad: Boolean) {
private val filesToDelete: MutableSet<String> = HashSet()
private val schemes: MutableList<T> = oldSchemes.toMutableList()
private var newSchemesOffset = schemes.size
// scheme could be changed - so, hashcode will be changed - we must use identity hashing strategy
private val schemeToInfo = IdentityHashMap<T, ExternalInfo>()
private val isApplied = AtomicBoolean()
private var digest: MessageDigest? = null
// or from current session, or from current state
private fun getInfoForExistingScheme(existingScheme: T): ExternalInfo? {
return schemeToInfo.get(existingScheme) ?: schemeManager.schemeToInfo.get(existingScheme)
}
private fun isFromFileWithNewExtension(existingScheme: T, fileNameWithoutExtension: String): Boolean {
return getInfoForExistingScheme(existingScheme)?.fileNameWithoutExtension == fileNameWithoutExtension
}
/**
* Returns list of new schemes.
*/
fun apply(): List<T> {
LOG.assertTrue(isApplied.compareAndSet(false, true))
if (filesToDelete.isNotEmpty() || preScheduledFilesToDelete.isNotEmpty()) {
LOG.debug { "Schedule to delete: ${filesToDelete.joinToString()} (and preScheduledFilesToDelete: ${preScheduledFilesToDelete.joinToString()})" }
schemeManager.filesToDelete.addAll(filesToDelete)
schemeManager.filesToDelete.addAll(preScheduledFilesToDelete)
}
schemeManager.schemeToInfo.putAll(schemeToInfo)
val result = schemes.subList(newSchemesOffset, schemes.size)
schemeManager.schemeListManager.replaceSchemeList(oldSchemes, schemes)
if (!isDuringLoad) {
for (newScheme in result) {
@Suppress("UNCHECKED_CAST")
schemeManager.processor.onSchemeAdded(newScheme as MUTABLE_SCHEME)
}
}
return result
}
private fun getDigest(): MessageDigest {
var result = digest
if (result == null) {
result = createDataDigest()
digest = result
}
else {
result.reset()
}
return result
}
private fun checkExisting(schemeKey: String, fileName: String, fileNameWithoutExtension: String, extension: String): Boolean {
val processor = schemeManager.processor
// schemes load session doesn't care about any scheme that added after session creation,
// e.g. for now, on apply, simply current manager list replaced atomically to the new one
// if later it will lead to some issues, this check should be done as merge operation (again, currently on apply old list is replaced and not merged)
val existingSchemeIndex = schemes.indexOfFirst { processor.getSchemeKey(it) == schemeKey }
val existingScheme = (if (existingSchemeIndex == -1) null else schemes.get(existingSchemeIndex)) ?: return true
if (schemeManager.schemeListManager.readOnlyExternalizableSchemes.get(processor.getSchemeKey(existingScheme)) === existingScheme) {
// so, bundled scheme is shadowed
schemes.removeAt(existingSchemeIndex)
if (existingSchemeIndex < newSchemesOffset) {
newSchemesOffset--
}
// not added to filesToDelete because it is only shadowed
return true
}
if (processor.isExternalizable(existingScheme)) {
val existingInfo = getInfoForExistingScheme(existingScheme)
// is from file with old extension
if (existingInfo != null && schemeManager.schemeExtension != existingInfo.fileExtension) {
schemeToInfo.remove(existingScheme)
existingInfo.scheduleDelete(filesToDelete, "from file with old extension")
schemes.removeAt(existingSchemeIndex)
if (existingSchemeIndex < newSchemesOffset) {
newSchemesOffset--
}
// when existing loaded scheme removed, we need to remove it from schemeManager.schemeToInfo,
// but SchemeManager will correctly remove info on save, no need to complicate
return true
}
}
if (schemeManager.schemeExtension != extension && isFromFileWithNewExtension(existingScheme, fileNameWithoutExtension)) {
// 1.oldExt is loading after 1.newExt - we should delete 1.oldExt
LOG.debug { "Schedule to delete: $fileName (reason: extension mismatch)" }
filesToDelete.add(fileName)
}
else {
// We don't load scheme with duplicated name - if we generate unique name for it, it will be saved then with new name.
// It is not what all can expect. Such situation in most cases indicates error on previous level, so, we just warn about it.
LOG.warn("Scheme file \"$fileName\" is not loaded because defines duplicated name \"$schemeKey\"")
}
return false
}
fun loadScheme(fileName: String, input: InputStream?, preloadedBytes: ByteArray?): MUTABLE_SCHEME? {
val extension = schemeManager.getFileExtension(fileName, isAllowAny = false)
if (isFileScheduledForDeleteInThisLoadSession(fileName)) {
LOG.warn("Scheme file \"$fileName\" is not loaded because marked to delete")
return null
}
val processor = schemeManager.processor
val fileNameWithoutExtension = fileName.substring(0, fileName.length - extension.length)
fun createInfo(schemeName: String, element: Element?): ExternalInfo {
val info = ExternalInfo(fileNameWithoutExtension, extension)
if (element != null) {
info.digest = element.digest(getDigest())
}
info.schemeKey = schemeName
return info
}
var scheme: MUTABLE_SCHEME? = null
if (processor is LazySchemeProcessor) {
val bytes = preloadedBytes ?: input!!.readBytes()
lazyPreloadScheme(bytes, schemeManager.isOldSchemeNaming) { name, parser ->
val attributeProvider = Function<String, String?> {
if (parser.eventType == XMLStreamConstants.START_ELEMENT) {
parser.getAttributeValue(null, it)
}
else {
null
}
}
val schemeKey = name
?: processor.getSchemeKey(attributeProvider, fileNameWithoutExtension)
?: throw nameIsMissed(bytes)
if (!checkExisting(schemeKey, fileName, fileNameWithoutExtension, extension)) {
return null
}
val externalInfo = createInfo(schemeKey, null)
scheme = processor.createScheme(SchemeDataHolderImpl(processor, bytes, externalInfo), schemeKey, attributeProvider)
schemeToInfo.put(scheme!!, externalInfo)
retainProbablyScheduledForDeleteFile(fileName)
}
}
else {
val element = when (preloadedBytes) {
null -> JDOMUtil.load(input)
else -> JDOMUtil.load(CharsetToolkit.inputStreamSkippingBOM(preloadedBytes.inputStream()))
}
scheme = (processor as NonLazySchemeProcessor).readScheme(element, isDuringLoad) ?: return null
val schemeKey = processor.getSchemeKey(scheme!!)
if (!checkExisting(schemeKey, fileName, fileNameWithoutExtension, extension)) {
return null
}
schemeToInfo.put(scheme!!, createInfo(schemeKey, element))
retainProbablyScheduledForDeleteFile(fileName)
}
schemes.add(scheme!!)
return scheme
}
private fun isFileScheduledForDeleteInThisLoadSession(fileName: String): Boolean {
return filesToDelete.contains(fileName)
}
private fun retainProbablyScheduledForDeleteFile(fileName: String) {
filesToDelete.remove(fileName)
preScheduledFilesToDelete.remove(fileName)
}
fun removeUpdatedScheme(changedScheme: MUTABLE_SCHEME) {
val index = ContainerUtil.indexOfIdentity(schemes, changedScheme)
if (LOG.assertTrue(index >= 0)) {
schemes.removeAt(index)
schemeToInfo.remove(changedScheme)
}
}
}
internal inline fun lazyPreloadScheme(bytes: ByteArray, isOldSchemeNaming: Boolean, consumer: (name: String?, parser: XMLStreamReader) -> Unit) {
val reader = createXmlStreamReader(CharsetToolkit.inputStreamSkippingBOM(bytes.inputStream()))
consumer(preload(isOldSchemeNaming, reader), reader)
}
private fun preload(isOldSchemeNaming: Boolean, parser: XMLStreamReader): String? {
var eventType = parser.eventType
fun findName(): String? {
eventType = parser.next()
while (eventType != XMLStreamConstants.END_DOCUMENT) {
when (eventType) {
XMLStreamConstants.START_ELEMENT -> {
if (parser.localName == "option" && parser.getAttributeValue(null, "name") == "myName") {
return parser.getAttributeValue(null, "value")
}
}
}
eventType = parser.next()
}
return null
}
do {
when (eventType) {
XMLStreamConstants.START_ELEMENT -> {
if (!isOldSchemeNaming || parser.localName != "component") {
if (parser.localName == "profile" || (isOldSchemeNaming && parser.localName == "copyright")) {
return findName()
}
else if (parser.localName == "inspections") {
// backward compatibility - we don't write PROFILE_NAME_TAG anymore
return parser.getAttributeValue(null, "profile_name") ?: findName()
}
else if (parser.localName == "configuration") {
// run configuration
return parser.getAttributeValue(null, "name")
}
else {
return null
}
}
}
}
eventType = parser.next()
}
while (eventType != XMLStreamConstants.END_DOCUMENT)
return null
}
internal class ExternalInfo(var fileNameWithoutExtension: String, var fileExtension: String?) {
// we keep it to detect rename
var schemeKey: String? = null
var digest: ByteArray? = null
val fileName: String
get() = "$fileNameWithoutExtension$fileExtension"
fun setFileNameWithoutExtension(nameWithoutExtension: String, extension: String) {
fileNameWithoutExtension = nameWithoutExtension
fileExtension = extension
}
fun isDigestEquals(newDigest: ByteArray) = Arrays.equals(digest, newDigest)
fun scheduleDelete(filesToDelete: MutableSet<String>, @NonNls reason: String) {
LOG.debug { "Schedule to delete: $fileName (reason: $reason)" }
filesToDelete.add(fileName)
}
override fun toString() = fileName
}
internal fun VirtualFile.getOrCreateChild(fileName: String, requestor: StorageManagerFileWriteRequestor): VirtualFile {
return findChild(fileName) ?: runAsWriteActionIfNeeded { createChildData(requestor, fileName) }
}
internal fun createDir(ioDir: Path, requestor: StorageManagerFileWriteRequestor): VirtualFile {
ioDir.createDirectories()
val parentFile = ioDir.parent
val parentVirtualFile = (if (parentFile == null) null else VfsUtil.createDirectoryIfMissing(parentFile.systemIndependentPath))
?: throw IOException(ProjectBundle.message("project.configuration.save.file.not.found", parentFile))
return parentVirtualFile.getOrCreateChild(ioDir.fileName.toString(), requestor)
} | apache-2.0 | 78b56f9b1b6878e3aab66f9e75b84f2a | 39.615132 | 153 | 0.709056 | 5.01666 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.