content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package com.cognifide.gradle.aem.common.instance.service.osgi
import com.cognifide.gradle.aem.common.instance.Instance
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import org.apache.commons.lang3.builder.EqualsBuilder
import org.apache.commons.lang3.builder.HashCodeBuilder
@JsonIgnoreProperties(ignoreUnknown = true)
class Component {
@JsonIgnore
lateinit var instance: Instance
lateinit var id: String
lateinit var name: String
lateinit var state: String
var stateRaw: Int = 0
var bundleId: Int? = -1
var pid: String? = null
val uid: String get() = pid ?: name
val active: Boolean get() = stateRaw == STATE_RAW_ACTIVE
val satisfied: Boolean get() = stateRaw == STATE_RAW_SATISTIED
val notUnsatisfied: Boolean get() = stateRaw != STATE_RAW_UNSATISFIED
val unsatisfied: Boolean get() = stateRaw == STATE_RAW_UNSATISFIED
val failedActivation: Boolean get() = stateRaw == STATE_RAW_FAILED_ACTIVATION
val noConfig: Boolean get() = state == STATE_NO_CONFIG
val disabled: Boolean get() = state == STATE_DISABLED
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Component
return EqualsBuilder()
.append(id, other.id)
.append(name, other.name)
.append(state, other.state)
.append(stateRaw, other.stateRaw)
.append(pid, other.pid)
.append(bundleId, other.bundleId)
.isEquals
}
override fun hashCode(): Int {
return HashCodeBuilder()
.append(id)
.append(bundleId)
.append(name)
.append(stateRaw)
.append(state)
.toHashCode()
}
override fun toString(): String = "Component(uid='$uid', state='$state', id='$id', bundleId='$bundleId', instance='${instance.name}')"
companion object {
const val STATE_RAW_DISABLED_OR_NO_CONFIG = -1
const val STATE_RAW_UNSATISFIED = 2
const val STATE_RAW_SATISTIED = 4
const val STATE_RAW_ACTIVE = 8
const val STATE_RAW_FAILED_ACTIVATION = 16
const val STATE_ACTIVE = "active"
const val STATE_SATISFIED = "satisfied"
const val STATE_NO_CONFIG = "no config"
const val STATE_DISABLED = "disabled"
}
}
| src/main/kotlin/com/cognifide/gradle/aem/common/instance/service/osgi/Component.kt | 418574123 |
package stan.androiddemo.project.petal.Module.Setting
import android.annotation.TargetApi
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.media.RingtoneManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.preference.*
import android.support.v4.app.NavUtils
import android.text.TextUtils
import android.view.MenuItem
import stan.androiddemo.R
class PetalSettingActivity : AppCompatPreferenceActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setupActionBar()
}
/**
* Set up the [android.app.ActionBar], if the API is available.
*/
private fun setupActionBar() {
val actionBar = getSupportActionBar()
actionBar?.setDisplayHomeAsUpEnabled(true)
}
override fun onMenuItemSelected(featureId: Int, item: MenuItem): Boolean {
val id = item.itemId
if (id == android.R.id.home) {
if (!super.onMenuItemSelected(featureId, item)) {
NavUtils.navigateUpFromSameTask(this)
}
return true
}
return super.onMenuItemSelected(featureId, item)
}
/**
* {@inheritDoc}
*/
override fun onIsMultiPane(): Boolean {
return isXLargeTablet(this)
}
/**
* {@inheritDoc}
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
override fun onBuildHeaders(target: List<PreferenceActivity.Header>) {
loadHeadersFromResource(R.xml.pref_headers, target)
}
/**
* This method stops fragment injection in malicious applications.
* Make sure to deny any unknown fragments here.
*/
override fun isValidFragment(fragmentName: String): Boolean {
return PreferenceFragment::class.java.name == fragmentName
|| GeneralPreferenceFragment::class.java.name == fragmentName
|| DataSyncPreferenceFragment::class.java.name == fragmentName
|| NotificationPreferenceFragment::class.java.name == fragmentName
}
/**
* This fragment shows general preferences only. It is used when the
* activity is showing a two-pane settings UI.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
class GeneralPreferenceFragment : PreferenceFragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
addPreferencesFromResource(R.xml.pref_general)
setHasOptionsMenu(true)
// Bind the summaries of EditText/List/Dialog/Ringtone preferences
// to their values. When their values change, their summaries are
// updated to reflect the new value, per the Android Design
// guidelines.
bindPreferenceSummaryToValue(findPreference("example_text"))
bindPreferenceSummaryToValue(findPreference("example_list"))
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.itemId
if (id == android.R.id.home) {
startActivity(Intent(activity, PetalSettingActivity::class.java))
return true
}
return super.onOptionsItemSelected(item)
}
}
/**
* This fragment shows notification preferences only. It is used when the
* activity is showing a two-pane settings UI.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
class NotificationPreferenceFragment : PreferenceFragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
addPreferencesFromResource(R.xml.pref_notification)
setHasOptionsMenu(true)
// Bind the summaries of EditText/List/Dialog/Ringtone preferences
// to their values. When their values change, their summaries are
// updated to reflect the new value, per the Android Design
// guidelines.
bindPreferenceSummaryToValue(findPreference("notifications_new_message_ringtone"))
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.itemId
if (id == android.R.id.home) {
startActivity(Intent(activity, PetalSettingActivity::class.java))
return true
}
return super.onOptionsItemSelected(item)
}
}
/**
* This fragment shows data and sync preferences only. It is used when the
* activity is showing a two-pane settings UI.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
class DataSyncPreferenceFragment : PreferenceFragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
addPreferencesFromResource(R.xml.pref_data_sync)
setHasOptionsMenu(true)
// Bind the summaries of EditText/List/Dialog/Ringtone preferences
// to their values. When their values change, their summaries are
// updated to reflect the new value, per the Android Design
// guidelines.
bindPreferenceSummaryToValue(findPreference("sync_frequency"))
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.itemId
if (id == android.R.id.home) {
startActivity(Intent(activity, PetalSettingActivity::class.java))
return true
}
return super.onOptionsItemSelected(item)
}
}
companion object {
private val sBindPreferenceSummaryToValueListener = Preference.OnPreferenceChangeListener { preference, value ->
val stringValue = value.toString()
if (preference is ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list.
val listPreference = preference
val index = listPreference.findIndexOfValue(stringValue)
// Set the summary to reflect the new value.
preference.setSummary(
if (index >= 0)
listPreference.entries[index]
else
null)
} else if (preference is RingtonePreference) {
// For ringtone preferences, look up the correct display value
// using RingtoneManager.
if (TextUtils.isEmpty(stringValue)) {
// Empty values correspond to 'silent' (no ringtone).
preference.setSummary(R.string.pref_ringtone_silent)
} else {
val ringtone = RingtoneManager.getRingtone(
preference.getContext(), Uri.parse(stringValue))
if (ringtone == null) {
// Clear the summary if there was a lookup error.
preference.setSummary(null)
} else {
// Set the summary to reflect the new ringtone display
// name.
val name = ringtone.getTitle(preference.getContext())
preference.setSummary(name)
}
}
} else {
// For all other preferences, set the summary to the value's
// simple string representation.
preference.summary = stringValue
}
true
}
/**
* Helper method to determine if the device has an extra-large screen. For
* example, 10" tablets are extra-large.
*/
private fun isXLargeTablet(context: Context): Boolean {
return context.resources.configuration.screenLayout and Configuration.SCREENLAYOUT_SIZE_MASK >= Configuration.SCREENLAYOUT_SIZE_XLARGE
}
/**
* Binds a preference's summary to its value. More specifically, when the
* preference's value is changed, its summary (line of text below the
* preference title) is updated to reflect the value. The summary is also
* immediately updated upon calling this method. The exact display format is
* dependent on the type of preference.
* @see .sBindPreferenceSummaryToValueListener
*/
private fun bindPreferenceSummaryToValue(preference: Preference) {
// Set the listener to watch for value changes.
preference.onPreferenceChangeListener = sBindPreferenceSummaryToValueListener
// Trigger the listener immediately with the preference's
// current value.
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.context)
.getString(preference.key, ""))
}
fun launch(activity: Activity) {
val intent = Intent(activity, PetalSettingActivity::class.java)
// ActivityCompat.startActivity();
activity.startActivity(intent)
}
}
}
| app/src/main/java/stan/androiddemo/project/petal/Module/Setting/PetalSettingActivity.kt | 3430794042 |
/*
* Copyright 2016 - 2022 busybusy, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.busybusy.flurry_provider
import com.busybusy.analyticskit_android.AnalyticsEvent
import com.busybusy.analyticskit_android.AnalyticsKitProvider.PriorityFilter
import com.flurry.android.FlurryAgent
import com.nhaarman.mockitokotlin2.times
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.entry
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentMatchers.*
import org.powermock.api.mockito.PowerMockito
import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
/**
* Tests the [FlurryProvider] class
*
* @author John Hunt on 3/21/16.
*/
@RunWith(PowerMockRunner::class)
class FlurryProviderTest {
private lateinit var provider: FlurryProvider
private var testEventName: String? = null
private lateinit var testEventPropertiesMap: Map<String, Any>
private var logEventNameOnlyCalled = false
private var logEventNameAndParamsCalled = false
private var logTimedEventNameOnlyCalled = false
private var logTimedEventNameAndParamsCalled = false
@Before
fun setup() {
provider = FlurryProvider()
testEventName = null
testEventPropertiesMap = mutableMapOf()
logEventNameOnlyCalled = false
logEventNameAndParamsCalled = false
logTimedEventNameOnlyCalled = false
logTimedEventNameAndParamsCalled = false
}
@Test
fun testSetAndGetPriorityFilter() {
val filter = PriorityFilter { false }
val filteringProvider = FlurryProvider(priorityFilter = filter)
assertThat(filteringProvider.getPriorityFilter()).isEqualTo(filter)
}
@Test
fun test_priorityFiltering_default() {
val event = AnalyticsEvent("Forecast: Event Flurries")
.setPriority(10)
.send()
assertThat(provider.getPriorityFilter().shouldLog(event.priority)).isEqualTo(true)
event.setPriority(-9)
.send()
assertThat(provider.getPriorityFilter().shouldLog(event.priority)).isEqualTo(true)
}
@Test
fun test_priorityFiltering_custom() {
val filter = PriorityFilter { priorityLevel -> priorityLevel < 10 }
val filteringProvider = FlurryProvider(priorityFilter = filter)
val event = AnalyticsEvent("Forecast: Event Flurries")
.setPriority(10)
.send()
assertThat(filteringProvider.getPriorityFilter().shouldLog(event.priority)).isEqualTo(false)
event.setPriority(9)
.send()
assertThat(filteringProvider.getPriorityFilter().shouldLog(event.priority)).isEqualTo(true)
}
@Test
fun testStringifyParameters_noParams() {
val flurryParams = provider.stringifyParameters(null)
assertThat(flurryParams).isNull()
}
@Test
fun testStringifyParameters_validParams() {
val eventParams = mutableMapOf<String, Any>("favorite_color" to "Blue", "favorite_number" to 42)
val flurryParams = provider.stringifyParameters(eventParams)
assertThat(flurryParams).isNotNull
assertThat(flurryParams).containsExactly(entry("favorite_color", "Blue"), entry("favorite_number", "42"))
}
@Test
fun testStringifyParameters_willThrow() {
val attributeMap = mutableMapOf<String, Any>()
for (count in 0..ATTRIBUTE_LIMIT + 1) {
attributeMap[count.toString()] = "placeholder"
}
var exceptionMessage: String? = ""
try {
provider.stringifyParameters(attributeMap)
} catch (e: IllegalStateException) {
exceptionMessage = e.message
}
assertThat(exceptionMessage).isEqualTo("Flurry events are limited to $ATTRIBUTE_LIMIT attributes")
}
@PrepareForTest(FlurryAgent::class)
@Test
fun testSendEvent_unTimed_noParams() {
val event = AnalyticsEvent("Flurry Test Run")
PowerMockito.mockStatic(FlurryAgent::class.java)
PowerMockito.`when`(FlurryAgent.logEvent(anyString()))
.thenAnswer { invocation ->
val args = invocation.arguments
testEventName = args[0] as String
logEventNameOnlyCalled = true
null
}
provider.sendEvent(event)
assertThat(testEventName).isEqualTo("Flurry Test Run")
assertThat(testEventPropertiesMap).isEmpty()
assertThat(logEventNameOnlyCalled).isEqualTo(true)
assertThat(logEventNameAndParamsCalled).isEqualTo(false)
assertThat(logTimedEventNameOnlyCalled).isEqualTo(false)
assertThat(logTimedEventNameAndParamsCalled).isEqualTo(false)
}
@Suppress("UNCHECKED_CAST")
@PrepareForTest(FlurryAgent::class)
@Test
fun testSendEvent_unTimed_withParams() {
val event = AnalyticsEvent("Flurry Event With Params Run")
.putAttribute("some_param", "yes")
.putAttribute("another_param", "yes again")
PowerMockito.mockStatic(FlurryAgent::class.java)
PowerMockito.`when`(FlurryAgent.logEvent(anyString(), anyMap()))
.thenAnswer { invocation ->
logEventNameAndParamsCalled = true
val args = invocation.arguments
testEventName = args[0] as String
testEventPropertiesMap = args[1] as Map<String, Any>
null
}
provider.sendEvent(event)
assertThat(testEventName).isEqualTo("Flurry Event With Params Run")
assertThat(testEventPropertiesMap).containsExactly(entry("some_param", "yes"), entry("another_param", "yes again"))
assertThat(logEventNameAndParamsCalled).isEqualTo(true)
assertThat(logEventNameOnlyCalled).isEqualTo(false)
assertThat(logTimedEventNameOnlyCalled).isEqualTo(false)
assertThat(logTimedEventNameAndParamsCalled).isEqualTo(false)
}
@PrepareForTest(FlurryAgent::class)
@Test
fun testSendEvent_timed_noParams() {
val event = AnalyticsEvent("Flurry Timed Event")
.setTimed(true)
PowerMockito.mockStatic(FlurryAgent::class.java)
PowerMockito.`when`(FlurryAgent.logEvent(anyString(), anyBoolean()))
.thenAnswer { invocation ->
val args = invocation.arguments
testEventName = args[0] as String
logTimedEventNameOnlyCalled = true
null
}
provider.sendEvent(event)
assertThat(testEventName).isEqualTo("Flurry Timed Event")
assertThat(testEventPropertiesMap).isEmpty()
assertThat(logTimedEventNameOnlyCalled).isEqualTo(true)
assertThat(logEventNameOnlyCalled).isEqualTo(false)
assertThat(logEventNameAndParamsCalled).isEqualTo(false)
assertThat(logTimedEventNameAndParamsCalled).isEqualTo(false)
}
@Suppress("UNCHECKED_CAST")
@PrepareForTest(FlurryAgent::class)
@Test
fun testSendEvent_timed_withParams() {
val event = AnalyticsEvent("Flurry Timed Event With Parameters")
.setTimed(true)
.putAttribute("some_param", "yes")
.putAttribute("another_param", "yes again")
PowerMockito.mockStatic(FlurryAgent::class.java)
PowerMockito.`when`(FlurryAgent.logEvent(anyString(), anyMap(), anyBoolean()))
.thenAnswer { invocation ->
val args = invocation.arguments
testEventName = args[0] as String
logTimedEventNameAndParamsCalled = true
testEventPropertiesMap = args[1] as Map<String, Any>
null
}
provider.sendEvent(event)
assertThat(testEventName).isEqualTo("Flurry Timed Event With Parameters")
assertThat(testEventPropertiesMap).containsExactly(entry("some_param", "yes"), entry("another_param", "yes again"))
assertThat(logTimedEventNameAndParamsCalled).isEqualTo(true)
assertThat(logTimedEventNameOnlyCalled).isEqualTo(false)
assertThat(logEventNameOnlyCalled).isEqualTo(false)
assertThat(logEventNameAndParamsCalled).isEqualTo(false)
}
@PrepareForTest(FlurryAgent::class)
@Test
fun testEndTimedEvent() {
val event = AnalyticsEvent("End timed event")
PowerMockito.mockStatic(FlurryAgent::class.java)
provider.endTimedEvent(event)
// Verify Flurry framework is called
PowerMockito.verifyStatic(FlurryAgent::class.java, times(1))
FlurryAgent.endTimedEvent(event.name())
}
}
| flurry-provider/src/test/kotlin/com/busybusy/flurry_provider/FlurryProviderTest.kt | 1340216151 |
package io.kotest.core.listeners
import io.kotest.core.test.TestCase
import io.kotest.core.test.TestResult
import io.kotest.core.test.TestType
interface BeforeContainerListener {
/**
* Registers a new before-container callback to be executed before every [TestCase]
* with type [TestType.Container].
* The [TestCase] about to be executed is provided as the parameter.
*/
suspend fun beforeContainer(testCase: TestCase): Unit = Unit
}
interface AfterContainerListener {
/**
* Registers a new after-container callback to be executed after every [TestCase]
* with type [TestType.Container].
* The callback provides two parameters - the test case that has just completed,
* and the [TestResult] outcome of that test.
*/
suspend fun afterContainer(testCase: TestCase, result: TestResult): Unit = Unit
}
| kotest-framework/kotest-framework-api/src/commonMain/kotlin/io/kotest/core/listeners/container.kt | 190633620 |
package glorantq.ramszesz.utils
/**
* Created by glora on 2017. 07. 28..
*/
fun String.tryParseInt(default: Int = 0): Int {
try {
return toInt()
} catch (e: NumberFormatException) {
return default
}
} | src/glorantq/ramszesz/utils/Extensions.kt | 854883884 |
package com.werb.pickphotoview
import android.app.Activity
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.support.annotation.Keep
import android.support.v4.view.PagerAdapter
import android.support.v4.view.ViewPager
import android.view.View
import android.view.ViewGroup
import android.view.animation.DecelerateInterpolator
import com.werb.eventbus.EventBus
import com.werb.eventbus.Subscriber
import com.werb.pickphotoview.event.PickPreviewEvent
import com.werb.pickphotoview.extensions.alphaColor
import com.werb.pickphotoview.extensions.color
import com.werb.pickphotoview.extensions.string
import com.werb.pickphotoview.util.PickConfig
import com.werb.pickphotoview.util.PickPhotoHelper
import com.werb.pickphotoview.widget.PreviewImage
import kotlinx.android.synthetic.main.pick_activty_preview_photo.*
import kotlinx.android.synthetic.main.pick_widget_my_toolbar.*
/**
* Created by wanbo on 2017/1/4.
*/
@Keep
class PickPhotoPreviewActivity : BasePickActivity() {
private var path: String? = null
private var dir: String? = null
private val selectImages = PickPhotoHelper.selectImages
private val allImages: List<String> by lazy { allImage() }
private val imageViews: List<PreviewImage> by lazy { imageViews() }
private var full = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
EventBus.register(this)
setContentView(R.layout.pick_activty_preview_photo)
path = intent.getStringExtra("path")
dir = intent.getStringExtra("dir")
initToolbar()
}
override fun onDestroy() {
super.onDestroy()
EventBus.unRegister(this)
}
private fun initToolbar() {
GlobalData.model?.let {
toolbar.setBackgroundColor(color(it.toolbarColor))
statusBar.setBackgroundColor(color(it.statusBarColor))
midTitle.setTextColor(color(it.toolbarTextColor))
cancel.setTextColor(color(it.toolbarTextColor))
if (selectImages.size > 0) {
sure.setTextColor(color(it.toolbarTextColor))
} else {
sure.setTextColor(alphaColor(color(it.toolbarTextColor)))
}
sure.text = String.format(string(R.string.pick_photo_sure), selectImages.size)
sure.setOnClickListener { add() }
cancel.setOnClickListener { finish() }
path?.let {
val index = allImages.indexOf(it)
val all = allImages.size
val current = index + 1
midTitle.text = "$current/$all"
viewPager.adapter = ListPageAdapter()
viewPager.currentItem = index
viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
}
override fun onPageSelected(position: Int) {
val i = position + 1
midTitle.text = "$i/$all"
}
override fun onPageScrollStateChanged(state: Int) {
}
})
}
}
}
private fun imageViews(): List<PreviewImage> = arrayListOf<PreviewImage>().apply {
for (index in 1..4) {
add(PreviewImage(this@PickPhotoPreviewActivity))
}
}
private fun add() {
if (selectImages.isNotEmpty()) {
finishForResult()
}
}
private fun allImage(): List<String> {
val groupImage = PickPhotoHelper.groupImage
return groupImage?.mGroupMap?.get(dir) ?: emptyList()
}
private fun full() {
full = !full
hideOrShowToolbar()
if (full) {
window.decorView.systemUiVisibility = View.INVISIBLE
} else {
window.decorView.systemUiVisibility = View.VISIBLE
GlobalData.model?.let {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (it.lightStatusBar) {
window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
}
}
}
}
}
private fun hideOrShowToolbar() {
appbar.animate()
.translationY(if (!full) 0f else -appbar.height.toFloat())
.setInterpolator(DecelerateInterpolator())
.start()
}
@Subscriber()
private fun select(event: PickPreviewEvent) {
GlobalData.model?.let {
if (selectImages.size > 0) {
sure.setTextColor(color(it.toolbarTextColor))
} else {
sure.setTextColor(alphaColor(color(it.toolbarTextColor)))
}
sure.text = String.format(string(R.string.pick_photo_sure), selectImages.size)
}
if (full) full()
}
//通过ViewPager实现滑动的图片
private inner class ListPageAdapter : PagerAdapter() {
override fun getCount(): Int {
return allImages.size
}
override fun isViewFromObject(view: View, any: Any): Boolean {
return view === any
}
override fun instantiateItem(container: ViewGroup, position: Int): Any {
val i = position % 4
val pic = imageViews[i]
val params = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
val path = allImages[position]
pic.setImage(path, this@PickPhotoPreviewActivity::full)
container.addView(pic, params)
return pic
}
override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
val i = position % 4
val imageView = imageViews[i]
container.removeView(imageView)
imageView.clear()
}
}
companion object {
fun startActivity(activity: Activity, requestCode: Int, currentPath: String, dirName: String) {
val intent = Intent(activity, PickPhotoPreviewActivity::class.java)
intent.putExtra("path", currentPath)
intent.putExtra("dir", dirName)
activity.startActivityForResult(intent, requestCode)
activity.overridePendingTransition(R.anim.activity_anim_right_to_current, R.anim.activity_anim_not_change)
}
}
override fun finish() {
super.finish()
overridePendingTransition(R.anim.activity_anim_not_change, R.anim.activity_anim_current_to_right)
}
private fun finishForResult() {
val intent = Intent()
intent.setClass(this@PickPhotoPreviewActivity, PickPhotoActivity::class.java)
setResult(PickConfig.PREVIEW_PHOTO_DATA, intent)
finish()
}
}
| pickphotoview/src/main/java/com/werb/pickphotoview/PickPhotoPreviewActivity.kt | 1083370027 |
/**
* HoTT Transmitter Config Copyright (C) 2013 Oliver Treichel
*
* 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:></http:>//www.gnu.org/licenses/>.
*/
package de.treichels.hott.mdlviewer.javafx
import de.treichels.hott.model.Curve
import de.treichels.hott.report.html.CurveImageGenerator
import javafx.embed.swing.SwingFXUtils
import javafx.scene.canvas.Canvas
import javafx.scene.image.Image
import javafx.scene.paint.Color
import javafx.scene.shape.StrokeLineCap
import javafx.scene.shape.StrokeLineJoin
import javafx.scene.text.Font
import org.apache.commons.math3.analysis.interpolation.SplineInterpolator
import tornadofx.*
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.util.*
import java.util.concurrent.CountDownLatch
import javax.imageio.ImageIO
/**
* Generate offline PNG image using JavaFX.
*
* @author Oliver Treichel <[email protected]>
*/
class JavaFxCurveImageGenerator : CurveImageGenerator {
private lateinit var image: Image
override fun getImageSource(curve: Curve, scale: Double, description: Boolean): String {
val pitchCurve = curve.point[0].position == 0
val canvas = Canvas((10 + 200 * scale), (10 + 250 * scale))
with(canvas.graphicsContext2D) {
// clear background
fill = Color.WHITE
fillRect(0.0, 0.0, (10 + 200 * scale), (10 + 250 * scale))
// draw out limit rect
stroke = Color.BLACK
strokeRect(5.0, 5.0, (200 * scale), (250 * scale))
// dashed gray lines
lineWidth = 1.0
lineCap = StrokeLineCap.BUTT
lineJoin = StrokeLineJoin.ROUND
miterLimit = 0.0
setLineDashes(5.0, 5.0)
stroke = Color.GRAY
// +100% and -100% horizontal lines
strokeLine(5.0, (5 + 25 * scale), (5 + 200 * scale), (5 + 25 * scale))
strokeLine(5.0, (5 + 225 * scale), (5 + 200 * scale), (5 + 225 * scale))
// horizontal 0% line
strokeLine(5.0, (5 + 125 * scale), (5 + 200 * scale), (5 + 125 * scale))
if (!pitchCurve) {
// vertical 0% line
strokeLine((5 + 100 * scale), 5.0, (5 + 100 * scale), (5 + 250 * scale))
}
lineWidth = 1.0
setLineDashes(0.0)
font = Font.font("Arial", 12.0)
stroke = Color.BLACK
val numPoints = curve.point.count { it.isEnabled }
val xVals = DoubleArray(numPoints)
val yVals = DoubleArray(numPoints)
curve.point.filter { it.isEnabled }.forEachIndexed { i, p ->
when (i) {
0 -> xVals[i] = if (pitchCurve) 0.0 else -100.0
numPoints - 1 -> xVals[i] = 100.0
else -> xVals[i] = p.position.toDouble()
}
yVals[i] = p.value.toDouble()
// draw dot and point number
if (description) {
val x0: Double
val y0: Double
if (pitchCurve) {
x0 = 5 + xVals[i] * 2.0 * scale
y0 = 5 + (225 - yVals[i] * 2) * scale
} else {
x0 = 5 + (100 + xVals[i]) * scale
y0 = 5 + (125 - yVals[i]) * scale
}
strokeOval(x0 - 2, y0 - 2, 4.0, 4.0)
clearRect(x0 - 6, y0 - 16, 8.0, 12.0)
strokeText(Integer.toString(p.number + 1), x0 - 3, y0 - 5)
}
}
lineWidth = 2.0
if (numPoints > 2 && curve.isSmoothing) {
// spline interpolate the curve points
val s = SplineInterpolator()
val function = s.interpolate(xVals, yVals)
beginPath()
if (pitchCurve) {
moveTo(5.0, 5 + (225 - yVals[0] * 2) * scale)
var x = 6.0
while (x < 4 + 200 * scale) {
lineTo(x, 5 + (225 - function.value((x - 5) / scale / 2.0) * 2) * scale)
x++
}
} else {
moveTo(5.0, 5 + (125 - yVals[0]) * scale)
var x = 6.0
while (x < 4 + 200 * scale) {
lineTo(x, 5 + (125 - function.value((x - 5) / scale - 100)) * scale)
x++
}
}
stroke()
} else {
beginPath()
if (pitchCurve) {
moveTo(5 + xVals[0] * 2.0 * scale, 5 + (225 - yVals[0] * 2) * scale)
for (i in 1 until numPoints) {
lineTo(5 + xVals[i] * 2.0 * scale, 5 + (225 - yVals[i] * 2) * scale)
}
} else {
moveTo(5 + (100 + xVals[0]) * scale, 5 + (125 - yVals[0]) * scale)
for (i in 1 until numPoints) {
lineTo(5 + (100 + xVals[i]) * scale, 5 + (125 - yVals[i]) * scale)
}
}
stroke()
}
}
val latch = CountDownLatch(1)
// take snapshot on ui thread
runLater {
image = canvas.snapshot(null, null)
latch.countDown()
}
// wait until snapshot completes
latch.await()
val renderedImage = SwingFXUtils.fromFXImage(image, null)
try {
ByteArrayOutputStream().use { baos ->
ImageIO.write(renderedImage, "png", baos)
return CurveImageGenerator.PREFIX + Base64.getEncoder().encodeToString(baos.toByteArray())
}
} catch (e: IOException) {
throw RuntimeException(e)
}
}
}
| MdlViewer/src/main/kotlin/de/treichels/hott/mdlviewer/javafx/JavaFxCurveImageGenerator.kt | 329978441 |
/*
* Copyright 2016 Datawire. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.datawire.discovery.gateway
import io.vertx.core.AbstractVerticle
import io.vertx.core.http.HttpHeaders
import io.vertx.core.http.HttpMethod
import io.vertx.core.json.JsonObject
import io.vertx.ext.auth.jwt.JWTAuth
import io.vertx.ext.web.Router
import io.vertx.core.logging.LoggerFactory
import io.vertx.ext.web.handler.CorsHandler
import io.vertx.ext.web.handler.JWTAuthHandler
class DiscoveryGatewayVerticle(): AbstractVerticle() {
private val log = LoggerFactory.getLogger(DiscoveryGatewayVerticle::class.java)
private val jsonContentType = "application/json; charset=utf-8"
override fun start() {
log.info("Starting Discovery Gateway")
val router = Router.router(vertx)
registerHealthCheck(router)
registerConnectHandler(router)
val server = vertx.createHttpServer()
server.requestHandler { router.accept(it) }.listen(config().getInteger("port"))
// todo(plombardi): replace with {} syntax once this bug fix is released
//
// https://github.com/eclipse/vert.x/pull/1282
log.info("Running server on {}", config().getInteger("port"))
}
private fun registerHealthCheck(router: Router) {
log.info("Registering health check (path: /health)")
router.get("/health").handler { rc ->
rc.response().setStatusCode(200).end()
}
}
private fun registerConnectHandler(router: Router) {
log.info("Registering JWT handler")
val jwtAuth = JWTAuth.create(vertx, config().getJsonObject("jsonWebToken"))
val jwt = JWTAuthHandler.create(jwtAuth, "/health")
router.route("/v1/connect*").handler(CorsHandler
.create("*")
.allowedMethods(setOf(HttpMethod.OPTIONS, HttpMethod.POST))
.allowedHeaders(setOf(
HttpHeaders.AUTHORIZATION,
HttpHeaders.CONTENT_TYPE,
HttpHeaders.CONTENT_LENGTH,
HttpHeaders.ORIGIN).map { it.toString() }.toSet())
.allowCredentials(true))
router.post("/v1/connect").handler(jwt)
log.info("Registering connector URL")
router.post("/v1/connect").produces("application/json").handler { rc ->
val response = rc.response()!!
vertx.eventBus().send<String>("discovery-resolver", "DEPRECATED") {
if (it.succeeded()) {
val address = it.result().body()
val connectOptions = JsonObject(mapOf(
"url" to "ws://$address/v1/messages"
))
response.setStatusCode(200).putHeader("content-type", jsonContentType).end(connectOptions.encodePrettily())
} else {
response.setStatusCode(500).end()
}
}
}
}
} | discovery-gateway/src/main/kotlin/io/datawire/discovery/gateway/DiscoveryGatewayVerticle.kt | 1245290996 |
/*
* MIT License
*
* Copyright (c) 2018 atlarge-research
*
* 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.atlarge.opendc.model.odc.integration.jpa.schema
import java.time.LocalDateTime
import javax.persistence.Entity
/**
* A [Simulation] has several [Path]s, which define the topology of the datacenter at different times. A [Simulation]
* also has several [Experiment]s, which can be run on a combination of [Path]s, [Scheduler]s and [Trace]s.
* [Simulation]s also serve as the scope to which different [User]s can be authorized.
*
*
* @property id The unique identifier of this simulation.
* @property name the name of the simulation.
* @property createdAt The date at which the simulation was created.
* @property lastEditedAt The date at which the simulation was lasted edited.
*/
@Entity
data class Simulation(val id: Int?, val name: String, val createdAt: LocalDateTime, val lastEditedAt: LocalDateTime)
| opendc-model-odc/jpa/src/main/kotlin/com/atlarge/opendc/model/odc/integration/jpa/schema/Simulation.kt | 1833576128 |
package fi.lasicaine.nutritionalvalue.data.network
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.asCoroutineDispatcher
import java.util.concurrent.Executors
val NETWORK = Executors.newFixedThreadPool(2).asCoroutineDispatcher()
val networkScope = CoroutineScope(NETWORK) | NutritionalValue/app/src/main/java/fi/lasicaine/nutritionalvalue/data/network/NetworkDispatcher.kt | 2748712178 |
/*
* Copyright (C) 2017-2019 Hazuki
*
* 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 jp.hazuki.yuzubrowser.legacy.userjs
import android.os.Bundle
import android.view.MenuItem
import jp.hazuki.yuzubrowser.legacy.R
import jp.hazuki.yuzubrowser.ui.app.ThemeActivity
class UserScriptListActivity : ThemeActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.fragment_base)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportFragmentManager.beginTransaction()
.replace(R.id.container, UserScriptListFragment())
.commit()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
finish()
return true
}
}
return super.onOptionsItemSelected(item)
}
}
| legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/userjs/UserScriptListActivity.kt | 3599715243 |
/*
* Copyright (C) 2017-2019 Hazuki
*
* 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 jp.hazuki.yuzubrowser.legacy.action
import android.os.Parcel
import android.os.Parcelable
import com.squareup.moshi.JsonEncodingException
import com.squareup.moshi.JsonReader
import com.squareup.moshi.JsonWriter
import jp.hazuki.yuzubrowser.legacy.utils.util.JsonConvertable
import okio.Buffer
import java.io.EOFException
import java.io.IOException
import java.util.*
class ActionList : ArrayList<Action>, Parcelable, JsonConvertable {
constructor() : super()
constructor(jsonStr: String) : super() {
fromJsonString(jsonStr)
}
constructor(source: Parcel) : super() {
source.readList(this, Action::class.java.classLoader)
}
override fun describeContents(): Int {
return 0
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeList(this)
}
fun add(`object`: SingleAction): Boolean {
return add(Action(`object`))
}
@Throws(IOException::class)
fun writeAction(writer: JsonWriter) {
writer.beginArray()
for (action in this) {
action.writeAction(writer)
}
writer.endArray()
}
@Throws(IOException::class)
fun loadAction(reader: JsonReader): Boolean {
if (reader.peek() != JsonReader.Token.BEGIN_ARRAY) return false
reader.beginArray()
while (reader.hasNext()) {
val action = Action()
if (!action.loadAction(reader)) {
return if (reader.peek() == JsonReader.Token.END_ARRAY)
break
else
false
}
add(action)
}
reader.endArray()
return true
}
override fun toJsonString(): String? {
val buffer = Buffer()
JsonWriter.of(buffer).use {
writeAction(it)
}
return buffer.readUtf8()
}
override fun fromJsonString(str: String): Boolean {
clear()
try {
JsonReader.of(Buffer().writeUtf8(str)).use {
return loadAction(it)
}
} catch (e: EOFException) {
return false
} catch (e: JsonEncodingException) {
return false
}
}
companion object {
const val serialVersionUID = 4454998466204378989L
@JvmField
val CREATOR: Parcelable.Creator<ActionList> = object : Parcelable.Creator<ActionList> {
override fun createFromParcel(source: Parcel): ActionList {
return ActionList(source)
}
override fun newArray(size: Int): Array<ActionList?> {
return arrayOfNulls(size)
}
}
}
}
| legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/action/ActionList.kt | 772525044 |
package com.osfans.trime.ime.lifecycle
import kotlinx.coroutines.MainScope
object CoroutineScopeJava {
@JvmStatic
val MainScopeJava
get() = MainScope()
}
| app/src/main/java/com/osfans/trime/ime/lifecycle/CoroutineScopeJava.kt | 327185865 |
/*
* Copyright (C) 2017 Hazuki
*
* 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 jp.hazuki.yuzubrowser.legacy.reader
class ReaderData(val title: String, val body: CharSequence)
| legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/reader/ReaderData.kt | 1114882139 |
package v_builders.builders
import util.questions.Answer
import util.questions.Answer.*
fun todoTask40(): Nothing = TODO(
"""
Task 40.
Look at the questions below and give your answers:
change 'insertAnswerHere()' in task40's map to your choice (a, b or c).
All the constants are imported via 'util.questions.Answer.*', so they can be accessed by name.
"""
)
fun insertAnswerHere(): Nothing = todoTask40()
fun task40() = linkedMapOf<Int, Answer>(
/*
1. In the Kotlin code
tr {
td {
text("Product")
}
td {
text("Popularity")
}
}
'td' is:
a. special built-in syntactic construct
b. function declaration
c. function invocation
*/
1 to insertAnswerHere(),
/*
2. In the Kotlin code
tr (color = "yellow") {
td {
text("Product")
}
td {
text("Popularity")
}
}
'color' is:
a. new variable declaration
b. argument name
c. argument value
*/
2 to insertAnswerHere(),
/*
3. The block
{
text("Product")
}
from the previous question is:
a. block inside built-in syntax construction 'td'
b. function literal (or "lambda")
c. something mysterious
*/
3 to insertAnswerHere(),
/*
4. For the code
tr (color = "yellow") {
this.td {
text("Product")
}
td {
text("Popularity")
}
}
which of the following is true:
a. this code doesn't compile
b. 'this' refers to an instance of an outer class
c. 'this' refers to a receiver parameter TR of the function literal:
tr (color = "yellow") { TR.(): Unit ->
this.td {
text("Product")
}
}
*/
4 to insertAnswerHere()
)
| src/v_builders/_40_BuildersHowItWorks.kt | 4179615314 |
// Copyright (c) 2020 Google LLC All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package com.google.idea.gn.psi.builtin
import com.google.idea.gn.GnKeys
import com.google.idea.gn.completion.CompletionIdentifier
import com.google.idea.gn.psi.*
import com.google.idea.gn.psi.Function
import com.google.idea.gn.psi.scope.Scope
class Template : Function {
override fun execute(call: GnCall, targetScope: Scope): GnValue? {
val name = GnPsiUtil.evaluateFirstToString(call.exprList, targetScope) ?: return null
val func = TemplateFunction(name, call, targetScope)
targetScope.installFunction(func)
call.putUserData(GnKeys.TEMPLATE_INSTALLED_FUNCTION, func)
return null
}
override val identifierType: CompletionIdentifier.IdentifierType
get() = CompletionIdentifier.IdentifierType.FUNCTION
override val isBuiltin: Boolean
get() = true
override val identifierName: String
get() = NAME
override val postInsertType: CompletionIdentifier.PostInsertType?
get() = CompletionIdentifier.PostInsertType.CALL_WITH_STRING
companion object {
const val NAME = "template"
const val TARGET_NAME = "target_name"
}
}
| src/main/java/com/google/idea/gn/psi/builtin/Template.kt | 2192482043 |
package org.evomaster.core.search.service.track
import com.google.inject.*
import com.netflix.governator.guice.LifecycleInjector
import org.evomaster.core.BaseModule
import org.evomaster.core.EMConfig
import org.evomaster.core.search.EvaluatedIndividual
import org.evomaster.core.search.algorithms.onemax.*
import org.evomaster.core.search.service.Archive
import org.evomaster.core.search.service.mutator.EvaluatedMutation
import org.evomaster.core.search.tracer.ArchiveMutationTrackService
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.BeforeEach
/**
* created by manzh on 2020-06-21
*/
class TraceableElementTest {
private lateinit var config: EMConfig
private lateinit var sampler : OneMaxSampler
private lateinit var ff : OneMaxFitness
private lateinit var mutator : ManipulatedOneMaxMutator
private lateinit var archive : Archive<OneMaxIndividual>
private lateinit var tracker : ArchiveMutationTrackService
@BeforeEach
fun init(){
val injector: Injector = LifecycleInjector.builder()
.withModules(* arrayOf<Module>(ManipulatedOneMaxModule(), BaseModule()))
.build().createInjector()
config = injector.getInstance(EMConfig::class.java)
sampler = injector.getInstance(OneMaxSampler::class.java)
ff = injector.getInstance(OneMaxFitness::class.java)
mutator = injector.getInstance(ManipulatedOneMaxMutator::class.java)
archive = injector.getInstance(
Key.get(
object : TypeLiteral<Archive<OneMaxIndividual>>(){}
)
)
tracker = injector.getInstance(ArchiveMutationTrackService::class.java)
}
// disable tracking individual and evaluated individual
@Test
fun testOneMaxIndividualWithFF(){
config.enableTrackIndividual = false
config.enableTrackEvaluatedIndividual = false
val inds10 = (0 until 10).map { sampler.sample()}
assert(inds10.all { it.trackOperator == null })
val evalInds10 = inds10.map { ff.calculateCoverage(it)!! }
assert(evalInds10.all { it.trackOperator == null && it.tracking == null })
}
// enable tracking evaluated individual but disable individual
@Test
fun testOneMaxIndividualWithFT(){
config.enableTrackIndividual = false
config.enableTrackEvaluatedIndividual = true
config.maxActionEvaluations = 100
config.stoppingCriterion = EMConfig.StoppingCriterion.FITNESS_EVALUATIONS
config.maxLengthOfTraces = 20
config.probOfArchiveMutation = 0.0
config.weightBasedMutationRate = false
config.testSuiteSplitType = EMConfig.TestSuiteSplitType.NONE
config.seed = 42
config.useTimeInFeedbackSampling = false
val inds10 = (0 until 10).map { ff.calculateCoverage(sampler.sample())!!.also { archive.addIfNeeded(it) }}
assert(inds10.all { it.trackOperator != null })
val eval = mutator.mutateAndSave(10, inds10[1], archive)
assertNotNull(eval.trackOperator)
assertNotNull(eval.tracking)
assertEquals(11, eval.tracking!!.history.size)
val eval2 = mutator.mutateAndSave(5, eval, archive)
assertNotNull(eval2.trackOperator)
assertNotNull(eval2.tracking)
assertEquals(16, eval2.tracking!!.history.size)
assertEquals(eval.tracking, eval2.tracking)
// with worsening mutator, all 16 history should be -1..0
assertEquals(16, eval2.getLast<EvaluatedIndividual<OneMaxIndividual>>(16, -1..0).size)
val first = eval2.tracking!!.history.first()
mutator.improve = true
val eval3 = mutator.mutateAndSave(5, eval2, archive)
assertNotNull(eval3.trackOperator)
assertNotNull(eval3.tracking)
assertEquals(20, eval3.tracking!!.history.size)
assertFalse(eval3.tracking!!.history.contains(first))
assertEquals(eval2.tracking, eval3.tracking)
assert(eval3.getLast<EvaluatedIndividual<OneMaxIndividual>>(5, EvaluatedMutation.range()).none { it.evaluatedResult == null || it.evaluatedResult == EvaluatedMutation.WORSE_THAN })
}
// enable tracking individual and but disable evaluated individual
@Test
fun testEvaluatedOneMaxIndividualWithFT(){
config.enableTrackEvaluatedIndividual = false
config.enableTrackIndividual = true
config.stoppingCriterion = EMConfig.StoppingCriterion.FITNESS_EVALUATIONS
config.probOfArchiveMutation = 0.0
config.weightBasedMutationRate = false
tracker.postConstruct()
val inds10 = (0 until 10).map { ff.calculateCoverage(sampler.sample())!!.also { archive.addIfNeeded(it) } }
assert(inds10.all { it.trackOperator != null && it.tracking == null})
val eval = mutator.mutateAndSave(10, inds10[1], archive)
assertNull(eval.tracking)
assertNotNull(eval.individual.tracking)
assertEquals(10, eval.individual.tracking!!.history.size)
}
} | core/src/test/kotlin/org/evomaster/core/search/service/track/TraceableElementTest.kt | 4148992038 |
package io.oversec.one.crypto.encoding
import io.oversec.one.crypto.encoding.pad.AbstractPadder
import java.io.IOException
import java.io.OutputStream
class ExtendedPaneStringMapperOutputStream(
private val mapping: Array<CharArray>,
private val padder: AbstractPadder?,
private val spread: Int
) : OutputStream() {
private val buf = StringBuilder()
private var cntInvisibleChars = 0
val encoded: String
get() = buf.toString()
@Throws(IOException::class)
override fun write(oneByte: Int) {
buf.append(mapping[oneByte and 0xFF])
cntInvisibleChars++
if (padder != null && spread > 0 && cntInvisibleChars > spread) {
buf.append(padder.nextPaddingChar)
cntInvisibleChars = 0
}
}
}
| crypto/src/main/java/io/oversec/one/crypto/encoding/ExtendedPaneStringMapperOutputStream.kt | 839666522 |
package io.oversec.one.crypto
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
object Help {
enum class ANCHOR {
encparams_pgp,
encparams_simple,
encparams_sym,
main_help,
main_apps,
main_keys,
main_help_acsconfig,
symkey_create_pbkdf,
symkey_create_random,
symkey_create_scan,
symkey_details,
appconfig_main,
appconfig_appearance,
appconfig_lab,
button_hide_visible,
button_hide_hidden, main_settings,
button_encrypt_initial,
button_encrypt_encryptionparamsremembered,
input_insufficientpadding,
input_corruptedencoding,
bossmode_active, main_padders, settextfailed, button_compose, paste_clipboard, main_help_accessibilitysettingsnotresolvable
}
fun open(ctx: Context, anchor: ANCHOR?) {
open(ctx, anchor?.name)
}
@JvmOverloads
fun open(ctx: Context, anchor: String? = null) {
try {
var url = anchor
if (url == null || !url.startsWith(getUrlIndex(ctx))) {
url = getUrlIndex(ctx) + if (anchor == null) "" else "#alias_$anchor"
}
val i = Intent(Intent.ACTION_VIEW)
i.data = Uri.parse(url)
//if (!(ctx instanceof Activity))
run { i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK) }
ctx.startActivity(i)
} catch (e: Exception) {
e.printStackTrace()
}
}
private fun getUrlIndex(ctx: Context): String {
return "http://" + ctx.getString(R.string.feature_help_host) + "/index.html"
}
@Throws(PackageManager.NameNotFoundException::class)
fun getAnchorForPackageInfos(ctx: Context, packagename: String): String {
val packageInfo = ctx.packageManager.getPackageInfo(packagename, 0)
val versionNumber = packageInfo.versionCode
val packageNameReplaced = packagename.replace('.', '-')
return getUrlIndex(ctx) + "#package_" + packageNameReplaced + "$" + versionNumber
}
fun openForPackage(ctx: Context, packagename: String?) {
if (packagename == null) return
try {
val url = getAnchorForPackageInfos(ctx, packagename)
val i = Intent(Intent.ACTION_VIEW)
i.data = Uri.parse(url)
if (ctx !is Activity) {
i.flags = Intent.FLAG_ACTIVITY_NEW_TASK
}
ctx.startActivity(i)
} catch (e: Exception) {
e.printStackTrace()
}
}
fun getApplicationName(ctx: Context, packagename: String): CharSequence {
return try {
val ai = ctx.packageManager.getApplicationInfo(packagename, 0)
ctx.packageManager.getApplicationLabel(ai)
} catch (e: PackageManager.NameNotFoundException) {
packagename
}
}
}
| crypto/src/main/java/io/oversec/one/crypto/Help.kt | 323668846 |
package org.evomaster.core.problem.rest.service.resource.model
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Test
interface ResourceBasedTestInterface {
/**
* it is mandatory to test whether resource cluster is initialized correctly
*/
fun testInitializedNumOfResourceCluster()
/**
* it is mandatory to test whether templates are initialized correctly
*/
fun testInitializedTemplatesForResources()
/**
* it is mandatory to test whether applicable resource-based sampling methods are initialized correctly
*/
fun testApplicableMethods()
/**
* it is not always required to test whether applicable methods is initialized correctly with specific setting
*/
fun testApplicableMethodsForNoneDependentResource() {}
/**
* it is not always required to test whether applicable methods is initialized correctly with specific setting
*/
fun testApplicableMethodsForOneDependentResource() {}
/**
* it is not always required to test whether applicable methods is initialized correctly with specific setting
*/
fun testApplicableMethodsForTwoDependentResource() {}
/**
* it is not always required to test whether applicable methods is initialized correctly with specific setting
*/
fun testApplicableMethodsForMoreThanTwoDependentResource() {}
/**
* it is mandatory to test whether an individual is sampled correctly using resource-based sampling method
*/
fun testResourceIndividualWithSampleMethods()
/**
* it is mandatory to test the binding functionality among rest actions
*/
fun testBindingValuesAmongRestActions()
/**
* it is mandatory to test relationship between resources and tables
*/
fun testResourceRelatedToTable()
/**
* it is mandatory to test binding functionality between rest action and db action
*/
fun testBindingValueBetweenRestActionAndDbAction()
/**
* it is mandatory to test whether the dependency is initialized properly
*/
fun testDependencyAmongResources()
/**
* it is mandatory to test S2dR sampling method with a consideration of dependency
*/
fun testS2dRWithDependency()
/**
* it is mandatory to test Resource Rest Structure
*/
fun testResourceStructureMutator()
/**
* it is mandatory to test Resource Rest Structure with dependency
*/
fun testResourceStructureMutatorWithDependency()
/**
* it is mandatory to test derivation of dependency with fitness
*/
fun testDerivationOfDependency()
/*************** integrated tests regarding a setting *************************/
fun setupWithoutDatabaseAndDependency()
@Test
fun testInitializedResourceClusterAndApplicableSampleMethods(){
setupWithoutDatabaseAndDependency()
testInitializedNumOfResourceCluster()
testInitializedTemplatesForResources()
testApplicableMethods()
testResourceIndividualWithSampleMethods()
testBindingValuesAmongRestActions()
testResourceStructureMutator()
}
fun setupWithDatabaseAndNameAnalysis()
@Disabled("issue with DB action refactoring")
@Test
fun testWithDatabaseAndNameAnalysis(){
setupWithDatabaseAndNameAnalysis()
testResourceRelatedToTable()
testBindingValueBetweenRestActionAndDbAction()
}
fun setupWithDatabaseAndDependencyAndNameAnalysis()
@Test
fun testWithDependencyAndNameAnalysis(){
setupWithDatabaseAndDependencyAndNameAnalysis()
testDependencyAmongResources()
testS2dRWithDependency()
//testResourceStructureMutatorWithDependency()
testDerivationOfDependency()
}
} | core-it/src/test/kotlin/org/evomaster/core/problem/rest/service/resource/model/ResourceBasedTestInterface.kt | 2786423797 |
package day17
fun main(args: Array<String>) {
var buffer = mutableListOf(0)
val steps = 376
var index = 0
for (i in 1..2017) {
index = (index + steps) % i
val l = buffer.toList()
buffer = l.subList(0, index + 1).toMutableList()
buffer.add(i)
buffer.addAll(l.subList(index + 1, l.size).toMutableList())
index++
}
println(buffer[buffer.indexOf(2017) + 1])
} | 2017/src/day17/part01.kt | 3217408340 |
package site.yanglong.promotion.controller
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.stereotype.Controller
/**
*
*
* 前端控制器
*
*
* @author Dr.YangLong
* @since 2017-11-01
*/
@Controller
@RequestMapping("/resources")
class ResourcesController
| src/main/kotlin/site/yanglong/promotion/controller/ResourcesController.kt | 2099893308 |
package trypp.support.time
import trypp.support.memory.Poolable
import trypp.support.time.Duration.Companion.of
import trypp.support.time.Duration.Companion.ofMilliseconds
import trypp.support.time.Duration.Companion.ofMinutes
import trypp.support.time.Duration.Companion.ofSeconds
/**
* An class which represents a time duration.
*/
data class Duration
/**
* Don't construct directly. Use [ofSeconds], [ofMinutes], [ofMilliseconds], or [of]
* instead.
*/
internal constructor(private var milliseconds: Float = 0f) : Poolable {
fun getMilliseconds(): Float {
return milliseconds
}
fun setMilliseconds(milliseconds: Float): Duration {
this.milliseconds = if (milliseconds > 0f) milliseconds else 0f
return this
}
fun getSeconds(): Float {
return milliseconds / 1000f
}
fun setSeconds(seconds: Float): Duration {
setMilliseconds(seconds * 1000f)
return this
}
fun getMinutes(): Float {
return getSeconds() / 60f
}
fun setMinutes(minutes: Float): Duration {
setSeconds(minutes * 60f)
return this
}
fun setFrom(duration: Duration): Duration {
milliseconds = duration.milliseconds
return this
}
fun addMilliseconds(milliseconds: Float): Duration {
setMilliseconds(getMilliseconds() + milliseconds)
return this
}
fun addSeconds(secs: Float): Duration {
setSeconds(getSeconds() + secs)
return this
}
fun addMinutes(minutes: Float): Duration {
setMinutes(getMinutes() + minutes)
return this
}
fun add(duration: Duration): Duration {
setMilliseconds(getMilliseconds() + duration.getMilliseconds())
return this
}
fun subtractMilliseconds(milliseconds: Float): Duration {
setMilliseconds(getMilliseconds() - milliseconds)
return this
}
fun subtractSeconds(secs: Float): Duration {
setSeconds(getSeconds() - secs)
return this
}
fun subtractMinutes(minutes: Float): Duration {
setMinutes(getMinutes() - minutes)
return this
}
fun subtract(duration: Duration): Duration {
setMilliseconds(getMilliseconds() - duration.getMilliseconds())
return this
}
fun setZero(): Duration {
setMilliseconds(0f)
return this
}
val isZero: Boolean
get() = milliseconds == 0f
/**
* Overridden from [Poolable]. Prefer using [setZero] instead for readability.
*/
override fun reset() {
setZero()
}
override fun toString(): String {
return "${getSeconds()}s"
}
companion object {
fun zero(): Duration {
return Duration()
}
fun ofSeconds(secs: Float): Duration {
val duration = Duration()
duration.setSeconds(secs)
return duration
}
fun ofMinutes(minutes: Float): Duration {
val duration = Duration()
duration.setMinutes(minutes)
return duration
}
fun ofMilliseconds(milliseconds: Float): Duration {
val duration = Duration()
duration.setMilliseconds(milliseconds)
return duration
}
fun of(duration: Duration): Duration {
val clonedDuration = Duration()
clonedDuration.setFrom(duration)
return clonedDuration
}
}
}
| src/main/code/trypp/support/time/Duration.kt | 181385795 |
package org.januson.kaktus.core
/**
* Created by Januson on 28.01.2017.
*/
//HTTP/1.1 204 No Content
//Tus-Resumable: 1.0.0
//Tus-Version: 1.0.0,0.2.2,0.2.1
//Tus-Max-Size: 1073741824
//Tus-Extension: creation,expiration
data class TusServerInfo(val version: Set<String>) | src/main/kotlin/org/januson/kaktus/core/TusServerInfo.kt | 3017504254 |
package kscript.app.parser
class ParseException(exceptionMessage: String) : RuntimeException(exceptionMessage)
| src/main/kotlin/kscript/app/parser/ParseException.kt | 2202013742 |
/*
* Copyright 2016 Blue Box Ware
*
* 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.gmail.blueboxware.libgdxplugin.inspections.java
import com.gmail.blueboxware.libgdxplugin.message
import com.gmail.blueboxware.libgdxplugin.utils.TEST_ID_MAP
import com.gmail.blueboxware.libgdxplugin.utils.isStringType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.JavaElementVisitor
import com.intellij.psi.PsiLiteralExpression
import com.intellij.psi.impl.source.tree.java.PsiLiteralExpressionImpl
import com.intellij.psi.util.PsiLiteralUtil
class JavaTestIdsInspection : LibGDXJavaBaseInspection() {
override fun getStaticDescription() = message("testid.html.description")
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : JavaElementVisitor() {
override fun visitLiteralExpression(expression: PsiLiteralExpression?) {
if (expression is PsiLiteralExpressionImpl && expression.type.isStringType(expression)) {
PsiLiteralUtil.getStringLiteralContent(expression)?.trim().let { value ->
if (TEST_ID_MAP.containsKey(value)) {
holder.registerProblem(
expression,
message("testid.problem.descriptor") + ": " + TEST_ID_MAP[value]
)
}
}
}
}
}
}
| src/main/kotlin/com/gmail/blueboxware/libgdxplugin/inspections/java/JavaTestIdsInspection.kt | 3182957218 |
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.expectedgeneratedtypes
import com.google.android.libraries.pcc.chronicle.api.DeletionTrigger
import com.google.android.libraries.pcc.chronicle.api.FieldType
import com.google.android.libraries.pcc.chronicle.api.ManagementStrategy
import com.google.android.libraries.pcc.chronicle.api.StorageMedia
import com.google.android.libraries.pcc.chronicle.api.Trigger
import com.google.android.libraries.pcc.chronicle.api.dataTypeDescriptor
import com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.annotatedtypes.ExampleKotlinOpaqueType
import com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.annotatedtypes.ExampleKotlinType
import com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.annotatedtypes.ExampleKotlinTypeReadWriter
import com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.annotatedtypes.ExampleKotlinTypeReader
import com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.annotatedtypes.ExampleKotlinTypeReaderWithDataCache
import com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.annotatedtypes.ExampleKotlinTypeWriter
import com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.annotatedtypes.ExampleKotlinTypeWriterWithDataCache
import com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.annotatedtypes.ExampleNestedKotlinType
import com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.annotatedtypes.ExampleSelfReferentialKotlinType
import java.time.Duration
@JvmField
val EXPECTED_EXAMPLE_KOTLIN_TYPE_GENERATED_DTD =
dataTypeDescriptor(ExampleKotlinType::class.qualifiedName!!, cls = ExampleKotlinType::class) {
"name" to FieldType.String
"amount" to FieldType.Integer
"others" to FieldType.List(FieldType.String)
"updateTime" to FieldType.Instant
"timeSinceLastOpen" to FieldType.Duration
"featuresEnabled" to
FieldType.List(
dataTypeDescriptor(name = "MapStringValueToBooleanValue", Map.Entry::class) {
"key" to FieldType.String
"value" to FieldType.Boolean
}
)
"nickName" to FieldType.Nullable(FieldType.String)
"categoryAndScore" to FieldType.Tuple(listOf(FieldType.String, FieldType.Double))
"threeThings" to FieldType.Tuple(listOf(FieldType.String, FieldType.Double, FieldType.Boolean))
"status" to
FieldType.Enum(
"com.google.android.libraries.pcc.chronicle.codegen.processor.testdata." +
"annotatedtypes.ExampleKotlinType.Status",
listOf("ON", "OFF", "UNKNOWN")
)
}
@JvmField
val EXPECTED_EXAMPLE_NESTED_KOTLIN_TYPE_GENERATED_DTD =
dataTypeDescriptor(
ExampleNestedKotlinType::class.qualifiedName!!,
cls = ExampleNestedKotlinType::class
) {
"name" to FieldType.String
"nested" to
dataTypeDescriptor(ExampleKotlinType::class.qualifiedName!!, cls = ExampleKotlinType::class) {
"name" to FieldType.String
"amount" to FieldType.Integer
"others" to FieldType.List(FieldType.String)
"updateTime" to FieldType.Instant
"timeSinceLastOpen" to FieldType.Duration
"featuresEnabled" to
FieldType.List(
dataTypeDescriptor(name = "MapStringValueToBooleanValue", Map.Entry::class) {
"key" to FieldType.String
"value" to FieldType.Boolean
}
)
"nickName" to FieldType.Nullable(FieldType.String)
"categoryAndScore" to FieldType.Tuple(listOf(FieldType.String, FieldType.Double))
"threeThings" to
FieldType.Tuple(listOf(FieldType.String, FieldType.Double, FieldType.Boolean))
"status" to
FieldType.Enum(
"com.google.android.libraries.pcc.chronicle.codegen.processor.testdata." +
"annotatedtypes.ExampleKotlinType.Status",
listOf("ON", "OFF", "UNKNOWN")
)
}
}
@JvmField
val EXPECTED_EXAMPLE_KOTLIN_OPAQUE_TYPE_GENERATED_DTD =
dataTypeDescriptor(
ExampleKotlinOpaqueType::class.qualifiedName!!,
cls = ExampleKotlinOpaqueType::class
) {
"name" to FieldType.String
"iBinder" to FieldType.Opaque("android.os.IBinder")
"activityId" to FieldType.Opaque("android.app.assist.ActivityId")
}
@JvmField
val EXPECTED_EXAMPLE_SELF_REFERENTIAL_KOTLIN_TYPE_GENERATED_DTD =
dataTypeDescriptor(
ExampleSelfReferentialKotlinType::class.qualifiedName!!,
cls = ExampleSelfReferentialKotlinType::class
) {
"children" to
FieldType.List(FieldType.Reference(ExampleSelfReferentialKotlinType::class.qualifiedName!!))
}
val EXPECTED_EXAMPLE_KOTLIN_TYPE_GENERATED_CONNECTIONS =
setOf(
ExampleKotlinTypeReader::class.java,
ExampleKotlinTypeWriter::class.java,
ExampleKotlinTypeReadWriter::class.java,
ExampleKotlinTypeReaderWithDataCache::class.java,
ExampleKotlinTypeWriterWithDataCache::class.java,
)
val EXPECTED_EXAMPLE_KOTLIN_TYPE_GENERATED_MAX_ITEMS = 1000
val EXPECTED_EXAMPLE_KOTLIN_TYPE_GENERATED_DATA_CACHE_STORE_MANAGEMENT_STRATEGY =
ManagementStrategy.Stored(
encrypted = false,
media = StorageMedia.MEMORY,
ttl = Duration.ofDays(2),
deletionTriggers = setOf(DeletionTrigger(Trigger.PACKAGE_UNINSTALLED, "packageName")),
)
| javatests/com/google/android/libraries/pcc/chronicle/codegen/processor/testdata/expectedgeneratedtypes/ExpectedKotlinGeneratedDtd.kt | 184087798 |
/*
* Notes Copyright (C) 2018 Nikhil Soni
* This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
* This is free software, and you are welcome to redistribute it
* under certain conditions; type `show c' for details.
*
* The hypothetical commands `show w' and `show c' should show the appropriate
* parts of the General Public License. Of course, your program's commands
* might be different; for a GUI interface, you would use an "about box".
*
* You should also get your employer (if you work as a programmer) or school,
* if any, to sign a "copyright disclaimer" for the program, if necessary.
* For more information on this, and how to apply and follow the GNU GPL, see
* <http://www.gnu.org/licenses/>.
*
* The GNU General Public License does not permit incorporating your program
* into proprietary programs. If your program is a subroutine library, you
* may consider it more useful to permit linking proprietary applications with
* the library. If this is what you want to do, use the GNU Lesser General
* Public License instead of this License. But first, please read
* <http://www.gnu.org/philosophy/why-not-lgpl.html>.
*/
package com.nrs.nsnik.notes.view.fragments
import android.annotation.SuppressLint
import android.app.SearchManager
import android.content.Context
import android.os.Bundle
import android.view.*
import androidx.appcompat.widget.SearchView
import androidx.fragment.app.Fragment
import com.nrs.nsnik.notes.R
//TODO
class SearchFragment : Fragment() {
private lateinit var searchView: SearchView
private lateinit var searchItem: MenuItem
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_search, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
inflater?.inflate(R.menu.main_menu, menu)
searchView = menu?.findItem(R.id.menuMainSearch)?.actionView as SearchView
searchItem = menu.findItem(R.id.menuMainSearch)
searchView.setSearchableInfo((activity?.getSystemService(Context.SEARCH_SERVICE) as SearchManager).getSearchableInfo(activity!!.componentName))
menuListener()
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
R.id.menuMainSearch -> {
}
}
return super.onOptionsItemSelected(item)
}
@SuppressLint("CheckResult")
private fun menuListener() {
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String?): Boolean {
return true
}
override fun onQueryTextChange(newText: String?): Boolean {
return true
}
})
searchItem.setOnActionExpandListener(object : MenuItem.OnActionExpandListener {
override fun onMenuItemActionExpand(menuItem: MenuItem?): Boolean {
return true
}
override fun onMenuItemActionCollapse(menuItem: MenuItem?): Boolean {
return true
}
})
}
}
| app/src/main/java/com/nrs/nsnik/notes/view/fragments/SearchFragment.kt | 78347790 |
package org.worshipsongs.dialog
import android.app.Dialog
import android.os.Bundle
import android.view.ContextThemeWrapper
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import org.worshipsongs.CommonConstants
import org.worshipsongs.R
import org.worshipsongs.domain.SongDragDrop
import org.worshipsongs.service.FavouriteService
/**
* Author: Seenivasan, Madasamy
* version :1.0.0
*/
class FavouritesDialogFragment : DialogFragment()
{
private val favouriteService = FavouriteService()
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog
{
val names = favouriteService.findNames()
names.add(0, "New favourite...")
val builder = AlertDialog.Builder(ContextThemeWrapper(activity, R.style.DialogTheme))
builder.setTitle(getString(R.string.addToPlayList))
builder.setItems(names.toTypedArray()) { dialog, which -> [email protected](which, names) }
return builder.create()
}
private fun onClick(which: Int, names: List<String>)
{
val args = arguments
val songName = args!!.getString(CommonConstants.TITLE_KEY)
val localisedName = args.getString(CommonConstants.LOCALISED_TITLE_KEY)
val id = args.getInt(CommonConstants.ID)
if (which == 0)
{
val addFavouritesDialogFragment = AddFavouritesDialogFragment.newInstance(args)
addFavouritesDialogFragment.show(activity!!.supportFragmentManager, AddFavouritesDialogFragment::class.java.simpleName)
} else
{
val songDragDrop = SongDragDrop(id.toLong(), songName, false)
songDragDrop.tamilTitle = localisedName
favouriteService.save(names[which], songDragDrop)
Toast.makeText(activity, "Song added to favourite...!", Toast.LENGTH_LONG).show()
}
}
companion object
{
fun newInstance(bundle: Bundle): FavouritesDialogFragment
{
val favouritesDialogFragment = FavouritesDialogFragment()
favouritesDialogFragment.arguments = bundle
return favouritesDialogFragment
}
}
}
| app/src/main/java/org/worshipsongs/dialog/FavouritesDialogFragment.kt | 3017165605 |
/*******************************************************************************
* *
* Copyright (C) 2017 by Max Lv <[email protected]> *
* Copyright (C) 2017 by Mygod Studio <[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.github.shadowsocks.plugin
import android.content.Intent
/**
* HelpCallback is an HelpActivity but you just need to produce a CharSequence help message instead of having to
* provide UI. To create a help callback, just extend this class, implement abstract methods, and add it to your
* manifest following the same procedure as adding a HelpActivity.
*/
abstract class HelpCallback : HelpActivity() {
abstract fun produceHelpMessage(options: PluginOptions): CharSequence
override fun onInitializePluginOptions(options: PluginOptions) {
setResult(RESULT_OK, Intent().putExtra(PluginContract.EXTRA_HELP_MESSAGE, produceHelpMessage(options)))
finish()
}
}
| plugin/src/main/java/com/github/shadowsocks/plugin/HelpCallback.kt | 143310618 |
/*
* Copyright 2020 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.auctions.bukkit.event.auction
interface RPKAuctionBiddingCloseEvent : RPKAuctionEvent | bukkit/rpk-auction-lib-bukkit/src/main/kotlin/com/rpkit/auctions/bukkit/event/auction/RPKAuctionBiddingCloseEvent.kt | 2167546910 |
/*
* Copyright (C) 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 com.example.inventory.data
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
/**
* Database class with a singleton INSTANCE object.
*/
@Database(entities = [Item::class], version = 1, exportSchema = false)
abstract class ItemRoomDatabase : RoomDatabase() {
abstract fun itemDao(): ItemDao
companion object {
@Volatile
private var INSTANCE: ItemRoomDatabase? = null
fun getDatabase(context: Context): ItemRoomDatabase {
// if the INSTANCE is not null, then return it,
// if it is, then create the database
return INSTANCE ?: synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
ItemRoomDatabase::class.java,
"item_database"
)
// Wipes and rebuilds instead of migrating if no Migration object.
// Migration is not part of this codelab.
.fallbackToDestructiveMigration()
.build()
INSTANCE = instance
// return instance
instance
}
}
}
} | app/src/main/java/com/example/inventory/data/ItemRoomDatabase.kt | 1361980858 |
/**
* Created by ice1000 on 2017/2/26.
*
* @author ice1000
* @since 1.0.0
*/
package org.lice
import org.lice.core.SymbolList
import org.lice.parse.Lexer
import org.lice.parse.Parser
import org.lice.util.InterpretException
import org.lice.util.ParseException
import java.io.File
import java.nio.file.*
object Lice {
@JvmOverloads
@JvmStatic
@Deprecated("Use nio instead", ReplaceWith("run(Paths.get(file.toURI()), symbolList)", "org.lice.Lice.run", "java.nio.file.Paths"))
fun run(file: File, symbolList: SymbolList = SymbolList()) = run(Paths.get(file.toURI()), symbolList)
@JvmOverloads
@JvmStatic
fun run(file: Path, symbolList: SymbolList = SymbolList()) = run(String(Files.readAllBytes(file)), symbolList)
@JvmOverloads
@JvmStatic
fun run(code: String, symbolList: SymbolList = SymbolList()): Any? {
try {
return Parser.parseTokenStream(Lexer(code)).accept(symbolList).eval()
} catch (e: ParseException) {
e.prettyPrint(code.split("\n"))
} catch (e: InterpretException) {
e.prettyPrint(code.split("\n"))
}
return null
}
@JvmOverloads
@JvmStatic
fun runBarely(code: String, symbolList: SymbolList = SymbolList()) =
Parser.parseTokenStream(Lexer(code)).accept(symbolList).eval()
}
| src/main/kotlin/org/lice/Lice.kt | 3414586187 |
package ii_collections
import util.TODO
fun todoCollectionTask(): Nothing = TODO(
"""
Common task for working with collections.
Look through the Shop API, which all the tasks are using.
Each individual task is described in the function name and the comment.
""",
references = { shop: Shop -> shop.customers }
)
| src/ii_collections/todoUtil.kt | 3656599553 |
package coil
import android.app.Application
/**
* A factory that creates new [ImageLoader] instances.
*
* To configure how the singleton [ImageLoader] is created **either**:
* - Implement [ImageLoaderFactory] in your [Application].
* - **Or** call [Coil.setImageLoader] with your [ImageLoaderFactory].
*/
fun interface ImageLoaderFactory {
/**
* Return a new [ImageLoader].
*/
fun newImageLoader(): ImageLoader
}
| coil-singleton/src/main/java/coil/ImageLoaderFactory.kt | 2688929505 |
package com.bastien7.transport.analyzer.park.service.implement
import com.bastien7.transport.analyzer.configuration.DataParameters
import com.bastien7.transport.analyzer.park.entity.Park
import com.bastien7.transport.analyzer.park.entity.ParkState
import com.bastien7.transport.analyzer.park.entityTFL.ParkTFL
import com.bastien7.transport.analyzer.park.repository.ParkStateRepository
import com.bastien7.transport.analyzer.park.service.ParkStateService
import com.bastien7.transport.analyzer.park.service.externalApi.ParkTflApi
import log
import org.springframework.stereotype.Component
import java.time.LocalDateTime
@Component
class ParkStateServiceImpl(val parkTflApi: ParkTflApi, val parkStateRepository: ParkStateRepository) : ParkStateService {
val log = log()
//@Scheduled(cron = "0 */" + DataParameters.DUMP_FREQUENCY + " * * * *")
override fun collectTflData() {
val apiResponse = parkTflApi.getAllParksTfl()
val parks = apiResponse.map { it.toPark() }
val parkState = ParkState(parks)
parkStateRepository.save(parkState)
log.info("Data collected from TFL api")
}
override fun getAllParksTfl(): List<ParkTFL> = parkTflApi.getAllParksTfl().sortedBy { it.properties.name }
override fun getAllParks(): List<Park> = parkTflApi.getAllParksTfl().map { it.toPark() }.sortedBy { it.name }
override fun getAllParkStates(): List<ParkState> = parkStateRepository.findAll().sortedBy { it.date }
override fun getParkState(date: LocalDateTime): ParkState? {
val reference: LocalDateTime = date.withSecond(0)
val result = parkStateRepository.findByDateBetween(
reference.minusMinutes((DataParameters.DUMP_FREQUENCY / 2).toLong()),
reference.plusMinutes((DataParameters.DUMP_FREQUENCY / 2).toLong())
)
return if (result.isEmpty()) null else result.first()
}
} | src/main/com/bastien7/transport/analyzer/park/service/implement/ParkStateServiceImpl.kt | 1184329581 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.viewbasedfeedlayoutsample
import android.os.Bundle
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.updateLayoutParams
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.setupActionBarWithNavController
import com.example.viewbasedfeedlayoutsample.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var appBarConfiguration: AppBarConfiguration
private lateinit var binding: ActivityMainBinding
private lateinit var navController: NavController
override fun onCreate(savedInstanceState: Bundle?) {
WindowCompat.setDecorFitsSystemWindows(window, false)
super.onCreate(savedInstanceState)
setupContentView()
setupActionBar()
}
override fun onSupportNavigateUp(): Boolean {
return navController.navigateUp(appBarConfiguration) ||
super.onSupportNavigateUp()
}
private fun setupContentView() {
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
ViewCompat.setOnApplyWindowInsetsListener(binding.root) { view, windowInsets ->
val insets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars())
view.updateLayoutParams<ViewGroup.MarginLayoutParams> {
topMargin = insets.top
leftMargin = insets.left
bottomMargin = insets.bottom
rightMargin = insets.right
}
WindowInsetsCompat.CONSUMED
}
}
private fun setupActionBar() {
setSupportActionBar(binding.toolbar)
navController =
(supportFragmentManager.findFragmentById(R.id.body) as NavHostFragment).navController
appBarConfiguration = AppBarConfiguration(navController.graph)
setupActionBarWithNavController(navController, appBarConfiguration)
}
}
| CanonicalLayouts/feed-view/app/src/main/java/com/example/viewbasedfeedlayoutsample/MainActivity.kt | 3478484393 |
package org.luxons.sevenwonders.engine.cards
import org.junit.Assume.assumeTrue
import org.junit.Test
import org.junit.experimental.theories.DataPoints
import org.junit.experimental.theories.FromDataPoints
import org.junit.experimental.theories.Theories
import org.junit.experimental.theories.Theory
import org.junit.runner.RunWith
import org.luxons.sevenwonders.engine.SimplePlayer
import org.luxons.sevenwonders.engine.test.sampleCards
import org.luxons.sevenwonders.engine.test.testTable
import org.luxons.sevenwonders.model.cards.HandRotationDirection
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertTrue
@RunWith(Theories::class)
class HandsTest {
@Test
fun get_failsOnMissingPlayer() {
val hands = createHands(4, 7)
assertFailsWith<IndexOutOfBoundsException> { hands[5] }
}
@Test
fun get_retrievesCorrectCards() {
val hand0 = sampleCards(5, 0)
val hand1 = sampleCards(10, 5)
val hands = Hands(listOf(hand0, hand1))
assertEquals(hand0, hands[0])
assertEquals(hand1, hands[1])
}
@Theory
fun isEmpty_falseWhenAtLeast1_allSame(
@FromDataPoints("nbPlayers") nbPlayers: Int,
@FromDataPoints("nbCardsPerPlayer") nbCardsPerPlayer: Int,
) {
assumeTrue(nbCardsPerPlayer >= 1)
val hands = createHands(nbPlayers, nbCardsPerPlayer)
assertFalse(hands.isEmpty)
}
@Theory
fun isEmpty_trueWhenAllEmpty(@FromDataPoints("nbPlayers") nbPlayers: Int) {
val hands = createHands(nbPlayers, 0)
assertTrue(hands.isEmpty)
}
@Theory
fun maxOneCardRemains_falseWhenAtLeast2_allSame(
@FromDataPoints("nbPlayers") nbPlayers: Int,
@FromDataPoints("nbCardsPerPlayer") nbCardsPerPlayer: Int,
) {
assumeTrue(nbCardsPerPlayer >= 2)
val hands = createHands(nbPlayers, nbCardsPerPlayer)
assertFalse(hands.maxOneCardRemains())
}
@Theory
fun maxOneCardRemains_trueWhenAtMost1_allSame(
@FromDataPoints("nbPlayers") nbPlayers: Int,
@FromDataPoints("nbCardsPerPlayer") nbCardsPerPlayer: Int,
) {
assumeTrue(nbCardsPerPlayer <= 1)
val hands = createHands(nbPlayers, nbCardsPerPlayer)
assertTrue(hands.maxOneCardRemains())
}
@Theory
fun maxOneCardRemains_trueWhenAtMost1_someZero(@FromDataPoints("nbPlayers") nbPlayers: Int) {
val hands = createHands(nbPlayers, 1)
assertTrue(hands.maxOneCardRemains())
}
@Test
fun rotate_movesOfCorrectOffset_right() {
val hands = createHands(3, 7)
val rotated = hands.rotate(HandRotationDirection.RIGHT)
assertEquals(rotated[1], hands[0])
assertEquals(rotated[2], hands[1])
assertEquals(rotated[0], hands[2])
}
@Test
fun rotate_movesOfCorrectOffset_left() {
val hands = createHands(3, 7)
val rotated = hands.rotate(HandRotationDirection.LEFT)
assertEquals(rotated[2], hands[0])
assertEquals(rotated[0], hands[1])
assertEquals(rotated[1], hands[2])
}
@Test
fun createHand_containsAllCards() {
val hand0 = sampleCards(5, 0)
val hand1 = sampleCards(10, 5)
val hands = Hands(listOf(hand0, hand1))
val table = testTable(2)
val hand = hands.createHand(SimplePlayer(0, table))
assertEquals(hand0.map { it.name }, hand.map { it.name })
}
companion object {
@JvmStatic
@DataPoints("nbCardsPerPlayer")
fun nbCardsPerPlayer(): IntArray {
return intArrayOf(0, 1, 2, 3, 4, 5, 6, 7)
}
@JvmStatic
@DataPoints("nbPlayers")
fun nbPlayers(): IntArray {
return intArrayOf(3, 4, 5, 6, 7)
}
private fun createHands(nbPlayers: Int, nbCardsPerPlayer: Int): Hands {
return sampleCards(nbCardsPerPlayer * nbPlayers, 0).deal(nbPlayers)
}
}
}
| sw-engine/src/test/kotlin/org/luxons/sevenwonders/engine/cards/HandsTest.kt | 1989587757 |
package com.bracketcove.postrainer
import com.bracketcove.postrainer.dependencyinjection.AndroidMovementProvider
import com.bracketcove.postrainer.movement.MovementContract
import com.bracketcove.postrainer.movement.MovementEvent
import com.bracketcove.postrainer.movement.MovementLogic
import com.wiseassblog.common.ResultWrapper
import com.wiseassblog.domain.domainmodel.Movement
import com.wiseassblog.domain.repository.IMovementRepository
import io.mockk.*
import kotlinx.coroutines.Dispatchers
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
class MovementLogicTest {
val repo: IMovementRepository = mockk()
val view: MovementContract.View = mockk(relaxed = true)
val viewModel: MovementContract.ViewModel = mockk()
val provider: AndroidMovementProvider = mockk()
val logic = MovementLogic(view, viewModel, provider, Dispatchers.Unconfined)
val IMAGE_RESOURCE_ONE = "im_passive_one"
val IMAGE_RESOURCE_TWO = "im_passive_two"
val IMAGE_RESOURCE_THREE = "im_passive_three"
private fun getMovement() = Movement(
"Passive Hang",
listOf("Chest, Shoulders, Arms, Back"),
"2 Sets/Day",
"30-60 Seconds",
true,
listOf(IMAGE_RESOURCE_ONE, IMAGE_RESOURCE_TWO, IMAGE_RESOURCE_THREE),
"Easy",
"www.youtube.com",
"description_passive_hang",
"instruction_passive_hang"
)
@BeforeEach
fun setUp() {
clearAllMocks()
every { provider.movementRepository } returns repo
}
/**
* OnStart: Get the appropriate Movement from the backend based on the ID passed in for OnStart. If successful, the
* next step is to call every function on the Fragment with the appropriate data, à la Martin Fowler's Passive View.
*/
@Test
fun `On Start valid arguments`() {
val MOVEMENT = getMovement()
coEvery { repo.getMovementById(MOVEMENT.name) } returns ResultWrapper.build { MOVEMENT }
logic.handleEvent(MovementEvent.OnStart(MOVEMENT.name))
coVerify(exactly = 1) { repo.getMovementById(MOVEMENT.name) }
coVerify(exactly = 1) { viewModel.setMovement(MOVEMENT) }
verify(exactly = 1) { view.setTootlbarTitle(MOVEMENT.name) }
verify(exactly = 1) { view.setParallaxImage(MOVEMENT.imageResourceNames[0]) }
verify(exactly = 1) { view.setTargets(MOVEMENT.targets) }
verify(exactly = 1) { view.setFrequency(MOVEMENT.frequency) }
verify(exactly = 1) { view.setIsTimed(MOVEMENT.isTimeBased) }
verify(exactly = 1) { view.setTimeOrRepetitions(MOVEMENT.timeOrRepetitions) }
verify(exactly = 1) { view.setDifficulty(MOVEMENT.difficulty) }
verify(exactly = 1) { view.setDescription(MOVEMENT.description) }
verify(exactly = 1) { view.setInstructions(MOVEMENT.instructions) }
verify(exactly = 1) { view.hideProgressBar() }
}
@Test
fun `On Start invalid arguments`() {
logic.handleEvent(MovementEvent.OnStart(""))
verify { view.showMessage(ERROR_GENERIC) }
verify { view.startMovementListView() }
}
/**
* When the user clicks on the parallax image, we want to cycle to the next image.
* ViewModel Tracks it's own index
*
* 1. Request list of imageResources from ViewModel
* 2. Request current index from ViewModel
* 3a. If list has next available image, get that (index +1)
* 4a. Give to the view
*/
@Test
fun `on Parallax Image Click has next`() {
val MOVEMENT = getMovement()
val INDEX = 0
every { viewModel.getCurrentIndex() } returns INDEX
every { viewModel.getMovement() } returns MOVEMENT
every { viewModel.getImageResource(INDEX + 1) } returns MOVEMENT.imageResourceNames[1]
logic.handleEvent(MovementEvent.OnImageClick)
verify(exactly = 1) { viewModel.getCurrentIndex() }
verify(exactly = 1) { viewModel.getMovement() }
verify(exactly = 1) { viewModel.getImageResource(INDEX + 1) }
verify(exactly = 1) { view.setParallaxImage(IMAGE_RESOURCE_TWO) }
}
/**
* 3b. If index is last, get first (index 0)
* 4b. Give to the View
*/
@Test
fun `on Parallax Image Click last item`() {
val MOVEMENT = getMovement()
val INDEX = 2
every { viewModel.getCurrentIndex() } returns INDEX
every { viewModel.getMovement() } returns MOVEMENT
every { viewModel.getImageResource(0) } returns MOVEMENT.imageResourceNames[0]
logic.handleEvent(MovementEvent.OnImageClick)
verify(exactly = 1) { viewModel.getCurrentIndex() }
verify(exactly = 1) { viewModel.getMovement() }
verify(exactly = 1) { viewModel.getImageResource(0) }
verify(exactly = 1) { view.setParallaxImage(IMAGE_RESOURCE_ONE) }
}
@Test
fun `On Show Video Click`() {
}
}
| app/src/test/java/com/bracketcove/postrainer/MovementLogicTest.kt | 2424859827 |
package ss.proximityservice
import android.annotation.SuppressLint
import android.app.KeyguardManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.PixelFormat
import android.hardware.Sensor
import android.hardware.SensorManager
import android.net.Uri
import android.os.*
import android.provider.Settings
import android.view.View
import android.view.WindowManager
import android.widget.FrameLayout
import android.widget.Toast
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import dagger.android.DaggerService
import ss.proximityservice.data.AppStorage
import ss.proximityservice.data.Mode
import ss.proximityservice.data.ProximityDetector
import ss.proximityservice.settings.NOTIFICATION_DISMISS
import ss.proximityservice.settings.OPERATIONAL_MODE
import ss.proximityservice.settings.SCREEN_OFF_DELAY
import ss.proximityservice.testing.OpenForTesting
import java.util.concurrent.atomic.AtomicInteger
import javax.inject.Inject
@OpenForTesting
class ProximityService : DaggerService(), ProximityDetector.ProximityListener {
private val sensorManager: SensorManager by lazy {
applicationContext.getSystemService(Context.SENSOR_SERVICE) as SensorManager
}
private val windowManager by lazy {
applicationContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager
}
private val broadcastManager: LocalBroadcastManager by lazy {
LocalBroadcastManager.getInstance(this)
}
private var proximityDetector: ProximityDetector? = null
private var overlay: View? = null
@SuppressLint("InlinedApi")
private val overlayFlags = (View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_FULLSCREEN)
private val proximityWakeLock: PowerManager.WakeLock? by lazy {
val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (powerManager.isWakeLockLevelSupported(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK)) {
powerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, TAG)
} else {
null
}
} else {
// no WakeLock level support checking for api < 21
powerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, TAG)
}
}
// using deprecated KeyguardLock as the suggested alternative (WindowManager.LayoutParams flags)
// is not suitable for a Service with no user interface
private val keyguardLock: KeyguardManager.KeyguardLock by lazy {
val keyguardManager = getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
keyguardManager.newKeyguardLock(TAG)
}
private val keyguardDisableCount: AtomicInteger = AtomicInteger(0)
private val notificationHelper: NotificationHelper by lazy {
NotificationHelper(applicationContext)
}
private val mainHandler: Handler = Handler(Looper.getMainLooper())
private val proximityHandler: Handler = Handler(Looper.myLooper())
@Inject
lateinit var appStorage: AppStorage
override fun onCreate() {
super.onCreate()
proximityDetector = ProximityDetector(this)
val sensor = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY)
sensor?.let {
sensorManager.registerListener(proximityDetector, it, SensorManager.SENSOR_DELAY_NORMAL)
}
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
when (intent.action) {
INTENT_ACTION_START -> start()
INTENT_ACTION_STOP -> stop()
}
return Service.START_NOT_STICKY
}
override fun onDestroy() {
if (isRunning) stop()
sensorManager.unregisterListener(proximityDetector)
}
// binding not supported
override fun onBind(intent: Intent): IBinder? = null
override fun onNear() {
if (isRunning) {
val delay = when (appStorage.getInt(SCREEN_OFF_DELAY, 0)) {
0 -> 0L
1 -> 500L
2 -> 1000L
3 -> 1500L
4 -> 2000L
5 -> 2500L
6 -> 3000L
else -> 0L
}
proximityHandler.postDelayed({ updateProximitySensorMode(true) }, delay)
}
}
override fun onFar() {
if (isRunning) {
proximityHandler.removeCallbacksAndMessages(null)
updateProximitySensorMode(false)
}
}
private fun start() {
proximityWakeLock?.let {
if (it.isHeld or isRunning) {
mainHandler.post { toast("Proximity Service is already active") }
} else {
mainHandler.post { toast("Proximity Service started") }
startForeground(NOTIFICATION_ID, notificationHelper.getRunningNotification())
isRunning = true
broadcastManager.sendBroadcast(Intent(INTENT_NOTIFY_ACTIVE))
}
} ?: run {
mainHandler.post { toast("Proximity WakeLock not supported on this device") }
}
}
private fun stop() {
mainHandler.post { toast("Proximity Service stopped") }
updateProximitySensorMode(false)
isRunning = false
broadcastManager.sendBroadcast(Intent(INTENT_NOTIFY_INACTIVE))
stopSelf()
if (!appStorage.getBoolean(NOTIFICATION_DISMISS, true)) {
notificationHelper.notify(NOTIFICATION_ID, notificationHelper.getStoppedNotification())
}
}
private fun updateProximitySensorMode(on: Boolean) {
when (appStorage.getInt(OPERATIONAL_MODE, Mode.DEFAULT.ordinal)) {
Mode.DEFAULT.ordinal -> updateDefaultMode(on)
Mode.AMOLED_WAKELOCK.ordinal -> updateAMOLEDMode(
on,
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
)
Mode.AMOLED_NO_WAKELOCK.ordinal -> updateAMOLEDMode(on)
}
}
private fun updateDefaultMode(on: Boolean) {
overlay?.let {
updateAMOLEDMode(false)
updateKeyguardMode(true)
}
proximityWakeLock?.let { wakeLock ->
synchronized(wakeLock) {
if (on) {
if (!wakeLock.isHeld) {
wakeLock.acquire()
updateKeyguardMode(false)
}
} else {
if (wakeLock.isHeld) {
wakeLock.release()
updateKeyguardMode(true)
}
}
}
}
}
private fun updateAMOLEDMode(on: Boolean, flags: Int = 0) {
proximityWakeLock?.let { wakeLock ->
if (wakeLock.isHeld) {
wakeLock.release()
updateKeyguardMode(true)
}
}
if (on && !checkDrawOverlaySetting()) return
synchronized(this) {
if (on) {
if (overlay == null) {
overlay = FrameLayout(this).apply {
systemUiVisibility = overlayFlags
setTheme(R.style.OverlayTheme)
}
val params = WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT,
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) WindowManager.LayoutParams.TYPE_SYSTEM_ALERT else WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
flags,
PixelFormat.OPAQUE
)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
params.layoutInDisplayCutoutMode =
WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
}
// simulate SYSTEM_UI_FLAG_IMMERSIVE_STICKY for devices below API 19
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
overlay?.setOnSystemUiVisibilityChangeListener { visibility ->
if ((visibility and View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
proximityHandler.postDelayed({
overlay?.systemUiVisibility = overlayFlags
}, 2000)
}
}
}
windowManager.addView(overlay, params)
updateKeyguardMode(true)
}
} else {
overlay?.let {
it.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
windowManager.removeView(it)
overlay = null
}
updateKeyguardMode(false)
}
}
}
private fun updateKeyguardMode(on: Boolean) {
synchronized(keyguardLock) {
if (on) {
if (keyguardDisableCount.get() > 0) {
if (keyguardDisableCount.decrementAndGet() == 0) {
keyguardLock.reenableKeyguard()
}
}
} else {
if (keyguardDisableCount.getAndAdd(1) == 0) {
keyguardLock.disableKeyguard()
}
}
}
}
private fun checkDrawOverlaySetting(): Boolean {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return true
val canDrawOverlays = Settings.canDrawOverlays(this)
if (!canDrawOverlays) {
startActivity(
Intent(
Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:$packageName")
).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
)
mainHandler.post { toast("AMOLED mode requires the permission for drawing over other apps / appear on top to be turned on") }
}
return canDrawOverlays
}
private fun toast(text: String) {
Toast.makeText(applicationContext, text, Toast.LENGTH_SHORT).show()
}
companion object {
private const val TAG = "ProximityService:ProximitySensorWakeLock"
const val INTENT_ACTION_START = "ss.proximityservice.START"
const val INTENT_ACTION_STOP = "ss.proximityservice.STOP"
const val INTENT_NOTIFY_ACTIVE = "ss.proximityservice.ACTIVE"
const val INTENT_NOTIFY_INACTIVE = "ss.proximityservice.INACTIVE"
private const val NOTIFICATION_ID = 1
var isRunning = false
}
}
| app/src/main/kotlin/ss/proximityservice/ProximityService.kt | 3328894255 |
/*
* Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and contributors
*
* 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.vanniktech.emoji.<%= package %>
import com.vanniktech.emoji.EmojiCategory
import com.vanniktech.emoji.EmojiProvider
<%= imports %>
class <%= name %>Provider : EmojiProvider {
override val categories: Array<EmojiCategory>
get() = arrayOf(<% categories.forEach(function(category) { %>
<%= category.name %>(),<% }); %>
)
override fun release() = Unit
}
| generator/template/EmojiProviderJvm.kt | 4193553511 |
package com.example.chenyong.android_demo
/**
* Created by focus on 17/1/18.
*/
class AlgorithmImpl {
/**
* 计算两个非负整数 p 和 q 的最大公约数:若 q 是 0,则最大公约数为 p。否则,将 p 除以 q得到余数r,p和q的最大公约数即为q和 r 的最大公约数。
*/
fun gcd(p: Int, q: Int): Int {
if (q == 0) return p
else {
val r = p % q
return gcd(q, r)
}
}
/**
* 编写递归代码的重要三点:
* 1.递归总有一个最简单的情况--方法的第一条语句总是一个包含return的条件语句
* 2.递归调用总是去尝试解决一个规模更小的子问题,这样递归才能收敛到最简单的情况
* 在下面的代码中,第四个参数和但三个参数的差值一直在缩小
* 3.递归调用的父问题和尝试解决的子问题之间不应该有交集
* 在代码中,两个子问题各自操作的数组部分是不同的
*/
fun rank(key: Int, a: IntArray, lo: Int = 0, hi: Int = a.size): Int {
if (lo > hi) return -1
val mid = lo + (hi - lo) / 2
if (key < a[mid]) return rank(key, a, lo, mid - 1)
else if (key > a[mid]) return rank(key, a, mid + 1, hi)
else return mid
}
} | app/src/main/kotlin/com/example/chenyong/android_demo/AlgorithmImpl.kt | 2980114228 |
package org.ligi.vectordrawableimporter.model
import java.io.File
class ImageAsset(val file: File) {
override fun toString(): String {
return file.name.replace(".png","")
}
}
| plugin/src/main/kotlin/org/ligi/vectordrawableimporter/model/ImageAsset.kt | 4175616971 |
package ee.system
open class JavaServiceCommands<T : JavaService> : JavaServiceCommandsBase<T> {
companion object {
val EMPTY = JavaServiceCommandsBase.EMPTY
}
constructor(item: T) : super(item) {
}
}
| ee-system/src/main/kotlin/ee/system/JavaServiceCommands.kt | 3963761205 |
data class Tuple109<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46, T47, T48, T49, T50, T51, T52, T53, T54, T55, T56, T57, T58, T59, T60, T61, T62, T63, T64, T65, T66, T67, T68, T69, T70, T71, T72, T73, T74, T75, T76, T77, T78, T79, T80, T81, T82, T83, T84, T85, T86, T87, T88, T89, T90, T91, T92, T93, T94, T95, T96, T97, T98, T99, T100, T101, T102, T103, T104, T105, T106, T107, T108, T109>(val item1: T1, val item2: T2, val item3: T3, val item4: T4, val item5: T5, val item6: T6, val item7: T7, val item8: T8, val item9: T9, val item10: T10, val item11: T11, val item12: T12, val item13: T13, val item14: T14, val item15: T15, val item16: T16, val item17: T17, val item18: T18, val item19: T19, val item20: T20, val item21: T21, val item22: T22, val item23: T23, val item24: T24, val item25: T25, val item26: T26, val item27: T27, val item28: T28, val item29: T29, val item30: T30, val item31: T31, val item32: T32, val item33: T33, val item34: T34, val item35: T35, val item36: T36, val item37: T37, val item38: T38, val item39: T39, val item40: T40, val item41: T41, val item42: T42, val item43: T43, val item44: T44, val item45: T45, val item46: T46, val item47: T47, val item48: T48, val item49: T49, val item50: T50, val item51: T51, val item52: T52, val item53: T53, val item54: T54, val item55: T55, val item56: T56, val item57: T57, val item58: T58, val item59: T59, val item60: T60, val item61: T61, val item62: T62, val item63: T63, val item64: T64, val item65: T65, val item66: T66, val item67: T67, val item68: T68, val item69: T69, val item70: T70, val item71: T71, val item72: T72, val item73: T73, val item74: T74, val item75: T75, val item76: T76, val item77: T77, val item78: T78, val item79: T79, val item80: T80, val item81: T81, val item82: T82, val item83: T83, val item84: T84, val item85: T85, val item86: T86, val item87: T87, val item88: T88, val item89: T89, val item90: T90, val item91: T91, val item92: T92, val item93: T93, val item94: T94, val item95: T95, val item96: T96, val item97: T97, val item98: T98, val item99: T99, val item100: T100, val item101: T101, val item102: T102, val item103: T103, val item104: T104, val item105: T105, val item106: T106, val item107: T107, val item108: T108, val item109: T109) {
}
| src/main/kotlin/com/github/kmizu/kollection/tuples/Tuple109.kt | 3474618006 |
package io.kotest.core.test
/**
* The description gives the full path to a [TestCase].
*
* It contains the name of every parent, with the root at index 0.
* And it includes the name of the test case it represents.
*
* This is useful when you want to write generic extensions and you
* need to be able to filter on certain tests only.
*
* @param parents each parent test case
* @param name the name of this test case
*/
@Suppress("MemberVisibilityCanBePrivate")
data class Description(val parents: List<String>, val name: String) {
companion object {
/**
* Creates a Spec level description object for the given name.
*/
fun spec(name: String) = Description(emptyList(), name)
}
fun append(name: String) =
Description(this.parents + this.name, name)
fun hasParent(description: Description): Boolean =
parents.containsAll(description.parents + listOf(description.name))
/**
* Returns the parent of this description, unless it is a spec then it will throw
*/
fun parent(): Description = if (isSpec()) error("Cannot call .parent() on a spec") else Description(
parents.dropLast(1),
parents.last()
)
fun isSpec(): Boolean = parents.isEmpty()
fun spec(): Description =
spec(parents.first())
fun tail() = if (parents.isEmpty()) throw NoSuchElementException() else Description(
parents.drop(1),
name
)
fun fullName(): String = (parents + listOf(name)).joinToString(" ")
/**
* Returns a String version of this description, which is
* the parents + this name concatenated with slashes.
*/
fun id(): String = (parents + listOf(name)).joinToString("/")
fun names(): List<String> = parents + name
fun depth() = names().size
/**
* Returns true if this instance is the immediate parent of the supplied argument.
*/
fun isParentOf(description: Description): Boolean =
parents + name == description.parents
/**
* Returns true if this instance is an ancestor (nth-parent) of the supplied argument.
*/
fun isAncestorOf(description: Description): Boolean {
if (isParentOf(description))
return true
return if (description.isSpec()) false else {
val p = description.parent()
isAncestorOf(p)
}
}
/**
* Returns true if this instance is on the path to the given descripton. That is, if this
* instance is either an ancestor of, of the same as, the given description.
*/
fun isOnPath(description: Description): Boolean = this == description || this.isAncestorOf(description)
fun isDescendentOf(description: Description): Boolean = description.isOnPath(this)
/**
* Returns true if this test is a top level test. In other words, if the
* test has no parents other than the spec itself.
*/
fun isTopLevel(): Boolean = parents.size == 1 && parent().isSpec()
}
| kotest-core/src/commonMain/kotlin/io/kotest/core/test/Description.kt | 3918014172 |
package com.waz.zclient.core.backend.datasources.remote
import com.waz.zclient.core.network.ApiService
import com.waz.zclient.core.network.NetworkHandler
class BackendApiService(
private val backendApi: BackendApi,
override val networkHandler: NetworkHandler
) : ApiService() {
suspend fun getCustomBackendConfig(url: String) =
request { backendApi.getCustomBackendConfig(url) }
}
| app/src/main/kotlin/com/waz/zclient/core/backend/datasources/remote/BackendApiService.kt | 844552848 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.settings
import com.intellij.application.options.editor.AutoImportOptionsProvider
import com.intellij.ui.IdeBorderFactory
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.layout.panel
import org.rust.openapiext.CheckboxDelegate
import javax.swing.JComponent
class RsAutoImportOptions : AutoImportOptionsProvider {
private val showImportPopupCheckbox: JBCheckBox = JBCheckBox("Show import popup")
private var showImportPopup: Boolean by CheckboxDelegate(showImportPopupCheckbox)
override fun createComponent(): JComponent = panel {
row { showImportPopupCheckbox() }
}.apply { border = IdeBorderFactory.createTitledBorder("Rust") }
override fun isModified(): Boolean {
return showImportPopup != RsCodeInsightSettings.getInstance().showImportPopup
}
override fun apply() {
RsCodeInsightSettings.getInstance().showImportPopup = showImportPopup
}
override fun reset() {
showImportPopup = RsCodeInsightSettings.getInstance().showImportPopup
}
}
| src/main/kotlin/org/rust/ide/settings/RsAutoImportOptions.kt | 1104092458 |
/*
* Copyright (c) 2021 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.yobidashi.main.initial
import android.content.Context
import android.content.SharedPreferences
import android.graphics.Color
import android.net.Uri
import androidx.core.content.ContextCompat
import io.mockk.MockKAnnotations
import io.mockk.Runs
import io.mockk.every
import io.mockk.impl.annotations.MockK
import io.mockk.just
import io.mockk.mockk
import io.mockk.mockkConstructor
import io.mockk.mockkObject
import io.mockk.mockkStatic
import io.mockk.spyk
import io.mockk.unmockkAll
import io.mockk.verify
import jp.toastkid.lib.preference.PreferenceApplier
import jp.toastkid.search.SearchCategory
import jp.toastkid.yobidashi.browser.FaviconFolderProviderService
import jp.toastkid.yobidashi.browser.bookmark.BookmarkInitializer
import jp.toastkid.yobidashi.settings.background.DefaultBackgroundImagePreparation
import jp.toastkid.yobidashi.settings.color.DefaultColorInsertion
import org.junit.After
import org.junit.Before
import org.junit.Test
class FirstLaunchInitializerTest {
private lateinit var firstLaunchInitializer: FirstLaunchInitializer
@MockK
private lateinit var context: Context
private lateinit var preferenceApplier: PreferenceApplier
@MockK
private lateinit var defaultColorInsertion: DefaultColorInsertion
@MockK
private lateinit var faviconFolderProviderService: FaviconFolderProviderService
@MockK
private lateinit var defaultBackgroundImagePreparation: DefaultBackgroundImagePreparation
@MockK
private lateinit var sharedPreferences: SharedPreferences
@MockK
private lateinit var editor: SharedPreferences.Editor
@Before
fun setUp() {
MockKAnnotations.init(this)
every { context.getSharedPreferences(any(), any()) }.returns(sharedPreferences)
every { sharedPreferences.edit() }.returns(editor)
every { editor.putInt(any(), any()) }.returns(editor)
every { editor.apply() }.just(Runs)
preferenceApplier = spyk(PreferenceApplier(context))
every { preferenceApplier.isFirstLaunch() }.returns(true)
every { defaultColorInsertion.insert(any()) }.returns(mockk())
every { faviconFolderProviderService.invoke(any()) }.returns(mockk())
every { defaultBackgroundImagePreparation.invoke(any(), any()) }.returns(mockk())
every { preferenceApplier.setDefaultSearchEngine(any()) }.just(Runs)
mockkStatic(ContextCompat::class)
every { ContextCompat.getColor(any(), any()) }.returns(Color.CYAN)
mockkStatic(Uri::class)
val returnValue = mockk<Uri>()
every { returnValue.host }.returns("yahoo.co.jp")
every { Uri.parse(any()) }.returns(returnValue)
mockkObject(SearchCategory)
every { SearchCategory.getDefaultCategoryName() }.returns("yahoo")
mockkConstructor(BookmarkInitializer::class)
every { anyConstructed<BookmarkInitializer>().invoke(any()) }.returns(mockk())
firstLaunchInitializer = FirstLaunchInitializer(
context,
preferenceApplier,
defaultColorInsertion,
faviconFolderProviderService,
defaultBackgroundImagePreparation
)
}
@After
fun tearDown() {
unmockkAll()
}
@Test
fun testInvoke() {
firstLaunchInitializer.invoke()
verify(exactly = 1) { preferenceApplier.isFirstLaunch() }
verify(exactly = 1) { defaultColorInsertion.insert(any()) }
verify(exactly = 1) { defaultBackgroundImagePreparation.invoke(any(), any()) }
verify(exactly = 1) { preferenceApplier.setDefaultSearchEngine(any()) }
}
@Test
fun test() {
every { preferenceApplier.isFirstLaunch() }.returns(false)
firstLaunchInitializer.invoke()
verify(exactly = 1) { preferenceApplier.isFirstLaunch() }
verify(exactly = 0) { defaultColorInsertion.insert(any()) }
verify(exactly = 0) { defaultBackgroundImagePreparation.invoke(any(), any()) }
verify(exactly = 0) { preferenceApplier.setDefaultSearchEngine(any()) }
}
} | app/src/test/java/jp/toastkid/yobidashi/main/initial/FirstLaunchInitializerTest.kt | 215142801 |
package com.mewhpm.mewsync.ui.recyclerview.impl
import android.content.Context
import android.util.AttributeSet
import androidx.core.content.ContextCompat
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.input.input
import com.mewhpm.mewsync.R
import com.mewhpm.mewsync.dao.KnownDevicesDao
import com.mewhpm.mewsync.data.BleDevice
import com.mewhpm.mewsync.ui.recyclerview.RecyclerViewAbstract
import com.mewhpm.mewsync.ui.recyclerview.data.TextPairWithIcon
import com.mikepenz.google_material_typeface_library.GoogleMaterial
import org.jetbrains.anko.alert
import org.jetbrains.anko.cancelButton
import org.jetbrains.anko.okButton
import org.jetbrains.anko.selector
class RecyclerViewDevicesImpl : RecyclerViewAbstract<BleDevice> {
constructor(context: Context) : super(context)
constructor(context: Context, attributeSet: AttributeSet?) : super(context, attributeSet)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
private val list = ArrayList<Pair<TextPairWithIcon, BleDevice>>()
var deleteEvent : (position: Int, item: TextPairWithIcon, obj: BleDevice) -> Unit = { _, _, _ -> throw NotImplementedError("deleteEvent not set") }
var setDefaultEvent : (position: Int, item: TextPairWithIcon, obj: BleDevice) -> Unit = { _, _, _ -> throw NotImplementedError("setDefaultEvent not set") }
var setDescriptionEvent : (obj: BleDevice, desc: String) -> Unit = { _, _ -> throw NotImplementedError("setDescriptionEvent not set") }
var deviceItemClickEvent : (dev : BleDevice) -> Unit = { throw NotImplementedError("deviceItemClickEvent not set") }
override fun requestList(): ArrayList<Pair<TextPairWithIcon, BleDevice>> = list
override fun onElementClick(position: Int, item: TextPairWithIcon, obj: BleDevice) {
deviceItemClickEvent.invoke(obj)
}
override fun onElementLongClick(position: Int, item: TextPairWithIcon, obj: BleDevice) {
if (KnownDevicesDao.isDeviceZero(obj.mac)) {
context.alert (title = "Device Zero", message = "Do you really want setup a Device Zero as default?") {
okButton {
sefDefault(position, item, obj)
}
cancelButton { }
}.show()
return
}
val actions = listOf("Set default", "Change description", "Delete")
context.selector("Actions", actions) { _, index ->
when (index) {
0 -> sefDefault(position, item, obj)
1 -> {
MaterialDialog([email protected]).show {
input(allowEmpty = true, prefill = obj.text) { _, text ->
item.text = if (text.isBlank()) obj.mac else text.toString()
setDescriptionEvent.invoke(obj, text.toString())
[email protected]?.notifyDataSetChanged()
}
title(R.string.change_desc)
positiveButton(R.string.change_description)
negativeButton(R.string.back)
}
}
2 -> {
context.alert (title = "Remove device", message = "Do you want delete the device with mac: \"${obj.mac}\" and name \"${obj.name}\"?") {
okButton {
remove(position, item, obj)
}
cancelButton { }
}.show()
}
}
}
}
private fun createDataTextPairWithIcon(dev : BleDevice) : TextPairWithIcon {
return TextPairWithIcon(
icon =
if (KnownDevicesDao.isDeviceZero(dev.mac))
GoogleMaterial.Icon.gmd_sd_storage
else
GoogleMaterial.Icon.gmd_bluetooth,
iconColor = ContextCompat.getColor(context, if (dev.default) R.color.colorBrandDefaultElement else R.color.colorBrandDark1),
iconSize = 48,
text = if (dev.text.isBlank()) dev.mac else dev.text,
textColor = ContextCompat.getColor(context, R.color.colorBrandDark2),
title = dev.name,
titleColor = ContextCompat.getColor(context, R.color.colorBrandBlack)
)
}
fun add(dev : BleDevice) {
val pair = Pair(createDataTextPairWithIcon(dev), dev)
list.add(pair)
this.adapter?.notifyDataSetChanged()
}
fun clear() {
list.clear()
this.adapter?.notifyDataSetChanged()
}
private fun sefDefault(position: Int, item: TextPairWithIcon, obj: BleDevice) {
list.forEach { it.first.iconColor = ContextCompat.getColor(context, R.color.colorBrandDark1) }
item.iconColor = ContextCompat.getColor(context, R.color.colorBrandDefaultElement)
this.adapter?.notifyDataSetChanged()
setDefaultEvent.invoke(position, item, obj)
}
private fun remove(position: Int, item: TextPairWithIcon, obj: BleDevice) {
list.removeAt(position)
this.adapter?.notifyDataSetChanged()
deleteEvent(position, item, obj)
}
fun reload() {
this.adapter?.notifyDataSetChanged()
}
override fun create() {
super.create()
this.adapter = TextPairWithIconAdapterImpl()
}
} | software/MeWSync/app/src/main/java/com/mewhpm/mewsync/ui/recyclerview/impl/RecyclerViewDevicesImpl.kt | 2943139076 |
package com.example.android.eyebody.camera
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
import com.example.android.eyebody.MainActivity
import com.example.android.eyebody.R
import kotlinx.android.synthetic.main.activity_confirm.*
import java.io.File
import android.widget.EditText
class ConfirmActivity : AppCompatActivity() {
var frontFileName: String? = null
var sideFileName: String? = null
var frontImageUri:String=""
var sideImageUri:String=""
var value:String=""
var memoImageDB:memoImageDb?=null
var time:String=""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_confirm)
memoImageDB =memoImageDb(baseContext,"memoImage.db",null,1)
showImage()
saveButtonClicked()
deleteButtonClicked()
memoButtonClicked()
}
//찍은 이미지를 화면에 뿌려주는 역할
private fun showImage() {
var intent = intent
frontImageUri = intent.getStringExtra("frontUri")//front 이미지 uri 받아옴
sideImageUri = intent.getStringExtra("sideUri")//side 이미지 uri
frontFileName = intent.extras.getString("frontName")//front 이미지 파일명
sideFileName = intent.extras.getString("sideName")//side 이미지 파일명
time=intent.extras.getString("time")
var sideImage = Uri.parse(sideImageUri)
var frontImage = Uri.parse(frontImageUri)
image_front.setImageURI(frontImage)
image_side.setImageURI(sideImage) //이미지 두개 imageview에 맵핑함
}
private fun goHomeActivity() {
var intent = Intent(this, MainActivity::class.java)
startActivity(intent)
}//홈으로 돌아감
private fun goCameraActivity() {
var intent = Intent(this, CameraActivity::class.java)
startActivity(intent)
}//카메라 엑티비티로 돌아감
//버튼을 두개로 할 예정 삭제. 저장
//저장버튼이 클릭되면 저장하였습니다 toast창 뜨고 홈으로 돌아감
private fun saveButtonClicked() {
button_save.setOnClickListener {
Toast.makeText(applicationContext, "저장되었습니다", Toast.LENGTH_SHORT).show()
putValuesInDb(time,frontImageUri,sideImageUri,value)
goHomeActivity()
}
}
private fun deleteFile() {
var frontFile = File(frontFileName)
var sideFile = File(sideFileName)
frontFile.delete()
sideFile.delete()
}
//삭제버튼 누르면 파일삭제. 다시 찍으시겠습니까?alertDialog뜨고 거절하면 홈으로 아니면 카메라 액티비티로 돌아감
private fun deleteButtonClicked() {
button_delete.setOnClickListener {
val alertDilog = AlertDialog.Builder(this@ConfirmActivity).create()
alertDilog.setTitle("삭제")
alertDilog.setMessage("삭제 하시겠습니까?")
alertDilog.setButton(AlertDialog.BUTTON_NEUTRAL, "삭제후 다시촬영", { dialogInterface, i ->
deleteFile()
Toast.makeText(applicationContext, "다시 촬영", Toast.LENGTH_SHORT).show()
goCameraActivity()
})
alertDilog.setButton(AlertDialog.BUTTON_POSITIVE, "취소", { dialogInterface, j ->
})//암것도 안함
alertDilog.setButton(AlertDialog.BUTTON_NEGATIVE, "삭제후 홈으로", { dialogInterface, k ->
deleteFile()
Toast.makeText(applicationContext, "삭제되었습니다", Toast.LENGTH_SHORT).show()
goHomeActivity()
})
alertDilog.show()
}
}
private fun memoButtonClicked(){
button_memo.setOnClickListener{
val ad = AlertDialog.Builder(this@ConfirmActivity)
ad.setTitle("메모") // 제목 설정
ad.setMessage("메모를 적어주세요") // 내용 설정
// EditText 삽입하기
val et = EditText(this@ConfirmActivity)
ad.setView(et)
// 확인 버튼 설정
ad.setPositiveButton("저장") { dialog, which ->
value = et!!.text.toString()
dialog.dismiss() //닫기
}
ad.setNegativeButton("닫기") { dialog, which ->
dialog.dismiss() //닫기
}
// 창 띄우기
ad.show()
}
}
private fun putValuesInDb(time:String, frontImage:String, sideImage:String,memo:String){
memoImageDB!!.insert(time,frontImage,sideImage,memo)
}
override fun onBackPressed() {
super.onBackPressed()
goCameraActivity()
}
}
| EyeBody2/app/src/main/java/com/example/android/eyebody/camera/ConfirmActivity.kt | 592699818 |
package net.dinkla.raytracer.materials
import net.dinkla.raytracer.colors.Color
import net.dinkla.raytracer.hits.Shade
import net.dinkla.raytracer.worlds.World
interface IMaterial {
fun shade(world: World, sr: Shade): Color
fun areaLightShade(world: World, sr: Shade): Color
fun getLe(sr: Shade): Color
//abstract public RGBColor pathShade(Shade sr);
} | src/main/kotlin/net/dinkla/raytracer/materials/IMaterial.kt | 3202411192 |
package eu.kanade.tachiyomi.data.track.shikimori
import eu.kanade.tachiyomi.data.database.models.Track
fun Track.toShikimoriStatus() = when (status) {
Shikimori.READING -> "watching"
Shikimori.COMPLETED -> "completed"
Shikimori.ON_HOLD -> "on_hold"
Shikimori.DROPPED -> "dropped"
Shikimori.PLANNING -> "planned"
Shikimori.REPEATING -> "rewatching"
else -> throw NotImplementedError("Unknown status: $status")
}
fun toTrackStatus(status: String) = when (status) {
"watching" -> Shikimori.READING
"completed" -> Shikimori.COMPLETED
"on_hold" -> Shikimori.ON_HOLD
"dropped" -> Shikimori.DROPPED
"planned" -> Shikimori.PLANNING
"rewatching" -> Shikimori.REPEATING
else -> throw NotImplementedError("Unknown status: $status")
}
| app/src/main/java/eu/kanade/tachiyomi/data/track/shikimori/ShikimoriModels.kt | 2231305260 |
package net.yslibrary.monotweety.license
import dagger.Module
import dagger.Provides
import net.yslibrary.monotweety.base.EventBus
import net.yslibrary.monotweety.base.di.ControllerScope
import net.yslibrary.monotweety.base.di.Names
import net.yslibrary.monotweety.license.domain.GetLicenses
import javax.inject.Named
@Module
class LicenseViewModule(private val activityBus: EventBus) {
@ControllerScope
@Provides
@Named(Names.FOR_ACTIVITY)
fun provideActivityBus(): EventBus = activityBus
@ControllerScope
@Provides
fun provideLicenseViewModel(getLicenses: GetLicenses): LicenseViewModel {
return LicenseViewModel(getLicenses)
}
interface DependencyProvider {
@Named(Names.FOR_ACTIVITY)
fun activityBus(): EventBus
}
}
| app/src/main/java/net/yslibrary/monotweety/license/LicenseViewModule.kt | 435791936 |
package org.wordpress.android.fluxc.quickstart
import com.yarolegovich.wellsql.WellSql
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.fluxc.SingleStoreWellSqlConfigForTests
import org.wordpress.android.fluxc.model.QuickStartTaskModel
import org.wordpress.android.fluxc.persistence.QuickStartSqlUtils
import org.wordpress.android.fluxc.store.QuickStartStore
import org.wordpress.android.fluxc.store.QuickStartStore.QuickStartNewSiteTask.CHECK_STATS
import org.wordpress.android.fluxc.store.QuickStartStore.QuickStartNewSiteTask.CREATE_SITE
import org.wordpress.android.fluxc.store.QuickStartStore.QuickStartNewSiteTask.ENABLE_POST_SHARING
import org.wordpress.android.fluxc.store.QuickStartStore.QuickStartNewSiteTask.FOLLOW_SITE
import org.wordpress.android.fluxc.store.QuickStartStore.QuickStartNewSiteTask.PUBLISH_POST
import org.wordpress.android.fluxc.store.QuickStartStore.QuickStartNewSiteTask.REVIEW_PAGES
import org.wordpress.android.fluxc.store.QuickStartStore.QuickStartNewSiteTask.UPDATE_SITE_TITLE
import org.wordpress.android.fluxc.store.QuickStartStore.QuickStartNewSiteTask.UPLOAD_SITE_ICON
import org.wordpress.android.fluxc.store.QuickStartStore.QuickStartNewSiteTask.VIEW_SITE
import org.wordpress.android.fluxc.store.QuickStartStore.QuickStartTaskType.CUSTOMIZE
import org.wordpress.android.fluxc.store.QuickStartStore.QuickStartTaskType.GROW
import org.wordpress.android.fluxc.test
@RunWith(RobolectricTestRunner::class)
class QuickStartStoreTest {
private val testLocalSiteId: Long = 72
private lateinit var quickStartStore: QuickStartStore
@Before
fun setUp() {
val appContext = RuntimeEnvironment.application.applicationContext
val config = SingleStoreWellSqlConfigForTests(
appContext,
listOf(QuickStartTaskModel::class.java), ""
)
WellSql.init(config)
config.reset()
quickStartStore = QuickStartStore(QuickStartSqlUtils(), Dispatcher())
}
@Test
fun orderOfDoneTasks() = test {
// marking tasks as done in random order
quickStartStore.setDoneTask(testLocalSiteId, VIEW_SITE, true)
quickStartStore.setDoneTask(testLocalSiteId, FOLLOW_SITE, true)
quickStartStore.setDoneTask(testLocalSiteId, CREATE_SITE, true)
// making sure done tasks are retrieved in a correct order
val completedCustomizeTasks = quickStartStore.getCompletedTasksByType(testLocalSiteId, CUSTOMIZE)
assertEquals(2, completedCustomizeTasks.size)
assertEquals(CREATE_SITE, completedCustomizeTasks[0])
assertEquals(VIEW_SITE, completedCustomizeTasks[1])
val completedGrowTasks = quickStartStore.getCompletedTasksByType(testLocalSiteId, GROW)
assertEquals(1, completedGrowTasks.size)
assertEquals(FOLLOW_SITE, completedGrowTasks[0])
// making sure undone tasks are retrieved in a correct order
val uncompletedCustomizeTasks = quickStartStore.getUncompletedTasksByType(testLocalSiteId, CUSTOMIZE)
assertEquals(3, uncompletedCustomizeTasks.size)
assertEquals(UPDATE_SITE_TITLE, uncompletedCustomizeTasks[0])
assertEquals(UPLOAD_SITE_ICON, uncompletedCustomizeTasks[1])
assertEquals(REVIEW_PAGES, uncompletedCustomizeTasks[2])
val uncompletedGrowTasks = quickStartStore.getUncompletedTasksByType(testLocalSiteId, GROW)
assertEquals(3, uncompletedGrowTasks.size)
assertEquals(ENABLE_POST_SHARING, uncompletedGrowTasks[0])
assertEquals(PUBLISH_POST, uncompletedGrowTasks[1])
assertEquals(CHECK_STATS, uncompletedGrowTasks[2])
}
}
| example/src/test/java/org/wordpress/android/fluxc/quickstart/QuickStartStoreTest.kt | 1592420457 |
package com.ff14.chousei.web
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMethod
@Controller
class TopController
{
open val PAGE: String = "/"
private val HTML: String = "top"
@GetMapping("/")
public fun top(model: Model): String
{
return this.HTML
}
} | src/main/kotlin/com/ff14/chousei/web/TopController.kt | 3955659463 |
/*
* Copyright 2020 Google LLC
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.ksp.symbol
/**
* Kind of a function declaration.
*/
enum class FunctionKind {
TOP_LEVEL, MEMBER, STATIC, ANONYMOUS, LAMBDA;
}
| api/src/main/kotlin/com/google/devtools/ksp/symbol/FunctionKind.kt | 1294832932 |
/*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.tivi.data.resultentities
import androidx.room.Embedded
import androidx.room.Ignore
import androidx.room.Relation
import app.tivi.data.entities.FollowedShowEntry
import app.tivi.data.entities.ShowTmdbImage
import app.tivi.data.entities.TiviShow
import app.tivi.data.entities.findHighestRatedBackdrop
import app.tivi.data.entities.findHighestRatedPoster
import app.tivi.data.views.FollowedShowsWatchStats
import app.tivi.extensions.unsafeLazy
import java.util.Objects
class FollowedShowEntryWithShow : EntryWithShow<FollowedShowEntry> {
@Embedded
override lateinit var entry: FollowedShowEntry
@Relation(parentColumn = "show_id", entityColumn = "id")
override lateinit var relations: List<TiviShow>
@Relation(parentColumn = "show_id", entityColumn = "show_id")
override lateinit var images: List<ShowTmdbImage>
@Suppress("PropertyName")
@Relation(parentColumn = "id", entityColumn = "id")
lateinit var _stats: List<FollowedShowsWatchStats>
val stats: FollowedShowsWatchStats?
get() = _stats.firstOrNull()
@delegate:Ignore
val backdrop: ShowTmdbImage? by unsafeLazy { images.findHighestRatedBackdrop() }
@delegate:Ignore
override val poster: ShowTmdbImage? by unsafeLazy { images.findHighestRatedPoster() }
override fun equals(other: Any?): Boolean = when {
other === this -> true
other is FollowedShowEntryWithShow -> {
entry == other.entry && relations == other.relations && stats == other.stats && images == other.images
}
else -> false
}
override fun hashCode(): Int = Objects.hash(entry, relations, stats, images)
}
| data/src/main/java/app/tivi/data/resultentities/FollowedShowEntryWithShow.kt | 2827332770 |
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.tivi.common.compose
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import app.tivi.settings.TiviPreferences
@Composable
fun TiviPreferences.shouldUseDarkColors(): Boolean {
val themePreference = observeTheme().collectAsState(initial = TiviPreferences.Theme.SYSTEM)
return when (themePreference.value) {
TiviPreferences.Theme.LIGHT -> false
TiviPreferences.Theme.DARK -> true
else -> isSystemInDarkTheme()
}
}
| common/ui/compose/src/main/java/app/tivi/common/compose/TiviPreferenceExtensions.kt | 2080942654 |
package net.tlalka.fiszki.utils
import net.tlalka.fiszki.domain.utils.ValidUtils
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class ValidUtilsTest {
@Test
fun testCheckIfObjectIsNull() {
assertTrue(ValidUtils.isNull(null))
}
@Test
fun testCheckIfObjectIsNotNull() {
assertTrue(ValidUtils.isNotNull("OK"))
}
@Test
fun testCheckIfArgumentIsTrue() {
assertTrue(ValidUtils.isTrue(true))
}
@Test
fun testCheckIfArgumentIsFalse() {
assertTrue(ValidUtils.isFalse(false))
}
@Test
fun testCheckIfNullArgumentIsFalse() {
assertFalse(ValidUtils.isTrue(null))
}
@Test
fun testCheckIfStringIsEmpty() {
assertTrue(ValidUtils.isEmpty(""))
}
@Test
fun testCheckIfListIsEmpty() {
assertTrue(ValidUtils.isEmpty(emptyList<Any>()))
}
@Test
fun testCheckIfMapIsEmpty() {
assertTrue(ValidUtils.isEmpty(emptyMap<Any, Any>()))
}
@Test
fun testCheckIfStringIsNotEmpty() {
assertTrue(ValidUtils.isNotEmpty("NOT EMPTY"))
}
@Test
fun testCheckIfListIsNotEmpty() {
assertTrue(ValidUtils.isNotEmpty(listOf("OK")))
}
@Test
fun testCheckIfMapIsNotEmpty() {
assertTrue(ValidUtils.isNotEmpty(mapOf(Pair("KEY", "OK"))))
}
@Test
fun testCheckIfNullStringIsEmpty() {
assertFalse(ValidUtils.isEmpty(getNullValue(String::class.java)))
}
@Test
fun testCheckIfNullListIsEmpty() {
assertFalse(ValidUtils.isEmpty(getNullValue(List::class.java)))
}
@Test
fun testCheckIfNullMapIsEmpty() {
assertFalse(ValidUtils.isEmpty(getNullValue(Map::class.java)))
}
@Suppress("UNUSED_PARAMETER")
private fun <E> getNullValue(clazz: Class<E>): E? {
return null
}
}
| app/src/test/kotlin/net/tlalka/fiszki/utils/ValidUtilsTest.kt | 644874 |
package edu.cs4730.archnavigationdemo_kt
import android.view.LayoutInflater
import android.view.ViewGroup
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.fragment.app.Fragment
/**
* This example receives arguments via the safe_arg version. Note safe args are included in Project build.grade (not module).
*/
class Fragment_Three : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val myView = inflater.inflate(R.layout.fragment__three, container, false)
val tv_passed = myView.findViewById<TextView>(R.id.tv_passed)
tv_passed.text = Fragment_ThreeArgs.fromBundle(requireArguments()).message
val tv_passed2 = myView.findViewById<TextView>(R.id.tv_passed2)
val stuff = "Data 2 is " + Fragment_ThreeArgs.fromBundle(requireArguments()).number
tv_passed2.text = stuff
return myView
}
} | Advanced/ArchNavigationDemo_kt/app/src/main/java/edu/cs4730/archnavigationdemo_kt/Fragment_Three.kt | 2364674140 |
package com.airbnb.mvrx
import org.junit.Test
data class StateWithMutableMap(val map: MutableMap<String, String> = mutableMapOf()) : MavericksState
data class StateWithImmutableMap(val map: Map<String, String> = mapOf()) : MavericksState
class MutableStateValidationTest : BaseTest() {
@Test(expected = IllegalArgumentException::class)
fun mutableStateShouldFail() {
class ViewModel(initialState: StateWithMutableMap) :
TestMavericksViewModel<StateWithMutableMap>(initialState) {
fun addKeyToMap() {
val myMap = withState(this) { it.map }
myMap["foo"] = "bar"
setState { copy(map = myMap) }
}
}
ViewModel(StateWithMutableMap()).addKeyToMap()
}
@Test
fun immutableStateShouldNotFail() {
class ViewModel(initialState: StateWithImmutableMap) :
TestMavericksViewModel<StateWithImmutableMap>(initialState) {
fun addKeyToMap() {
val myMap = withState(this) { it.map }.toMutableMap()
myMap["foo"] = "bar"
setState { copy(map = myMap) }
}
}
ViewModel(StateWithImmutableMap()).addKeyToMap()
}
}
| mvrx/src/test/kotlin/com/airbnb/mvrx/MutableStateValidationTest.kt | 3085043475 |
package at.yawk.javap.model
import at.yawk.javap.Sdk
import at.yawk.javap.SdkLanguage
import at.yawk.javap.Sdks
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.SerializationException
import kotlinx.serialization.builtins.SetSerializer
import kotlinx.serialization.builtins.nullable
import kotlinx.serialization.builtins.serializer
import kotlinx.serialization.descriptors.buildClassSerialDescriptor
import kotlinx.serialization.encoding.CompositeDecoder
import kotlinx.serialization.encoding.CompositeEncoder
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
typealias CompilerConfiguration = Map<String, Any?>
object ConfigProperties {
fun validateAndBuildCommandLine(sdk: Sdk, config: CompilerConfiguration): List<String> {
val out = mutableListOf<String>()
val properties: Iterable<ConfigProperty<*>> = properties.getValue(sdk.language)
val remaining = config.keys.toMutableSet()
for (property in properties) {
if (property.canApplyTo(sdk)) {
if (remaining.remove(property.id)) {
property.validateFrom(sdk, config)
property.applyFrom(out, config)
} // else not set
}
}
require(remaining.isEmpty())
if (sdk is Sdk.Java) {
val debugLines = config.getOrElse("debugLines") { true } as Boolean
val debugSource = config.getOrElse("debugSource") { true } as Boolean
val debugVars = config.getOrElse("debugVars") { true } as Boolean
// build -g
if (debugLines && debugSource && debugVars) {
out.add("-g")
} else if (!debugLines && !debugSource && !debugVars) {
out.add("-g:none")
} else {
out.add("-g:" + listOfNotNull(
if (debugLines) "lines" else null,
if (debugVars) "vars" else null,
if (debugSource) "source" else null
).joinToString(","))
}
val warningsAsErrors = config.getOrElse("warningsAsErrors") { false } as Boolean
if (warningsAsErrors) {
if (sdk is Sdk.Ecj) {
out.add("-failOnWarning")
} else {
out.add("-Werror")
}
}
} else if (sdk is Sdk.Scala) {
val languageOpts = listOf("dynamics", "postfixOps", "reflectiveCalls", "implicitConversions",
"higherKinds", "existentials")
if (languageOpts.any { config[it] == true }) {
out.add("-language:" + languageOpts.filter { config[it] == true }.joinToString(","))
}
}
if (sdk is Sdk.HasLint) {
val lint = lint.get(config)
if (lint != null) {
when (sdk) {
is Sdk.Ecj -> {
when {
lint.isEmpty() -> out.add("-warn:none")
lint.containsAll(sdk.supportedWarnings) -> out.add("-warn:all")
else -> out.add("-warn:" + lint.intersect(sdk.supportedWarnings).joinToString(","))
}
}
is Sdk.OpenJdk -> {
when {
lint.isEmpty() -> out.add("-Xlint:none")
lint.containsAll(sdk.supportedWarnings) -> out.add("-Xlint:all")
else -> out.add("-Xlint:" + lint.intersect(sdk.supportedWarnings).joinToString(","))
}
}
is Sdk.Scala -> {
when {
lint.isEmpty() -> out.add("-Xlint:")
lint.containsAll(sdk.supportedWarnings) -> out.add("-Xlint:_")
else -> out.add("-Xlint:" + lint.intersect(sdk.supportedWarnings).joinToString(","))
}
}
else -> {
throw AssertionError()
}
}
}
}
return out
}
private inline fun releaseChoice(id: String,
param: String,
crossinline range: (Int) -> IntRange): ConfigProperty.RangeChoice =
object : ConfigProperty.RangeChoice(id, param, default = null) {
override fun apply(out: MutableList<String>, value: Int?) {
if (value != null) {
out.add(param)
if (value <= 5) {
out.add("1.$value")
} else {
out.add(value.toString())
}
}
}
override fun getRange(sdk: Sdk): IntRange {
val release = (sdk as Sdk.Java).release
return range(release)
}
}
private val propertyRelease = releaseChoice("release", "--release") { release ->
when {
release <= 8 -> throw AssertionError()
release <= 11 -> 6..release
else -> 7..release
}
}.apply { minJavaVersion = 9 }
val lombok: ConfigProperty<Boolean> = object : ConfigProperty.SpecialFlag("lombok", "Lombok", default = true) {
// don't show for SDKs that don't have lombok support
override fun canApplyTo(sdk: Sdk) = sdk is Sdk.Java && sdk.lombok != null
}
val lint: ConfigProperty<Set<String>?> = object : ConfigProperty.Special<Set<String>?>(
"lint", default = null,
serializer = SetSerializer(String.serializer()).nullable) {
override fun canApplyTo(sdk: Sdk) = sdk is Sdk.HasLint
override fun validate(sdk: Sdk, value: Set<String>?) {
require(value == null || Sdks.allSupportedWarnings.containsAll(value))
}
}
private val propertiesJava = listOf<ConfigProperty<*>>(
propertyRelease,
releaseChoice("source", "-source") { release ->
when {
release <= 8 -> 3..release
release <= 11 -> 6..release
else -> 7..release
}
}.apply {
enableDependsOn = ConfigProperty.Interdependency(propertyRelease) { _, it -> it == null }
},
releaseChoice("target", "-target") { release ->
when {
release <= 8 -> 1..release
release <= 11 -> 6..release
else -> 7..release
}
}.apply {
enableDependsOn = ConfigProperty.Interdependency(propertyRelease) { _, it -> it == null }
},
ConfigProperty.SpecialFlag("debugLines", "-g:lines", default = true),
ConfigProperty.SpecialFlag("debugVars", "-g:vars", default = true),
ConfigProperty.SpecialFlag("debugSource", "-g:source", default = true),
ConfigProperty.SimpleFlag("verbose", "-verbose"),
ConfigProperty.SimpleFlag("deprecation", "-deprecation"),
lombok,
ConfigProperty.SimpleFlag("reflectionParameters", "-parameters").apply { minJavaVersion = 8 },
object : ConfigProperty.SpecialFlag("warningsAsErrors", "-Werror") {
override fun canApplyTo(sdk: Sdk) =
super.canApplyTo(sdk) && (sdk !is Sdk.Ecj || sdk.release >= 9)
},
lint,
ConfigProperty.SimpleFlag("preview", "--enable-preview").apply {
minJavaVersion = 11
},
ConfigProperty.SimpleFlag("proceedOnError", "-proceedOnError", default = true).apply {
requireEcj = true
},
ConfigProperty.SimpleFlag("preserveAllLocals", "-preserveAllLocals").apply {
requireEcj = true
},
ConfigProperty.SimpleFlag("genericSignature", "-genericsignature").apply {
requireEcj = true
}
)
private val v1_0_2 = KotlinVersion(1, 0, 2)
private val v1_0_3 = KotlinVersion(1, 0, 3)
private val v1_0_5 = KotlinVersion(1, 0, 5)
private val v1_1_1 = KotlinVersion(1, 1, 1)
private val v1_2_30 = KotlinVersion(1, 2, 30)
private val v1_3_10 = KotlinVersion(1, 3, 10)
private val v1_3_50 = KotlinVersion(1, 3, 50)
private val propertyLanguageVersion: ConfigProperty.Choice<String?> = object : ConfigProperty.Choice<String?>(
"languageVersion",
"-language-version",
default = null, serializer = String.serializer().nullable) {
override fun apply(out: MutableList<String>, value: String?) {
if (value != null) {
out.add("-language-version")
// validated by strict getChoices
out.add(value)
}
}
override fun getChoices(sdk: Sdk) = mapOf("" to null) +
languageVersionMap
.filter { it.value <= (sdk as Sdk.Kotlin).release }
.keys.associateBy { it }
}
private val propertiesKotlin = listOf<ConfigProperty<*>>(
ConfigProperty.SimpleFlag("verbose", "-verbose")
.apply { minKotlinVersion = v1_0_2 },
ConfigProperty.SimpleFlag("noCallAssertions", "-Xno-call-assertions")
.apply { minKotlinVersion = v1_0_2 },
ConfigProperty.SimpleFlag("noParamAssertions", "-Xno-param-assertions")
.apply { minKotlinVersion = v1_0_2 },
ConfigProperty.SimpleFlag("noOptimize", "-Xno-optimize")
.apply { minKotlinVersion = v1_0_2 },
ConfigProperty.SimpleFlag("noInline", "-Xno-inline")
.apply { minKotlinVersion = v1_0_2 },
object : ConfigProperty.Choice<Int?>("jvmTarget", "-jvm-target",
default = null, serializer = Int.serializer().nullable) {
/**
* Supported jvm targets. 7 should be excluded
*/
/**
* Supported jvm targets. 7 should be excluded
*/
private fun jvmTargets(sdk: Sdk.Kotlin): IntRange {
if (sdk.release >= v1_3_50) return 6..12
if (sdk.release >= v1_1_1) return 6..8
if (sdk.release >= v1_0_3) return 6..6
throw AssertionError()
}
override fun apply(out: MutableList<String>, value: Int?) {
if (value != null) {
out.add("-jvm-target")
if (value <= 8) {
out.add("1.$value")
} else {
out.add("$value")
}
}
}
override fun getChoices(sdk: Sdk) =
mapOf("" to null) +
jvmTargets(sdk as Sdk.Kotlin).filter { it != 7 }.associateBy { "$it" }
}.apply { minKotlinVersion = v1_0_3 },
propertyLanguageVersion.apply { minKotlinVersion = v1_0_3 },
object : ConfigProperty.Choice<String?>("apiVersion", "-api-version", default = null,
serializer = String.serializer().nullable) {
init {
choicesDependOn = Interdependency(propertyLanguageVersion) { sdk, langVersion ->
mapOf("" to null) + languageVersionMap
.filter { it.value <= (sdk as Sdk.Kotlin).release }
.filter {
langVersion == null ||
it.value <= languageVersionMap.getValue(langVersion)
}
.keys.associateBy { it }
}
}
override fun apply(out: MutableList<String>, value: String?) {
if (value != null) {
out.add("-api-version")
// validated by strict getChoices
out.add(value)
}
}
override fun getChoices(sdk: Sdk) = throw AssertionError()
}.apply { minKotlinVersion = v1_0_5 },
ConfigProperty.SimpleFlag("javaParameters", "-java-parameters")
.apply { minKotlinVersion = v1_1_1 },
ConfigProperty.SimpleFlag("coroutines", "-Xcoroutines=enable")
.apply { minKotlinVersion = v1_1_1 },
ConfigProperty.SimpleFlag("warningsAsErrors", "-Werror")
.apply { minKotlinVersion = v1_2_30 },
object : ConfigProperty.Choice<Boolean?>("normalizeConstructorCalls", "-Xnormalize-constructor-calls",
default = null,
serializer = Boolean.serializer().nullable) {
override fun apply(out: MutableList<String>, value: Boolean?) {
if (value != null) {
out.add("-Xnormalize-constructor-calls=${if (value) "enable" else "disable"}")
}
}
override fun getChoices(sdk: Sdk) = mapOf("" to null, "enable" to true, "disable" to false)
}.apply { minKotlinVersion = v1_2_30 },
ConfigProperty.SimpleFlag("noExceptionOnExplicitEqualsForBoxedNull",
"-Xno-exception-on-explicit-equals-for-boxed-null")
.apply { minKotlinVersion = v1_2_30 },
ConfigProperty.SimpleFlag("noReceiverAssertions", "-Xno-receiver-assertions")
.apply { minKotlinVersion = v1_2_30 },
ConfigProperty.SimpleFlag("effectSystem", "-Xeffect-system")
.apply { minKotlinVersion = v1_2_30 },
object : ConfigProperty.Choice<AssertionMode?>("assertions",
"-Xassertions",
default = null,
serializer = AssertionMode.serializer().nullable) {
private val choices = mapOf(
AssertionMode.ALWAYS_ENABLE to "always-enable",
AssertionMode.ALWAYS_DISABLE to "always-disable",
AssertionMode.JVM to "jvm",
AssertionMode.LEGACY to "legacy"
)
override fun apply(out: MutableList<String>, value: AssertionMode?) {
if (value != null) {
out.add("-Xassertions=" + choices.getValue(value))
}
}
override fun getChoices(sdk: Sdk) = mapOf("" to null) +
choices.entries.associate { it.value to it.key }
}.apply { minKotlinVersion = v1_3_10 },
object : ConfigProperty.Choice<JvmDefaultMode?>("jvmDefault", "-Xjvm-default", default = null,
serializer = JvmDefaultMode.serializer().nullable) {
private val choices = mapOf(
JvmDefaultMode.ENABLE to "enable",
JvmDefaultMode.DISABLE to "disable",
JvmDefaultMode.COMPATIBILITY to "compatibility"
)
override fun apply(out: MutableList<String>, value: JvmDefaultMode?) {
if (value != null) {
out.add("-Xjvm-default=" + choices.getValue(value))
}
}
override fun getChoices(sdk: Sdk) = mapOf("" to null) +
choices.entries.associate { it.value to it.key }
}.apply { minKotlinVersion = v1_3_10 },
ConfigProperty.SimpleFlag("allowResultReturnType", "-Xallow-result-return-type")
.apply { minKotlinVersion = v1_2_30 },
ConfigProperty.SimpleFlag("properIeee754Comparisons", "-Xproper-ieee754-comparisons")
.apply { minKotlinVersion = v1_2_30 },
ConfigProperty.SimpleFlag("sanitizeParentheses", "-Xsanitize-parentheses")
.apply { minKotlinVersion = v1_3_50 },
ConfigProperty.SimpleFlag("listPhases", "-Xlist-phases")
.apply { minKotlinVersion = v1_3_50 },
ConfigProperty.SimpleFlag("polymorphicSignature", "-Xpolymorphic-signature")
.apply { minKotlinVersion = v1_3_50 }
)
@Serializable
private enum class AssertionMode {
ALWAYS_ENABLE,
ALWAYS_DISABLE,
JVM,
LEGACY,
}
@Serializable
private enum class JvmDefaultMode {
ENABLE,
DISABLE,
COMPATIBILITY
}
private val languageVersionMap = listOf(
KotlinVersion(1, 0),
KotlinVersion(1, 1),
KotlinVersion(1, 2),
KotlinVersion(1, 3)
).associateBy { "${it.major}.${it.minor}" }
private val v2_11_8 = KotlinVersion(2, 11, 8)
private val v2_12_5 = KotlinVersion(2, 12, 5)
private val scala = listOf(
ConfigProperty.SimpleFlag("deprecation", "-deprecation"),
ConfigProperty.SimpleFlag("explainTypes", "-explaintypes"),
object : ConfigProperty.Choice<String>("debug", "-g", serializer = String.serializer(), default = "vars") {
override fun apply(out: MutableList<String>, value: String) {
if (value != default) {
out.add("-g:$value")
}
}
override fun getChoices(sdk: Sdk) =
listOf("none", "source", "line", "vars", "notailcalls").associateBy { it }
},
ConfigProperty.SpecialFlag("debugSource", "-g:source"),
ConfigProperty.SpecialFlag("debugLine", "-g:line"),
ConfigProperty.SpecialFlag("debugVars", "-g:vars"),
ConfigProperty.SpecialFlag("debugNoTailCalls", "-g:notailcalls"),
ConfigProperty.SimpleFlag("debugNoSpecialization", "-no-specialization"),
ConfigProperty.SimpleFlag("optimise", "-optimise").apply { maxScalaVersion = v2_11_8 },
object : ConfigProperty.RangeChoice("target", "-target", default = null) {
override fun apply(out: MutableList<String>, value: Int?) {
if (value != null) {
out.add("-target")
out.add("jvm-1.$value")
}
}
override fun getRange(sdk: Sdk): IntRange {
return 5..8
}
},
object : ConfigProperty.RangeChoice("release", "-release", default = null) {
override fun apply(out: MutableList<String>, value: Int?) {
if (value != null) {
out.add("-release")
out.add(value.toString())
}
}
override fun getRange(sdk: Sdk): IntRange {
return 6..9
}
},
ConfigProperty.SimpleFlag("unchecked", "-unchecked"),
ConfigProperty.SimpleFlag("uniqid", "-uniqid"),
ConfigProperty.SimpleFlag("verbose", "-verbose"),
ConfigProperty.SimpleFlag("checkInit", "-Xcheckinit"),
ConfigProperty.SimpleFlag("dev", "-Xdev"),
ConfigProperty.SimpleFlag("disableAssertions", "-Xdisable-assertions"),
ConfigProperty.SimpleFlag("experimental", "-Xexperimental"),
ConfigProperty.SimpleFlag("warningsAsErrors", "-Xfatal-warnings"),
ConfigProperty.SimpleFlag("fullLubs", "-Xfull-lubs"),
ConfigProperty.SimpleFlag("future", "-Xfuture"),
ConfigProperty.SimpleFlag("noForwarders", "-Xno-forwarders"),
ConfigProperty.SimpleFlag("noPatmatAnalysis", "-Xno-patmat-analysis"),
ConfigProperty.SimpleFlag("noUescape", "-Xno-uescape"),
ConfigProperty.SpecialFlag("dynamics", "-language:dynamics"),
ConfigProperty.SpecialFlag("postfixOps", "-language:postfixOps"),
ConfigProperty.SpecialFlag("reflectiveCalls", "-language:reflectiveCalls"),
ConfigProperty.SpecialFlag("implicitConversions", "-language:implicitConversions"),
ConfigProperty.SpecialFlag("higherKinds", "-language:higherKinds"),
ConfigProperty.SpecialFlag("existentials", "-language:existentials"),
ConfigProperty.SimpleFlag("virtPatMat", "-Yvirtpatmat").apply {
minScalaVersion = v2_12_5
maxScalaVersion = v2_12_5
},
lint
)
val properties = mapOf(
SdkLanguage.JAVA to propertiesJava,
SdkLanguage.KOTLIN to propertiesKotlin,
SdkLanguage.SCALA to scala
)
init {
for ((language, list) in properties) {
for (property in list) {
property.init(language)
}
}
}
val serializers: Map<SdkLanguage, KSerializer<CompilerConfiguration>> =
properties.mapValues { (language, properties) ->
object : KSerializer<CompilerConfiguration> {
override val descriptor = buildClassSerialDescriptor("CompilerConfiguration.$language") {
for (property in properties) {
element(property.id, property.serializer.descriptor)
}
}
private fun <T> serializeEntry(
structure: CompositeEncoder,
config: CompilerConfiguration,
index: Int,
property: ConfigProperty<T>
) {
if (config.containsKey(property.id)) {
val value = config[property.id]
if (value != property.default) {
@Suppress("UNCHECKED_CAST")
structure.encodeSerializableElement(
descriptor,
index,
property.serializer,
value as T
)
}
}
}
override fun serialize(encoder: Encoder, value: CompilerConfiguration) {
val structure = encoder.beginStructure(descriptor)
for ((index, property) in properties.withIndex()) {
serializeEntry(structure, value, index, property)
}
structure.endStructure(descriptor)
}
override fun deserialize(decoder: Decoder): CompilerConfiguration {
val result = mutableMapOf<String, Any?>()
val structure = decoder.beginStructure(descriptor)
while (true) {
val i = structure.decodeElementIndex(descriptor)
if (i == CompositeDecoder.DECODE_DONE) break
val property = properties.getOrNull(i) ?: throw SerializationException("unknown index $i")
result[property.id] = structure.decodeSerializableElement(
property.serializer.descriptor, i, property.serializer)
}
structure.endStructure(descriptor)
return result
}
}
}
}
sealed class ConfigProperty<T>(
val id: String,
val default: T,
internal val serializer: KSerializer<T>
) {
private companion object {
private val ktv1 = KotlinVersion(1, 0)
private val ktvInf = KotlinVersion(255, 0)
}
private lateinit var language: SdkLanguage
internal var minJavaVersion = 0
internal var requireEcj = false
internal var minKotlinVersion: KotlinVersion = ktv1
internal var minScalaVersion: KotlinVersion = ktv1
internal var maxScalaVersion: KotlinVersion = ktvInf
/**
* Only allow setting this property if a given interdependency is met
*/
var enableDependsOn: Interdependency<*, Boolean>? = null
internal set
internal fun init(language: SdkLanguage) {
this.language = language
}
fun get(config: CompilerConfiguration): T {
if (config.containsKey(id)) {
@Suppress("UNCHECKED_CAST")
return config[id] as T
} else {
return default
}
}
open fun canApplyTo(sdk: Sdk) = when (sdk) {
is Sdk.OpenJdk, is Sdk.Ecj ->
language == SdkLanguage.JAVA &&
minJavaVersion <= (sdk as Sdk.Java).release &&
(!requireEcj || sdk is Sdk.Ecj)
is Sdk.KotlinJar, is Sdk.KotlinDistribution ->
language == SdkLanguage.KOTLIN && minKotlinVersion <= (sdk as Sdk.Kotlin).release
is Sdk.Scala ->
language == SdkLanguage.SCALA &&
minScalaVersion <= sdk.release &&
maxScalaVersion >= sdk.release
}
internal fun applyFrom(out: MutableList<String>, config: CompilerConfiguration) =
apply(out, get(config))
protected abstract fun apply(out: MutableList<String>, value: T)
internal open fun validateFrom(sdk: Sdk, config: CompilerConfiguration) {
val value = get(config)
if (value != default) {
val enableDependsOn = enableDependsOn
if (enableDependsOn != null) {
require(enableDependsOn(sdk, config))
}
}
validate(sdk, value)
}
protected abstract fun validate(sdk: Sdk, value: T)
open class Special<T>(id: String, default: T, serializer: KSerializer<T>) : ConfigProperty<T>(id,
default,
serializer) {
override fun apply(out: MutableList<String>, value: T) {
// special handling
}
override fun validate(sdk: Sdk, value: T) {
// special handling
}
}
abstract class Choice<T>(id: String,
val name: String, default: T, serializer: KSerializer<T>) :
ConfigProperty<T>(id, default, serializer) {
/**
* Change the choices based on an interdependency
*/
var choicesDependOn: Interdependency<*, Map<String, T>>? = null
internal set
abstract fun getChoices(sdk: Sdk): Map<String, T>
override fun validateFrom(sdk: Sdk, config: CompilerConfiguration) {
super.validateFrom(sdk, config)
val choicesDependOn = choicesDependOn
if (choicesDependOn != null) {
require(get(config) in choicesDependOn(sdk, config).values)
}
}
override fun validate(sdk: Sdk, value: T) {
if (choicesDependOn == null) {
require(value in getChoices(sdk).values)
}
// else validated above
}
}
abstract class RangeChoice(id: String, name: String, default: Int? = null) :
Choice<Int?>(id, name, default, Int.serializer().nullable) {
override fun getChoices(sdk: Sdk) =
mapOf("" to null) + getRange(sdk).associateBy { "$it" }
abstract fun getRange(sdk: Sdk): IntRange
override fun validate(sdk: Sdk, value: Int?) {
require(value == null || value in getRange(sdk))
}
}
/**
* A boolean flag
*/
abstract class Flag(
id: String,
val displayName: String,
default: Boolean
) : ConfigProperty<Boolean>(id, default = default, serializer = Boolean.serializer()) {
override fun validate(sdk: Sdk, value: Boolean) {
}
}
internal open class SpecialFlag(
id: String,
displayName: String,
default: Boolean = false
) : Flag(id, displayName, default) {
override fun apply(out: MutableList<String>, value: Boolean) {
}
}
/**
* A flag that leads to a simple added command line param
*/
internal class SimpleFlag(
id: String,
private val value: String,
default: Boolean = false
) : Flag(id, value, default = default) {
override fun apply(out: MutableList<String>, value: Boolean) {
if (value) {
out.add(this.value)
}
}
}
data class Interdependency<T, R>(
val dependsOn: ConfigProperty<T>,
val function: (Sdk, T) -> R
) {
operator fun invoke(sdk: Sdk, config: CompilerConfiguration) = function(sdk, dependsOn.get(config))
}
} | shared/src/commonMain/kotlin/at/yawk/javap/model/CompilerConfiguration.kt | 1308214172 |
/*
* Copyright (C) 2017 Moez Bhatti <[email protected]>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.receiver
import android.app.Activity
import android.content.BroadcastReceiver
import android.content.ContentUris
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.Telephony
import com.google.android.mms.MmsException
import com.google.android.mms.util_alt.SqliteWrapper
import com.klinker.android.send_message.Transaction
import com.moez.QKSMS.interactor.SyncMessage
import dagger.android.AndroidInjection
import timber.log.Timber
import java.io.File
import javax.inject.Inject
class MmsSentReceiver : BroadcastReceiver() {
@Inject lateinit var syncMessage: SyncMessage
override fun onReceive(context: Context, intent: Intent) {
AndroidInjection.inject(this, context)
Timber.v("MMS sending result: $resultCode")
val uri = Uri.parse(intent.getStringExtra(Transaction.EXTRA_CONTENT_URI))
Timber.v(uri.toString())
when (resultCode) {
Activity.RESULT_OK -> {
Timber.v("MMS has finished sending, marking it as so in the database")
val values = ContentValues(1)
values.put(Telephony.Mms.MESSAGE_BOX, Telephony.Mms.MESSAGE_BOX_SENT)
SqliteWrapper.update(context, context.contentResolver, uri, values, null, null)
}
else -> {
Timber.v("MMS has failed to send, marking it as so in the database")
try {
val messageId = ContentUris.parseId(uri)
val values = ContentValues(1)
values.put(Telephony.Mms.MESSAGE_BOX, Telephony.Mms.MESSAGE_BOX_FAILED)
SqliteWrapper.update(context, context.contentResolver, Telephony.Mms.CONTENT_URI, values,
"${Telephony.Mms._ID} = ?", arrayOf(messageId.toString()))
// TODO this query isn't able to find any results
// Need to figure out why the message isn't appearing in the PendingMessages Uri,
// so that we can properly assign the error type
val errorTypeValues = ContentValues(1)
errorTypeValues.put(Telephony.MmsSms.PendingMessages.ERROR_TYPE,
Telephony.MmsSms.ERR_TYPE_GENERIC_PERMANENT)
SqliteWrapper.update(context, context.contentResolver, Telephony.MmsSms.PendingMessages.CONTENT_URI,
errorTypeValues, "${Telephony.MmsSms.PendingMessages.MSG_ID} = ?",
arrayOf(messageId.toString()))
} catch (e: MmsException) {
e.printStackTrace()
}
}
}
val filePath = intent.getStringExtra(Transaction.EXTRA_FILE_PATH)
Timber.v(filePath)
File(filePath).delete()
Uri.parse(intent.getStringExtra("content_uri"))?.let { uri ->
val pendingResult = goAsync()
syncMessage.execute(uri) { pendingResult.finish() }
}
}
} | data/src/main/java/com/moez/QKSMS/receiver/MmsSentReceiver.kt | 2196060002 |
/*
Copyright (C) 2015 - 2019 Electronic Arts Inc. All rights reserved.
This file is part of the Orbit Project <https://www.orbit.cloud>.
See license in LICENSE.
*/
package orbit.server.mesh
data class LocalServerInfo(val port: Int, val url: String) | src/orbit-server/src/main/kotlin/orbit/server/mesh/LocalServerInfo.kt | 2085837585 |
/*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.moshi
import com.squareup.moshi.JsonValueReader.JsonIterator
import com.squareup.moshi.internal.knownNotNull
import okio.Buffer
import okio.BufferedSource
import java.math.BigDecimal
/** Sentinel object pushed on [JsonValueReader.stack] when the reader is closed. */
private val JSON_READER_CLOSED = Any()
/**
* This class reads a JSON document by traversing a Java object comprising maps, lists, and JSON
* primitives. It does depth-first traversal keeping a stack starting with the root object. During
* traversal a stack tracks the current position in the document:
* * The next element to act upon is on the top of the stack.
* * When the top of the stack is a [List], calling [beginArray] replaces the list with a [JsonIterator]. The first
* element of the iterator is pushed on top of the iterator.
* * Similarly, when the top of the stack is a [Map], calling [beginObject] replaces the map with an [JsonIterator]
* of its entries. The first element of the iterator is pushed on top of the iterator.
* * When the top of the stack is a [Map.Entry], calling [nextName] returns the entry's key and replaces the entry
* with its value on the stack.
* * When an element is consumed it is popped. If the new top of the stack has a non-exhausted iterator, the next
* element of that iterator is pushed.
* * If the top of the stack is an exhausted iterator, calling [endArray] or [endObject] will pop it.
*/
internal class JsonValueReader : JsonReader {
private var stack: Array<Any?>
constructor(root: Any?) {
scopes[stackSize] = JsonScope.NONEMPTY_DOCUMENT
stack = arrayOfNulls(32)
stack[stackSize++] = root
}
/** Copy-constructor makes a deep copy for peeking. */
constructor(copyFrom: JsonValueReader) : super(copyFrom) {
stack = copyFrom.stack.clone()
for (i in 0 until stackSize) {
val element = stack[i]
if (element is JsonIterator) {
stack[i] = element.clone()
}
}
}
override fun beginArray() {
val peeked = require<List<*>>(Token.BEGIN_ARRAY)
val iterator = JsonIterator(Token.END_ARRAY, peeked.toTypedArray(), 0)
stack[stackSize - 1] = iterator
scopes[stackSize - 1] = JsonScope.EMPTY_ARRAY
pathIndices[stackSize - 1] = 0
// If the iterator isn't empty push its first value onto the stack.
if (iterator.hasNext()) {
push(iterator.next())
}
}
override fun endArray() {
val peeked = require<JsonIterator>(Token.END_ARRAY)
if (peeked.endToken != Token.END_ARRAY || peeked.hasNext()) {
throw typeMismatch(peeked, Token.END_ARRAY)
}
remove()
}
override fun beginObject() {
val peeked = require<Map<*, *>>(Token.BEGIN_OBJECT)
val iterator = JsonIterator(Token.END_OBJECT, peeked.entries.toTypedArray(), 0)
stack[stackSize - 1] = iterator
scopes[stackSize - 1] = JsonScope.EMPTY_OBJECT
// If the iterator isn't empty push its first value onto the stack.
if (iterator.hasNext()) {
push(iterator.next())
}
}
override fun endObject() {
val peeked = require<JsonIterator>(Token.END_OBJECT)
if (peeked.endToken != Token.END_OBJECT || peeked.hasNext()) {
throw typeMismatch(peeked, Token.END_OBJECT)
}
pathNames[stackSize - 1] = null
remove()
}
override fun hasNext(): Boolean {
if (stackSize == 0) return false
val peeked = stack[stackSize - 1]
return peeked !is Iterator<*> || peeked.hasNext()
}
override fun peek(): Token {
if (stackSize == 0) return Token.END_DOCUMENT
// If the top of the stack is an iterator, take its first element and push it on the stack.
return when (val peeked = stack[stackSize - 1]) {
is JsonIterator -> peeked.endToken
is List<*> -> Token.BEGIN_ARRAY
is Map<*, *> -> Token.BEGIN_OBJECT
is Map.Entry<*, *> -> Token.NAME
is String -> Token.STRING
is Boolean -> Token.BOOLEAN
is Number -> Token.NUMBER
null -> Token.NULL
else -> ifNotClosed(peeked) {
throw typeMismatch(peeked, "a JSON value")
}
}
}
override fun nextName(): String {
val peeked = require<Map.Entry<*, *>>(Token.NAME)
// Swap the Map.Entry for its value on the stack and return its key.
val result = stringKey(peeked)
stack[stackSize - 1] = peeked.value
pathNames[stackSize - 2] = result
return result
}
override fun selectName(options: Options): Int {
val peeked = require<Map.Entry<*, *>>(Token.NAME)
val name = stringKey(peeked)
for (i in options.strings.indices) {
// Swap the Map.Entry for its value on the stack and return its key.
if (options.strings[i] == name) {
stack[stackSize - 1] = peeked.value
pathNames[stackSize - 2] = name
return i
}
}
return -1
}
override fun skipName() {
if (failOnUnknown) {
// Capture the peeked value before nextName() since it will reset its value.
val peeked = peek()
nextName() // Move the path forward onto the offending name.
throw JsonDataException("Cannot skip unexpected $peeked at $path")
}
val (_, value) = require<Map.Entry<*, *>>(Token.NAME)
// Swap the Map.Entry for its value on the stack.
stack[stackSize - 1] = value
pathNames[stackSize - 2] = "null"
}
override fun nextString(): String {
return when (val peeked = if (stackSize != 0) stack[stackSize - 1] else null) {
is String -> {
remove()
peeked
}
is Number -> {
remove()
peeked.toString()
}
else -> ifNotClosed(peeked) {
throw typeMismatch(peeked, Token.STRING)
}
}
}
override fun selectString(options: Options): Int {
val peeked = if (stackSize != 0) stack[stackSize - 1] else null
if (peeked !is String) {
ifNotClosed(peeked) {
-1
}
}
for (i in options.strings.indices) {
if (options.strings[i] == peeked) {
remove()
return i
}
}
return -1
}
override fun nextBoolean(): Boolean {
val peeked = require<Boolean>(Token.BOOLEAN)
remove()
return peeked
}
override fun <T> nextNull(): T? {
requireNull()
remove()
return null
}
override fun nextDouble(): Double {
val result = when (val peeked = require<Any>(Token.NUMBER)) {
is Number -> peeked.toDouble()
is String -> {
try {
peeked.toDouble()
} catch (e: NumberFormatException) {
throw typeMismatch(peeked, Token.NUMBER)
}
}
else -> {
throw typeMismatch(peeked, Token.NUMBER)
}
}
if (!lenient && (result.isNaN() || result.isInfinite())) {
throw JsonEncodingException("JSON forbids NaN and infinities: $result at path $path")
}
remove()
return result
}
override fun nextLong(): Long {
val result: Long = when (val peeked = require<Any>(Token.NUMBER)) {
is Number -> peeked.toLong()
is String -> try {
peeked.toLong()
} catch (e: NumberFormatException) {
try {
BigDecimal(peeked).longValueExact()
} catch (e2: NumberFormatException) {
throw typeMismatch(peeked, Token.NUMBER)
}
}
else -> throw typeMismatch(peeked, Token.NUMBER)
}
remove()
return result
}
override fun nextInt(): Int {
val result = when (val peeked = require<Any>(Token.NUMBER)) {
is Number -> peeked.toInt()
is String -> try {
peeked.toInt()
} catch (e: NumberFormatException) {
try {
BigDecimal(peeked).intValueExact()
} catch (e2: NumberFormatException) {
throw typeMismatch(peeked, Token.NUMBER)
}
}
else -> throw typeMismatch(peeked, Token.NUMBER)
}
remove()
return result
}
override fun skipValue() {
if (failOnUnknown) {
throw JsonDataException("Cannot skip unexpected ${peek()} at $path")
}
// If this element is in an object clear out the key.
if (stackSize > 1) {
pathNames[stackSize - 2] = "null"
}
val skipped = if (stackSize != 0) stack[stackSize - 1] else null
if (skipped is JsonIterator) {
throw JsonDataException("Expected a value but was ${peek()} at path $path")
}
if (skipped is Map.Entry<*, *>) {
// We're skipping a name. Promote the map entry's value.
val entry = stack[stackSize - 1] as Map.Entry<*, *>
stack[stackSize - 1] = entry.value
} else if (stackSize > 0) {
// We're skipping a value.
remove()
} else {
throw JsonDataException("Expected a value but was ${peek()} at path $path")
}
}
override fun nextSource(): BufferedSource {
val value = readJsonValue()
val result = Buffer()
JsonWriter.of(result).use { jsonWriter -> jsonWriter.jsonValue(value) }
return result
}
override fun peekJson(): JsonReader = JsonValueReader(this)
override fun promoteNameToValue() {
if (hasNext()) {
val name = nextName()
push(name)
}
}
override fun close() {
stack.fill(null, 0, stackSize)
stack[0] = JSON_READER_CLOSED
scopes[0] = JsonScope.CLOSED
stackSize = 1
}
private fun push(newTop: Any?) {
if (stackSize == stack.size) {
if (stackSize == 256) {
throw JsonDataException("Nesting too deep at $path")
}
scopes = scopes.copyOf(scopes.size * 2)
pathNames = pathNames.copyOf(pathNames.size * 2)
pathIndices = pathIndices.copyOf(pathIndices.size * 2)
stack = stack.copyOf(stack.size * 2)
}
stack[stackSize++] = newTop
}
private inline fun <reified T> require(expected: Token): T = knownNotNull(require(T::class.java, expected))
private fun requireNull() = require(Void::class.java, Token.NULL)
/**
* Returns the top of the stack which is required to be a `type`. Throws if this reader is
* closed, or if the type isn't what was expected.
*/
private fun <T> require(type: Class<T>, expected: Token): T? {
val peeked = if (stackSize != 0) stack[stackSize - 1] else null
if (type.isInstance(peeked)) {
return type.cast(peeked)
}
if (peeked == null && expected == Token.NULL) {
return null
}
ifNotClosed(peeked) {
throw typeMismatch(peeked, expected)
}
}
private fun stringKey(entry: Map.Entry<*, *>): String {
val name = entry.key
if (name is String) return name
throw typeMismatch(name, Token.NAME)
}
private inline fun <T> ifNotClosed(peeked: Any?, body: () -> T): T {
check(peeked !== JSON_READER_CLOSED) { "JsonReader is closed" }
return body()
}
/**
* Removes a value and prepares for the next. If we're iterating a map or list this advances the
* iterator.
*/
private fun remove() {
stackSize--
stack[stackSize] = null
scopes[stackSize] = 0
// If we're iterating an array or an object push its next element on to the stack.
if (stackSize > 0) {
pathIndices[stackSize - 1]++
val parent = stack[stackSize - 1]
if (parent is Iterator<*> && parent.hasNext()) {
push(parent.next())
}
}
}
internal class JsonIterator(
val endToken: Token,
val array: Array<Any?>,
var next: Int
) : Iterator<Any?>, Cloneable {
override fun hasNext() = next < array.size
override fun next() = array[next++]
// No need to copy the array; it's read-only.
public override fun clone() = JsonIterator(endToken, array, next)
}
}
| moshi/src/main/java/com/squareup/moshi/JsonValueReader.kt | 3631961394 |
package org.http4k.client
import org.http4k.core.BodyMode
import org.http4k.core.HttpHandler
import org.http4k.server.ServerConfig
import org.http4k.server.SunHttp
import org.http4k.streaming.StreamingContract
class ApacheClientStreamingContractTest : StreamingContract() {
override fun serverConfig(): ServerConfig = SunHttp(0)
override fun createClient(): HttpHandler = ApacheClient(requestBodyMode = BodyMode.Stream, responseBodyMode = BodyMode.Stream)
}
| http4k-client/apache/src/test/kotlin/org/http4k/client/ApacheClientStreamingContractTest.kt | 3279045770 |
package me.myatminsoe.mdetect
import java.util.concurrent.BlockingQueue
import java.util.concurrent.Executor
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.ThreadFactory
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit
class JobExecutor : Executor {
private val workQueue: BlockingQueue<Runnable>
private val threadPoolExecutor: ThreadPoolExecutor
private val threadFactory: ThreadFactory
init {
this.workQueue = LinkedBlockingQueue()
this.threadFactory = JobThreadFactory()
this.threadPoolExecutor = ThreadPoolExecutor(
INITIAL_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME.toLong(),
KEEP_ALIVE_TIME_UNIT, this.workQueue, this.threadFactory
)
}
override fun execute(runnable: Runnable?) {
if (runnable == null) {
throw IllegalArgumentException("Runnable to execute cannot be null")
}
this.threadPoolExecutor.execute(runnable)
}
private class JobThreadFactory : ThreadFactory {
private var counter = 0
override fun newThread(runnable: Runnable): Thread {
return Thread(runnable, THREAD_NAME + counter++)
}
companion object {
private val THREAD_NAME = "android_"
}
}
companion object {
private val INITIAL_POOL_SIZE = 3
private val MAX_POOL_SIZE = 5
// Sets the amount of time an idle thread waits before terminating
private val KEEP_ALIVE_TIME = 10
// Sets the Time Unit to seconds
private val KEEP_ALIVE_TIME_UNIT = TimeUnit.SECONDS
}
}
| mdetect/src/main/java/me/myatminsoe/mdetect/JobExecutor.kt | 1569661498 |
package src.configuration
import components.progressBar.Panel
/**
* Created by vicboma on 02/12/16.
*/
class ConfigurationImpl internal constructor(override val display: Display, override val panel: Panel) : Configuration {
companion object {
fun create(display: Display, panel: Panel): Configuration {
return ConfigurationImpl(display, panel)
}
}
}
| 00-start-async-application/src/main/kotlin/configuration/ConfigurationImpl.kt | 1665790653 |
package com.lbbento.pitchupwear.main
import com.lbbento.pitchupcore.TuningStatus.DEFAULT
import com.lbbento.pitchuptuner.GuitarTunerReactive
import com.lbbento.pitchupwear.AppSchedulers
import com.lbbento.pitchupwear.di.ForActivity
import com.lbbento.pitchupwear.ui.BasePresenter
import com.lbbento.pitchupwear.util.PermissionHelper
import javax.inject.Inject
@ForActivity
class MainPresenter @Inject constructor(val appSchedulers: AppSchedulers,
val permissionHelper: PermissionHelper,
val guitarTunerReactive: GuitarTunerReactive,
val mapper: TunerServiceMapper) : BasePresenter<MainView>() {
override fun onCreated() {
super.onCreated()
mView.setAmbientEnabled()
mView.setupGauge()
}
override fun onViewResuming() {
if (permissionHelper.handleMicrophonePermission()) {
guitarTunerReactive.listenToNotes()
.subscribeOn(appSchedulers.io())
.observeOn(appSchedulers.ui())
.subscribeAndManage(
{ tunerResultReceived(mapper.tunerResultToViewModel(it!!)) },
{ tunerResultError() })
}
}
private fun tunerResultReceived(tunerViewModel: TunerViewModel) {
if (tunerViewModel.tuningStatus != DEFAULT) {
mView.updateNote(tunerViewModel.note)
mView.updateIndicator((tunerViewModel.diffInCents * -1).toFloat())
mView.updateCurrentFrequency((tunerViewModel.expectedFrequency + (tunerViewModel.diffFrequency * -1)).toFloat())
} else {
mView.updateToDefaultStatus()
}
}
private fun tunerResultError() {
mView.informError()
}
} | wear2/src/main/kotlin/com/lbbento/pitchupwear/main/MainPresenter.kt | 1625808164 |
/*
* Copyright (c) 2010-2022 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.habdroid.model
import android.graphics.Color
import android.location.Location
import android.os.Parcelable
import java.util.IllegalFormatException
import java.util.Locale
import java.util.regex.Pattern
import kotlin.math.roundToInt
import kotlinx.parcelize.Parcelize
@Parcelize
data class HsvState internal constructor(val hue: Float, val saturation: Float, val value: Float) : Parcelable {
fun toColor(includeValue: Boolean = true): Int {
return Color.HSVToColor(floatArrayOf(hue, saturation, if (includeValue) value else 100F))
}
}
@Parcelize
data class ParsedState internal constructor(
val asString: String,
val asBoolean: Boolean,
val asNumber: NumberState?,
val asHsv: HsvState?,
val asBrightness: Int?,
val asLocation: Location?
) : Parcelable {
override fun equals(other: Any?): Boolean {
return other is ParsedState && asString == other.asString
}
override fun hashCode(): Int {
return asString.hashCode()
}
companion object {
internal fun parseAsBoolean(state: String): Boolean {
// If state is ON for switches return True
if (state == "ON") {
return true
}
val brightness = parseAsBrightness(state)
if (brightness != null) {
return brightness != 0
}
return try {
val decimalValue = Integer.valueOf(state)
decimalValue > 0
} catch (e: NumberFormatException) {
false
}
}
internal fun parseAsNumber(state: String, format: String?): NumberState? {
return when (state) {
"ON" -> NumberState(100F)
"OFF" -> NumberState(0F)
else -> {
val brightness = parseAsBrightness(state)
if (brightness != null) {
NumberState(brightness.toFloat())
} else {
val spacePos = state.indexOf(' ')
val number = if (spacePos >= 0) state.substring(0, spacePos) else state
val unit = if (spacePos >= 0) state.substring(spacePos + 1) else null
return try {
NumberState(number.toFloat(), unit, format)
} catch (e: NumberFormatException) {
null
}
}
}
}
}
internal fun parseAsHsv(state: String): HsvState? {
val stateSplit = state.split(",")
if (stateSplit.size == 3) { // We need exactly 3 numbers to operate this
try {
return HsvState(stateSplit[0].toFloat(),
stateSplit[1].toFloat() / 100,
stateSplit[2].toFloat() / 100)
} catch (e: NumberFormatException) {
// fall through
}
}
return null
}
internal fun parseAsLocation(state: String): Location? {
val splitState = state.split(",")
// Valid states are either "latitude,longitude" or "latitude,longitude,elevation",
if (splitState.size == 2 || splitState.size == 3) {
try {
val l = Location("openhab")
l.latitude = splitState[0].toDouble()
l.longitude = splitState[1].toDouble()
l.time = System.currentTimeMillis()
if (splitState.size == 3) {
l.altitude = splitState[2].toDouble()
}
// Do our best to avoid parsing e.g. HSV values into location by
// sanity checking the values
if (Math.abs(l.latitude) <= 90 && Math.abs(l.longitude) <= 180) {
return l
}
} catch (e: NumberFormatException) {
// ignored
}
}
return null
}
internal fun parseAsBrightness(state: String): Int? {
val hsbMatcher = HSB_PATTERN.matcher(state)
if (hsbMatcher.find()) {
try {
return hsbMatcher.group(3)?.toFloat()?.roundToInt()
} catch (e: NumberFormatException) {
// fall through
}
}
return null
}
private val HSB_PATTERN = Pattern.compile("^([0-9]*\\.?[0-9]+),([0-9]*\\.?[0-9]+),([0-9]*\\.?[0-9]+)$")
}
@Parcelize
class NumberState internal constructor(
val value: Float,
val unit: String? = null,
val format: String? = null
) : Parcelable {
override fun toString(): String {
return toString(Locale.getDefault())
}
/**
* Like [toString][.toString], but using a specific locale for formatting.
*/
fun toString(locale: Locale): String {
if (!format.isNullOrEmpty()) {
val actualFormat = format.replace("%unit%", unit.orEmpty())
try {
return String.format(locale, actualFormat, getActualValue())
} catch (e: IllegalFormatException) {
// State format pattern doesn't match the actual data type
// -> ignore and fall back to our own formatting
}
}
return if (unit == null) formatValue() else "${formatValue()} $unit"
}
fun formatValue(): String {
return getActualValue().toString()
}
private fun getActualValue(): Number {
return if (format != null && format.contains("%d")) value.roundToInt() else value
}
}
}
fun ParsedState.NumberState?.withValue(value: Float): ParsedState.NumberState {
return ParsedState.NumberState(value, this?.unit, this?.format)
}
/**
* Parses a state string into the parsed representation.
*
* @param numberPattern Format to use when parsing the input as number
* @return null if state string is null, parsed representation otherwise
*/
fun String?.toParsedState(numberPattern: String? = null): ParsedState? {
if (this == null) {
return null
}
return ParsedState(this,
ParsedState.parseAsBoolean(this),
ParsedState.parseAsNumber(this, numberPattern),
ParsedState.parseAsHsv(this),
ParsedState.parseAsBrightness(this),
ParsedState.parseAsLocation(this))
}
| mobile/src/main/java/org/openhab/habdroid/model/ParsedState.kt | 704627855 |
package lt.vilnius.tvarkau.prefs
import android.content.SharedPreferences
import com.vinted.preferx.PreferxSerializer
import com.vinted.preferx.longPreference
import com.vinted.preferx.objectPreference
import com.vinted.preferx.stringPreference
import lt.vilnius.tvarkau.auth.ApiToken
import lt.vilnius.tvarkau.data.GsonSerializer
import lt.vilnius.tvarkau.entity.City
import java.lang.reflect.Type
class AppPreferencesImpl(
private val preferences: SharedPreferences,
private val gsonSerializer: GsonSerializer
) : AppPreferences {
private val serializer = object : PreferxSerializer {
override fun fromString(string: String, type: Type): Any {
return gsonSerializer.fromJsonType(string, type)
}
override fun toString(value: Any): String {
return gsonSerializer.toJson(value)
}
}
override val apiToken by lazy {
preferences.objectPreference(
name = API_TOKEN,
defaultValue = ApiToken(),
serializer = serializer,
clazz = ApiToken::class.java
)
}
override val photoInstructionsLastSeen by lazy {
preferences.longPreference(LAST_DISPLAYED_PHOTO_INSTRUCTIONS, 0L)
}
override val reportStatusSelectedFilter by lazy {
preferences.stringPreference(SELECTED_FILTER_REPORT_STATUS, "")
}
override val reportTypeSelectedFilter by lazy {
preferences.stringPreference(SELECTED_FILTER_REPORT_TYPE, "")
}
override val reportStatusSelectedListFilter by lazy {
preferences.stringPreference(LIST_SELECTED_FILTER_REPORT_STATUS, "")
}
override val reportTypeSelectedListFilter by lazy {
preferences.stringPreference(LIST_SELECTED_FILTER_REPORT_TYPE, "")
}
override val selectedCity by lazy {
preferences.objectPreference(
name = SELECTED_CITY,
defaultValue = City.NOT_SELECTED,
serializer = serializer,
clazz = City::class.java
)
}
companion object {
const val API_TOKEN = "api_token"
const val SELECTED_CITY = "selected_city"
const val SELECTED_FILTER_REPORT_STATUS = "filter_report_status"
const val SELECTED_FILTER_REPORT_TYPE = "filter_report_type"
const val LIST_SELECTED_FILTER_REPORT_STATUS = "list_filter_report_status"
const val LIST_SELECTED_FILTER_REPORT_TYPE = "list_filter_report_type"
const val LAST_DISPLAYED_PHOTO_INSTRUCTIONS = "last_displayed_photo_instructions"
}
}
| app/src/main/java/lt/vilnius/tvarkau/prefs/AppPreferencesImpl.kt | 1506860924 |
/*
Copyright (c) 2020 David Allison <[email protected]>
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 3 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.anki
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.ichi2.anki.cardviewer.ViewerCommand
import com.ichi2.anki.cardviewer.ViewerCommand.*
import com.ichi2.anki.reviewer.CardMarker.Companion.FLAG_BLUE
import com.ichi2.anki.reviewer.CardMarker.Companion.FLAG_GREEN
import com.ichi2.anki.reviewer.CardMarker.Companion.FLAG_NONE
import com.ichi2.anki.reviewer.CardMarker.Companion.FLAG_ORANGE
import com.ichi2.anki.reviewer.CardMarker.Companion.FLAG_PINK
import com.ichi2.anki.reviewer.CardMarker.Companion.FLAG_PURPLE
import com.ichi2.anki.reviewer.CardMarker.Companion.FLAG_RED
import com.ichi2.anki.reviewer.CardMarker.Companion.FLAG_TURQUOISE
import com.ichi2.anki.reviewer.CardMarker.FlagDef
import com.ichi2.anki.reviewer.ReviewerUi.ControlBlock
import com.ichi2.libanki.Card
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.equalTo
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentMatchers.anyInt
import org.mockito.Mockito.*
import org.mockito.invocation.InvocationOnMock
import org.mockito.kotlin.whenever
@RunWith(AndroidJUnit4::class)
class AbstractFlashcardViewerCommandTest : RobolectricTest() {
@Test
fun doubleTapSetsNone() {
val viewer = createViewer()
viewer.executeCommand(TOGGLE_FLAG_RED)
viewer.executeCommand(TOGGLE_FLAG_RED)
assertThat(viewer.lastFlag, equalTo(FLAG_NONE))
}
@Test
fun noneDoesNothing() {
val viewer = createViewer()
viewer.executeCommand(UNSET_FLAG)
assertThat(viewer.lastFlag, equalTo(FLAG_NONE))
}
@Test
fun doubleNoneDoesNothing() {
val viewer = createViewer()
viewer.executeCommand(UNSET_FLAG)
viewer.executeCommand(UNSET_FLAG)
assertThat(viewer.lastFlag, equalTo(FLAG_NONE))
}
@Test
fun flagCanBeChanged() {
val viewer = createViewer()
viewer.executeCommand(TOGGLE_FLAG_RED)
viewer.executeCommand(TOGGLE_FLAG_BLUE)
assertThat(viewer.lastFlag, equalTo(FLAG_BLUE))
}
@Test
fun unsetUnsets() {
val viewer = createViewer()
viewer.executeCommand(TOGGLE_FLAG_RED)
viewer.executeCommand(UNSET_FLAG)
assertThat(viewer.lastFlag, equalTo(FLAG_NONE))
}
@Test
fun tapRedFlagSetsRed() {
val viewer = createViewer()
viewer.executeCommand(TOGGLE_FLAG_RED)
assertThat(viewer.lastFlag, equalTo(FLAG_RED))
}
@Test
fun tapOrangeFlagSetsOrange() {
val viewer = createViewer()
viewer.executeCommand(TOGGLE_FLAG_ORANGE)
assertThat(viewer.lastFlag, equalTo(FLAG_ORANGE))
}
@Test
fun tapGreenFlagSesGreen() {
val viewer = createViewer()
viewer.executeCommand(TOGGLE_FLAG_GREEN)
assertThat(viewer.lastFlag, equalTo(FLAG_GREEN))
}
@Test
fun tapBlueFlagSetsBlue() {
val viewer = createViewer()
viewer.executeCommand(TOGGLE_FLAG_BLUE)
assertThat(viewer.lastFlag, equalTo(FLAG_BLUE))
}
@Test
fun tapPinkFlagSetsPink() {
val viewer = createViewer()
viewer.executeCommand(TOGGLE_FLAG_PINK)
assertThat(viewer.lastFlag, equalTo(FLAG_PINK))
}
@Test
fun tapTurquoiseFlagSetsTurquoise() {
val viewer = createViewer()
viewer.executeCommand(TOGGLE_FLAG_TURQUOISE)
assertThat(viewer.lastFlag, equalTo(FLAG_TURQUOISE))
}
@Test
fun tapPurpleFlagSetsPurple() {
val viewer = createViewer()
viewer.executeCommand(TOGGLE_FLAG_PURPLE)
assertThat(viewer.lastFlag, equalTo(FLAG_PURPLE))
}
@Test
fun doubleTapUnsets() {
testDoubleTapUnsets(TOGGLE_FLAG_RED)
testDoubleTapUnsets(TOGGLE_FLAG_ORANGE)
testDoubleTapUnsets(TOGGLE_FLAG_GREEN)
testDoubleTapUnsets(TOGGLE_FLAG_BLUE)
testDoubleTapUnsets(TOGGLE_FLAG_PINK)
testDoubleTapUnsets(TOGGLE_FLAG_TURQUOISE)
testDoubleTapUnsets(TOGGLE_FLAG_PURPLE)
}
private fun testDoubleTapUnsets(command: ViewerCommand) {
val viewer = createViewer()
viewer.executeCommand(command)
viewer.executeCommand(command)
assertThat(command.toString(), viewer.lastFlag, equalTo(FLAG_NONE))
}
private fun createViewer(): CommandTestCardViewer {
return CommandTestCardViewer(cardWith(FLAG_NONE))
}
private fun cardWith(@Suppress("SameParameterValue") @FlagDef flag: Int): Card {
val c = mock(Card::class.java)
val flags = intArrayOf(flag)
whenever(c.userFlag()).then { flags[0] }
doAnswer { invocation: InvocationOnMock ->
flags[0] = invocation.getArgument(0)
null
}.whenever(c).setUserFlag(anyInt())
return c
}
private class CommandTestCardViewer(private var currentCardOverride: Card?) : Reviewer() {
var lastFlag = 0
private set
override var currentCard: Card?
get() = currentCardOverride
set(card) {
// we don't have getCol() here and we don't need the additional sound processing.
currentCardOverride = card
}
override fun setTitle() {
// Intentionally blank
}
override fun performReload() {
// intentionally blank
}
override var controlBlocked: ControlBlock
get() = ControlBlock.UNBLOCKED
set(controlBlocked) {
super.controlBlocked = controlBlocked
}
override val isControlBlocked: Boolean
get() = controlBlocked !== ControlBlock.UNBLOCKED
override fun onFlag(card: Card?, @FlagDef flag: Int) {
lastFlag = flag
currentCard!!.setUserFlag(flag)
}
}
}
| AnkiDroid/src/test/java/com/ichi2/anki/AbstractFlashcardViewerCommandTest.kt | 2993058205 |
package com.octaldata.domain.topics
data class TenantName(val value: String)
data class Tenant(val name: TenantName, val props: Map<String, String>)
data class NamespaceName(val value: String)
data class Namespace(
val tenantName: TenantName,
val name: NamespaceName,
val props: Map<String, String>
) | streamops-domain/src/main/kotlin/com/octaldata/domain/topics/namespaces.kt | 969857442 |
package de.westnordost.streetcomplete.quests.parking_access
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType
import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.CAR
class AddParkingAccess : OsmFilterQuestType<ParkingAccess>() {
// Exclude parking=street_side lacking any access tags, because most of
// these are found alongside public access roads, and likely will be
// access=yes by default. Leaving these in makes this quest repetitive and
// leads to users adding lots of redundant access=yes tags to satisfy the
// quest. parking=street_side with access=unknown seems like a valid target
// though.
//
// Cf. #2408: Parking access might omit parking=street_side
override val elementFilter = """
nodes, ways, relations with amenity = parking
and (
access = unknown
or (!access and parking !~ street_side|lane)
)
"""
override val commitMessage = "Add type of parking access"
override val wikiLink = "Tag:amenity=parking"
override val icon = R.drawable.ic_quest_parking_access
override val questTypeAchievements = listOf(CAR)
override fun getTitle(tags: Map<String, String>) = R.string.quest_parking_access_title
override fun createForm() = AddParkingAccessForm()
override fun applyAnswerTo(answer: ParkingAccess, changes: StringMapChangesBuilder) {
changes.addOrModify("access", answer.osmValue)
}
}
| app/src/main/java/de/westnordost/streetcomplete/quests/parking_access/AddParkingAccess.kt | 689187323 |
package com.fracturedskies.render.common.components.gl
import com.fracturedskies.engine.collections.*
import com.fracturedskies.engine.jeact.*
import com.fracturedskies.engine.math.Matrix4
import com.fracturedskies.engine.math.Matrix4.Companion.orthogonal
class GLOrthogonal : Component<Unit>(Unit) {
companion object {
fun Node.Builder<*>.orthogonal(location: Int, near: Float = 0.03f, far: Float = 1000f, additionalProps: MultiTypeMap = MultiTypeMap()) {
nodes.add(Node(GLOrthogonal::class, MultiTypeMap(
LOCATION to location,
NEAR to near,
FAR to far
).with(additionalProps)))
}
val LOCATION = TypedKey<Int>("location")
val NEAR = TypedKey<Float>("near")
val FAR = TypedKey<Float>("far")
}
override fun componentWillUpdate(nextProps: MultiTypeMap, nextState: Unit) {
super.componentWillUpdate(nextProps, nextState)
// Reset project
this.bounds = Bounds(0, 0, 0, 0)
}
private lateinit var projection: Matrix4
override fun glRender(bounds: Bounds) {
if (bounds != this.bounds)
projection = orthogonal(bounds.height.toFloat(), bounds.width.toFloat(), 0f, 0f, props[NEAR], props[FAR])
glUniform(props[LOCATION], projection)
super.glRender(bounds)
}
} | src/main/kotlin/com/fracturedskies/render/common/components/gl/GLOrthogonal.kt | 1289639981 |
/*
* Copyright (c) 2018.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager 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 ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package net.devrieze.util.db
import io.github.pdvrieze.kotlinsql.ddl.Database
import io.github.pdvrieze.kotlinsql.monadic.DBReceiver
import io.github.pdvrieze.kotlinsql.monadic.actions.DBAction
import io.github.pdvrieze.kotlinsql.monadic.actions.mapSeq
import net.devrieze.util.*
import java.sql.SQLException
import java.util.*
open class DBHandleMap<TMP, V : Any, TR : MonadicDBTransaction<DB>, DB : Database>(
transactionFactory: DBTransactionFactory<TR, DB>,
elementFactory: HMElementFactory<TMP, V, TR, DB>,
handleAssigner: (V, Handle<V>) -> V? = ::HANDLE_AWARE_ASSIGNER
) : DbSet<TMP, V, TR, DB>(transactionFactory, elementFactory, handleAssigner),
MutableTransactionedHandleMap<V, TR> {
override val elementFactory: HMElementFactory<TMP, V, TR, DB>
get() = super.elementFactory as HMElementFactory<TMP, V, TR, DB>
private val pendingCreates = TreeMap<Handle<V>, TMP>()
protected fun isPending(handle: Handle<V>): Boolean {
return pendingCreates.containsKey(handle)
}
fun pendingValue(handle: Handle<V>): TMP? {
return pendingCreates[handle]
}
fun <W : V> put(value: W): Handle<W> = withDB { dbReceiver ->
put(dbReceiver, value)
}
fun <W : V> put(receiver: DBReceiver<DB>, value: W): DBAction<DB, Handle<W>> {
return addWithKey(receiver, value).map { it ?: throw RuntimeException("Adding element $value failed") }
}
@Deprecated("Use monadic function")
override fun <W : V> put(transaction: TR, value: W): Handle<W> =
with(transaction) {
put(receiver = this, value = value).evaluateNow()
}
fun get(handle: Handle<V>): V? = withDB { dbReceiver ->
get(dbReceiver, handle)
}
override fun get(transaction: TR, handle: Handle<V>): V? {
return with(transaction) {
get(dbReceiver = transaction, handle).evaluateNow()
}
}
fun get(dbReceiver: DBReceiver<DB>, handle: Handle<V>): DBAction<DB, V?> {
dbReceiver.transaction {
val tr = this
if (pendingCreates.containsKey(handle)) {
throw IllegalArgumentException("Pending create") // XXX This is not the best way
}
val factory = elementFactory
return SELECT(factory.createColumns)
.WHERE { factory.getHandleCondition(this, handle) AND factory.filter(this) }
.flatMapEach { rowData ->
sequence {
yield(elementFactory.createBuilder(tr, rowData))
}.asIterable()
}.then {
it.singleOrNull()?.let { result ->
factory.createFromBuilder(tr, FactoryAccess(), result as TMP)
} ?: value(null)
}
}
}
fun castOrGet(handle: Handle<V>): V? = withDB { dbReceiver ->
castOrGet(dbReceiver, handle)
}
override fun castOrGet(transaction: TR, handle: Handle<V>): V? {
return with(transaction) { castOrGet(dbReceiver = this, handle).evaluateNow() }
}
fun castOrGet(dbReceiver: DBReceiver<DB>, handle: Handle<V>): DBAction<DB, V?> {
val element = elementFactory.asInstance(handle)
if (element != null) {
return dbReceiver.value(element)
} // If the element is it's own handle, don't bother looking it up.
return get(dbReceiver, handle)
}
fun set(handle: Handle<V>, value: V): V? = withDB { dbReceiver ->
set(dbReceiver, handle, value)
}
@Throws(SQLException::class)
override fun set(transaction: TR, handle: Handle<V>, value: V): V? {
return with(transaction) {
get(dbReceiver = transaction, handle).then { oldValue ->
set(transaction, handle, oldValue, value)
}.evaluateNow()
}
}
fun set(dbReceiver: DBReceiver<DB>, handle: Handle<V>, value: V): DBAction<DB, V?> {
return get(dbReceiver, handle).then { oldValue ->
set(dbReceiver, handle, oldValue, value)
}
}
@Throws(SQLException::class)
protected operator fun set(
dbReceiver: DBReceiver<DB>,
handle: Handle<V>,
oldValue: V?,
newValue: V
): DBAction<DB, V?> {
if (elementFactory.isEqualForStorage(oldValue, newValue)) {
return dbReceiver.value(newValue)
}
val newValueWithHandle = handleAssigner(newValue, handle) ?: newValue
return dbReceiver.transaction {
val tr = this
UPDATE { elementFactory.store(this, newValueWithHandle) }
.WHERE { elementFactory.filter(this) AND elementFactory.getHandleCondition(this, handle) }
.then {
elementFactory.postStore(tr, handle, oldValue, newValueWithHandle)
.then(value(oldValue))
}
}
}
override fun iterator(transaction: TR, readOnly: Boolean): MutableIterator<V> {
return with(transaction) {
super.iterator(dbReceiver = transaction).evaluateNow()
}
}
/*
override fun iterator2(transaction: TR, readOnly: Boolean): MutableAutoCloseableIterator<V> {
try {
return super.iterator(transaction, readOnly)
} catch (e: SQLException) {
throw RuntimeException(e)
}
}
*/
override fun iterable(transaction: TR): MutableIterable<V> {
return with(transaction) {
iterable(dbReceiver = this).evaluateNow()
}
}
fun iterable(dbReceiver: DBReceiver<DB>): DBAction<DB, MutableIterable<V>> {
return with(dbReceiver) {
iterator(this).map {
object : MutableIterable<V> {
override fun iterator(): MutableIterator<V> = it
}
}
}
}
fun containsElement(element: Any): Boolean {
if (element is Handle<*>) {
return containsElement(element.handleValue)
}
return super.contains(element)
}
override fun containsElement(transaction: TR, element: Any): Boolean {
return with(transaction) { containsElement(dbReceiver = this, element).evaluateNow() }
}
fun containsElement(dbReceiver: DBReceiver<DB>, element: Any): DBAction<DB, Boolean> {
if (element is Handle<*>) {
return containsElement(dbReceiver, element.handleValue)
}
return super.contains(dbReceiver, element)
}
override fun contains(transaction: TR, handle: Handle<V>): Boolean {
return with(transaction) { contains(dbReceiver = this, handle).evaluateNow() }
}
override fun contains(dbReceiver: DBReceiver<DB>, element: Any): DBAction<DB, Boolean> {
@Suppress("UNCHECKED_CAST")
return when (element) {
is Handle<*> -> contains(dbReceiver, handle = element as Handle<V>)
else -> super.contains(dbReceiver, element)
}
}
fun contains(dbReceiver: DBReceiver<DB>, handle: Handle<V>): DBAction<DB, Boolean> {
return with(dbReceiver) {
SELECT(COUNT(elementFactory.createColumns[0]))
.WHERE { elementFactory.getHandleCondition(this, handle) AND elementFactory.filter(this) }
.mapSeq { it.single()!! > 0 }
}
}
/*
@Throws(SQLException::class)
override fun contains2(transaction: TR, handle: Handle<V>): Boolean {
val query = database
.SELECT(database.COUNT(elementFactory.createColumns[0]))
.WHERE { elementFactory.getHandleCondition(this, handle) AND elementFactory.filter(this) }
try {
return query.getSingleList(transaction.connection) { _, data ->
data[0] as Int > 0
}
} catch (e: RuntimeException) {
return false
}
}
*/
fun containsAll(c: Collection<*>): Boolean = withDB { dbReceiver ->
containsAll(dbReceiver, c)
}
override fun containsAll(transaction: TR, c: Collection<*>): Boolean {
return with(transaction) { containsAll(dbReceiver = this, c).evaluateNow() }
}
fun containsAll(dbReceiver: DBReceiver<DB>, c: Collection<*>): DBAction<DB, Boolean> {
return with(dbReceiver) {
c.fold(value(true)) { i: DBAction<DB, Boolean>, elem: Any? ->
when (elem) {
null -> value(false)
else -> i.then { acc ->
when (acc) {
true -> contains(dbReceiver = dbReceiver, elem)
else -> value(false)
}
}
}
}
}
}
fun remove(handle: Handle<V>): Boolean {
return withTransaction { remove(dbReceiver = this, handle).commit() }
}
override fun remove(transaction: TR, handle: Handle<V>): Boolean {
return with(transaction) { remove(dbReceiver = this, handle).evaluateNow() }
}
fun remove(dbReceiver: DBReceiver<DB>, handle: Handle<V>): DBAction<DB, Boolean> {
return dbReceiver.transaction {
elementFactory.preRemove(this, handle)
.then {
DELETE_FROM(elementFactory.table)
.WHERE { elementFactory.getHandleCondition(this, handle) AND elementFactory.filter(this) }
.map { it > 0 }
}
}
}
override fun clear(transaction: TR) {
return with(transaction) { clear(dbReceiver = this).evaluateNow() }
}
override fun invalidateCache(handle: Handle<V>) =// No-op, there is no cache
Unit
override fun invalidateCache() {
/* No-op, no cache */
}
private inline fun <R> withDB(crossinline action: (DBReceiver<DB>) -> DBAction<DB, R>): R {
return withTransaction { action(this).commit() }
}
private inner class FactoryAccess() : DBSetAccess<TMP> {
}
}
| java-common/src/jvmMain/kotlin/net/devrieze/util/db/DBHandleMap.kt | 3111028332 |
package com.vocalabs.egtest.codegenerator
interface ClassBuilder: CodeBuilding {
fun addAnnotation(annotationName: String, annotationBody: String?)
} | kotlin-generator/src/main/kotlin/com/vocalabs/egtest/codegenerator/ClassBuilder.kt | 2308375223 |
/*
* Copyright (c) 2016. Sunghyouk Bae <[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 debop4k.timeperiod.timeranges
import debop4k.core.collections.fastListOf
import debop4k.core.kodatimes.today
import debop4k.timeperiod.DefaultTimeCalendar
import debop4k.timeperiod.ITimeCalendar
import debop4k.timeperiod.utils.daysInMonth
import debop4k.timeperiod.utils.relativeMonthPeriod
import org.joda.time.DateTime
/**
* Created by debop
*/
open class MonthTimeRange @JvmOverloads constructor(startTime: DateTime = today(),
val monthCount: Int = 1,
calendar: ITimeCalendar = DefaultTimeCalendar) :
CalendarTimeRange(startTime.relativeMonthPeriod(monthCount), calendar) {
fun daySequence(): Sequence<DayRange> {
return (0 until monthCount).flatMap { m ->
val monthStart = start.plusMonths(m)
val dayCountInMonth = monthStart.daysInMonth()
(0 until dayCountInMonth).map {
DayRange(monthStart.plusDays(it), calendar)
}
}.asSequence()
}
fun days(): List<DayRange> {
return fastListOf(daySequence().iterator())
}
} | debop4k-timeperiod/src/main/kotlin/debop4k/timeperiod/timeranges/MonthTimeRange.kt | 2699001861 |
/*
* Copyright (C) 2016 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.ui.credits
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import butterknife.BindView
import butterknife.OnClick
import net.simonvt.cathode.R
import net.simonvt.cathode.api.enumeration.Department
import net.simonvt.cathode.api.enumeration.ItemType
import net.simonvt.cathode.common.ui.fragment.RefreshableToolbarFragment
import net.simonvt.cathode.common.util.Ids
import net.simonvt.cathode.common.util.guava.Preconditions
import net.simonvt.cathode.common.widget.RemoteImageView
import net.simonvt.cathode.ui.CathodeViewModelFactory
import net.simonvt.cathode.ui.NavigationListener
import javax.inject.Inject
class CreditsFragment @Inject constructor(
private val viewModelFactory: CathodeViewModelFactory
) : RefreshableToolbarFragment() {
private lateinit var navigationListener: NavigationListener
private lateinit var itemType: ItemType
private var itemId: Long = 0
private var title: String? = null
lateinit var viewModel: CreditsViewModel
private var credits: Credits? = null
private var itemCount: Int = 0
@BindView(R.id.cast_header)
@JvmField
var castHeader: LinearLayout? = null
@BindView(R.id.cast_items)
@JvmField
var castItems: LinearLayout? = null
@BindView(R.id.production_header)
@JvmField
var productionHeader: LinearLayout? = null
@BindView(R.id.production_items)
@JvmField
var productionItems: LinearLayout? = null
@BindView(R.id.art_header)
@JvmField
var artHeader: LinearLayout? = null
@BindView(R.id.art_items)
@JvmField
var artItems: LinearLayout? = null
@BindView(R.id.crew_header)
@JvmField
var crewHeader: LinearLayout? = null
@BindView(R.id.crew_items)
@JvmField
var crewItems: LinearLayout? = null
@BindView(R.id.costume_makeup_header)
@JvmField
var costumeMakeupHeader: LinearLayout? = null
@BindView(R.id.costume_makeup_items)
@JvmField
var costumeMakeupItems: LinearLayout? = null
@BindView(R.id.directing_header)
@JvmField
var directingHeader: LinearLayout? = null
@BindView(R.id.directing_items)
@JvmField
var directingItems: LinearLayout? = null
@BindView(R.id.writing_header)
@JvmField
var writingHeader: LinearLayout? = null
@BindView(R.id.writing_items)
@JvmField
var writingItems: LinearLayout? = null
@BindView(R.id.sound_header)
@JvmField
var soundHeader: LinearLayout? = null
@BindView(R.id.sound_items)
@JvmField
var soundItems: LinearLayout? = null
@BindView(R.id.camera_header)
@JvmField
var cameraHeader: LinearLayout? = null
@BindView(R.id.camera_items)
@JvmField
var cameraItems: LinearLayout? = null
override fun onAttach(context: Context) {
super.onAttach(context)
navigationListener = requireActivity() as NavigationListener
}
override fun onCreate(inState: Bundle?) {
super.onCreate(inState)
val args = requireArguments()
itemId = args.getLong(ARG_ITEM_ID)
title = args.getString(ARG_TITLE)
itemType = args.getSerializable(ARG_TYPE) as ItemType
setTitle(title)
itemCount = resources.getInteger(R.integer.creditColumns)
viewModel = ViewModelProviders.of(this, viewModelFactory).get(CreditsViewModel::class.java)
viewModel.setItemTypeAndId(itemType, itemId)
viewModel.loading.observe(this, Observer { loading -> setRefreshing(loading) })
viewModel.credits.observe(this, Observer { credits -> updateView(credits) })
}
override fun onRefresh() {
viewModel.refresh()
}
override fun createView(inflater: LayoutInflater, container: ViewGroup?, inState: Bundle?): View {
return inflater.inflate(R.layout.fragment_credits, container, false)
}
override fun onViewCreated(view: View, inState: Bundle?) {
super.onViewCreated(view, inState)
updateView(credits)
}
@OnClick(R.id.cast_header)
fun onDisplayCastCredits() {
navigationListener.onDisplayCredit(itemType, itemId, Department.CAST)
}
@OnClick(R.id.production_header)
fun onDisplayProductionCredits() {
navigationListener.onDisplayCredit(itemType, itemId, Department.PRODUCTION)
}
@OnClick(R.id.art_header)
fun onDisplayArtCredits() {
navigationListener.onDisplayCredit(itemType, itemId, Department.ART)
}
@OnClick(R.id.crew_header)
fun onDisplayCrewCredits() {
navigationListener.onDisplayCredit(itemType, itemId, Department.CREW)
}
@OnClick(R.id.costume_makeup_header)
fun onDisplayCostumeMakeUpCredits() {
navigationListener.onDisplayCredit(itemType, itemId, Department.COSTUME_AND_MAKEUP)
}
@OnClick(R.id.directing_header)
fun onDisplayDirectingCredits() {
navigationListener.onDisplayCredit(itemType, itemId, Department.DIRECTING)
}
@OnClick(R.id.writing_header)
fun onDisplayWritingCredits() {
navigationListener.onDisplayCredit(itemType, itemId, Department.WRITING)
}
@OnClick(R.id.sound_header)
fun onDisplaySoundCredits() {
navigationListener.onDisplayCredit(itemType, itemId, Department.SOUND)
}
@OnClick(R.id.camera_header)
fun onDisplayCameraCredits() {
navigationListener.onDisplayCredit(itemType, itemId, Department.CAMERA)
}
private fun updateView(credits: Credits?) {
this.credits = credits
if (credits != null && view != null) {
updateItems(castHeader, castItems!!, credits.cast)
updateItems(productionHeader, productionItems!!, credits.production)
updateItems(artHeader, artItems!!, credits.art)
updateItems(crewHeader, crewItems!!, credits.crew)
updateItems(costumeMakeupHeader, costumeMakeupItems!!, credits.costumeAndMakeUp)
updateItems(directingHeader, directingItems!!, credits.directing)
updateItems(writingHeader, writingItems!!, credits.writing)
updateItems(soundHeader, soundItems!!, credits.sound)
updateItems(cameraHeader, cameraItems!!, credits.camera)
}
}
private fun updateItems(header: View?, items: ViewGroup, credits: List<Credit>?) {
items.removeAllViews()
val size = credits?.size ?: 0
if (size > 0) {
header!!.visibility = View.VISIBLE
items.visibility = View.VISIBLE
var i = 0
while (i < size && i < itemCount) {
val credit = credits!![i]
val view =
LayoutInflater.from(requireContext()).inflate(R.layout.credit_item_credit, items, false)
val headshot = view.findViewById<RemoteImageView>(R.id.headshot)
val name = view.findViewById<TextView>(R.id.name)
val job = view.findViewById<TextView>(R.id.job)
headshot.setImage(credit.getHeadshot())
name.text = credit.getName()
if (credit.getJob() != null) {
job.text = credit.getJob()
} else {
job.text = credit.getCharacter()
}
view.setOnClickListener { navigationListener.onDisplayPerson(credit.getPersonId()) }
items.addView(view)
i++
}
} else {
header!!.visibility = View.GONE
items.visibility = View.GONE
}
}
companion object {
private const val TAG = "net.simonvt.cathode.ui.credits.CreditsFragment"
private const val ARG_TYPE = "net.simonvt.cathode.ui.credits.CreditsFragment.itemType"
private const val ARG_ITEM_ID = "net.simonvt.cathode.ui.credits.CreditsFragment.itemId"
private const val ARG_TITLE = "net.simonvt.cathode.ui.credits.CreditsFragment.title"
@JvmStatic
fun getTag(itemId: Long): String {
return TAG + "/" + itemId + "/" + Ids.newId()
}
@JvmStatic
fun getArgs(itemType: ItemType, itemId: Long, title: String?): Bundle {
Preconditions.checkArgument(itemId >= 0, "itemId must be >= 0")
val args = Bundle()
args.putSerializable(ARG_TYPE, itemType)
args.putLong(ARG_ITEM_ID, itemId)
args.putString(ARG_TITLE, title)
return args
}
}
}
| cathode/src/main/java/net/simonvt/cathode/ui/credits/CreditsFragment.kt | 3867934580 |
/*
* Copyright (c) 2016. Sunghyouk Bae <[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 debop4k.science.netcdf
import debop4k.core.areEquals
import debop4k.core.loggerOf
import debop4k.core.utils.LINE_SEPARATOR
import debop4k.core.utils.TAB
import org.eclipse.collections.impl.list.mutable.primitive.DoubleArrayList
import org.eclipse.collections.impl.list.mutable.primitive.FloatArrayList
import org.eclipse.collections.impl.list.mutable.primitive.IntArrayList
import org.eclipse.collections.impl.list.mutable.primitive.LongArrayList
import ucar.nc2.NetcdfFile
import ucar.nc2.Variable
import ucar.nc2.util.CancelTask
import java.io.File
import java.io.IOException
import java.net.URI
/**
* Net CDF 파일의 정보를 읽어드립니다.
* Created by debop
*/
object NetCdfReader {
private val log = loggerOf(javaClass)
@JvmField val CAHCE_EXTENSIONS = arrayOf("gbx9", "ncx3", "idx")
/**
* 지정된 경로의 NetCDF 파일을 오픈합니다.
* @param path 파일의 전체경로
* *
* @return [NetcdfFile] 인스턴스
*/
@JvmStatic fun open(path: String): NetcdfFile = NetcdfFile.open(path)
/**
* 지정된 경로의 NetCDF 파일을 오픈합니다.
*
* @param path 파일의 전체경로
* @return {@link NetcdfFile} 인스턴스
*/
@JvmStatic fun open(path: String,
bufferSize: Int = -1,
cancelTask: CancelTask? = null,
iospMessage: Any? = null): NetcdfFile
= NetcdfFile.open(path, bufferSize, cancelTask, iospMessage)
/**
* 지정된 경로의 NetCDF 파일을 오픈하고, 데이터를 메모리에 모두 로드합니다.
*
* @param filename 파일의 전체경로
* @return {@link NetcdfFile} 인스턴스
*/
@JvmStatic fun openInMemory(filename: String): NetcdfFile = NetcdfFile.openInMemory(filename)
/**
* 지정된 경로의 NetCDF 파일을 오픈하고, 데이터를 메모리에 모두 로드합니다.
*
* @param uri 파일의 전체경로
* @return {@link NetcdfFile} 인스턴스
*/
@JvmStatic fun openInMemory(uri: URI): NetcdfFile = NetcdfFile.openInMemory(uri)
@JvmOverloads
@JvmStatic fun openInMemoery(name: String, data: ByteArray, iospClassName: String? = null): NetcdfFile {
return NetcdfFile.openInMemory(name, data, iospClassName)
}
/**
* 파일을 NetCdf 형식으로 읽을 수 있는지 여부를 판단한다.
*
* @param path 파일 전체 경로
* @return NetCdf 형식으로 읽을 수 있는지 여부
*/
@JvmStatic fun canRead(path: String): Boolean = canRead(File(path))
/**
* 파일을 NetCdf 형식으로 읽을 수 있는지 여부를 판단한다.
*
* @param file 파일 인스턴스
* @return NetCdf 형식으로 읽을 수 있는지 여부
*/
@JvmStatic fun canRead(file: File): Boolean {
return !file.isDirectory &&
!isNetcdfCacheFile(file) &&
NetcdfFile.canOpen(file.canonicalPath)
}
/**
* 파일을 NetCdf 형식으로 읽을 수 있는지 여부를 판단한다.
*
* @param path 파일 전체 경로
* @return NetCdf 형식으로 읽을 수 있는지 여부
*/
@JvmStatic fun isNetcdfCacheFile(path: String): Boolean = isNetcdfCacheFile(File(path))
/**
* 파일을 NetCdf 형식으로 읽을 수 있는지 여부를 판단한다.
*
* @param file 파일 인스턴스
* @return NetCdf 형식으로 읽을 수 있는지 여부
*/
@JvmStatic fun isNetcdfCacheFile(file: File): Boolean {
if (file.exists() && file.isFile) {
val filename = file.name.toLowerCase()
return CAHCE_EXTENSIONS.find { filename.endsWith(it) } != null
} else {
return false
}
}
/**
* NetCDF 파일 내의 지정한 이름의 [Variable] 을 구합니다.
* @param nc [NetcdfFile] 인스턴스
* @param varName 찾고자하는 [Variable]의 명칭
* @return [Variable] 인스턴스. 해당 이름의 Variable 이 없는 경우에는 null 을 반환한다.
*/
@JvmStatic fun getVariable(nc: NetcdfFile, varName: String): Variable? {
for (v in nc.variables) {
log.trace("varName={}, v={}", varName, v.fullName)
if (areEquals(v.fullName, varName)) {
return v
}
}
return null
}
/**
* NetCDF 파일 내의 지정한 접두사로 시작하는 [Variable] 중 첫번째 찾은 변수를 반환합니다.
* @param nc [NetcdfFile] 인스턴스
* *
* @param prefix 찾고자하는 [Variable]의 접두사
* *
* @return [Variable] 인스턴스. 해당 이름의 Variable 이 없는 경우에는 null 을 반환한다.
*/
@JvmStatic fun getVariableStartsWith(nc: NetcdfFile, prefix: String): Variable? {
for (v in nc.variables) {
if (v != null && v.fullName != null && v.fullName.startsWith(prefix)) {
return v
}
}
return null
}
/**
* NetCDF 파일 내의 지정한 접미사를 가진 [Variable] 중 첫번째 찾은 변수를 반환합니다.
*
* @param nc [NetcdfFile] 인스턴스
* @param surfix 찾고자하는 [Variable]의 접미사
* @return [Variable] 인스턴스. 해당 이름의 Variable 이 없는 경우에는 null 을 반환한다.
*/
@JvmStatic fun getVariableEndsWith(nc: NetcdfFile, surfix: String): Variable? {
for (v in nc.variables) {
if (v != null && v.fullName != null && v.fullName.endsWith(surfix)) {
return v
}
}
return null
}
/**
* NetCDF 파일 내의 지정한 검색어를 가진 [Variable] 중 첫번째 찾은 변수를 반환합니다.
*
* @param nc [NetcdfFile] 인스턴스
* @param nameToMatch 찾고자하는 [Variable]의 이름
* @return [Variable] 인스턴스. 해당 이름의 Variable 이 없는 경우에는 null 을 반환한다.
*/
@JvmStatic fun getVariableContains(nc: NetcdfFile, nameToMatch: String): Variable? {
for (v in nc.variables) {
if (v != null && v.fullName != null && v.fullName.contains(nameToMatch)) {
return v
}
}
return null
}
/**
* [Variable]이 가진 Data 값이 스칼라 형식인지 여부
* @param v [Variable] 인스턴스
* @return Variable이 나타내는 데이터 값이 스칼라 값인지 여부
*/
@JvmStatic fun isScalar(v: Variable): Boolean = getValueSize(v) == 1
/**
* [Variable]이 가진 데이터의 크기 (모든 Dimension 크기)
* @param v [Variable] 인스턴스
* @return 데이터의 전체 크기
*/
@JvmStatic fun getValueSize(v: Variable): Int {
var size = 1
for (shape in v.shape) {
size *= shape
}
return size
}
/**
* [Variable] 의 값을 Integer 수형으로 읽는다.
* @param v [Variable] 인스턴스
* @return [Variable]의 데이터 값을 Integer 수형으로 반환한다. 없으면 null을 반환한다.
*/
@JvmStatic fun readInt(v: Variable): Int = readInt(v, 0)
/**
* [Variable] 의 값을 Integer 수형으로 읽는다.
* @param v [Variable] 인스턴스
* @param dv 데이터 값이 없거나, 읽는데 실패한 경우 반환할 기본 값
* @return [Variable]의 데이터 값을 Integer 수형으로 반환한다.
*/
@JvmStatic fun readInt(v: Variable, dv: Int): Int {
try {
return v.readScalarInt()
} catch (t: Throwable) {
return dv
}
}
/**
* [Variable] 의 값을 Long 수형으로 읽는다.
* @param v [Variable] 인스턴스
* @return [Variable]의 데이터 값을 Long 수형으로 반환한다. 없으면 null을 반환한다.
*/
@JvmStatic fun readLong(v: Variable): Long = v.readScalarLong()
/**
* [Variable] 의 값을 Long 수형으로 읽는다.
* @param v [Variable] 인스턴스
* @param dv 데이터 값이 없거나, 읽는데 실패한 경우 반환할 기본 값
* @return [Variable]의 데이터 값을 Long 수형으로 반환한다.
*/
@JvmStatic fun readLong(v: Variable, dv: Long): Long {
try {
return v.readScalarLong()
} catch (t: Throwable) {
return dv
}
}
/**
* [Variable] 의 값을 Float 수형으로 읽는다.
*
* @param v [Variable] 인스턴스
* @return [Variable]의 데이터 값을 Float 수형으로 반환한다.
*/
@JvmStatic fun readFloat(v: Variable): Float = v.readScalarFloat()
/**
* [Variable] 의 값을 Float 수형으로 읽는다.
*
* @param v [Variable] 인스턴스
* @param dv 데이터 값이 없거나, 읽는데 실패한 경우 반환할 기본 값
* @return [Variable]의 데이터 값을 Float 수형으로 반환한다.
*/
@JvmStatic fun readFloat(v: Variable, dv: Float): Float {
try {
return v.readScalarFloat()
} catch(e: IOException) {
return dv
}
}
/**
* [Variable] 의 값을 Double 수형으로 읽는다.
*
* @param v [Variable] 인스턴스
* @return [Variable]의 데이터 값을 Double 수형으로 반환한다.
*/
@JvmStatic fun readDouble(v: Variable): Double = v.readScalarDouble()
/**
* [Variable] 의 값을 Double 수형으로 읽는다.
*
* @param v [Variable] 인스턴스
* @param dv 데이터 값이 없거나, 읽는데 실패한 경우 반환할 기본 값
* @return [Variable]의 데이터 값을 Double 수형으로 반환한다.
*/
@JvmStatic fun readDouble(v: Variable, dv: Double): Double {
try {
return v.readScalarDouble()
} catch(e: IOException) {
return dv
}
}
/**
* [Variable] 의 값을 Integer 수형의 1차원 배열로 읽습니다.
*
* @param v [Variable] 인스턴스
* @return [Variable]의 데이터 값을 Integer 수형의 1차원 배열로 반환한다.
*/
@JvmStatic fun readIntArray(v: Variable): IntArrayList {
val length = getValueSize(v)
val elements = IntArrayList(length)
val iter = v.read().indexIterator
while (iter.hasNext()) {
elements.add(iter.intNext)
}
return elements
}
/**
* [Variable] 의 값을 Long 수형의 1차원 배열로 읽습니다.
*
* @param v [Variable] 인스턴스
* @return [Variable]의 데이터 값을 Long 수형의 1차원 배열로 반환한다.
*/
@JvmStatic fun readLongArray(v: Variable): LongArrayList {
val length = getValueSize(v)
val elements = LongArrayList(length)
val iter = v.read().indexIterator
while (iter.hasNext()) {
elements.add(iter.longNext)
}
return elements
}
/**
* [Variable] 의 값을 Float 수형의 1차원 배열로 읽습니다.
*
* @param v [Variable] 인스턴스
* @return [Variable]의 데이터 값을 Float 수형의 1차원 배열로 반환한다.
*/
@JvmStatic fun readFloatArray(v: Variable): FloatArrayList {
val length = getValueSize(v)
val elements = FloatArrayList(length)
val iter = v.read().indexIterator
while (iter.hasNext()) {
elements.add(iter.floatNext)
}
return elements
}
/**
* [Variable] 의 값을 Double 수형의 1차원 배열로 읽습니다.
* @param v [Variable] 인스턴스
* *
* @return [Variable]의 데이터 값을 Double 수형의 1차원 배열로 반환한다.
* *
* @see NetCdfReader.read1DJavaArray
*/
@JvmStatic fun readDoubleArray(v: Variable): DoubleArrayList {
val length = getValueSize(v)
val elements = DoubleArrayList(length)
val iter = v.read().indexIterator
while (iter.hasNext()) {
elements.add(iter.doubleNext)
}
return elements
}
/**
* Variable의 Dimension 을 판단하여 값을 읽어들여 N 차원의 Java 배열로 반환합니다.
*
* // 3차원 데이터인 경우
* double[][][] matrix = (double[][][])NetCdfReader.readNDJavaArray(v);
*
* @param v [Variable] 인스턴스
* @return N 차원의 Java 배열
*/
@JvmStatic fun readNDJavaArray(v: Variable): Any {
return v.read().copyToNDJavaArray()
}
/**
* Variable 의 값들을 모두 읽어, 원하는 요소 수형의 1차원 배열로 반환합니다.
*
* double[] elements = (double[])NetCdfReader.read1DJavaArray(v, double.class);
* @param v [Variable] 인스턴스
* @param elementType Java 배열의 수형 (ex. double.class, int.class)
* @return Java 1차원 배열
*/
@JvmStatic fun read1DJavaArray(v: Variable, elementType: Class<*>): Any {
return v.read().get1DJavaArray(elementType)
}
/**
* [NetcdfFile] 의 내부 속성 정보를 로그애 씁니다.
* @param nc [NetcdfFile] 인스턴스
*/
@JvmStatic fun displayNetcdfFile(nc: NetcdfFile) {
for (v in nc.variables) {
log.debug("variable name={}, dimensions={}, dataType={}", v.fullName, v.dimensions, v.dataType)
for (dim in v.dimensions) {
log.debug("dimension = {}, length={}", dim.fullName, dim.length)
}
}
}
/**
* [NetcdfFile] 의 내부 속성 정보를 문자열로 반환합니다.
* @param nc [NetcdfFile] 인스턴스
* @return NetCDF 파일의 정보
*/
@JvmStatic fun getInformation(nc: NetcdfFile): String {
val builder = StringBuilder()
for (v in nc.variables) {
builder.append("Variable")
.append(" name=").append(v.fullName)
.append(", dimensions=").append(v.dimensions)
.append(", dataType=").append(v.dataType)
.append(LINE_SEPARATOR)
for (dim in v.dimensions) {
builder.append(TAB)
.append("dimension name=").append(dim.fullName)
.append(", length=").append(dim.length)
.append(LINE_SEPARATOR)
}
}
return builder.toString()
}
} | debop4k-science/src/main/kotlin/debop4k/science/netcdf/NetCdfReader.kt | 4213357904 |
package fr.geobert.radis.ui
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v4.util.SimpleArrayMap
import android.util.Log
import android.view.View
import android.widget.RelativeLayout
import android.widget.TextView
import com.github.mikephil.charting.charts.*
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.data.*
import com.github.mikephil.charting.formatter.DefaultValueFormatter
import com.github.mikephil.charting.utils.ColorTemplate
import fr.geobert.radis.BaseActivity
import fr.geobert.radis.R
import fr.geobert.radis.data.Operation
import fr.geobert.radis.data.Statistic
import fr.geobert.radis.db.OperationTable
import fr.geobert.radis.tools.*
import hirondelle.date4j.DateTime
import kotlinx.android.synthetic.main.statistic_activity.*
import java.text.DateFormatSymbols
import java.util.*
class StatisticActivity : BaseActivity() {
companion object {
val STAT = "statistic"
}
val accountNameLbl: TextView by lazy { findViewById(R.id.chart_account_name) as TextView }
val filterLbl: TextView by lazy { findViewById(R.id.filter_lbl) as TextView }
val timeScaleLbl: TextView by lazy { findViewById(R.id.time_scale_lbl) as TextView }
//val chart_cont: RelativeLayout by lazy { findViewById(R.id.chart_cont) as RelativeLayout }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val extras = intent.extras
val stat = extras.getParcelable<Statistic>(STAT)
setContentView(R.layout.statistic_activity)
title = stat.name
setIconOnClick(View.OnClickListener { onBackPressed() })
mToolbar.menu.clear()
setIcon(R.drawable.ok_48)
accountNameLbl.text = stat.accountName
filterLbl.text = getString(stat.getFilterStr())
val (start, end) = stat.createTimeRange()
timeScaleLbl.text = "${start.formatDateLong()} ${getString(R.string.rarr)} ${end.formatDateLong()}"
val p = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT)
try {
val chart = createChartView(stat)
chart_cont.addView(chart, p)
chart.invalidate()
} catch(e: InputMismatchException) {
val lbl = TextView(this)
lbl.text = getString(R.string.no_statistic_data)
chart_cont.addView(lbl, p)
}
}
// generate chart data
private fun getColorsArray(id: Int): List<Int> =
resources.getStringArray(id)?.map({ Color.parseColor(it) }) as List<Int>
private val pos_colors: List<Int> by lazy(LazyThreadSafetyMode.NONE) {
getColorsArray(R.array.positive_colors)
}
private val neg_colors: List<Int> by lazy(LazyThreadSafetyMode.NONE) {
getColorsArray(R.array.negative_colors)
}
/**
* get the ops list according to the time range, split by sum sign and group each by partFunc
* @param stat the stat to analyse
* @return a map with the group key and List(Operation)
*/
private fun partOps(stat: Statistic): Pair<Map<String, List<Operation>>, Map<String, List<Operation>>> {
val (startDate, endDate) = stat.createTimeRange()
val ops = OperationTable.getOpsBetweenDate(this, startDate, endDate, stat.accountId).map({ Operation(it) })
val (pos, neg) = ops.partition { it.mSum > 0 }
return Pair(pos.groupBy { partFunc(stat)(it) }, neg.groupBy { partFunc(stat)(it) })
}
/**
* get the partitioning function according to filterType
* @param stat the stat to analyse
* @return the partitioning function
*/
private fun partFunc(stat: Statistic): (Operation) -> String =
when (stat.filterType) {
Statistic.THIRD_PARTY -> { o: Operation -> o.mThirdParty }
Statistic.TAGS -> { o: Operation -> o.mTag }
Statistic.MODE -> { o: Operation -> o.mMode }
else -> { // Statistic.NO_FILTER
o: Operation ->
val g = GregorianCalendar()
g.timeInMillis = o.getDate()
when (stat.timePeriodType) {
Statistic.PERIOD_DAYS, Statistic.PERIOD_ABSOLUTE -> g.time.formatDate()
Statistic.PERIOD_MONTHES ->
if (Build.VERSION.SDK_INT >= 9) {
g.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.getDefault()) ?: ""
} else {
DateFormatSymbols().shortMonths?.get(g[Calendar.MONTH]) ?: ""
}
Statistic.PERIOD_YEARS -> g[Calendar.YEAR].toString()
else -> {
""
}
}
}
}
// group sums that represents less than 10% of the total in a "misc" category
private fun cleanMap(m: Map<String, Long>, total: Long): Map<String, Long> {
val limit = Math.abs(total * 0.01)
val result: MutableMap<String, Long> = hashMapOf()
val miscKey = getString(R.string.misc_chart_cat)
m.forEach {
Log.d("StatisticListFragment", "key: ${it.key} / value: ${it.value} / limit: $limit / total: $total / m.size: ${m.size}")
if (Math.abs(it.value) < limit) {
val p = result[miscKey]
if (p != null) {
result.put(miscKey, p + it.value)
} else {
result.put(miscKey, it.value)
}
} else {
result.put(it.key, it.value)
}
}
return result
}
private fun sumPerFilter(stat: Statistic): Pair<Map<String, Long>, Map<String, Long>> {
// partition the list according to filterType
fun sumMapOfList(m: Map<String, List<Operation>>) = m.mapValues { it.value.fold(0L) { s: Long, o: Operation -> s + o.mSum } }
fun sumMap(m: Map<String, Long>) = m.values.fold(0L) { s: Long, l: Long -> s + l }
val (pos, neg) = partOps(stat)
val sumP = sumMapOfList(pos)
val sumN = sumMapOfList(neg)
val total = sumMap(sumP) + Math.abs(sumMap(sumN))
return Pair(cleanMap(sumP, total), cleanMap(sumN, total))
}
// private fun initNumFormat(stat: Statistic): NumberFormat {
// val cursor = AccountTable.fetchAccount(this, stat.accountId)
// cursor.moveToFirst()
// val account = Account(cursor)
// val numFormat = NumberFormat.getCurrencyInstance()
// numFormat.currency = Currency.getInstance(account.currency)
// numFormat.minimumFractionDigits = 2
// return numFormat
// }
// for pie chart
private fun createPieData(stat: Statistic): PieData {
val yValues = ArrayList<Entry>()
val xValues = ArrayList<String>()
// fill the data
val (pos, neg) = sumPerFilter(stat)
var i: Int = 0
val cols = ArrayList<Int>()
fun construct(m: Map<String, Long>, colors: List<Int>) {
m.forEach {
val k = if (it.key.length > 0) it.key else getString(when (stat.filterType) {
1 -> R.string.no_tag
2 -> R.string.no_mode
else -> throw IllegalArgumentException("No values for filter only happens for tag and mode")
}).format(getString(if (it.value > 0) R.string.pos_values else R.string.neg_values))
xValues.add(k)
yValues.add(Entry(Math.abs(it.value) / 100.0f, i++))
cols.add(colors[(yValues.size - 1) % colors.size])
}
}
construct(pos, pos_colors)
construct(neg, neg_colors)
val set = PieDataSet(yValues, "")
for (c in ColorTemplate.COLORFUL_COLORS) cols.add(c)
set.colors = cols
val d = PieData(xValues, set)
d.setValueFormatter(DefaultValueFormatter(2))
return d
}
// for lines chart
private fun createLineData(stat: Statistic): LineData {
val (pos, neg) = partOps(stat)
val data = LineData()
fun createDataSet(yVals: ArrayList<Entry>, name: String, color: Int): LineDataSet {
val dataSet = LineDataSet(yVals, name)
dataSet.setDrawValues(false)
dataSet.color = color
dataSet.setDrawCircleHole(false)
dataSet.setCircleColor(color)
dataSet.circleSize = 3.0f
return dataSet
}
return when (stat.filterType) {
Statistic.NO_FILTER -> {
fun construct(m: Map<String, List<Operation>>, colors: List<Int>, name: String) {
var i = 0
val yVals = ArrayList<Entry>()
m.toSortedMap().forEach {
val v = Math.abs(it.value.fold(0L) { i: Long, op: Operation ->
i + op.mSum
}) + 0.0f
yVals.add(Entry(v / 100.0f, i))
i += 1
data.addXValue(it.key)
}
val dataSet = createDataSet(yVals, name, colors[0])
data.addDataSet(dataSet)
}
construct(pos, pos_colors, getString(R.string.positive_values))
construct(neg, neg_colors, getString(R.string.negative_values))
data
}
else -> {
fun findMinMax(): Pair<DateTime?, DateTime?> {
val posList = pos.flatMap { e -> e.value }
val negList = neg.flatMap { e -> e.value }
val posMin: DateTime? = posList.minBy { it.mDate }?.mDate
val negMin: DateTime? = negList.minBy { it.mDate }?.mDate
val posMax: DateTime? = posList.maxBy { it.mDate }?.mDate
val negMax: DateTime? = negList.maxBy { it.mDate }?.mDate
return Pair(if ((posMin?.compareTo(negMin) ?: 0) < 0) posMin else negMin,
if ((posMax?.compareTo(negMax) ?: 0) > 0) posMax else negMax)
}
fun addPeriodicity(stat: Statistic, date: DateTime): DateTime {
return when (stat.timeScaleType) {
Statistic.PERIOD_DAYS -> {
date.plusDays(1)
}
Statistic.PERIOD_MONTHES -> {
date.plusMonth(1)
}
Statistic.PERIOD_YEARS -> {
date.plusYear(1)
}
else -> {
throw IllegalArgumentException("Time scale should be day, month or year only")
}
}
}
val (minDate, maxDate) = findMinMax()
if (minDate != null && maxDate != null) {
var min: DateTime = minDate
while (min.compareTo(maxDate) < 0) {
data.addXValue(min.formatDateLong())
min = addPeriodicity(stat, min)
}
} else {
throw InputMismatchException("No data to display")
}
fun construct(m: Map<String, List<Operation>>, colors: List<Int>) {
var i = 0
m.forEach {
if (it.key.length > 0) {
val yVals = ArrayList<Entry>()
it.value.toSortedSet().forEach {
val v = Math.abs(it.mSum / 100.0f)
val idx = data.xVals.indexOf(it.mDate.formatDateLong())
yVals.add(Entry(v, idx))
}
val s = createDataSet(yVals, it.key, colors[i % colors.count()])
i += 1
data.addDataSet(s)
}
}
}
construct(pos, pos_colors)
construct(neg, neg_colors)
data
}
}
}
// private fun filterName(stat: Statistic): String {
// val stId = when (stat.filterType) {
// Statistic.THIRD_PARTY -> R.string.third_parties
// Statistic.TAGS -> R.string.tags
// Statistic.MODE -> R.string.modes
// else -> R.string.time
// }
// return getString(stId)
// }
// for bar chart
private fun createBarData(stat: Statistic): BarData {
val xValues = ArrayList<String>()
var (tmpPos, tmpNeg) = sumPerFilter(stat)
val pos: MutableMap<String, Long> = hashMapOf()
pos.putAll(tmpPos)
val neg: MutableMap<String, Long> = hashMapOf()
neg.putAll(tmpNeg)
pos.forEach {
if (!neg.contains(it.key)) neg.put(it.key, 0L)
}
neg.forEach {
if (!pos.contains(it.key)) pos.put(it.key, 0L)
}
var xLabels: SimpleArrayMap<String, Int> = SimpleArrayMap()
fun construct(m: Map<String, Long>, isPos: Boolean): BarDataSet {
val yValues = ArrayList<BarEntry>()
val colors = ArrayList<Int>()
m.forEach {
val lbl = if (it.key.length == 0) getString(R.string.no_lbl) else it.key
val v: Float = Math.abs(it.value / 100.0f)
val existingSeries: Int? = xLabels[lbl]
if (existingSeries == null) {
val idx = yValues.count()
xLabels.put(lbl, idx)
xValues.add(lbl)
yValues.add(BarEntry(v, idx))
} else {
yValues.add(BarEntry(v, existingSeries))
}
colors.add(if (isPos) pos_colors[0] else neg_colors[0])
}
val set = BarDataSet(yValues, "")
set.colors = colors
return set
}
val sets = listOf(construct(pos, isPos = true),
construct(neg, isPos = false))
return BarData(xValues, sets)
}
fun createChartView(stat: Statistic): Chart<out ChartData<out DataSet<out Entry>>> {
fun lineAndBarConfig(c: BarLineChartBase<out BarLineScatterCandleBubbleData<out BarLineScatterCandleBubbleDataSet<out Entry>>>) {
c.setPinchZoom(true)
c.isDragEnabled = true
c.isScaleXEnabled = true
c.setTouchEnabled(true)
c.setDescription("")
c.legend.textColor = Color.WHITE
c.setGridBackgroundColor(Color.TRANSPARENT)
c.axisLeft.textColor = Color.WHITE
c.axisRight.isEnabled = false
c.xAxis.position = XAxis.XAxisPosition.BOTTOM
c.xAxis.textColor = Color.WHITE
}
val chart = when (stat.chartType) {
Statistic.CHART_PIE -> {
val c = PieChart(this)
c.data = createPieData(stat)
c.setHoleColor(ContextCompat.getColor(this, R.color.normal_bg))
c.legend.textColor = Color.WHITE
c
}
Statistic.CHART_BAR -> {
val c = BarChart(this)
c.data = createBarData(stat)
lineAndBarConfig(c)
c.legend.isEnabled = false
c
}
Statistic.CHART_LINE -> {
val c = LineChart(this)
c.data = createLineData(stat)
lineAndBarConfig(c)
c.legend.isWordWrapEnabled = true
c
}
else -> {
throw IllegalArgumentException("Unknown chart type")
}
}
chart.setBackgroundColor(Color.TRANSPARENT)
return chart
}
}
| app/src/main/kotlin/fr/geobert/radis/ui/StatisticActivity.kt | 1649878272 |
package net.ndrei.teslapoweredthingies.machines.cropcloner
import net.minecraft.block.properties.PropertyInteger
import net.minecraft.block.state.IBlockState
import net.minecraft.item.ItemStack
import net.minecraft.util.NonNullList
import net.minecraft.util.math.BlockPos
import net.minecraft.world.World
import java.util.*
/**
* Created by CF on 2017-07-15.
*/
abstract class GenericCropClonerPlant: ICropClonerPlant {
override fun getAgeProperty(thing: IBlockState): PropertyInteger? {
return thing.propertyKeys
.filterIsInstance<PropertyInteger>()
.firstOrNull { it.name === "age" }
}
override fun getDrops(world: World, pos: BlockPos, state: IBlockState): List<ItemStack> {
val stacks = NonNullList.create<ItemStack>()
state.block.getDrops(stacks, world, pos, state, 0)
return stacks.toList()
}
override fun grow(thing: IBlockState, ageProperty: PropertyInteger, rand: Random): IBlockState {
if (rand.nextInt(3) == 1) {
return thing.withProperty(ageProperty, thing.getValue(ageProperty) + 1)
}
return thing
}
} | src/main/kotlin/net/ndrei/teslapoweredthingies/machines/cropcloner/GenericCropClonerPlant.kt | 611779875 |
package net.ndrei.teslapoweredthingies.machines.cropfarm
import com.google.common.collect.Lists
import net.minecraft.block.state.IBlockState
import net.minecraft.item.ItemStack
import net.minecraft.util.math.BlockPos
import net.minecraft.world.World
class ImmersiveHempPlant(private val world: World, private val pos: BlockPos) : IPlantWrapper {
override fun canBeHarvested(): Boolean {
val state = this.world.getBlockState(this.pos.up())
return (state.block.registryName?.toString() == REGISTRY_NAME) && (state.block.getMetaFromState(state) == 5)
}
override fun harvest(fortune: Int): List<ItemStack> {
val loot = Lists.newArrayList<ItemStack>()
if (this.canBeHarvested()) {
val state = this.world.getBlockState(pos.up())
loot.addAll(state.block.getDrops(this.world, this.pos.up(), state, fortune))
this.world.setBlockToAir(pos.up())
}
return loot
}
override fun canBlockNeighbours() = false
override fun blocksNeighbour(pos: BlockPos) = false
override fun canUseFertilizer() = true
override fun useFertilizer(fertilizer: ItemStack) =
VanillaGenericPlant.useFertilizer(this.world, this.pos, fertilizer)
companion object {
const val REGISTRY_NAME = "immersiveengineering:hemp"
fun isMatch(state: IBlockState) =
state.block.registryName?.toString() == REGISTRY_NAME
}
} | src/main/kotlin/net/ndrei/teslapoweredthingies/machines/cropfarm/ImmersiveHempPlant.kt | 3914344481 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.roots
import com.intellij.openapi.components.BaseState
import com.intellij.pom.java.LanguageLevel
import com.intellij.util.xmlb.annotations.Attribute
class LanguageLevelState : BaseState() {
@get:Attribute("LANGUAGE_LEVEL")
var languageLevel by storedProperty<LanguageLevel?>()
} | java/java-analysis-api/src/com/intellij/openapi/roots/LanguageLevelState.kt | 4260783946 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.stats.completion
import com.google.common.net.HttpHeaders
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.ApplicationComponent
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.Disposer
import com.intellij.stats.completion.experiment.WebServiceStatusProvider
import com.intellij.util.Alarm
import com.intellij.util.Time
import org.apache.commons.codec.binary.Base64OutputStream
import org.apache.http.HttpResponse
import org.apache.http.client.fluent.Form
import org.apache.http.client.fluent.Request
import org.apache.http.entity.ContentType
import org.apache.http.message.BasicHeader
import org.apache.http.util.EntityUtils
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.IOException
import java.util.zip.GZIPOutputStream
import javax.swing.SwingUtilities
fun assertNotEDT() {
val isInTestMode = ApplicationManager.getApplication().isUnitTestMode
assert(!SwingUtilities.isEventDispatchThread() || isInTestMode)
}
class SenderComponent(val sender: StatisticSender, val statusHelper: WebServiceStatusProvider) : ApplicationComponent {
private val LOG = logger<SenderComponent>()
private val disposable = Disposer.newDisposable()
private val alarm = Alarm(Alarm.ThreadToUse.POOLED_THREAD, disposable)
private val sendInterval = 5 * Time.MINUTE
private fun send() {
if (ApplicationManager.getApplication().isUnitTestMode) return
try {
ApplicationManager.getApplication().executeOnPooledThread {
statusHelper.updateStatus()
if (statusHelper.isServerOk()) {
val dataServerUrl = statusHelper.getDataServerUrl()
sender.sendStatsData(dataServerUrl)
}
}
} catch (e: Exception) {
LOG.error(e.message)
} finally {
alarm.addRequest({ send() }, sendInterval)
}
}
override fun disposeComponent() {
Disposer.dispose(disposable)
}
override fun initComponent() {
ApplicationManager.getApplication().executeOnPooledThread {
send()
}
}
}
class StatisticSender(val requestService: RequestService, val filePathProvider: FilePathProvider) {
fun sendStatsData(url: String) {
assertNotEDT()
filePathProvider.cleanupOldFiles()
val filesToSend = filePathProvider.getDataFiles()
filesToSend.forEach {
if (it.length() > 0) {
val isSentSuccessfully = sendContent(url, it)
if (isSentSuccessfully) {
it.delete()
}
else {
return
}
}
}
}
private fun sendContent(url: String, file: File): Boolean {
val data = requestService.postZipped(url, file)
if (data != null && data.code >= 200 && data.code < 300) {
return true
}
return false
}
}
abstract class RequestService {
abstract fun post(url: String, params: Map<String, String>): ResponseData?
abstract fun post(url: String, file: File): ResponseData?
abstract fun postZipped(url: String, file: File): ResponseData?
abstract fun get(url: String): ResponseData?
}
class SimpleRequestService: RequestService() {
private val LOG = logger<SimpleRequestService>()
override fun post(url: String, params: Map<String, String>): ResponseData? {
val form = Form.form()
params.forEach { form.add(it.key, it.value) }
try {
val response = Request.Post(url).bodyForm(form.build()).execute()
val httpResponse = response.returnResponse()
return ResponseData(httpResponse.status())
} catch (e: IOException) {
LOG.debug(e)
return null
}
}
override fun postZipped(url: String, file: File): ResponseData? {
try {
val zippedArray = getZippedContent(file)
val request = Request.Post(url).bodyByteArray(zippedArray).apply {
addHeader(BasicHeader(HttpHeaders.CONTENT_ENCODING, "gzip"))
}
val response = request.execute().returnResponse()
return ResponseData(response.status(), response.text())
} catch (e: IOException) {
LOG.debug(e)
return null
}
}
private fun getZippedContent(file: File): ByteArray {
val fileText = file.readText()
return GzipBase64Compressor.compress(fileText)
}
override fun post(url: String, file: File): ResponseData? {
try {
val response = Request.Post(url).bodyFile(file, ContentType.TEXT_HTML).execute()
val httpResponse = response.returnResponse()
val text = EntityUtils.toString(httpResponse.entity)
return ResponseData(httpResponse.statusLine.statusCode, text)
}
catch (e: IOException) {
LOG.debug(e)
return null
}
}
override fun get(url: String): ResponseData? {
try {
var data: ResponseData? = null
Request.Get(url).execute().handleResponse {
val text = EntityUtils.toString(it.entity)
data = ResponseData(it.statusLine.statusCode, text)
}
return data
} catch (e: IOException) {
LOG.debug(e)
return null
}
}
}
data class ResponseData(val code: Int, val text: String = "") {
fun isOK() = code in 200..299
}
object GzipBase64Compressor {
fun compress(text: String): ByteArray {
val outputStream = ByteArrayOutputStream()
val base64Stream = GZIPOutputStream(Base64OutputStream(outputStream))
base64Stream.write(text.toByteArray())
base64Stream.close()
return outputStream.toByteArray()
}
}
fun HttpResponse.text(): String = EntityUtils.toString(entity)
fun HttpResponse.status(): Int = statusLine.statusCode | plugins/stats-collector/src/com/intellij/stats/completion/SenderComponent.kt | 128908822 |
/*
* Copyright 2017 - Chimerapps BVBA
*
* 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.chimerapps.moshigenerator
import com.squareup.javapoet.ClassName
import com.squareup.javapoet.CodeBlock
import com.squareup.javapoet.FieldSpec
import com.squareup.javapoet.JavaFile
import com.squareup.javapoet.MethodSpec
import com.squareup.javapoet.ParameterSpec
import com.squareup.javapoet.ParameterizedTypeName
import com.squareup.javapoet.TypeName
import com.squareup.javapoet.TypeSpec
import com.squareup.javapoet.WildcardTypeName
import com.squareup.moshi.Json
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.JsonReader
import com.squareup.moshi.JsonWriter
import com.squareup.moshi.Moshi
import java.io.IOException
import java.lang.reflect.Type
import java.util.logging.Level
import java.util.logging.Logger
import javax.annotation.processing.Filer
import javax.lang.model.element.Modifier
import javax.lang.model.element.VariableElement
import javax.lang.model.util.Elements
/**
* @author Nicola Verbeeck
* * Date 23/05/2017.
*/
@SuppressWarnings("WeakerAccess")
class AdapterGenerator(private val clazz: MoshiAnnotatedClass, private val filer: Filer, private val elementUtils: Elements, private val logger: SimpleLogger) {
private val logging = clazz.debugLogs()
@Throws(AnnotationError::class, IOException::class)
fun generate() {
val from = createFromJson()
val to = createToJson()
val constructor = createConstructor()
val adapterClassBuilder = TypeSpec.classBuilder(clazz.element.simpleName.toString() + "Adapter")
adapterClassBuilder.superclass(ParameterizedTypeName.get(ClassName.get(BaseGeneratedAdapter::class.java), ClassName.get(clazz.element)))
adapterClassBuilder.addModifiers(Modifier.PUBLIC)
adapterClassBuilder.addOriginatingElement(clazz.element)
adapterClassBuilder.addJavadoc("Generated using moshi-generator")
if (logging) {
adapterClassBuilder.addField(
FieldSpec.builder(Logger::class.java, "LOGGER",
Modifier.FINAL,
Modifier.PRIVATE,
Modifier.STATIC)
.initializer("\$T.getLogger(\$S)",
ClassName.get(Logger::class.java),
"${clazz.packageName}.${clazz.element.simpleName}Adapter").build())
}
adapterClassBuilder.addField(FieldSpec.builder(Moshi::class.java, "moshi", Modifier.PRIVATE).build())
adapterClassBuilder.addMethod(constructor)
adapterClassBuilder.addMethod(from)
adapterClassBuilder.addMethod(to)
adapterClassBuilder.addMethod(generateSetMoshiMethod())
if (clazz.generatesFactory()) {
MoshiFactoryGenerator(clazz.element.simpleName.toString() + "AdapterFactory",
clazz.packageName,
listOf(ClassName.bestGuess("${clazz.packageName}.${clazz.element.simpleName}")),
filer,
elementUtils)
.generate()
}
JavaFile.builder(clazz.packageName, adapterClassBuilder.build())
.indent("\t")
.build().writeTo(filer)
}
private fun createToJson(): MethodSpec {
return MethodSpec.methodBuilder("toJson")
.addAnnotation(Override::class.java)
.addModifiers(Modifier.PUBLIC)
.addException(IOException::class.java)
.returns(TypeName.VOID)
.addParameter(ParameterSpec.builder(JsonWriter::class.java, "writer", Modifier.FINAL).build())
.addParameter(ParameterSpec.builder(ClassName.get(clazz.element), "value", Modifier.FINAL).build())
.addCode(createWriterBlock())
.build()
}
private fun createFromJson(): MethodSpec {
return MethodSpec.methodBuilder("fromJson")
.addAnnotation(Override::class.java)
.addModifiers(Modifier.PUBLIC)
.addException(IOException::class.java)
.returns(ClassName.get(clazz.element))
.addParameter(ParameterSpec.builder(JsonReader::class.java, "reader", Modifier.FINAL).build())
.addCode(createReaderBlock())
.build()
}
private fun createConstructor(): MethodSpec {
val builder = MethodSpec.constructorBuilder()
.addModifiers(Modifier.PUBLIC)
.addParameter(JsonAdapter.Factory::class.java, "factory", Modifier.FINAL)
.addParameter(Type::class.java, "type", Modifier.FINAL)
.addStatement("super(factory,type)")
if (logging) {
builder.addStatement("LOGGER.log(\$T.FINE, \"Constructing \$N\")", ClassName.get(Level::class.java), "${clazz.element.simpleName}Adapter")
}
return builder.build()
}
private fun createReaderBlock(): CodeBlock {
val builder = CodeBlock.builder()
if (logging) {
builder.addStatement("LOGGER.log(\$T.FINE, \"Reading json\")", ClassName.get(Level::class.java))
}
builder.beginControlFlow("if (reader.peek() == \$T.Token.NULL)", ClassName.get(JsonReader::class.java))
builder.addStatement("return reader.nextNull()")
builder.endControlFlow()
val fields = clazz.fields
for (variableElement in fields) {
builder.addStatement("\$T __\$N = null", TypeName.get(variableElement.asType()).box(), variableElement.simpleName.toString())
}
builder.addStatement("reader.beginObject()")
builder.beginControlFlow("while (reader.hasNext())")
builder.addStatement("final \$T _name = reader.nextName()", ClassName.get(String::class.java))
if (logging) {
builder.addStatement("LOGGER.log(\$T.FINE, \"\tGot name: {0}\", _name)", ClassName.get(Level::class.java))
}
builder.beginControlFlow("switch (_name)")
for (variableElement in fields) {
builder.add("case \$S: ", getJsonFieldName(variableElement))
generateReader(builder, variableElement)
builder.addStatement("break")
}
builder.addStatement("default: reader.skipValue()")
builder.endControlFlow()
builder.endControlFlow()
builder.addStatement("reader.endObject()")
generateNullChecks(builder, fields)
builder.add("return new \$T(", ClassName.get(clazz.element))
fields.forEachIndexed { index, variableElement ->
if (index != 0) {
builder.add(", ")
}
builder.add("__\$N", variableElement.simpleName.toString())
}
builder.addStatement(")")
return builder.build()
}
private fun createWriterBlock(): CodeBlock {
val builder = CodeBlock.builder()
if (clazz.generatesWriter()) {
val writesNulls = clazz.writerSerializesNulls()
builder.beginControlFlow("if (value == null)")
.addStatement("writer.nullValue()")
.addStatement("return")
.endControlFlow()
builder.addStatement("writer.beginObject()")
val fields = clazz.writerFields
for (variableElement in fields) {
if (writesNulls || !isNullable(variableElement)) {
builder.addStatement("writer.name(\$S)", getJsonFieldName(variableElement))
generateWriter(builder, variableElement, accessorOverride = null)
} else {
builder.beginControlFlow("")
builder.addStatement("final \$T __nullCheck = value.${valueAccessor(variableElement)}", TypeName.get(variableElement.asType()))
builder.beginControlFlow("if (__nullCheck != null)")
builder.addStatement("writer.name(\$S)", getJsonFieldName(variableElement))
generateWriter(builder, variableElement, "__nullCheck")
builder.endControlFlow()
builder.endControlFlow()
}
}
builder.addStatement("writer.endObject()")
} else {
builder.addStatement("moshi.nextAdapter(factory, type, EMPTY_ANNOTATIONS).toJson(writer, value)")
}
return builder.build()
}
private fun generateNullChecks(builder: CodeBlock.Builder, fields: List<VariableElement>) {
for (field in fields) {
if (!isNullable(field)) { //No annotation -> required
builder.beginControlFlow("if (__\$N == null)", field.simpleName.toString())
builder.addStatement("throw new \$T(\$S)", ClassName.get(IOException::class.java), getJsonFieldName(field) + " is non-optional but was not found in the json")
builder.endControlFlow()
}
}
}
private fun generateReader(builder: CodeBlock.Builder, variableElement: VariableElement) {
val typeName = TypeName.get(variableElement.asType())
if (typeName.isPrimitive || typeName.isBoxedPrimitive) {
generatePrimitiveReader(builder, typeName, variableElement)
} else if (typeName == ClassName.get(String::class.java)) {
if (isNullable(variableElement))
builder.addStatement("__\$N = (reader.peek() == \$T.Token.NULL) ? reader.<\$T>nextNull() : reader.nextString()", variableElement.simpleName.toString(), ClassName.get(JsonReader::class.java), typeName.box())
else
builder.addStatement("__\$N = reader.nextString()", variableElement.simpleName.toString())
} else {
generateDelegatedReader(builder, typeName, variableElement)
}
}
private fun generateWriter(builder: CodeBlock.Builder, variableElement: VariableElement, accessorOverride: String?) {
val typeName = TypeName.get(variableElement.asType())
if (typeName.isPrimitive || typeName.isBoxedPrimitive || typeName == ClassName.get(String::class.java)) {
generatePrimitiveWriter(builder, variableElement, accessorOverride)
} else {
generateDelegatedWriter(builder, typeName, variableElement, accessorOverride)
}
}
private fun generatePrimitiveReader(builder: CodeBlock.Builder, typeName: TypeName, variableElement: VariableElement) {
val primitive = typeName.unbox()
var method: String? = null
if (primitive == TypeName.BOOLEAN) {
method = "nextBoolean"
} else if (primitive == TypeName.BYTE) {
throw AnnotationError("Byte not supported")
} else if (primitive == TypeName.SHORT) {
builder.addStatement("__\$N = (short)reader.nextInt()", variableElement.simpleName.toString())
} else if (primitive == TypeName.INT) {
method = "nextInt"
} else if (primitive == TypeName.LONG) {
method = "nextLong"
} else if (primitive == TypeName.CHAR) {
throw AnnotationError("Char not supported")
} else if (primitive == TypeName.FLOAT) {
builder.addStatement("__\$N = (float)reader.nextDouble()", variableElement.simpleName.toString())
} else if (primitive == TypeName.DOUBLE) {
method = "nextDouble"
}
if (method != null) {
if (isNullable(variableElement))
builder.addStatement("__\$N = (reader.peek() == \$T.Token.NULL) ? reader.<\$T>nextNull() : \$T.valueOf(reader.\$N())", variableElement.simpleName.toString(), ClassName.get(JsonReader::class.java), typeName.box(), typeName.box(), method)
else
builder.addStatement("__\$N = reader.\$N()", variableElement.simpleName.toString(), method)
}
}
private fun generatePrimitiveWriter(builder: CodeBlock.Builder, variableElement: VariableElement, accessorOverride: String?) {
if (accessorOverride != null)
builder.addStatement("writer.value($accessorOverride)")
else
builder.addStatement("writer.value(value.${valueAccessor(variableElement)})")
}
private fun generateDelegatedReader(builder: CodeBlock.Builder, typeName: TypeName, variableElement: VariableElement) {
val subBuilder = CodeBlock.builder()
subBuilder.beginControlFlow("")
subBuilder.addStatement("final \$T _adapter = moshi.adapter(" + makeType(typeName) + ")", ParameterizedTypeName.get(ClassName.get(JsonAdapter::class.java), typeName))
if (logging) {
subBuilder.addStatement("LOGGER.log(\$T.FINE, \"\tGot delegate adapter: {0}\", _adapter)", ClassName.get(Level::class.java))
}
subBuilder.addStatement("__\$N = _adapter.fromJson(reader)", variableElement.simpleName.toString())
if (logging) {
subBuilder.addStatement("LOGGER.log(\$T.FINE, \"\tGot model data: {0}\", __\$N)", ClassName.get(Level::class.java), variableElement.simpleName.toString())
}
subBuilder.endControlFlow()
builder.add(subBuilder.build())
}
private fun generateDelegatedWriter(builder: CodeBlock.Builder, typeName: TypeName, variableElement: VariableElement, accessorOverride: String?) {
val subBuilder = CodeBlock.builder()
subBuilder.beginControlFlow("")
subBuilder.addStatement("final \$T _adapter = moshi.adapter(" + makeType(typeName) + ")", ParameterizedTypeName.get(ClassName.get(JsonAdapter::class.java), typeName))
if (logging) {
subBuilder.addStatement("LOGGER.log(\$T.FINE, \"\tGot delegate adapter: {0}\", _adapter)", ClassName.get(Level::class.java))
}
if (accessorOverride != null)
subBuilder.addStatement("_adapter.toJson(writer, $accessorOverride)")
else
subBuilder.addStatement("_adapter.toJson(writer, value.${valueAccessor(variableElement)})")
subBuilder.endControlFlow()
builder.add(subBuilder.build())
}
private fun makeType(typeName: TypeName): String {
if (typeName is ParameterizedTypeName) {
val parameterizedTypeName = typeName
val builder = StringBuilder("com.squareup.moshi.Types.newParameterizedType(")
builder.append(parameterizedTypeName.rawType.toString())
builder.append(".class, ")
parameterizedTypeName.typeArguments.forEachIndexed { index, typeArgument ->
if (index != 0) {
builder.append(", ")
}
builder.append(makeType(typeArgument))
}
builder.append(')')
return builder.toString()
} else if (typeName is WildcardTypeName) {
return makeType(typeName.upperBounds[0])
} else {
return typeName.toString() + ".class"
}
}
private fun isNullable(field: VariableElement): Boolean {
field.annotationMirrors.forEach {
when (it.annotationType.toString()) {
INTELLIJ_NULLABLE -> return true
ANDROID_NULLABLE -> return true
}
}
return false
}
private fun getJsonFieldName(variableElement: VariableElement): String {
return variableElement.getAnnotation(Json::class.java)?.name
?: variableElement.getAnnotation(JsonName::class.java)?.name
?: return variableElement.simpleName.toString()
}
private fun valueAccessor(variableElement: VariableElement): String {
val name = variableElement.simpleName.toString()
if (clazz.hasVisibleField(name)) {
return name
}
val type = TypeName.get(variableElement.asType())
if (type == TypeName.BOOLEAN || (type.isBoxedPrimitive && type.unbox() == TypeName.BOOLEAN)) {
val getterName = if (name.startsWith("is")) name else "is${name.capitalize()}"
if (clazz.hasGetter(getterName, variableElement.asType())) {
return "$getterName()"
}
}
return "get${name.capitalize()}()"
}
private fun generateSetMoshiMethod(): MethodSpec {
return MethodSpec.methodBuilder("setMoshi")
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addParameter(TypeName.get(Moshi::class.java), "moshi", Modifier.FINAL)
.addStatement("this.moshi = moshi")
.build()
}
companion object {
private val INTELLIJ_NULLABLE = "org.jetbrains.annotations.Nullable"
private val ANDROID_NULLABLE = "android.support.annotation.Nullable"
}
}
| moshi-generator/src/main/kotlin/com/chimerapps/moshigenerator/AdapterGenerator.kt | 3970764787 |
package org.videolan.vlc.util
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import org.videolan.libvlc.Dialog
import org.videolan.vlc.gui.dialogs.VlcLoginDialog
import org.videolan.vlc.gui.dialogs.VlcProgressDialog
import org.videolan.vlc.gui.dialogs.VlcQuestionDialog
import videolan.org.commontools.LiveEvent
private const val TAG = "DialogDelegate"
interface IDialogHandler
interface IDialogDelegate {
fun observeDialogs(lco: LifecycleOwner, manager: IDialogManager)
}
interface IDialogManager {
fun fireDialog(dialog: Dialog)
fun dialogCanceled(dialog: Dialog?)
}
class DialogDelegate : IDialogDelegate {
override fun observeDialogs(lco: LifecycleOwner, manager: IDialogManager) {
dialogEvt.observe(lco, Observer {
when(it) {
is Show -> manager.fireDialog(it.dialog)
is Cancel -> manager.dialogCanceled(it.dialog)
}
})
}
companion object DialogsListener : Dialog.Callbacks {
private val dialogEvt: LiveEvent<DialogEvt> = LiveEvent()
var dialogCounter = 0
override fun onProgressUpdate(dialog: Dialog.ProgressDialog) {
val vlcProgressDialog = dialog.context as? VlcProgressDialog ?: return
if (vlcProgressDialog.isVisible) vlcProgressDialog.updateProgress()
}
override fun onDisplay(dialog: Dialog.ErrorMessage) {
dialogEvt.value = Cancel(dialog)
}
override fun onDisplay(dialog: Dialog.LoginDialog) {
dialogEvt.value = Show(dialog)
}
override fun onDisplay(dialog: Dialog.QuestionDialog) {
dialogEvt.value = Show(dialog)
}
override fun onDisplay(dialog: Dialog.ProgressDialog) {
dialogEvt.value = Show(dialog)
}
override fun onCanceled(dialog: Dialog?) {
(dialog?.context as? DialogFragment)?.dismiss()
dialogEvt.value = Cancel(dialog)
}
}
}
fun Fragment.showVlcDialog(dialog: Dialog) {
activity?.showVlcDialog(dialog)
}
@Suppress("INACCESSIBLE_TYPE")
fun FragmentActivity.showVlcDialog(dialog: Dialog) {
val dialogFragment = when (dialog) {
is Dialog.LoginDialog -> VlcLoginDialog().apply {
vlcDialog = dialog
}
is Dialog.QuestionDialog -> VlcQuestionDialog().apply {
vlcDialog = dialog
}
is Dialog.ProgressDialog -> VlcProgressDialog().apply {
vlcDialog = dialog
}
else -> null
} ?: return
val fm = supportFragmentManager
dialogFragment.show(fm, "vlc_dialog_${++DialogDelegate.dialogCounter}")
}
private sealed class DialogEvt
private class Show(val dialog: Dialog) : DialogEvt()
private class Cancel(val dialog: Dialog?) : DialogEvt() | application/vlc-android/src/org/videolan/vlc/util/DialogDelegates.kt | 611472845 |
package de.esymetric.jerusalem.routing.algorithms
import de.esymetric.jerusalem.ownDataRepresentation.Node
import de.esymetric.jerusalem.ownDataRepresentation.fileSystem.PartitionedNodeListFile
import de.esymetric.jerusalem.ownDataRepresentation.fileSystem.PartitionedTransitionListFile
import de.esymetric.jerusalem.ownDataRepresentation.fileSystem.PartitionedWayCostFile
import de.esymetric.jerusalem.ownDataRepresentation.geoData.GPSMath.calculateDistance
import de.esymetric.jerusalem.ownDataRepresentation.geoData.Position
import de.esymetric.jerusalem.ownDataRepresentation.geoData.importExport.KML
import de.esymetric.jerusalem.routing.Router
import de.esymetric.jerusalem.routing.RoutingAlgorithm
import de.esymetric.jerusalem.routing.RoutingHeuristics
import de.esymetric.jerusalem.routing.RoutingType
import de.esymetric.jerusalem.utils.Utils
import java.util.*
class TomsAStarStarRouting : RoutingAlgorithm {
private var openList: SortedSet<Node> = TreeSet()
private var openListMap = HashMap<Long, Node>()
private var closedList = HashSet<Long>()
lateinit var nlf: PartitionedNodeListFile
lateinit var wlf: PartitionedTransitionListFile
lateinit var wcf: PartitionedWayCostFile
lateinit var type: RoutingType
lateinit var target: Node
lateinit var heuristics: RoutingHeuristics
override fun getRoute(
start: Node, target: Node, type: RoutingType,
nlf: PartitionedNodeListFile, wlf: PartitionedTransitionListFile, wcf: PartitionedWayCostFile,
heuristics: RoutingHeuristics, targetNodeMasterNodes: List<Node>, maxExecutionTimeSec: Int,
useOptimizedPath: Boolean
): List<Node>? {
this.nlf = nlf
this.wlf = wlf
this.wcf = wcf
this.type = type
this.target = target
this.heuristics = heuristics
val maxTime = Date().time + maxExecutionTimeSec.toLong() * 1000L
// clear
openList.clear()
openListMap.clear()
closedList.clear()
start.totalCost = calculateDistance(
start.lat, start.lng,
target.lat, target.lng
) * heuristics.estimateRemainingCost(type) / 1000.0
start.realCostSoFar = 0.0
openList.add(start)
openListMap[start.uID] = start
var node: Node
var bestNode: Node? = null
var count = 0
while (openList.size > 0) {
node = openList.first()
openList.remove(node)
openListMap.remove(node.uID)
if (bestNode == null || bestNode.remainingCost() > node.remainingCost()) bestNode = node
if (node == target) {
if (Router.debugMode) println(
"final number of open nodes was "
+ openList.size + " - closed list size was "
+ closedList.size + " - final cost is "
+ Utils.formatTimeStopWatch((node.totalCost.toInt() * 1000).toLong())
)
return getFullPath(node)
}
if (SAVE_STATE_AS_KML) saveStateAsKml(getFullPath(node), ++count) // for debugging
expand(node, targetNodeMasterNodes)
closedList.add(node.uID)
if (closedList.size > MAX_NODES_IN_CLOSED_LIST) break
if (closedList.size and 0xfff == 0
&& Date().time > maxTime
) break
if (Router.debugMode && closedList.size and 0xffff == 0) println(
"closed list now contains "
+ closedList.size + " entries"
)
}
if (Router.debugMode) println(
"no route - open list is empty - final number of open nodes was "
+ openList.size
+ " - closed list size was "
+ closedList.size
)
bestNode ?: return null
return getFullPath(bestNode)
}
private fun getFullPath(sourceNode: Node): List<Node> {
var node: Node = sourceNode
val foundPath: MutableList<Node> = LinkedList()
while (true) {
foundPath.add(node)
node = if (node.predecessor == null) break else {
node.predecessor!!
}
}
foundPath.reverse()
return foundPath
}
fun expand(currentNode: Node, targetNodeMasterNodes: List<Node?>) {
// falls es sich um eine mit dem Ziel verbunde Kreuzungsnode handelt,
// den Original-Pfad verfolgen und nicht den optimierten Pfad, welcher
// die targetNode �berspringen w�rde
for (t in currentNode.listTransitions(nlf, wlf, wcf)) {
var transition = t
if (targetNodeMasterNodes.contains(t.targetNode) && targetNodeMasterNodes.contains(currentNode) ) {
transition = wlf.getTransition(currentNode, t.id, nlf, wcf) ?: t
}
var successor = transition.targetNode
if (closedList.contains(successor!!.uID)) continue
// clone successor object - this is required because successor
// contains search path specific information and can be in open list
// multiple times
successor = successor.clone() as Node
var cost = currentNode.realCostSoFar
val transitionCost = transition.getCost(type)
if (transitionCost == RoutingHeuristics.BLOCKED_WAY_COST) continue
cost += transitionCost
successor.realCostSoFar = cost
cost += successor.getRemainingCost(target, type, heuristics)
successor.totalCost = cost
if (openListMap.containsKey(successor.uID)
&& cost > openListMap[successor.uID]!!.totalCost
) continue
successor.predecessor = currentNode
openList.remove(successor)
openList.add(successor)
openListMap[successor.uID] = successor
}
}
/**
* Enable this method to document the process of route creation.
*/
fun saveStateAsKml(route: List<Node?>?, count: Int) {
val kml = KML()
val trackPts = Vector<Position>()
for (n in route!!) {
val p = Position()
p.latitude = n!!.lat
p.longitude = n.lng
trackPts.add(p)
}
kml.trackPositions = trackPts
kml.save("current_$count.kml")
}
companion object {
const val MAX_NODES_IN_CLOSED_LIST = 1000000
const val SAVE_STATE_AS_KML = false
}
} | src/main/java/de/esymetric/jerusalem/routing/algorithms/TomsAStarStarRouting.kt | 2625671104 |
/*
* Copyright (C) 2014-2022 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>,
* Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors.
*
* This file is part of Amaze File Manager.
*
* Amaze File Manager 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.amaze.filemanager.filesystem.ftpserver.commands
import com.amaze.filemanager.R
import com.amaze.filemanager.application.AppConfig
import org.apache.ftpserver.command.AbstractCommand
import org.apache.ftpserver.ftplet.DefaultFtpReply
import org.apache.ftpserver.ftplet.FtpReply
import org.apache.ftpserver.ftplet.FtpRequest
import org.apache.ftpserver.impl.FtpIoSession
import org.apache.ftpserver.impl.FtpServerContext
/**
* Custom [org.apache.ftpserver.command.impl.FEAT] to add [AVBL] command to the list.
*/
class FEAT : AbstractCommand() {
override fun execute(session: FtpIoSession, context: FtpServerContext, request: FtpRequest) {
session.resetState()
session.write(
DefaultFtpReply(
FtpReply.REPLY_211_SYSTEM_STATUS_REPLY,
AppConfig.getInstance().getString(R.string.ftp_command_FEAT)
)
)
}
}
| app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/commands/FEAT.kt | 1890031056 |
@file:Suppress("unused")
package com.ternaryop.photoshelf.debug
import android.content.Context
import androidx.preference.PreferenceManager
import com.github.scribejava.core.model.OAuth1AccessToken
import com.ternaryop.photoshelf.PhotoShelfApplicationEnv
import com.ternaryop.photoshelf.R
import com.ternaryop.photoshelf.api.ApiManager
import com.ternaryop.photoshelf.core.prefs.PREF_PHOTOSHELF_APIKEY
import com.ternaryop.tumblr.android.TokenPreference
class DebugApplicationEnv : PhotoShelfApplicationEnv {
override fun setup(context: Context) {
ApiManager.updateToken(context.getString(R.string.PHOTOSHELF_ACCESS_TOKEN))
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putString(PREF_PHOTOSHELF_APIKEY, context.getString(R.string.PHOTOSHELF_ACCESS_TOKEN))
.apply()
val token = OAuth1AccessToken(
context.getString(R.string.TUMBLR_OAUTH_TOKEN),
context.getString(R.string.TUMBLR_OAUTH_TOKEN_SECRET))
TokenPreference.from(context).storeAccessToken(token)
}
} | app/src/debug/java/com/ternaryop/photoshelf/debug/DebugApplicationEnv.kt | 1457741292 |
package org.blitzortung.android.location.provider
import android.content.Context
import android.location.Location
import android.location.LocationManager
import org.blitzortung.android.app.BOApplication
import org.blitzortung.android.location.LocationHandler
import org.jetbrains.anko.defaultSharedPreferences
internal fun createLocationProvider(context: Context, backgroundMode: Boolean, tmp: (Location?) -> Unit, providerName: String): LocationProvider {
val provider = when(providerName) {
LocationManager.GPS_PROVIDER -> GPSLocationProvider(context, backgroundMode, tmp)
LocationManager.NETWORK_PROVIDER -> NetworkLocationProvider(context, backgroundMode, tmp)
LocationManager.PASSIVE_PROVIDER -> PassiveLocationProvider(context, backgroundMode, tmp)
LocationHandler.MANUAL_PROVIDER -> ManualLocationProvider(tmp, BOApplication.sharedPreferences)
else -> null
} ?: throw IllegalArgumentException("Cannot find provider for name $providerName")
return provider
}
| app/src/main/java/org/blitzortung/android/location/provider/LocationProviderFactory.kt | 1199312738 |
package com.nextfaze.devfun.demo
import android.content.pm.ActivityInfo
import android.view.View
import androidx.test.espresso.UiController
import androidx.test.espresso.ViewAction
import androidx.test.espresso.matcher.ViewMatchers.isRoot
import androidx.test.runner.lifecycle.ActivityLifecycleMonitorRegistry
import androidx.test.runner.lifecycle.Stage
import org.hamcrest.Matcher
fun orientationLandscape(): ViewAction = OrientationChangeAction(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
fun orientationPortrait(): ViewAction = OrientationChangeAction(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
private class OrientationChangeAction(private val orientation: Int) : ViewAction {
override fun getConstraints(): Matcher<View> = isRoot()
override fun getDescription() = "Change orientation to $orientation"
override fun perform(uiController: UiController, view: View) {
uiController.loopMainThreadUntilIdle()
ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED).single().requestedOrientation = orientation
uiController.loopMainThreadUntilIdle()
val resumedActivities = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED)
if (resumedActivities.isEmpty()) {
throw RuntimeException("Could not change orientation")
}
}
}
| demo/src/androidTest/java/com/nextfaze/devfun/demo/OrientationChangeAction.kt | 1223388772 |
/*
* Copyright 2016-2021 Adrian Cotfas
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
package com.apps.adrcotfas.goodtime.statistics.main
import android.graphics.Canvas
import com.github.mikephil.charting.utils.ViewPortHandler
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.renderer.XAxisRenderer
import com.github.mikephil.charting.utils.MPPointF
import com.github.mikephil.charting.utils.Transformer
import com.github.mikephil.charting.utils.Utils
/**
* Custom X-axis renderer which helps with the drawing of labels on more than one line.
* It is useful for drawing the year bellow the month.
*/
class CustomXAxisRenderer(viewPortHandler: ViewPortHandler?, xAxis: XAxis?, trans: Transformer?) :
XAxisRenderer(viewPortHandler, xAxis, trans) {
override fun drawLabel(
c: Canvas,
formattedLabel: String,
x: Float,
y: Float,
anchor: MPPointF,
angleDegrees: Float
) {
val lines = formattedLabel.split("\n".toRegex()).toTypedArray()
for (i in lines.indices) {
val vOffset = i * mAxisLabelPaint.textSize
Utils.drawXAxisValue(c, lines[i], x, y + vOffset, mAxisLabelPaint, anchor, angleDegrees)
}
}
} | app/src/main/java/com/apps/adrcotfas/goodtime/statistics/main/CustomXAxisRenderer.kt | 3186444896 |
package tinyscript.compiler.core
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
object FunctionExpressionSpec : Spek({
describe("function expression") {
it("can be used with and without parameters") {
assertAnalysis("""
multiplyByTwo = [n: Int] -> n * 2
double = multiplyByTwo[n = 1]
sayHi = -> println[m = "Hi"]
sayHi[]
""")
}
it("has to be called with the right arguments") {
assertAnalysisFails("""
multiplyByTwo = [n: Int] -> n * 2
foo = multiplyByTwo[]
""")
}
it("must be analysed even when not called") {
assertAnalysisFails("""
foo = -> abc
""")
assertAnalysisFails("""
foo = -> (-> abc)
""")
}
it("can be used with an explicit type") {
assertAnalysis("""
multiplyByTwo: [n: Int] -> Int = [n: Int] -> n * 2
""")
assertAnalysis("""
multiplyByTwo: [n: Int, foo: String] -> ? = [n: Int] -> n * 2
""")
assertAnalysisFails("""
multiplyByTwo: [] -> Int = [n: Int] -> n * 2
""")
assertAnalysisFails("""
multiplyByTwo: [n: Int] -> String = [n: Int] -> n * 2
""")
}
it("can use forward references until it is called") {
assertAnalysis("""
sayHi = -> println[m = hiMessage]
hiMessage = "Hi"
sayHi[]
""")
assertAnalysisFails("""
sayHi = -> println[m = hiMessage]
sayHi[]
hiMessage = "Hi"
""")
}
}
})
| compiler-core/src/test/kotlin/tinyscript/compiler/core/FunctionExpressionSpec.kt | 482479902 |
package com.uber.okbuck.kotlin
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.Button
import android.widget.LinearLayout
import com.uber.okbuck.kotlin.android.R
import kotlinx.android.synthetic.main.test_layout.view.*
class TestLayout(context: Context, attrs: AttributeSet) : LinearLayout(context, attrs) {
init {
LayoutInflater.from(context).inflate(R.layout.test_layout, this)
button.setText("test")
}
}
| libraries/kotlinandroidlibrary/src/main/kotlin/com/uber/okbuck/kotlin/TestLayout.kt | 1428885064 |
package net.nemerosa.ontrack.extension.git.service
import net.nemerosa.ontrack.extension.scm.service.SCMService
import net.nemerosa.ontrack.extension.scm.service.SCMServiceProvider
import net.nemerosa.ontrack.model.structure.Branch
import net.nemerosa.ontrack.model.structure.Project
import org.springframework.stereotype.Component
import java.util.*
@Component
class GitServiceProvider(
private val gitService: GitService,
) : SCMServiceProvider {
override fun getScmService(branch: Branch): Optional<SCMService> = getScmService(branch.project)
override fun getScmService(project: Project): Optional<SCMService> {
val projectConfiguration = gitService.getProjectConfiguration(project)
return if (projectConfiguration != null) {
Optional.of(gitService)
} else {
Optional.empty()
}
}
override fun getProjectScmService(project: Project): SCMService? {
val projectConfiguration = gitService.getProjectConfiguration(project)
return if (projectConfiguration != null) {
gitService
} else {
null
}
}
} | ontrack-extension-git/src/main/java/net/nemerosa/ontrack/extension/git/service/GitServiceProvider.kt | 1567802001 |
package com.xiaojinzi.component.impl
import android.content.Intent
import com.xiaojinzi.component.support.Utils
/**
* 这个类表示一次成功路由的返回结果对象
* time : 2018/11/10
*
* @author : xiaojinzi
*/
data class RouterResult
@JvmOverloads constructor(
/**
* 最原始的请求,谁都更改不了的,而且不可能为空在这里
*/
val originalRequest: RouterRequest,
/**
* 获取可能由拦截器修改过的 request 对象,大部分没有被修改的其实就是最原始的 request 对象
* 如果成功了,这个会有值,这个可能不是最原始的请求啦,可能是拦截器修改过或者
* 整个 request 对象都被改了
*/
val finalRequest: RouterRequest,
/**
* 如果是跳转为了目标的 Intent
*/
val targetIntent: Intent? = null
) | ComponentImpl/src/main/java/com/xiaojinzi/component/impl/RouterResult.kt | 3881720610 |
/*
* This file is part of BOINC.
* http://boinc.berkeley.edu
* Copyright (C) 2020 University of California
*
* BOINC 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.
*
* BOINC 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 BOINC. If not, see <http://www.gnu.org/licenses/>.
*/
package edu.berkeley.boinc.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import edu.berkeley.boinc.databinding.EventLogClientListItemLayoutBinding
import edu.berkeley.boinc.rpc.Message
import edu.berkeley.boinc.utils.secondsToLocalDateTime
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
class ClientLogRecyclerViewAdapter(private val messages: List<Message>) :
RecyclerView.Adapter<ClientLogRecyclerViewAdapter.ViewHolder>() {
private val dateTimeFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val binding = EventLogClientListItemLayoutBinding.inflate(LayoutInflater.from(parent.context))
return ViewHolder(binding)
}
override fun getItemCount() = messages.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.date.text = getDateTimeString(position)
holder.message.text = getMessage(position)
val project = getProject(position)
if (project.isEmpty()) {
holder.project.visibility = View.GONE
} else {
holder.project.visibility = View.VISIBLE
holder.project.text = project
}
}
fun getDateTimeString(position: Int): String = dateTimeFormatter.format(messages[position].timestamp.secondsToLocalDateTime())
fun getMessage(position: Int) = messages[position].body
fun getProject(position: Int) = messages[position].project
class ViewHolder(binding: EventLogClientListItemLayoutBinding) : RecyclerView.ViewHolder(binding.root) {
val date = binding.msgsDate
val project = binding.msgsProject
val message = binding.msgsMessage
}
}
| android/BOINC/app/src/main/java/edu/berkeley/boinc/adapter/ClientLogRecyclerViewAdapter.kt | 518832355 |
package graphql.relay
/**
* represents an edge in relay.
*/
interface Edge<out T> {
val node: T?
val cursor: ConnectionCursor
}
| src/main/kotlin/graphql/relay/Edge.kt | 3719326053 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.