content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package ch.yvu.teststore.result
import ch.yvu.teststore.common.CassandraRepository
import com.datastax.driver.mapping.MappingManager
import org.springframework.beans.factory.annotation.Autowired
import java.util.*
open class CassandraResultRepository @Autowired constructor(mappingManager: MappingManager) :
ResultRepository, CassandraRepository<Result>(mappingManager, "result", Result::class.java) {
override fun updateFailureReason(runId: UUID, testName: String, retryNum: Int, failureReason: String) {
session.execute("UPDATE result SET failureReason=? WHERE run=? AND testName=? AND retryNum=?",
failureReason,
runId,
testName,
retryNum)
}
override fun findAllByRunIdAndTestName(runId: UUID, testName: String): List<Result> {
val results = session.execute("SELECT * FROM result WHERE run=? AND testName=?", runId, testName)
return mapper.map(results).all().toList()
}
override fun findAllByRunId(runId: UUID): List<Result> {
val results = session.execute("SELECT * FROM result WHERE run=?", runId)
return mapper.map(results).all().toList()
}
} | backend/src/main/kotlin/ch/yvu/teststore/result/CassandraResultRepository.kt | 3965658966 |
/*
* Copyright (c) 2022, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package no.nordicsemi.android.hts.repository
import android.content.Intent
import androidx.lifecycle.lifecycleScope
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import no.nordicsemi.android.service.DEVICE_DATA
import no.nordicsemi.android.service.NotificationService
import no.nordicsemi.ui.scanner.DiscoveredBluetoothDevice
import javax.inject.Inject
@AndroidEntryPoint
internal class HTSService : NotificationService() {
@Inject
lateinit var repository: HTSRepository
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId)
val device = intent!!.getParcelableExtra<DiscoveredBluetoothDevice>(DEVICE_DATA)!!
repository.start(device, lifecycleScope)
repository.hasBeenDisconnected.onEach {
if (it) stopSelf()
}.launchIn(lifecycleScope)
return START_REDELIVER_INTENT
}
}
| profile_hts/src/main/java/no/nordicsemi/android/hts/repository/HTSService.kt | 442716177 |
package io.gitlab.arturbosch.detekt.api
import org.jetbrains.kotlin.psi.KtFile
/**
* A rule set is a collection of rules and must be defined within a rule set provider implementation.
*
* @author Artur Bosch
*/
class RuleSet(val id: String, val rules: List<BaseRule>) {
init {
validateIdentifier(id)
}
/**
* Visits given file with all rules of this rule set, returning a list
* of all code smell findings.
*/
fun accept(file: KtFile): List<Finding> {
val findings: MutableList<Finding> = mutableListOf()
rules.forEach {
it.visitFile(file)
findings += it.findings
}
return findings
}
}
| detekt-api/src/main/kotlin/io/gitlab/arturbosch/detekt/api/RuleSet.kt | 2207221228 |
package edu.cs4730.bottomnavigationviewdemo_kt
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.NavigationUI
import com.google.android.material.bottomnavigation.BottomNavigationView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val navView = findViewById<BottomNavigationView>(R.id.nav_view)
/* if not using arch navigation, then you need to implement this.
navView.setOnItemSelectedListener(
NavigationBarView.OnItemSelectedListener { item -> //setup the fragments here.
val id = item.itemId
if (id == R.id.action_first) {
supportFragmentManager.beginTransaction().replace(R.id.container, OneFragment())
.commit()
item.isChecked = true
return@OnItemSelectedListener true
} else if (id == R.id.action_second) {
supportFragmentManager.beginTransaction().replace(R.id.container, TwoFragment())
.commit()
item.isChecked = true
} else if (id == R.id.action_third) {
supportFragmentManager.beginTransaction()
.replace(R.id.container, threeFragment()).commit()
item.isChecked = true
}
false
}
)*/
// Passing each menu ID as a set of Ids because each menu should be considered as top level destinations.
//Note for this to work with arch Navigation, these id must be the same id in menu.xml and the nav_graph.
val appBarConfiguration = AppBarConfiguration.Builder(
R.id.action_first, R.id.action_second, R.id.action_third
)
.build()
//val navController = Navigation.findNavController(this, R.id.nav_host_fragment)
//NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
val navHostFragment =
supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment?
val navController = navHostFragment!!.navController
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration)
NavigationUI.setupWithNavController(navView, navController)
//In order to have badges, you need to use the Theme.MaterialComponents.DayNight (doesn't have to be daynight, but MaterialComponents).
//In order to have badges, you need to use the Theme.MaterialComponents.DayNight (doesn't have to be daynight, but MaterialComponents).
val badge = navView.getOrCreateBadge(R.id.action_second)
badge.number = 12 //should show a 12 in the "badge" for the second one.
badge.isVisible = true
}
} | Advanced/BottomNavigationViewDemo_kt/app/src/main/java/edu/cs4730/bottomnavigationviewdemo_kt/MainActivity.kt | 3668447412 |
package com.airbnb.mvrx.sample.views
import android.content.Context
import android.util.AttributeSet
import android.widget.FrameLayout
import com.airbnb.epoxy.ModelView
import com.airbnb.mvrx.sample.R
@ModelView(autoLayout = ModelView.Size.MATCH_WIDTH_WRAP_HEIGHT)
class LoadingRow @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
init {
inflate(context, R.layout.loading_row, this)
}
}
| sample/src/main/java/com/airbnb/mvrx/sample/views/LoadingRow.kt | 777776567 |
import org.junit.Test
import org.junit.Ignore
import org.junit.experimental.runners.Enclosed
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import kotlin.test.assertEquals
@RunWith(Enclosed::class)
class AtbashTest {
@RunWith(Parameterized::class)
class EncodeTest(val input: String, val expectedOutput: String) {
companion object {
@JvmStatic
@Parameterized.Parameters
fun data() = listOf(
arrayOf("no", "ml"),
arrayOf("yes", "bvh"),
arrayOf("OMG", "lnt"),
arrayOf("mindblowingly", "nrmwy oldrm tob"),
arrayOf("Testing, 1 2 3, testing.", "gvhgr mt123 gvhgr mt"),
arrayOf("Truth is fiction.", "gifgs rhurx grlm"),
arrayOf("The quick brown fox jumps over the lazy dog.", "gsvjf rxpyi ldmul cqfnk hlevi gsvoz abwlt")
)
}
@Test
fun test() {
assertEquals(expectedOutput, Atbash.encode(input))
}
}
@RunWith(Parameterized::class)
class DecodeTest(val input: String, val expectedOutput: String) {
companion object {
@JvmStatic
@Parameterized.Parameters
fun data() = listOf(
arrayOf("vcvix rhn", "exercism"),
arrayOf("zmlyh gzxov rhlug vmzhg vkkrm thglm v", "anobstacleisoftenasteppingstone"),
arrayOf("gvhgr mt123 gvhgr mt", "testing123testing")
)
}
@Ignore
@Test
fun test() {
assertEquals(expectedOutput, Atbash.decode(input))
}
}
}
| exercises/atbash-cipher/src/test/kotlin/AtbashTest.kt | 1698385189 |
package com.sangcomz.fishbun
import android.app.Activity
import android.content.Context
import android.content.Intent
import androidx.activity.result.ActivityResultLauncher
import androidx.fragment.app.Fragment
import com.sangcomz.fishbun.adapter.image.ImageAdapter
import java.lang.ref.WeakReference
class FishBun private constructor(activity: Activity?, fragment: Fragment?) {
private val _activity: WeakReference<Activity?> = WeakReference(activity)
private val _fragment: WeakReference<Fragment?> = WeakReference(fragment)
val fishBunContext: FishBunContext get() = FishBunContext()
fun setImageAdapter(imageAdapter: ImageAdapter): FishBunCreator {
val fishton = Fishton.apply {
refresh()
this.imageAdapter = imageAdapter
}
return FishBunCreator(this, fishton)
}
companion object {
@Deprecated("To be deleted along with the startAlbum function")
const val FISHBUN_REQUEST_CODE = 27
const val INTENT_PATH = "intent_path"
@JvmStatic
fun with(activity: Activity) = FishBun(activity, null)
@JvmStatic
fun with(fragment: Fragment) = FishBun(null, fragment)
}
inner class FishBunContext {
private val activity = _activity.get()
private val fragment = _fragment.get()
fun getContext(): Context =
activity ?: fragment?.context ?: throw NullPointerException("Activity or Fragment Null")
fun startActivityForResult(intent: Intent, requestCode: Int) {
when {
activity != null -> activity.startActivityForResult(intent, requestCode)
fragment != null -> fragment.startActivityForResult(intent, requestCode)
else -> throw NullPointerException("Activity or Fragment Null")
}
}
fun startWithRegisterForActivityResult(
activityResultLauncher: ActivityResultLauncher<Intent>,
intent: Intent
) {
when {
activity != null || fragment != null -> activityResultLauncher.launch(intent)
else -> throw NullPointerException("Activity or Fragment Null")
}
}
}
}
| FishBun/src/main/java/com/sangcomz/fishbun/FishBun.kt | 3522334559 |
package kodando.rxjs.tests
import kotlin.browser.window
import kotlin.js.Promise
fun waitTime(time: Int): Promise<Unit> {
return Promise { resolve, _ ->
window.setTimeout({ resolve(Unit) }, time)
}
}
| kodando-rxjs/src/test/kotlin/kodando/rxjs/tests/Util.kt | 4145492096 |
/*
* 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.ape.apps.sample.baypilot.data.creditplan
import com.google.gson.Gson
enum class CreditPlanType {
MONTHLY, WEEKLY, DAILY;
companion object {
fun toString(creditPlanType: CreditPlanType?): String? {
return when (creditPlanType) {
MONTHLY -> "MONTHLY"
WEEKLY -> "WEEKLY"
DAILY -> "DAILY"
else -> null
}
}
fun toCreditPlanType(planType: String?): CreditPlanType? {
return when (planType) {
"DAILY" -> DAILY
"WEEKLY" -> WEEKLY
"MONTHLY" -> MONTHLY
else -> null
}
}
}
}
// Class to store all details related to device credit plan.
// TODO: Currently it has only few essential members for testing, add others.
class CreditPlanInfo(
val totalAmount: Int? = 0,
val totalPaidAmount: Int? = 0,
val dueDate: String? = null,
val nextDueAmount: Int? = 0,
val planType: CreditPlanType? = null
) {
companion object {
// Serialize a single object.
fun serializeToJson(cpi: CreditPlanInfo?): String? {
val gson = Gson()
return gson.toJson(cpi)
}
// Deserialize to single object.
fun deserializeFromJson(jsonString: String?): CreditPlanInfo? {
val gson = Gson()
return gson.fromJson(jsonString, CreditPlanInfo::class.java)
}
}
fun toDebugString(): String {
return "Credit Plan details: Due Date = $dueDate, Total device cost = $totalAmount, " +
"Amount paid till now: $totalPaidAmount Next installment due = $nextDueAmount, Plan type = $planType"
}
} | app/src/main/java/com/ape/apps/sample/baypilot/data/creditplan/CreditPlanInfo.kt | 166219080 |
package com.rm.translateit.api.translation.source.wiki
import com.rm.translateit.api.translation.source.Source
import dagger.Module
import dagger.Provides
import dagger.multibindings.IntoSet
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import javax.inject.Singleton
@Module
internal class WikiModule {
@Provides
@Singleton
fun url() = WikiUrl()
@Provides
@Singleton
fun detailsUrl() = WikiDetailsUrl()
@Provides @IntoSet
@Singleton
fun service(
url: WikiUrl,
detailsUrl: WikiDetailsUrl,
restService: WikiRestService
): Source = WikiSource(url, detailsUrl, restService)
@Provides
@Singleton
fun restService(): WikiRestService = Retrofit.Builder()
.baseUrl("http://wikipedia.org")
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build()
.create(WikiRestService::class.java)
} | api/src/main/kotlin/com/rm/translateit/api/translation/source/wiki/WikiModule.kt | 2471336256 |
package io.gitlab.arturbosch.detekt.core.processors
import io.gitlab.arturbosch.detekt.core.path
import io.gitlab.arturbosch.detekt.test.compileForTest
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.kotlin.psi.KtFile
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
class ClassCountVisitorTest : Spek({
describe("something") {
it("twoClassesInSeparateFile") {
val files = arrayOf(
compileForTest(path.resolve("Test.kt")),
compileForTest(path.resolve("Default.kt"))
)
val count = getClassCount(files)
assertThat(count).isEqualTo(2)
}
it("oneClassWithOneNestedClass") {
val file = compileForTest(path.resolve("ComplexClass.kt"))
val count = getClassCount(arrayOf(file))
assertThat(count).isEqualTo(2)
}
it("testEnumAndInterface") {
val files = arrayOf(
compileForTest(path.resolve("../empty/EmptyEnum.kt")),
compileForTest(path.resolve("../empty/EmptyInterface.kt"))
)
val count = getClassCount(files)
assertThat(count).isEqualTo(2)
}
}
})
private fun getClassCount(files: Array<KtFile>): Int {
return files
.map { getData(it) }
.sum()
}
private fun getData(file: KtFile): Int {
return with(file) {
accept(ClassCountVisitor())
@Suppress("UnsafeCallOnNullableType")
getUserData(numberOfClassesKey)!!
}
}
| detekt-core/src/test/kotlin/io/gitlab/arturbosch/detekt/core/processors/ClassCountVisitorTest.kt | 4189846508 |
package de.christinecoenen.code.zapp.app.settings.ui
import android.content.Context
import android.os.Bundle
import androidx.appcompat.app.AppCompatDelegate
import androidx.preference.ListPreference
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import de.christinecoenen.code.zapp.R
import de.christinecoenen.code.zapp.app.settings.helper.ShortcutPreference
import de.christinecoenen.code.zapp.app.settings.repository.SettingsRepository
/**
* Use the [SettingsFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class SettingsFragment : PreferenceFragmentCompat() {
companion object {
private const val PREF_SHORTCUTS = "pref_shortcuts"
private const val PREF_UI_MODE = "pref_ui_mode"
/**
* Use this factory method to create a new instance of
* this fragment.
*/
@JvmStatic
fun newInstance(): SettingsFragment {
return SettingsFragment()
}
}
private lateinit var settingsRepository: SettingsRepository
private lateinit var shortcutPreference: ShortcutPreference
private lateinit var uiModePreference: ListPreference
private val uiModeChangeListener = Preference.OnPreferenceChangeListener { _, newValue ->
val uiMode = settingsRepository.prefValueToUiMode(newValue as String?)
AppCompatDelegate.setDefaultNightMode(uiMode)
true
}
override fun onAttach(context: Context) {
super.onAttach(context)
settingsRepository = SettingsRepository(context)
}
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
addPreferencesFromResource(R.xml.preferences)
shortcutPreference = preferenceScreen.findPreference(PREF_SHORTCUTS)!!
uiModePreference = preferenceScreen.findPreference(PREF_UI_MODE)!!
}
override fun onResume() {
super.onResume()
shortcutPreference.onPreferenceChangeListener = shortcutPreference
uiModePreference.onPreferenceChangeListener = uiModeChangeListener
}
override fun onPause() {
super.onPause()
shortcutPreference.onPreferenceChangeListener = null
uiModePreference.onPreferenceChangeListener = null
}
}
| app/src/main/java/de/christinecoenen/code/zapp/app/settings/ui/SettingsFragment.kt | 2772409422 |
package quickbeer.android.domain.beerlist.store
import javax.inject.Inject
import quickbeer.android.data.store.StoreCore
import quickbeer.android.domain.beer.store.BeerStoreCore
import quickbeer.android.domain.idlist.IdList
import quickbeer.android.inject.IdListPersistedCore
class BeerSearchStore @Inject constructor(
@IdListPersistedCore indexStoreCore: StoreCore<String, IdList>,
private val beerStoreCore: BeerStoreCore
) : BeerListStore(INDEX_PREFIX, indexStoreCore, beerStoreCore) {
fun search(query: String) = beerStoreCore.search(query)
companion object {
const val INDEX_PREFIX = "beerSearch/"
}
}
| app/src/main/java/quickbeer/android/domain/beerlist/store/BeerSearchStore.kt | 3435386594 |
/*
* Copyright (C) 2020 Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Flow.
*
* Akvo Flow 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.
*
* Akvo Flow 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 Akvo Flow. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.flow.presentation.form.languages
import android.os.Parcel
import android.os.Parcelable
import org.akvo.flow.domain.entity.readStringNonNull
data class Language(
val languageCode: String,
val language: String,
var isSelected: Boolean
) : Parcelable {
constructor(parcel: Parcel) : this(
parcel.readStringNonNull(),
parcel.readStringNonNull(),
parcel.readByte() != 0.toByte()
)
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(languageCode)
parcel.writeString(language)
parcel.writeByte(if (isSelected) 1 else 0)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<Language> {
override fun createFromParcel(parcel: Parcel): Language {
return Language(parcel)
}
override fun newArray(size: Int): Array<Language?> {
return arrayOfNulls(size)
}
}
}
| app/src/main/java/org/akvo/flow/presentation/form/languages/Language.kt | 3744559005 |
/*
* Westford Wayland Compositor.
* Copyright (C) 2016 Erik De Rijcke
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.westford.compositor.wlshell
import com.google.auto.factory.AutoFactory
import com.google.auto.factory.Provided
import org.freedesktop.wayland.server.*
import org.freedesktop.wayland.shared.WlShellSurfaceResize
import org.freedesktop.wayland.shared.WlShellSurfaceTransient
import org.freedesktop.wayland.util.Fixed
import org.westford.compositor.core.*
import org.westford.compositor.core.calc.Mat4
import org.westford.compositor.core.events.KeyboardFocusGained
import org.westford.compositor.core.events.PointerGrab
import org.westford.compositor.protocol.WlKeyboard
import org.westford.compositor.protocol.WlPointer
import org.westford.compositor.protocol.WlSurface
@AutoFactory(className = "PrivateShellSurfaceFactory",
allowSubclasses = true) class ShellSurface(@Provided display: Display,
@param:Provided private val compositor: Compositor,
@param:Provided private val scene: Scene,
private val surfaceView: SurfaceView,
private val pingSerial: Int) : Role {
private val timerEventSource: EventSource
private var keyboardFocusListener: ((KeyboardFocusGained) -> Unit)? = null
var isActive = true
private set
var clazz: String? = null
set(value) {
field = value
this.compositor.requestRender()
}
var title: String? = null
set(value) {
field = value
this.compositor.requestRender()
}
init {
this.timerEventSource = display.eventLoop.addTimer {
this.isActive = false
0
}
}
fun pong(wlShellSurfaceResource: WlShellSurfaceResource,
pingSerial: Int) {
if (this.pingSerial == pingSerial) {
this.isActive = true
wlShellSurfaceResource.ping(pingSerial)
this.timerEventSource.updateTimer(5000)
}
}
fun move(wlSurfaceResource: WlSurfaceResource,
wlPointerResource: WlPointerResource,
grabSerial: Int) {
val wlSurface = wlSurfaceResource.implementation as WlSurface
val surface = wlSurface.surface
val wlPointer = wlPointerResource.implementation as WlPointer
val pointerDevice = wlPointer.pointerDevice
val pointerPosition = pointerDevice.position
pointerDevice.grab?.takeIf {
surface.views.contains(it)
}?.let {
val surfacePosition = it.global(Point(0,
0))
val pointerOffset = pointerPosition - surfacePosition
//FIXME pick a surface view based on the pointer position
pointerDevice.grabMotion(wlSurfaceResource,
grabSerial) { motion ->
it.updatePosition(motion.point - pointerOffset)
}
}
}
fun resize(wlShellSurfaceResource: WlShellSurfaceResource,
wlSurfaceResource: WlSurfaceResource,
wlPointerResource: WlPointerResource,
buttonPressSerial: Int,
edges: Int) {
val wlSurface = wlSurfaceResource.implementation as WlSurface
val surface = wlSurface.surface
val wlPointer = wlPointerResource.implementation as WlPointer
val pointerDevice = wlPointer.pointerDevice
val pointerStartPos = pointerDevice.position
pointerDevice.grab?.takeIf {
surface.views.contains(it)
}?.let {
val local = it.local(pointerStartPos)
val size = surface.size
val quadrant = quadrant(edges)
val transform = transform(quadrant,
size,
local)
val inverseTransform = it.inverseTransform
val grabMotionSuccess = pointerDevice.grabMotion(wlSurfaceResource,
buttonPressSerial) {
val motionLocal = inverseTransform * it.point.toVec4()
val resize = transform * motionLocal
val width = resize.x.toInt()
val height = resize.y.toInt()
wlShellSurfaceResource.configure(quadrant.value,
if (width < 1) 1 else width,
if (height < 1) 1 else height)
}
if (grabMotionSuccess) {
wlPointerResource.leave(pointerDevice.nextLeaveSerial(),
wlSurfaceResource)
pointerDevice.pointerGrabSignal.connect(object : (PointerGrab) -> Unit {
override fun invoke(event: PointerGrab) {
if (pointerDevice.grab == null) {
pointerDevice.pointerGrabSignal.disconnect(this)
wlPointerResource.enter(pointerDevice.nextEnterSerial(),
wlSurfaceResource,
Fixed.create(local.x),
Fixed.create(local.y))
}
}
})
}
}
}
private fun quadrant(edges: Int): WlShellSurfaceResize {
when (edges) {
0 -> return WlShellSurfaceResize.NONE
1 -> return WlShellSurfaceResize.TOP
2 -> return WlShellSurfaceResize.BOTTOM
4 -> return WlShellSurfaceResize.LEFT
5 -> return WlShellSurfaceResize.TOP_LEFT
6 -> return WlShellSurfaceResize.BOTTOM_LEFT
8 -> return WlShellSurfaceResize.RIGHT
9 -> return WlShellSurfaceResize.TOP_RIGHT
10 -> return WlShellSurfaceResize.BOTTOM_RIGHT
else -> return WlShellSurfaceResize.NONE
}
}
private fun transform(quadrant: WlShellSurfaceResize,
size: Rectangle,
pointerLocal: Point): Mat4 {
val width = size.width
val height = size.height
val transformation: Mat4
val pointerdx: Float
val pointerdy: Float
when (quadrant) {
WlShellSurfaceResize.TOP -> {
transformation = Transforms._180.copy(m00 = 0f,
m30 = width.toFloat())
val pointerLocalTransformed = transformation * pointerLocal.toVec4()
pointerdx = 0f
pointerdy = height - pointerLocalTransformed.y
}
WlShellSurfaceResize.TOP_LEFT -> {
transformation = Transforms._180.copy(m30 = width.toFloat(),
m31 = height.toFloat())
val localTransformed = transformation * pointerLocal.toVec4()
pointerdx = width - localTransformed.x
pointerdy = height - localTransformed.y
}
WlShellSurfaceResize.LEFT -> {
transformation = Transforms.FLIPPED.copy(m11 = 0f,
m31 = height.toFloat())
val localTransformed = transformation * pointerLocal.toVec4()
pointerdx = width - localTransformed.x
pointerdy = 0f
}
WlShellSurfaceResize.BOTTOM_LEFT -> {
transformation = Transforms.FLIPPED.copy(m30 = width.toFloat())
val localTransformed = transformation * pointerLocal.toVec4()
pointerdx = width - localTransformed.x
pointerdy = height - localTransformed.y
}
WlShellSurfaceResize.RIGHT -> {
transformation = Transforms.NORMAL.copy(m11 = 0f,
m31 = height.toFloat())
val localTransformed = transformation * pointerLocal.toVec4()
pointerdx = width - localTransformed.x
pointerdy = 0f
}
WlShellSurfaceResize.TOP_RIGHT -> {
transformation = Transforms.FLIPPED_180.copy(m31 = height.toFloat())
val localTransformed = transformation * pointerLocal.toVec4()
pointerdx = width - localTransformed.x
pointerdy = height - localTransformed.y
}
WlShellSurfaceResize.BOTTOM -> {
transformation = Transforms.NORMAL.copy(m00 = 0f,
m30 = width.toFloat())
val pointerLocalTransformed = transformation * pointerLocal.toVec4()
pointerdx = 0f
pointerdy = height - pointerLocalTransformed.y
}
WlShellSurfaceResize.BOTTOM_RIGHT -> {
transformation = Transforms.NORMAL
val localTransformed = pointerLocal.toVec4()
pointerdx = width - localTransformed.x
pointerdy = height - localTransformed.y
}
else -> {
transformation = Transforms.NORMAL
pointerdx = 0f
pointerdy = 0f
}
}
return transformation.copy(m30 = (transformation.m30 + pointerdx),
m31 = (transformation.m31 + pointerdy))
}
fun setTransient(wlSurfaceResource: WlSurfaceResource,
parent: WlSurfaceResource,
x: Int,
y: Int,
flags: Int) {
val wlSurface = wlSurfaceResource.implementation as WlSurface
val surface = wlSurface.surface
this.keyboardFocusListener?.let {
surface.keyboardFocusGainedSignal.disconnect(it)
}
if ((flags and WlShellSurfaceTransient.INACTIVE.value) != 0) {
val slot: (KeyboardFocusGained) -> Unit = {
//clean collection of focuses, so they don't get notify of keyboard related events
surface.keyboardFocuses.clear()
}
surface.keyboardFocusGainedSignal.connect(slot)
//first time focus clearing, also send out leave events
val keyboardFocuses = surface.keyboardFocuses
keyboardFocuses.forEach {
val wlKeyboard = it.implementation as WlKeyboard
val keyboardDevice = wlKeyboard.keyboardDevice
it.leave(keyboardDevice.nextKeyboardSerial(),
wlSurfaceResource)
}
keyboardFocuses.clear()
this.keyboardFocusListener = slot
}
val parentWlSurface = parent.implementation as WlSurface
val parentSurface = parentWlSurface.surface
this.scene.removeView(this.surfaceView)
parentSurface.views.forEach {
this.surfaceView.parent = it
}
parentSurface.addSibling(Sibling(Point(x,
y),
wlSurfaceResource))
}
override fun accept(roleVisitor: RoleVisitor) = roleVisitor.visit(this)
fun setTopLevel(wlSurfaceResource: WlSurfaceResource) {
val wlSurface = wlSurfaceResource.implementation as WlSurface
val surface = wlSurface.surface
surface.views.forEach {
it.parent?.let {
val parentWlSurfaceResource = it.wlSurfaceResource
val parentWlSurface = parentWlSurfaceResource.implementation as WlSurface
val parentSurface = parentWlSurface.surface
parentSurface.removeSibling(Sibling(wlSurfaceResource))
}
}
this.scene.removeView(this.surfaceView)
this.scene.applicationLayer.surfaceViews.add(this.surfaceView)
}
}
| compositor/src/main/kotlin/org/westford/compositor/wlshell/ShellSurface.kt | 2812712902 |
/*
* Copyright (c) 2017. Toshi Inc
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.toshi.model.local
import com.toshi.model.sofa.SofaMessage
data class IncomingMessage(
val sofaMessage: SofaMessage,
val recipient: Recipient,
val conversation: Conversation
) | app/src/main/java/com/toshi/model/local/IncomingMessage.kt | 1316846488 |
package com.byagowi.persiancalendar.ui.calendar.dialogs
import android.app.Dialog
import android.os.Bundle
import android.text.Editable
import android.text.InputFilter
import android.text.Spanned
import android.text.TextWatcher
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.AdapterView
import android.widget.ArrayAdapter
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatDialogFragment
import androidx.core.content.edit
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.byagowi.persiancalendar.PREF_SHIFT_WORK_RECURS
import com.byagowi.persiancalendar.PREF_SHIFT_WORK_SETTING
import com.byagowi.persiancalendar.PREF_SHIFT_WORK_STARTING_JDN
import com.byagowi.persiancalendar.R
import com.byagowi.persiancalendar.databinding.ShiftWorkItemBinding
import com.byagowi.persiancalendar.databinding.ShiftWorkSettingsBinding
import com.byagowi.persiancalendar.entities.ShiftWorkRecord
import com.byagowi.persiancalendar.ui.MainActivity
import com.byagowi.persiancalendar.utils.*
class ShiftWorkDialog : AppCompatDialogFragment() {
private var jdn: Long = -1L
private var selectedJdn: Long = -1L
var onSuccess = fun() {}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val mainActivity = activity as MainActivity
applyAppLanguage(mainActivity)
updateStoredPreference(mainActivity)
selectedJdn = arguments?.getLong(BUNDLE_KEY, -1L) ?: -1L
if (selectedJdn == -1L) selectedJdn = getTodayJdn()
jdn = shiftWorkStartingJdn
var isFirstSetup = false
if (jdn == -1L) {
isFirstSetup = true
jdn = selectedJdn
}
val binding = ShiftWorkSettingsBinding.inflate(mainActivity.layoutInflater, null, false)
binding.recyclerView.layoutManager = LinearLayoutManager(mainActivity)
val shiftWorkItemAdapter = ItemsAdapter(
if (shiftWorks.isEmpty()) listOf(ShiftWorkRecord("d", 0)) else shiftWorks,
binding
)
binding.recyclerView.adapter = shiftWorkItemAdapter
binding.description.text = getString(
if (isFirstSetup) R.string.shift_work_starting_date
else R.string.shift_work_starting_date_edit
).format(formatDate(getDateFromJdnOfCalendar(mainCalendar, jdn)))
binding.resetLink.setOnClickListener {
jdn = selectedJdn
binding.description.text = getString(R.string.shift_work_starting_date)
.format(formatDate(getDateFromJdnOfCalendar(mainCalendar, jdn)))
shiftWorkItemAdapter.reset()
}
binding.recurs.isChecked = shiftWorkRecurs
return AlertDialog.Builder(mainActivity)
.setView(binding.root)
.setTitle(null)
.setPositiveButton(R.string.accept) { _, _ ->
val result = shiftWorkItemAdapter.rows.filter { it.length != 0 }.joinToString(",") {
"${it.type.replace("=", "").replace(",", "")}=${it.length}"
}
mainActivity.appPrefs.edit {
putLong(PREF_SHIFT_WORK_STARTING_JDN, if (result.isEmpty()) -1 else jdn)
putString(PREF_SHIFT_WORK_SETTING, result.toString())
putBoolean(PREF_SHIFT_WORK_RECURS, binding.recurs.isChecked)
}
onSuccess()
}
.setCancelable(true)
.setNegativeButton(R.string.cancel, null)
.create()
}
override fun onResume() {
super.onResume()
// https://stackoverflow.com/a/46248107
dialog?.window?.run {
clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
}
}
private inner class ItemsAdapter internal constructor(
var rows: List<ShiftWorkRecord> = emptyList(),
private val binding: ShiftWorkSettingsBinding
) : RecyclerView.Adapter<ItemsAdapter.ViewHolder>() {
init {
updateShiftWorkResult()
}
fun shiftWorkKeyToString(type: String): String = shiftWorkTitles[type] ?: type
private fun updateShiftWorkResult() =
rows.filter { it.length != 0 }.joinToString(spacedComma) {
getString(R.string.shift_work_record_title)
.format(formatNumber(it.length), shiftWorkKeyToString(it.type))
}.also {
binding.result.text = it
binding.result.visibility = if (it.isEmpty()) View.GONE else View.VISIBLE
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder(
ShiftWorkItemBinding.inflate(parent.context.layoutInflater, parent, false)
)
override fun onBindViewHolder(holder: ViewHolder, position: Int) = holder.bind(position)
override fun getItemCount(): Int = rows.size + 1
internal fun reset() {
rows = listOf(ShiftWorkRecord("d", 0))
notifyDataSetChanged()
updateShiftWorkResult()
}
internal inner class ViewHolder(private val binding: ShiftWorkItemBinding) :
RecyclerView.ViewHolder(binding.root) {
init {
val context = binding.root.context
binding.lengthSpinner.adapter = ArrayAdapter(
context,
android.R.layout.simple_spinner_dropdown_item,
(0..7).map {
if (it == 0) getString(R.string.shift_work_days_head) else formatNumber(it)
}
)
binding.typeAutoCompleteTextView.run {
val adapter = ArrayAdapter(
context,
android.R.layout.simple_spinner_dropdown_item,
resources.getStringArray(R.array.shift_work)
)
setAdapter(adapter)
setOnClickListener {
if (text.toString().isNotEmpty()) adapter.filter.filter(null)
showDropDown()
}
onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>, view: View, position: Int, id: Long
) {
rows = rows.mapIndexed { i, x ->
if (i == adapterPosition) ShiftWorkRecord(
text.toString(), rows[adapterPosition].length
)
else x
}
updateShiftWorkResult()
}
override fun onNothingSelected(parent: AdapterView<*>) {}
}
addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {}
override fun beforeTextChanged(
s: CharSequence?, start: Int, count: Int, after: Int
) = Unit
override fun onTextChanged(
s: CharSequence?, start: Int, before: Int, count: Int
) {
rows = rows.mapIndexed { i, x ->
if (i == adapterPosition) ShiftWorkRecord(
text.toString(),
rows[adapterPosition].length
)
else x
}
updateShiftWorkResult()
}
})
filters = arrayOf(object : InputFilter {
override fun filter(
source: CharSequence?, start: Int, end: Int,
dest: Spanned?, dstart: Int, dend: Int
) = if ("[=,]".toRegex() in (source ?: "")) "" else null
})
}
binding.remove.setOnClickListener { remove() }
binding.lengthSpinner.onItemSelectedListener =
object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>) {}
override fun onItemSelected(
parent: AdapterView<*>, view: View, position: Int, id: Long
) {
rows = rows.mapIndexed { i, x ->
if (i == adapterPosition) ShiftWorkRecord(x.type, position)
else x
}
updateShiftWorkResult()
}
}
binding.addButton.setOnClickListener {
rows = rows + ShiftWorkRecord("r", 0)
notifyDataSetChanged()
updateShiftWorkResult()
}
}
fun remove() {
rows = rows.filterIndexed { i, _ -> i != adapterPosition }
notifyDataSetChanged()
updateShiftWorkResult()
}
fun bind(position: Int) = if (position < rows.size) {
val shiftWorkRecord = rows[position]
binding.rowNumber.text = "%s:".format(formatNumber(position + 1))
binding.lengthSpinner.setSelection(shiftWorkRecord.length)
binding.typeAutoCompleteTextView.setText(shiftWorkKeyToString(shiftWorkRecord.type))
binding.detail.visibility = View.VISIBLE
binding.addButton.visibility = View.GONE
} else {
binding.detail.visibility = View.GONE
binding.addButton.visibility = if (rows.size < 20) View.VISIBLE else View.GONE
}
}
}
companion object {
private const val BUNDLE_KEY = "jdn"
fun newInstance(jdn: Long) = ShiftWorkDialog().apply {
arguments = Bundle().apply {
putLong(BUNDLE_KEY, jdn)
}
}
}
}
| PersianCalendar/src/main/java/com/byagowi/persiancalendar/ui/calendar/dialogs/ShiftWorkDialog.kt | 970761596 |
package org.wordpress.android.fluxc.store
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.google.gson.JsonPrimitive
import kotlinx.coroutines.flow.Flow
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.fluxc.Payload
import org.wordpress.android.fluxc.action.WCProductAction
import org.wordpress.android.fluxc.annotations.action.Action
import org.wordpress.android.fluxc.domain.Addon
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.WCProductCategoryModel
import org.wordpress.android.fluxc.model.WCProductImageModel
import org.wordpress.android.fluxc.model.WCProductModel
import org.wordpress.android.fluxc.model.WCProductReviewModel
import org.wordpress.android.fluxc.model.WCProductShippingClassModel
import org.wordpress.android.fluxc.model.WCProductTagModel
import org.wordpress.android.fluxc.model.WCProductVariationModel
import org.wordpress.android.fluxc.model.WCProductVariationModel.ProductVariantOption
import org.wordpress.android.fluxc.model.addons.RemoteAddonDto
import org.wordpress.android.fluxc.network.BaseRequest.BaseNetworkError
import org.wordpress.android.fluxc.network.BaseRequest.GenericErrorType
import org.wordpress.android.fluxc.network.BaseRequest.GenericErrorType.UNKNOWN
import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooError
import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooErrorType
import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooErrorType.INVALID_RESPONSE
import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooPayload
import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooResult
import org.wordpress.android.fluxc.network.rest.wpcom.wc.addons.mappers.MappingRemoteException
import org.wordpress.android.fluxc.network.rest.wpcom.wc.addons.mappers.RemoteAddonMapper
import org.wordpress.android.fluxc.network.rest.wpcom.wc.product.BatchProductVariationsUpdateApiResponse
import org.wordpress.android.fluxc.network.rest.wpcom.wc.product.CoreProductStockStatus
import org.wordpress.android.fluxc.network.rest.wpcom.wc.product.ProductRestClient
import org.wordpress.android.fluxc.persistence.ProductSqlUtils
import org.wordpress.android.fluxc.persistence.dao.AddonsDao
import org.wordpress.android.fluxc.store.WCProductStore.ProductCategorySorting.NAME_ASC
import org.wordpress.android.fluxc.store.WCProductStore.ProductErrorType.GENERIC_ERROR
import org.wordpress.android.fluxc.store.WCProductStore.ProductSorting.TITLE_ASC
import org.wordpress.android.fluxc.tools.CoroutineEngine
import org.wordpress.android.fluxc.utils.AppLogWrapper
import org.wordpress.android.util.AppLog
import org.wordpress.android.util.AppLog.T
import org.wordpress.android.util.AppLog.T.API
import java.util.Locale
import javax.inject.Inject
import javax.inject.Singleton
@Suppress("LargeClass")
@Singleton
class WCProductStore @Inject constructor(
dispatcher: Dispatcher,
private val wcProductRestClient: ProductRestClient,
private val coroutineEngine: CoroutineEngine,
private val addonsDao: AddonsDao,
private val logger: AppLogWrapper
) : Store(dispatcher) {
companion object {
const val NUM_REVIEWS_PER_FETCH = 25
const val DEFAULT_PRODUCT_PAGE_SIZE = 25
const val DEFAULT_PRODUCT_CATEGORY_PAGE_SIZE = 100
const val DEFAULT_PRODUCT_VARIATIONS_PAGE_SIZE = 25
const val DEFAULT_PRODUCT_SHIPPING_CLASS_PAGE_SIZE = 25
const val DEFAULT_PRODUCT_TAGS_PAGE_SIZE = 100
val DEFAULT_PRODUCT_SORTING = TITLE_ASC
val DEFAULT_CATEGORY_SORTING = NAME_ASC
}
/**
* Defines the filter options currently supported in the app
*/
enum class ProductFilterOption {
STOCK_STATUS, STATUS, TYPE, CATEGORY;
override fun toString() = name.toLowerCase(Locale.US)
}
class FetchProductSkuAvailabilityPayload(
var site: SiteModel,
var sku: String
) : Payload<BaseNetworkError>()
class FetchSingleProductPayload(
var site: SiteModel,
var remoteProductId: Long
) : Payload<BaseNetworkError>()
class FetchProductsPayload(
var site: SiteModel,
var pageSize: Int = DEFAULT_PRODUCT_PAGE_SIZE,
var offset: Int = 0,
var sorting: ProductSorting = DEFAULT_PRODUCT_SORTING,
var remoteProductIds: List<Long>? = null,
var filterOptions: Map<ProductFilterOption, String>? = null,
var excludedProductIds: List<Long>? = null
) : Payload<BaseNetworkError>()
class SearchProductsPayload(
var site: SiteModel,
var searchQuery: String,
var isSkuSearch: Boolean = false,
var pageSize: Int = DEFAULT_PRODUCT_PAGE_SIZE,
var offset: Int = 0,
var sorting: ProductSorting = DEFAULT_PRODUCT_SORTING,
var excludedProductIds: List<Long>? = null
) : Payload<BaseNetworkError>()
class FetchProductVariationsPayload(
var site: SiteModel,
var remoteProductId: Long,
var pageSize: Int = DEFAULT_PRODUCT_VARIATIONS_PAGE_SIZE,
var offset: Int = 0
) : Payload<BaseNetworkError>()
class FetchProductShippingClassListPayload(
var site: SiteModel,
var pageSize: Int = DEFAULT_PRODUCT_SHIPPING_CLASS_PAGE_SIZE,
var offset: Int = 0
) : Payload<BaseNetworkError>()
class FetchSingleProductShippingClassPayload(
var site: SiteModel,
var remoteShippingClassId: Long
) : Payload<BaseNetworkError>()
class FetchProductReviewsPayload(
var site: SiteModel,
var offset: Int = 0,
var reviewIds: List<Long>? = null,
var productIds: List<Long>? = null,
var filterByStatus: List<String>? = null
) : Payload<BaseNetworkError>()
class FetchSingleProductReviewPayload(
var site: SiteModel,
var remoteReviewId: Long
) : Payload<BaseNetworkError>()
class FetchProductPasswordPayload(
var site: SiteModel,
var remoteProductId: Long
) : Payload<BaseNetworkError>()
class UpdateProductPasswordPayload(
var site: SiteModel,
var remoteProductId: Long,
var password: String
) : Payload<BaseNetworkError>()
class UpdateProductReviewStatusPayload(
var site: SiteModel,
var remoteReviewId: Long,
var newStatus: String
) : Payload<BaseNetworkError>()
class UpdateProductImagesPayload(
var site: SiteModel,
var remoteProductId: Long,
var imageList: List<WCProductImageModel>
) : Payload<BaseNetworkError>()
class UpdateProductPayload(
var site: SiteModel,
val product: WCProductModel
) : Payload<BaseNetworkError>()
class UpdateVariationPayload(
var site: SiteModel,
val variation: WCProductVariationModel
) : Payload<BaseNetworkError>()
/**
* Payload used by [batchUpdateVariations] function.
*
* @param remoteProductId Id of the product.
* @param remoteVariationsIds Ids of variations that are going to be updated.
* @param modifiedProperties Map of the properties of variation that are going to be updated.
* Keys correspond to the names of variation properties. Values are the updated properties values.
*/
class BatchUpdateVariationsPayload(
val site: SiteModel,
val remoteProductId: Long,
val remoteVariationsIds: Collection<Long>,
val modifiedProperties: Map<String, Any>
) : Payload<BaseNetworkError>() {
/**
* Builder class used for instantiating [BatchUpdateVariationsPayload].
*/
class Builder(
private val site: SiteModel,
private val remoteProductId: Long,
private val variationsIds: Collection<Long>
) {
private val variationsModifications = mutableMapOf<String, Any>()
fun regularPrice(regularPrice: String) = apply {
variationsModifications["regular_price"] = regularPrice
}
fun salePrice(salePrice: String) = apply {
variationsModifications["sale_price"] = salePrice
}
fun startOfSale(startOfSale: String) = apply {
variationsModifications["date_on_sale_from"] = startOfSale
}
fun endOfSale(endOfSale: String) = apply {
variationsModifications["date_on_sale_to"] = endOfSale
}
fun stockQuantity(stockQuantity: Int) = apply {
variationsModifications["stock_quantity"] = stockQuantity
}
fun stockStatus(stockStatus: CoreProductStockStatus) = apply {
variationsModifications["stock_status"] = stockStatus
}
fun weight(weight: String) = apply {
variationsModifications["weight"] = weight
}
fun dimensions(length: String, width: String, height: String) = apply {
val dimensions = JsonObject().apply {
add("length", JsonPrimitive(length))
add("width", JsonPrimitive(width))
add("height", JsonPrimitive(height))
}
variationsModifications["dimensions"] = dimensions
}
fun shippingClassId(shippingClassId: String) = apply {
variationsModifications["shipping_class_id"] = shippingClassId
}
fun shippingClassSlug(shippingClassSlug: String) = apply {
variationsModifications["shipping_class"] = shippingClassSlug
}
fun build() = BatchUpdateVariationsPayload(
site,
remoteProductId,
variationsIds,
variationsModifications
)
}
}
class FetchProductCategoriesPayload(
var site: SiteModel,
var pageSize: Int = DEFAULT_PRODUCT_CATEGORY_PAGE_SIZE,
var offset: Int = 0,
var productCategorySorting: ProductCategorySorting = DEFAULT_CATEGORY_SORTING
) : Payload<BaseNetworkError>()
class AddProductCategoryPayload(
val site: SiteModel,
val category: WCProductCategoryModel
) : Payload<BaseNetworkError>()
class FetchProductTagsPayload(
var site: SiteModel,
var pageSize: Int = DEFAULT_PRODUCT_TAGS_PAGE_SIZE,
var offset: Int = 0,
var searchQuery: String? = null
) : Payload<BaseNetworkError>()
class AddProductTagsPayload(
val site: SiteModel,
val tags: List<String>
) : Payload<BaseNetworkError>()
class AddProductPayload(
var site: SiteModel,
val product: WCProductModel
) : Payload<BaseNetworkError>()
class DeleteProductPayload(
var site: SiteModel,
val remoteProductId: Long,
val forceDelete: Boolean = false
) : Payload<BaseNetworkError>()
enum class ProductErrorType {
INVALID_PRODUCT_ID,
INVALID_PARAM,
INVALID_REVIEW_ID,
INVALID_IMAGE_ID,
DUPLICATE_SKU,
// indicates duplicate term name. Currently only used when adding product categories
TERM_EXISTS,
// Happens if a store is running Woo 4.6 and below and tries to delete the product image
// from a variation. See this PR for more detail:
// https://github.com/woocommerce/woocommerce/pull/27299
INVALID_VARIATION_IMAGE_ID,
GENERIC_ERROR;
companion object {
private val reverseMap = values().associateBy(ProductErrorType::name)
fun fromString(type: String) = reverseMap[type.toUpperCase(Locale.US)] ?: GENERIC_ERROR
}
}
class ProductError(val type: ProductErrorType = GENERIC_ERROR, val message: String = "") : OnChangedError
enum class ProductSorting {
TITLE_ASC,
TITLE_DESC,
DATE_ASC,
DATE_DESC
}
enum class ProductCategorySorting {
NAME_ASC,
NAME_DESC
}
class RemoteProductSkuAvailabilityPayload(
val site: SiteModel,
var sku: String,
val available: Boolean
) : Payload<ProductError>() {
constructor(
error: ProductError,
site: SiteModel,
sku: String,
available: Boolean
) : this(site, sku, available) {
this.error = error
}
}
class RemoteProductPayload(
val product: WCProductModel,
val site: SiteModel
) : Payload<ProductError>() {
constructor(
error: ProductError,
product: WCProductModel,
site: SiteModel
) : this(product, site) {
this.error = error
}
}
class RemoteVariationPayload(
val variation: WCProductVariationModel,
val site: SiteModel
) : Payload<ProductError>() {
constructor(
error: ProductError,
variation: WCProductVariationModel,
site: SiteModel
) : this(variation, site) {
this.error = error
}
}
class RemoteProductPasswordPayload(
val remoteProductId: Long,
val site: SiteModel,
val password: String
) : Payload<ProductError>() {
constructor(
error: ProductError,
remoteProductId: Long,
site: SiteModel,
password: String
) : this(remoteProductId, site, password) {
this.error = error
}
}
class RemoteUpdatedProductPasswordPayload(
val remoteProductId: Long,
val site: SiteModel,
val password: String
) : Payload<ProductError>() {
constructor(
error: ProductError,
remoteProductId: Long,
site: SiteModel,
password: String
) : this(remoteProductId, site, password) {
this.error = error
}
}
class RemoteProductListPayload(
val site: SiteModel,
val products: List<WCProductModel> = emptyList(),
var offset: Int = 0,
var loadedMore: Boolean = false,
var canLoadMore: Boolean = false,
val remoteProductIds: List<Long>? = null,
val excludedProductIds: List<Long>? = null
) : Payload<ProductError>() {
constructor(
error: ProductError,
site: SiteModel
) : this(site) {
this.error = error
}
}
class RemoteSearchProductsPayload(
var site: SiteModel,
var searchQuery: String?,
var isSkuSearch: Boolean = false,
var products: List<WCProductModel> = emptyList(),
var offset: Int = 0,
var loadedMore: Boolean = false,
var canLoadMore: Boolean = false
) : Payload<ProductError>() {
constructor(error: ProductError, site: SiteModel, query: String?, skuSearch: Boolean) : this(
site = site,
searchQuery = query,
isSkuSearch = skuSearch
) {
this.error = error
}
}
class RemoteUpdateProductImagesPayload(
var site: SiteModel,
val product: WCProductModel
) : Payload<ProductError>() {
constructor(
error: ProductError,
site: SiteModel,
product: WCProductModel
) : this(site, product) {
this.error = error
}
}
class RemoteUpdateProductPayload(
var site: SiteModel,
val product: WCProductModel
) : Payload<ProductError>() {
constructor(
error: ProductError,
site: SiteModel,
product: WCProductModel
) : this(site, product) {
this.error = error
}
}
class RemoteUpdateVariationPayload(
var site: SiteModel,
val variation: WCProductVariationModel
) : Payload<ProductError>() {
constructor(
error: ProductError,
site: SiteModel,
variation: WCProductVariationModel
) : this(site, variation) {
this.error = error
}
}
class RemoteProductVariationsPayload(
val site: SiteModel,
val remoteProductId: Long,
val variations: List<WCProductVariationModel> = emptyList(),
var offset: Int = 0,
var loadedMore: Boolean = false,
var canLoadMore: Boolean = false
) : Payload<ProductError>() {
constructor(
error: ProductError,
site: SiteModel,
remoteProductId: Long
) : this(site, remoteProductId) {
this.error = error
}
}
class RemoteProductShippingClassListPayload(
val site: SiteModel,
val shippingClassList: List<WCProductShippingClassModel> = emptyList(),
var offset: Int = 0,
var loadedMore: Boolean = false,
var canLoadMore: Boolean = false
) : Payload<ProductError>() {
constructor(
error: ProductError,
site: SiteModel
) : this(site) {
this.error = error
}
}
class RemoteProductShippingClassPayload(
val productShippingClassModel: WCProductShippingClassModel,
val site: SiteModel
) : Payload<ProductError>() {
constructor(
error: ProductError,
productShippingClassModel: WCProductShippingClassModel,
site: SiteModel
) : this(productShippingClassModel, site) {
this.error = error
}
}
class RemoteProductReviewPayload(
val site: SiteModel,
val productReview: WCProductReviewModel? = null
) : Payload<ProductError>() {
constructor(
error: ProductError,
site: SiteModel
) : this(site) {
this.error = error
}
}
class FetchProductReviewsResponsePayload(
val site: SiteModel,
val reviews: List<WCProductReviewModel> = emptyList(),
val filterProductIds: List<Long>? = null,
val filterByStatus: List<String>? = null,
val loadedMore: Boolean = false,
val canLoadMore: Boolean = false
) : Payload<ProductError>() {
constructor(error: ProductError, site: SiteModel) : this(site) {
this.error = error
}
}
class RemoteProductCategoriesPayload(
val site: SiteModel,
val categories: List<WCProductCategoryModel> = emptyList(),
var offset: Int = 0,
var loadedMore: Boolean = false,
var canLoadMore: Boolean = false
) : Payload<ProductError>() {
constructor(
error: ProductError,
site: SiteModel
) : this(site) {
this.error = error
}
}
class RemoteAddProductCategoryResponsePayload(
val site: SiteModel,
val category: WCProductCategoryModel?
) : Payload<ProductError>() {
constructor(
error: ProductError,
site: SiteModel,
category: WCProductCategoryModel?
) : this(site, category) {
this.error = error
}
}
class RemoteProductTagsPayload(
val site: SiteModel,
val tags: List<WCProductTagModel> = emptyList(),
var offset: Int = 0,
var loadedMore: Boolean = false,
var canLoadMore: Boolean = false,
var searchQuery: String? = null
) : Payload<ProductError>() {
constructor(
error: ProductError,
site: SiteModel
) : this(site) {
this.error = error
}
}
class RemoteAddProductTagsResponsePayload(
val site: SiteModel,
val tags: List<WCProductTagModel> = emptyList()
) : Payload<ProductError>() {
constructor(
error: ProductError,
site: SiteModel,
addedTags: List<WCProductTagModel> = emptyList()
) : this(site, addedTags) {
this.error = error
}
}
class RemoteAddProductPayload(
var site: SiteModel,
val product: WCProductModel
) : Payload<ProductError>() {
constructor(
error: ProductError,
site: SiteModel,
product: WCProductModel
) : this(site, product) {
this.error = error
}
}
class RemoteDeleteProductPayload(
var site: SiteModel,
val remoteProductId: Long
) : Payload<ProductError>() {
constructor(
error: ProductError,
site: SiteModel,
remoteProductId: Long
) : this(site, remoteProductId) {
this.error = error
}
}
// OnChanged events
class OnProductChanged(
var rowsAffected: Int,
var remoteProductId: Long = 0L, // only set for fetching or deleting a single product
var canLoadMore: Boolean = false
) : OnChanged<ProductError>() {
var causeOfChange: WCProductAction? = null
}
class OnVariationChanged(
var remoteProductId: Long = 0L,
var remoteVariationId: Long = 0L
) : OnChanged<ProductError>()
class OnProductSkuAvailabilityChanged(
var sku: String,
var available: Boolean
) : OnChanged<ProductError>() {
var causeOfChange: WCProductAction? = null
}
class OnProductsSearched(
var searchQuery: String?,
var isSkuSearch: Boolean = false,
var searchResults: List<WCProductModel> = emptyList(),
var canLoadMore: Boolean = false
) : OnChanged<ProductError>()
class OnProductReviewChanged(
var rowsAffected: Int,
var canLoadMore: Boolean = false
) : OnChanged<ProductError>() {
var causeOfChange: WCProductAction? = null
}
class OnProductShippingClassesChanged(
var rowsAffected: Int,
var canLoadMore: Boolean = false
) : OnChanged<ProductError>() {
var causeOfChange: WCProductAction? = null
}
class OnProductImagesChanged(
var rowsAffected: Int,
var remoteProductId: Long
) : OnChanged<ProductError>() {
var causeOfChange: WCProductAction? = null
}
class OnProductPasswordChanged(
var remoteProductId: Long,
var password: String?
) : OnChanged<ProductError>() {
var causeOfChange: WCProductAction? = null
}
class OnProductUpdated(
var rowsAffected: Int,
var remoteProductId: Long
) : OnChanged<ProductError>() {
var causeOfChange: WCProductAction? = null
}
class OnVariationUpdated(
var rowsAffected: Int,
var remoteProductId: Long,
var remoteVariationId: Long
) : OnChanged<ProductError>() {
var causeOfChange: WCProductAction? = null
}
class OnProductCategoryChanged(
var rowsAffected: Int,
var canLoadMore: Boolean = false
) : OnChanged<ProductError>() {
var causeOfChange: WCProductAction? = null
}
class OnProductTagChanged(
var rowsAffected: Int,
var canLoadMore: Boolean = false
) : OnChanged<ProductError>() {
var causeOfChange: WCProductAction? = null
}
class OnProductCreated(
var rowsAffected: Int,
var remoteProductId: Long = 0L
) : OnChanged<ProductError>() {
var causeOfChange: WCProductAction? = null
}
/**
* returns the corresponding product from the database as a [WCProductModel].
*/
fun getProductByRemoteId(site: SiteModel, remoteProductId: Long): WCProductModel? =
ProductSqlUtils.getProductByRemoteId(site, remoteProductId)
/**
* returns the corresponding variation from the database as a [WCProductVariationModel].
*/
fun getVariationByRemoteId(
site: SiteModel,
remoteProductId: Long,
remoteVariationId: Long
): WCProductVariationModel? =
ProductSqlUtils.getVariationByRemoteId(site, remoteProductId, remoteVariationId)
/**
* returns true if the corresponding product exists in the database
*/
fun geProductExistsByRemoteId(site: SiteModel, remoteProductId: Long) =
ProductSqlUtils.geProductExistsByRemoteId(site, remoteProductId)
/**
* returns true if the product exists with this [sku] in the database
*/
fun geProductExistsBySku(site: SiteModel, sku: String) =
ProductSqlUtils.getProductExistsBySku(site, sku)
/**
* returns a list of variations for a specific product in the database
*/
fun getVariationsForProduct(site: SiteModel, remoteProductId: Long): List<WCProductVariationModel> =
ProductSqlUtils.getVariationsForProduct(site, remoteProductId)
/**
* returns a list of shipping classes for a specific site in the database
*/
fun getShippingClassListForSite(site: SiteModel): List<WCProductShippingClassModel> =
ProductSqlUtils.getProductShippingClassListForSite(site.id)
/**
* returns the corresponding product shipping class from the database as a [WCProductShippingClassModel].
*/
fun getShippingClassByRemoteId(site: SiteModel, remoteShippingClassId: Long): WCProductShippingClassModel? =
ProductSqlUtils.getProductShippingClassByRemoteId(remoteShippingClassId, site.id)
/**
* returns a list of [WCProductModel] for the give [SiteModel] and [remoteProductIds]
* if it exists in the database
*/
fun getProductsByRemoteIds(site: SiteModel, remoteProductIds: List<Long>): List<WCProductModel> =
ProductSqlUtils.getProductsByRemoteIds(site, remoteProductIds)
/**
* returns a list of [WCProductModel] for the given [SiteModel] and [filterOptions]
* if it exists in the database. To filter by category, make sure the [filterOptions] value
* is the category ID in String.
*/
fun getProductsByFilterOptions(
site: SiteModel,
filterOptions: Map<ProductFilterOption, String>,
sortType: ProductSorting = DEFAULT_PRODUCT_SORTING,
excludedProductIds: List<Long>? = null
): List<WCProductModel> =
ProductSqlUtils.getProductsByFilterOptions(site, filterOptions, sortType, excludedProductIds)
fun getProductsForSite(site: SiteModel, sortType: ProductSorting = DEFAULT_PRODUCT_SORTING) =
ProductSqlUtils.getProductsForSite(site, sortType)
fun deleteProductsForSite(site: SiteModel) = ProductSqlUtils.deleteProductsForSite(site)
fun getProductReviewsForSite(site: SiteModel): List<WCProductReviewModel> =
ProductSqlUtils.getProductReviewsForSite(site)
fun getProductReviewsForProductAndSiteId(localSiteId: Int, remoteProductId: Long): List<WCProductReviewModel> =
ProductSqlUtils.getProductReviewsForProductAndSiteId(localSiteId, remoteProductId)
/**
* returns the count of products for the given [SiteModel] and [remoteProductIds]
* if it exists in the database
*/
fun getProductCountByRemoteIds(site: SiteModel, remoteProductIds: List<Long>): Int =
ProductSqlUtils.getProductCountByRemoteIds(site, remoteProductIds)
/**
* returns the count of virtual products for the given [SiteModel] and [remoteProductIds]
* if it exists in the database
*/
fun getVirtualProductCountByRemoteIds(site: SiteModel, remoteProductIds: List<Long>): Int =
ProductSqlUtils.getVirtualProductCountByRemoteIds(site, remoteProductIds)
/**
* returns a list of tags for a specific site in the database
*/
fun getTagsForSite(site: SiteModel): List<WCProductTagModel> =
ProductSqlUtils.getProductTagsForSite(site.id)
fun getProductTagsByNames(site: SiteModel, tagNames: List<String>) =
ProductSqlUtils.getProductTagsByNames(site.id, tagNames)
fun getProductTagByName(site: SiteModel, tagName: String) =
ProductSqlUtils.getProductTagByName(site.id, tagName)
fun getProductReviewByRemoteId(
localSiteId: Int,
remoteReviewId: Long
): WCProductReviewModel? = ProductSqlUtils
.getProductReviewByRemoteId(localSiteId, remoteReviewId)
fun deleteProductReviewsForSite(site: SiteModel) = ProductSqlUtils.deleteAllProductReviewsForSite(site)
fun deleteAllProductReviews() = ProductSqlUtils.deleteAllProductReviews()
fun deleteProductImage(site: SiteModel, remoteProductId: Long, remoteMediaId: Long) =
ProductSqlUtils.deleteProductImage(site, remoteProductId, remoteMediaId)
fun getProductCategoriesForSite(site: SiteModel, sortType: ProductCategorySorting = DEFAULT_CATEGORY_SORTING) =
ProductSqlUtils.getProductCategoriesForSite(site, sortType)
fun getProductCategoryByRemoteId(site: SiteModel, remoteId: Long) =
ProductSqlUtils.getProductCategoryByRemoteId(site.id, remoteId)
fun getProductCategoryByNameAndParentId(
site: SiteModel,
categoryName: String,
parentId: Long = 0L
) = ProductSqlUtils.getProductCategoryByNameAndParentId(site.id, categoryName, parentId)
@Suppress("LongMethod", "ComplexMethod")
@Subscribe(threadMode = ThreadMode.ASYNC)
override fun onAction(action: Action<*>) {
val actionType = action.type as? WCProductAction ?: return
when (actionType) {
// remote actions
WCProductAction.FETCH_PRODUCT_SKU_AVAILABILITY ->
fetchProductSkuAvailability(action.payload as FetchProductSkuAvailabilityPayload)
WCProductAction.FETCH_PRODUCTS ->
fetchProducts(action.payload as FetchProductsPayload)
WCProductAction.SEARCH_PRODUCTS ->
searchProducts(action.payload as SearchProductsPayload)
WCProductAction.UPDATE_PRODUCT_IMAGES ->
updateProductImages(action.payload as UpdateProductImagesPayload)
WCProductAction.UPDATE_PRODUCT ->
updateProduct(action.payload as UpdateProductPayload)
WCProductAction.FETCH_SINGLE_PRODUCT_SHIPPING_CLASS ->
fetchProductShippingClass(action.payload as FetchSingleProductShippingClassPayload)
WCProductAction.FETCH_PRODUCT_SHIPPING_CLASS_LIST ->
fetchProductShippingClasses(action.payload as FetchProductShippingClassListPayload)
WCProductAction.FETCH_PRODUCT_PASSWORD ->
fetchProductPassword(action.payload as FetchProductPasswordPayload)
WCProductAction.UPDATE_PRODUCT_PASSWORD ->
updateProductPassword(action.payload as UpdateProductPasswordPayload)
WCProductAction.FETCH_PRODUCT_CATEGORIES ->
fetchProductCategories(action.payload as FetchProductCategoriesPayload)
WCProductAction.ADD_PRODUCT_CATEGORY ->
addProductCategory(action.payload as AddProductCategoryPayload)
WCProductAction.FETCH_PRODUCT_TAGS ->
fetchProductTags(action.payload as FetchProductTagsPayload)
WCProductAction.ADD_PRODUCT_TAGS ->
addProductTags(action.payload as AddProductTagsPayload)
WCProductAction.ADD_PRODUCT ->
addProduct(action.payload as AddProductPayload)
WCProductAction.DELETE_PRODUCT ->
deleteProduct(action.payload as DeleteProductPayload)
// remote responses
WCProductAction.FETCHED_PRODUCT_SKU_AVAILABILITY ->
handleFetchProductSkuAvailabilityCompleted(action.payload as RemoteProductSkuAvailabilityPayload)
WCProductAction.FETCHED_PRODUCTS ->
handleFetchProductsCompleted(action.payload as RemoteProductListPayload)
WCProductAction.SEARCHED_PRODUCTS ->
handleSearchProductsCompleted(action.payload as RemoteSearchProductsPayload)
WCProductAction.UPDATED_PRODUCT_IMAGES ->
handleUpdateProductImages(action.payload as RemoteUpdateProductImagesPayload)
WCProductAction.UPDATED_PRODUCT ->
handleUpdateProduct(action.payload as RemoteUpdateProductPayload)
WCProductAction.FETCHED_PRODUCT_SHIPPING_CLASS_LIST ->
handleFetchProductShippingClassesCompleted(action.payload as RemoteProductShippingClassListPayload)
WCProductAction.FETCHED_SINGLE_PRODUCT_SHIPPING_CLASS ->
handleFetchProductShippingClassCompleted(action.payload as RemoteProductShippingClassPayload)
WCProductAction.FETCHED_PRODUCT_PASSWORD ->
handleFetchProductPasswordCompleted(action.payload as RemoteProductPasswordPayload)
WCProductAction.UPDATED_PRODUCT_PASSWORD ->
handleUpdatedProductPasswordCompleted(action.payload as RemoteUpdatedProductPasswordPayload)
WCProductAction.FETCHED_PRODUCT_CATEGORIES ->
handleFetchProductCategories(action.payload as RemoteProductCategoriesPayload)
WCProductAction.ADDED_PRODUCT_CATEGORY ->
handleAddProductCategory(action.payload as RemoteAddProductCategoryResponsePayload)
WCProductAction.FETCHED_PRODUCT_TAGS ->
handleFetchProductTagsCompleted(action.payload as RemoteProductTagsPayload)
WCProductAction.ADDED_PRODUCT_TAGS ->
handleAddProductTags(action.payload as RemoteAddProductTagsResponsePayload)
WCProductAction.ADDED_PRODUCT ->
handleAddNewProduct(action.payload as RemoteAddProductPayload)
WCProductAction.DELETED_PRODUCT ->
handleDeleteProduct(action.payload as RemoteDeleteProductPayload)
}
}
fun observeProducts(
site: SiteModel,
sortType: ProductSorting = DEFAULT_PRODUCT_SORTING,
filterOptions: Map<ProductFilterOption, String> = emptyMap()
): Flow<List<WCProductModel>> =
ProductSqlUtils.observeProducts(site, sortType, filterOptions)
fun observeVariations(site: SiteModel, productId: Long): Flow<List<WCProductVariationModel>> =
ProductSqlUtils.observeVariations(site, productId)
fun observeCategories(
site: SiteModel,
sortType: ProductCategorySorting = DEFAULT_CATEGORY_SORTING
): Flow<List<WCProductCategoryModel>> =
ProductSqlUtils.observeCategories(site, sortType)
suspend fun submitProductAttributeChanges(
site: SiteModel,
productId: Long,
attributes: List<WCProductModel.ProductAttribute>
): WooResult<WCProductModel> =
coroutineEngine.withDefaultContext(API, this, "submitProductAttributes") {
wcProductRestClient.updateProductAttributes(site, productId, Gson().toJson(attributes))
.asWooResult()
.model?.asProductModel()
?.apply {
localSiteId = site.id
ProductSqlUtils.insertOrUpdateProduct(this)
}
?.let { WooResult(it) }
} ?: WooResult(WooError(WooErrorType.GENERIC_ERROR, UNKNOWN))
suspend fun submitVariationAttributeChanges(
site: SiteModel,
productId: Long,
variationId: Long,
attributes: List<WCProductModel.ProductAttribute>
): WooResult<WCProductVariationModel> =
coroutineEngine.withDefaultContext(API, this, "submitVariationAttributes") {
wcProductRestClient.updateVariationAttributes(site, productId, variationId, Gson().toJson(attributes))
.asWooResult()
.model?.asProductVariationModel()
?.apply {
ProductSqlUtils.insertOrUpdateProductVariation(this)
}
?.let { WooResult(it) }
} ?: WooResult(WooError(WooErrorType.GENERIC_ERROR, UNKNOWN))
suspend fun generateEmptyVariation(
site: SiteModel,
product: WCProductModel
): WooResult<WCProductVariationModel> =
coroutineEngine.withDefaultContext(API, this, "generateEmptyVariation") {
product.attributeList
.filter { it.variation }
.map { ProductVariantOption(it.id, it.name, "") }
.let { Gson().toJson(it) }
.let { wcProductRestClient.generateEmptyVariation(site, product.remoteProductId, it) }
.asWooResult()
.model?.asProductVariationModel()
?.apply {
ProductSqlUtils.insertOrUpdateProductVariation(this)
}
?.let { WooResult(it) }
?: WooResult(WooError(INVALID_RESPONSE, GenericErrorType.INVALID_RESPONSE))
}
suspend fun deleteVariation(
site: SiteModel,
productId: Long,
variationId: Long
): WooResult<WCProductVariationModel> =
coroutineEngine.withDefaultContext(API, this, "deleteVariation") {
wcProductRestClient.deleteVariation(site, productId, variationId)
.asWooResult()
.model?.asProductVariationModel()
?.apply {
ProductSqlUtils.deleteVariationsForProduct(site, productId)
}
?.let { WooResult(it) }
?: WooResult(WooError(INVALID_RESPONSE, GenericErrorType.INVALID_RESPONSE))
}
override fun onRegister() = AppLog.d(API, "WCProductStore onRegister")
@Suppress("ForbiddenComment")
suspend fun fetchSingleProduct(payload: FetchSingleProductPayload): OnProductChanged {
return coroutineEngine.withDefaultContext(API, this, "fetchSingleProduct") {
val result = with(payload) { wcProductRestClient.fetchSingleProduct(site, remoteProductId) }
return@withDefaultContext if (result.isError) {
OnProductChanged(0).also {
it.error = result.error
it.remoteProductId = result.product.remoteProductId
}
} else {
val rowsAffected = ProductSqlUtils.insertOrUpdateProduct(result.product)
// TODO: 18/08/2021 @wzieba add tests
coroutineEngine.launch(T.DB, this, "cacheProductAddons") {
val domainAddons = mapProductAddonsToDomain(result.product.addons)
addonsDao.cacheProductAddons(
productRemoteId = result.product.remoteProductId,
siteRemoteId = result.site.siteId,
addons = domainAddons
)
}
OnProductChanged(rowsAffected).also {
it.remoteProductId = result.product.remoteProductId
}
}
}
}
suspend fun fetchSingleVariation(
site: SiteModel,
remoteProductId: Long,
remoteVariationId: Long
): OnVariationChanged {
return coroutineEngine.withDefaultContext(T.API, this, "fetchSingleVariation") {
val result = wcProductRestClient
.fetchSingleVariation(site, remoteProductId, remoteVariationId)
return@withDefaultContext if (result.isError) {
OnVariationChanged().also {
it.error = result.error
it.remoteProductId = result.variation.remoteProductId
it.remoteVariationId = result.variation.remoteVariationId
}
} else {
ProductSqlUtils.insertOrUpdateProductVariation(result.variation)
OnVariationChanged().also {
it.remoteProductId = result.variation.remoteProductId
it.remoteVariationId = result.variation.remoteVariationId
}
}
}
}
private fun fetchProductSkuAvailability(payload: FetchProductSkuAvailabilityPayload) {
with(payload) { wcProductRestClient.fetchProductSkuAvailability(site, sku) }
}
private fun fetchProducts(payload: FetchProductsPayload) {
with(payload) {
wcProductRestClient.fetchProducts(
site = site,
pageSize = pageSize,
offset = offset,
sortType = sorting,
includedProductIds = remoteProductIds,
filterOptions = filterOptions,
excludedProductIds = excludedProductIds
)
}
}
suspend fun fetchProductListSynced(site: SiteModel, productIds: List<Long>): List<WCProductModel>? {
return coroutineEngine.withDefaultContext(API, this, "fetchProductList") {
wcProductRestClient.fetchProductsWithSyncRequest(site = site, includedProductIds = productIds).result
}?.also {
ProductSqlUtils.insertOrUpdateProducts(it)
}
}
suspend fun fetchProductCategoryListSynced(
site: SiteModel,
categoryIds: List<Long>
): List<WCProductCategoryModel>? {
return coroutineEngine.withDefaultContext(API, this, "fetchProductCategoryList") {
wcProductRestClient.fetchProductsCategoriesWithSyncRequest(
site = site,
includedCategoryIds = categoryIds
).result
}?.also {
ProductSqlUtils.insertOrUpdateProductCategories(it)
}
}
private fun searchProducts(payload: SearchProductsPayload) {
with(payload) {
wcProductRestClient.searchProducts(
site = site,
searchQuery = searchQuery,
isSkuSearch = isSkuSearch,
pageSize = pageSize,
offset = offset,
sorting = sorting,
excludedProductIds = excludedProductIds
)
}
}
suspend fun fetchProductVariations(payload: FetchProductVariationsPayload): OnProductChanged {
return coroutineEngine.withDefaultContext(API, this, "fetchProductVariations") {
val result = with(payload) {
wcProductRestClient.fetchProductVariations(site, remoteProductId, pageSize, offset)
}
return@withDefaultContext if (result.isError) {
OnProductChanged(0, payload.remoteProductId).also { it.error = result.error }
} else {
// delete product variations for site if this is the first page of results, otherwise
// product variations deleted outside of the app will persist
if (result.offset == 0) {
ProductSqlUtils.deleteVariationsForProduct(result.site, result.remoteProductId)
}
val rowsAffected = ProductSqlUtils.insertOrUpdateProductVariations(
result.variations
)
OnProductChanged(rowsAffected, payload.remoteProductId, canLoadMore = result.canLoadMore)
}
}
}
private fun fetchProductShippingClass(payload: FetchSingleProductShippingClassPayload) {
with(payload) { wcProductRestClient.fetchSingleProductShippingClass(site, remoteShippingClassId) }
}
private fun fetchProductShippingClasses(payload: FetchProductShippingClassListPayload) {
with(payload) { wcProductRestClient.fetchProductShippingClassList(site, pageSize, offset) }
}
suspend fun fetchProductReviews(payload: FetchProductReviewsPayload): OnProductReviewChanged {
return coroutineEngine.withDefaultContext(API, this, "fetchProductReviews") {
val response = with(payload) {
wcProductRestClient.fetchProductReviews(site, offset, reviewIds, productIds, filterByStatus)
}
val onProductReviewChanged = if (response.isError) {
OnProductReviewChanged(0).also { it.error = response.error }
} else {
// Clear existing product reviews if this is a fresh fetch (loadMore = false).
// This is the simplest way to keep our local reviews in sync with remote reviews
// in case of deletions.
if (!response.loadedMore) {
ProductSqlUtils.deleteAllProductReviewsForSite(response.site)
}
val rowsAffected = ProductSqlUtils.insertOrUpdateProductReviews(response.reviews)
OnProductReviewChanged(rowsAffected, canLoadMore = response.canLoadMore)
}
onProductReviewChanged
}
}
suspend fun fetchSingleProductReview(payload: FetchSingleProductReviewPayload): OnProductReviewChanged {
return coroutineEngine.withDefaultContext(API, this, "fetchSingleProductReview") {
val result = wcProductRestClient.fetchProductReviewById(payload.site, payload.remoteReviewId)
return@withDefaultContext if (result.isError) {
OnProductReviewChanged(0).also { it.error = result.error }
} else {
val rowsAffected = result.productReview?.let {
ProductSqlUtils.insertOrUpdateProductReview(it)
} ?: 0
OnProductReviewChanged(rowsAffected)
}
}
}
private fun fetchProductPassword(payload: FetchProductPasswordPayload) {
with(payload) { wcProductRestClient.fetchProductPassword(site, remoteProductId) }
}
private fun updateProductPassword(payload: UpdateProductPasswordPayload) {
with(payload) { wcProductRestClient.updateProductPassword(site, remoteProductId, password) }
}
suspend fun updateProductReviewStatus(site: SiteModel, reviewId: Long, newStatus: String) =
coroutineEngine.withDefaultContext(API, this, "updateProductReviewStatus") {
val result = wcProductRestClient.updateProductReviewStatus(site, reviewId, newStatus)
return@withDefaultContext if (result.isError) {
WooResult(result.error)
} else {
result.result?.let { review ->
if (review.status == "spam" || review.status == "trash") {
// Delete this review from the database
ProductSqlUtils.deleteProductReview(review)
} else {
// Insert or update in the database
ProductSqlUtils.insertOrUpdateProductReview(review)
}
}
WooResult(result.result)
}
}
private fun updateProductImages(payload: UpdateProductImagesPayload) {
with(payload) { wcProductRestClient.updateProductImages(site, remoteProductId, imageList) }
}
private fun fetchProductCategories(payloadProduct: FetchProductCategoriesPayload) {
with(payloadProduct) {
wcProductRestClient.fetchProductCategories(
site, pageSize, offset, productCategorySorting
)
}
}
private fun addProductCategory(payload: AddProductCategoryPayload) {
with(payload) { wcProductRestClient.addProductCategory(site, category) }
}
private fun fetchProductTags(payload: FetchProductTagsPayload) {
with(payload) { wcProductRestClient.fetchProductTags(site, pageSize, offset, searchQuery) }
}
private fun addProductTags(payload: AddProductTagsPayload) {
with(payload) { wcProductRestClient.addProductTags(site, tags) }
}
private fun updateProduct(payload: UpdateProductPayload) {
with(payload) {
val storedProduct = getProductByRemoteId(site, product.remoteProductId)
wcProductRestClient.updateProduct(site, storedProduct, product)
}
}
suspend fun updateVariation(payload: UpdateVariationPayload): OnVariationUpdated {
return coroutineEngine.withDefaultContext(API, this, "updateVariation") {
with(payload) {
val storedVariation = getVariationByRemoteId(
site,
variation.remoteProductId,
variation.remoteVariationId
)
val result: RemoteUpdateVariationPayload = wcProductRestClient.updateVariation(
site,
storedVariation,
variation
)
return@withDefaultContext if (result.isError) {
OnVariationUpdated(
0,
result.variation.remoteProductId,
result.variation.remoteVariationId
).also { it.error = result.error }
} else {
val rowsAffected = ProductSqlUtils.insertOrUpdateProductVariation(
result.variation
)
OnVariationUpdated(
rowsAffected,
result.variation.remoteProductId,
result.variation.remoteVariationId
)
}
}
}
}
/**
* Batch updates variations on the backend and updates variations locally after successful request.
*
* @param payload Instance of [BatchUpdateVariationsPayload]. It can be produced using
* [BatchUpdateVariationsPayload.Builder] class.
*/
suspend fun batchUpdateVariations(payload: BatchUpdateVariationsPayload):
WooResult<BatchProductVariationsUpdateApiResponse> =
coroutineEngine.withDefaultContext(API, this, "batchUpdateVariations") {
with(payload) {
val result: WooPayload<BatchProductVariationsUpdateApiResponse> =
wcProductRestClient.batchUpdateVariations(
site,
remoteProductId,
remoteVariationsIds,
modifiedProperties
)
return@withDefaultContext if (result.isError) {
WooResult(result.error)
} else {
val updatedVariations = result.result?.updatedVariations?.map { response ->
response.asProductVariationModel().apply {
remoteProductId = payload.remoteProductId
localSiteId = payload.site.id
}
} ?: emptyList()
ProductSqlUtils.insertOrUpdateProductVariations(updatedVariations)
WooResult(result.result)
}
}
}
suspend fun fetchProductCategories(
site: SiteModel,
offset: Int = 0,
pageSize: Int = DEFAULT_PRODUCT_CATEGORY_PAGE_SIZE,
sortType: ProductCategorySorting = DEFAULT_CATEGORY_SORTING,
includedCategoryIds: List<Long> = emptyList(),
excludedCategoryIds: List<Long> = emptyList()
): WooResult<Boolean> {
return coroutineEngine.withDefaultContext(API, this, "fetchProductCategories") {
val response = wcProductRestClient.fetchProductsCategoriesWithSyncRequest(
site = site,
offset = offset,
pageSize = pageSize,
productCategorySorting = sortType,
includedCategoryIds = includedCategoryIds,
excludedCategoryIds = excludedCategoryIds
)
when {
response.isError -> WooResult(response.error)
response.result != null -> {
if (offset == 0 && includedCategoryIds.isEmpty() && excludedCategoryIds.isEmpty()) {
ProductSqlUtils.deleteAllProductCategories()
}
ProductSqlUtils.insertOrUpdateProductCategories(response.result)
val canLoadMore = response.result.size == pageSize
WooResult(canLoadMore)
}
else -> WooResult(WooError(WooErrorType.GENERIC_ERROR, UNKNOWN))
}
}
}
// Returns a boolean indicating whether more coupons can be fetched
@Suppress("ComplexCondition")
suspend fun fetchProducts(
site: SiteModel,
offset: Int = 0,
pageSize: Int = DEFAULT_PRODUCT_PAGE_SIZE,
sortType: ProductSorting = DEFAULT_PRODUCT_SORTING,
includedProductIds: List<Long> = emptyList(),
excludedProductIds: List<Long> = emptyList(),
filterOptions: Map<ProductFilterOption, String> = emptyMap()
): WooResult<Boolean> {
return coroutineEngine.withDefaultContext(API, this, "fetchProducts") {
val response = wcProductRestClient.fetchProductsWithSyncRequest(
site = site,
offset = offset,
pageSize = pageSize,
sortType = sortType,
includedProductIds = includedProductIds,
excludedProductIds = excludedProductIds,
filterOptions = filterOptions
)
when {
response.isError -> WooResult(response.error)
response.result != null -> {
if (offset == 0 &&
includedProductIds.isEmpty() &&
excludedProductIds.isEmpty() &&
filterOptions.isEmpty()
) {
ProductSqlUtils.deleteProductsForSite(site)
}
ProductSqlUtils.insertOrUpdateProducts(response.result)
val canLoadMore = response.result.size == pageSize
WooResult(canLoadMore)
}
else -> WooResult(WooError(WooErrorType.GENERIC_ERROR, UNKNOWN))
}
}
}
suspend fun searchProducts(
site: SiteModel,
searchString: String,
isSkuSearch: Boolean = false,
offset: Int = 0,
pageSize: Int = DEFAULT_PRODUCT_PAGE_SIZE
): WooResult<ProductSearchResult> {
return coroutineEngine.withDefaultContext(API, this, "searchProducts") {
val response = wcProductRestClient.fetchProductsWithSyncRequest(
site = site,
offset = offset,
pageSize = pageSize,
searchQuery = searchString,
isSkuSearch = isSkuSearch
)
when {
response.isError -> WooResult(response.error)
response.result != null -> {
ProductSqlUtils.insertOrUpdateProducts(response.result)
val productIds = response.result.map { it.remoteProductId }
val products = if (productIds.isNotEmpty()) {
ProductSqlUtils.getProductsByRemoteIds(site, productIds)
} else {
emptyList()
}
val canLoadMore = response.result.size == pageSize
WooResult(ProductSearchResult(products, canLoadMore))
}
else -> WooResult(WooError(WooErrorType.GENERIC_ERROR, UNKNOWN))
}
}
}
suspend fun searchProductCategories(
site: SiteModel,
searchString: String,
offset: Int = 0,
pageSize: Int = DEFAULT_PRODUCT_CATEGORY_PAGE_SIZE
): WooResult<ProductCategorySearchResult> {
return coroutineEngine.withDefaultContext(
API,
this,
"searchProductCategories"
) {
val response = wcProductRestClient.fetchProductsCategoriesWithSyncRequest(
site = site,
offset = offset,
pageSize = pageSize,
searchQuery = searchString
)
when {
response.isError -> WooResult(response.error)
response.result != null -> {
ProductSqlUtils.insertOrUpdateProductCategories(response.result)
val categoryIds = response.result.map { it.remoteCategoryId }
val categories = if (categoryIds.isNotEmpty()) {
ProductSqlUtils.getProductCategoriesByRemoteIds(site, categoryIds)
} else {
emptyList()
}
val canLoadMore = response.result.size == pageSize
WooResult(ProductCategorySearchResult(categories, canLoadMore))
}
else -> WooResult(WooError(WooErrorType.GENERIC_ERROR, UNKNOWN))
}
}
}
// Returns a boolean indicating whether more coupons can be fetched
suspend fun fetchProductVariations(
site: SiteModel,
productId: Long,
offset: Int = 0,
pageSize: Int = DEFAULT_PRODUCT_VARIATIONS_PAGE_SIZE,
includedVariationIds: List<Long> = emptyList(),
excludedVariationIds: List<Long> = emptyList()
): WooResult<Boolean> {
return coroutineEngine.withDefaultContext(API, this, "fetchProductVariations") {
val response = wcProductRestClient.fetchProductVariationsWithSyncRequest(
site = site,
productId = productId,
offset = offset,
pageSize = pageSize,
includedVariationIds = includedVariationIds,
excludedVariationIds = excludedVariationIds
)
when {
response.isError -> WooResult(response.error)
response.result != null -> {
if (offset == 0 &&
includedVariationIds.isEmpty() &&
excludedVariationIds.isEmpty()
) {
ProductSqlUtils.deleteVariationsForProduct(site, productId)
}
ProductSqlUtils.insertOrUpdateProductVariations(response.result)
val canLoadMore = response.result.size == pageSize
WooResult(canLoadMore)
}
else -> WooResult(WooError(WooErrorType.GENERIC_ERROR, UNKNOWN))
}
}
}
private fun addProduct(payload: AddProductPayload) {
with(payload) {
wcProductRestClient.addProduct(site, product)
}
}
private fun deleteProduct(payload: DeleteProductPayload) {
with(payload) {
wcProductRestClient.deleteProduct(site, remoteProductId, forceDelete)
}
}
private fun mapProductAddonsToDomain(remoteAddons: Array<RemoteAddonDto>?): List<Addon> {
return remoteAddons.orEmpty()
.toList()
.mapNotNull { remoteAddonDto ->
try {
RemoteAddonMapper.toDomain(remoteAddonDto)
} catch (exception: MappingRemoteException) {
logger.e(API, "Exception while parsing $remoteAddonDto: ${exception.message}")
null
}
}
}
private fun handleFetchProductSkuAvailabilityCompleted(payload: RemoteProductSkuAvailabilityPayload) {
val onProductSkuAvailabilityChanged = OnProductSkuAvailabilityChanged(payload.sku, payload.available)
if (payload.isError) {
onProductSkuAvailabilityChanged.also { it.error = payload.error }
}
onProductSkuAvailabilityChanged.causeOfChange = WCProductAction.FETCH_PRODUCT_SKU_AVAILABILITY
emitChange(onProductSkuAvailabilityChanged)
}
@Suppress("ForbiddenComment")
private fun handleFetchProductsCompleted(payload: RemoteProductListPayload) {
coroutineEngine.launch(T.DB, this, "handleFetchProductsCompleted") {
val onProductChanged: OnProductChanged
if (payload.isError) {
onProductChanged = OnProductChanged(0).also { it.error = payload.error }
} else {
// remove the existing products for this site if this is the first page of results
// or if the remoteProductIds or excludedProductIds are null, otherwise
// products deleted outside of the app will persist
if (payload.offset == 0 && payload.remoteProductIds == null && payload.excludedProductIds == null) {
ProductSqlUtils.deleteProductsForSite(payload.site)
}
val rowsAffected = ProductSqlUtils.insertOrUpdateProducts(payload.products)
onProductChanged = OnProductChanged(rowsAffected, canLoadMore = payload.canLoadMore)
// TODO: 18/08/2021 @wzieba add tests
coroutineEngine.launch(T.DB, this, "cacheProductsAddons") {
payload.products.forEach { product ->
val domainAddons = mapProductAddonsToDomain(product.addons)
addonsDao.cacheProductAddons(
productRemoteId = product.remoteProductId,
siteRemoteId = payload.site.siteId,
addons = domainAddons
)
}
}
}
onProductChanged.causeOfChange = WCProductAction.FETCH_PRODUCTS
emitChange(onProductChanged)
}
}
private fun handleSearchProductsCompleted(payload: RemoteSearchProductsPayload) {
if (payload.isError) {
emitChange(
OnProductsSearched(
searchQuery = payload.searchQuery,
isSkuSearch = payload.isSkuSearch
)
)
} else {
coroutineEngine.launch(T.DB, this, "handleSearchProductsCompleted") {
ProductSqlUtils.insertOrUpdateProducts(payload.products)
emitChange(
OnProductsSearched(
searchQuery = payload.searchQuery,
isSkuSearch = payload.isSkuSearch,
searchResults = payload.products,
canLoadMore = payload.canLoadMore
)
)
}
}
}
private fun handleFetchProductShippingClassesCompleted(payload: RemoteProductShippingClassListPayload) {
val onProductShippingClassesChanged = if (payload.isError) {
OnProductShippingClassesChanged(0).also { it.error = payload.error }
} else {
// delete product shipping class list for site if this is the first page of results, otherwise
// shipping class list deleted outside of the app will persist
if (payload.offset == 0) {
ProductSqlUtils.deleteProductShippingClassListForSite(payload.site)
}
val rowsAffected = ProductSqlUtils.insertOrUpdateProductShippingClassList(payload.shippingClassList)
OnProductShippingClassesChanged(rowsAffected, canLoadMore = payload.canLoadMore)
}
onProductShippingClassesChanged.causeOfChange = WCProductAction.FETCH_PRODUCT_SHIPPING_CLASS_LIST
emitChange(onProductShippingClassesChanged)
}
private fun handleFetchProductShippingClassCompleted(payload: RemoteProductShippingClassPayload) {
val onProductShippingClassesChanged = if (payload.isError) {
OnProductShippingClassesChanged(0).also { it.error = payload.error }
} else {
val rowsAffected = ProductSqlUtils.insertOrUpdateProductShippingClass(payload.productShippingClassModel)
OnProductShippingClassesChanged(rowsAffected)
}
onProductShippingClassesChanged.causeOfChange = WCProductAction.FETCH_SINGLE_PRODUCT_SHIPPING_CLASS
emitChange(onProductShippingClassesChanged)
}
private fun handleFetchProductPasswordCompleted(payload: RemoteProductPasswordPayload) {
val onProductPasswordChanged = if (payload.isError) {
OnProductPasswordChanged(payload.remoteProductId, "").also { it.error = payload.error }
} else {
OnProductPasswordChanged(payload.remoteProductId, payload.password)
}
onProductPasswordChanged.causeOfChange = WCProductAction.FETCH_PRODUCT_PASSWORD
emitChange(onProductPasswordChanged)
}
private fun handleUpdatedProductPasswordCompleted(payload: RemoteUpdatedProductPasswordPayload) {
val onProductPasswordUpdated = if (payload.isError) {
OnProductPasswordChanged(payload.remoteProductId, null).also { it.error = payload.error }
} else {
OnProductPasswordChanged(payload.remoteProductId, payload.password)
}
onProductPasswordUpdated.causeOfChange = WCProductAction.UPDATE_PRODUCT_PASSWORD
emitChange(onProductPasswordUpdated)
}
private fun handleUpdateProductImages(payload: RemoteUpdateProductImagesPayload) {
coroutineEngine.launch(T.DB, this, "handleUpdateProductImages") {
val onProductImagesChanged: OnProductImagesChanged
if (payload.isError) {
onProductImagesChanged = OnProductImagesChanged(
0,
payload.product.remoteProductId
).also {
it.error = payload.error
}
} else {
val rowsAffected = ProductSqlUtils.insertOrUpdateProduct(payload.product)
onProductImagesChanged = OnProductImagesChanged(
rowsAffected,
payload.product.remoteProductId
)
}
onProductImagesChanged.causeOfChange = WCProductAction.UPDATED_PRODUCT_IMAGES
emitChange(onProductImagesChanged)
}
}
private fun handleUpdateProduct(payload: RemoteUpdateProductPayload) {
coroutineEngine.launch(T.DB, this, "handleUpdateProduct") {
val onProductUpdated: OnProductUpdated
if (payload.isError) {
onProductUpdated = OnProductUpdated(0, payload.product.remoteProductId)
.also { it.error = payload.error }
} else {
val rowsAffected = ProductSqlUtils.insertOrUpdateProduct(payload.product)
onProductUpdated = OnProductUpdated(rowsAffected, payload.product.remoteProductId)
}
onProductUpdated.causeOfChange = WCProductAction.UPDATED_PRODUCT
emitChange(onProductUpdated)
}
}
private fun handleFetchProductCategories(payload: RemoteProductCategoriesPayload) {
coroutineEngine.launch(T.DB, this, "handleFetchProductCategories") {
val onProductCategoryChanged: OnProductCategoryChanged
if (payload.isError) {
onProductCategoryChanged = OnProductCategoryChanged(0).also { it.error = payload.error }
} else {
// Clear existing product categories if this is a fresh fetch (loadMore = false).
// This is the simplest way to keep our local categories in sync with remote categories
// in case of deletions.
if (!payload.loadedMore) {
ProductSqlUtils.deleteAllProductCategoriesForSite(payload.site)
}
val rowsAffected = ProductSqlUtils.insertOrUpdateProductCategories(
payload.categories
)
onProductCategoryChanged = OnProductCategoryChanged(
rowsAffected,
canLoadMore = payload.canLoadMore
)
}
onProductCategoryChanged.causeOfChange = WCProductAction.FETCH_PRODUCT_CATEGORIES
emitChange(onProductCategoryChanged)
}
}
private fun handleAddProductCategory(payload: RemoteAddProductCategoryResponsePayload) {
coroutineEngine.launch(T.DB, this, "handleAddProductCategory") {
val onProductCategoryChanged: OnProductCategoryChanged
if (payload.isError) {
onProductCategoryChanged = OnProductCategoryChanged(0).also { it.error = payload.error }
} else {
val rowsAffected = payload.category?.let {
ProductSqlUtils.insertOrUpdateProductCategory(it)
} ?: 0
onProductCategoryChanged = OnProductCategoryChanged(rowsAffected)
}
onProductCategoryChanged.causeOfChange = WCProductAction.ADDED_PRODUCT_CATEGORY
emitChange(onProductCategoryChanged)
}
}
private fun handleFetchProductTagsCompleted(payload: RemoteProductTagsPayload) {
val onProductTagsChanged = if (payload.isError) {
OnProductTagChanged(0).also { it.error = payload.error }
} else {
// delete product tags for site if this is the first page of results, otherwise
// tags deleted outside of the app will persist
if (payload.offset == 0 && payload.searchQuery.isNullOrEmpty()) {
ProductSqlUtils.deleteProductTagsForSite(payload.site)
}
val rowsAffected = ProductSqlUtils.insertOrUpdateProductTags(payload.tags)
OnProductTagChanged(rowsAffected, canLoadMore = payload.canLoadMore)
}
onProductTagsChanged.causeOfChange = WCProductAction.FETCH_PRODUCT_TAGS
emitChange(onProductTagsChanged)
}
private fun handleAddProductTags(payload: RemoteAddProductTagsResponsePayload) {
val onProductTagsChanged: OnProductTagChanged
if (payload.isError) {
onProductTagsChanged = OnProductTagChanged(0).also { it.error = payload.error }
} else {
val rowsAffected = ProductSqlUtils.insertOrUpdateProductTags(payload.tags.filter { it.name.isNotEmpty() })
onProductTagsChanged = OnProductTagChanged(rowsAffected)
}
onProductTagsChanged.causeOfChange = WCProductAction.ADDED_PRODUCT_TAGS
emitChange(onProductTagsChanged)
}
private fun handleAddNewProduct(payload: RemoteAddProductPayload) {
coroutineEngine.launch(T.DB, this, "handleAddNewProduct") {
val onProductCreated: OnProductCreated
if (payload.isError) {
onProductCreated = OnProductCreated(
0,
payload.product.remoteProductId
).also { it.error = payload.error }
} else {
val rowsAffected = ProductSqlUtils.insertOrUpdateProduct(payload.product)
onProductCreated = OnProductCreated(rowsAffected, payload.product.remoteProductId)
}
onProductCreated.causeOfChange = WCProductAction.ADDED_PRODUCT
emitChange(onProductCreated)
}
}
private fun handleDeleteProduct(payload: RemoteDeleteProductPayload) {
coroutineEngine.launch(T.DB, this, "handleDeleteProduct") {
val onProductChanged: OnProductChanged
if (payload.isError) {
onProductChanged = OnProductChanged(0).also { it.error = payload.error }
} else {
val rowsAffected = ProductSqlUtils.deleteProduct(
payload.site,
payload.remoteProductId
)
onProductChanged = OnProductChanged(rowsAffected, payload.remoteProductId)
}
onProductChanged.causeOfChange = WCProductAction.DELETED_PRODUCT
emitChange(onProductChanged)
}
}
data class ProductSearchResult(
val products: List<WCProductModel>,
val canLoadMore: Boolean
)
data class ProductCategorySearchResult(
val categories: List<WCProductCategoryModel>,
val canLoadMore: Boolean
)
}
| plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/store/WCProductStore.kt | 421652644 |
package org.zaproxy.zap
data class GitHubUser(val name: String, val email: String, val authToken: String?)
| buildSrc/src/main/kotlin/org/zaproxy/zap/GitHubUser.kt | 3997506545 |
/* generic EPD Controller for Android devices,
* based on https://github.com/unwmun/refreshU */
package org.koreader.launcher.device.epd
import org.koreader.launcher.device.EPDInterface
import org.koreader.launcher.device.epd.rockchip.RK30xxEPDController
class RK3026EPDController : RK30xxEPDController(), EPDInterface {
override fun getPlatform(): String {
return "rockchip"
}
override fun getMode(): String {
return "full-only"
}
override fun getWaveformFull(): Int {
return EINK_MODE_FULL
}
override fun getWaveformPartial(): Int {
return EINK_MODE_PARTIAL
}
override fun getWaveformFullUi(): Int {
return EINK_MODE_FULL_UI
}
override fun getWaveformPartialUi(): Int {
return EINK_MODE_PARTIAL_UI
}
override fun getWaveformFast(): Int {
return EINK_MODE_FAST
}
override fun getWaveformDelay(): Int {
return EINK_WAVEFORM_DELAY
}
override fun getWaveformDelayUi(): Int {
return EINK_WAVEFORM_DELAY
}
override fun getWaveformDelayFast(): Int {
return EINK_WAVEFORM_DELAY
}
override fun needsView(): Boolean {
return false
}
override fun setEpdMode(targetView: android.view.View,
mode: Int, delay: Long,
x: Int, y: Int, width: Int, height: Int, epdMode: String?)
{
requestEpdMode(targetView, epdMode!!, true)
}
override fun resume() {}
override fun pause() {}
}
| app/src/main/java/org/koreader/launcher/device/epd/RK3026EPDController.kt | 233880002 |
/*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.registry.type.effect.particle
import org.lanternpowered.api.effect.firework.FireworkEffect
import org.lanternpowered.api.registry.CatalogTypeRegistry
import org.lanternpowered.api.registry.CatalogTypeRegistryBuilder
import org.lanternpowered.api.registry.catalogTypeRegistry
import org.lanternpowered.server.effect.particle.LanternParticleOption
import org.lanternpowered.api.key.NamespacedKey
import org.spongepowered.api.block.BlockState
import org.spongepowered.api.data.type.NotePitch
import org.spongepowered.api.effect.particle.ParticleOption
import org.spongepowered.api.effect.potion.PotionEffectType
import org.spongepowered.api.item.inventory.ItemStackSnapshot
import org.spongepowered.api.util.Color
import org.spongepowered.api.util.Direction
import org.spongepowered.math.vector.Vector3d
val ParticleOptionRegistry: CatalogTypeRegistry<ParticleOption<*>> = catalogTypeRegistry {
register<BlockState>("block_state")
register<Color>("color")
register<Direction>("direction")
register<List<FireworkEffect>>("firework_effects") { value -> check(value.isNotEmpty()) { "The firework effects list may not be empty" } }
register<Int>("quantity") { value -> check(value >= 1) { "Quantity must be at least 1" } }
register<ItemStackSnapshot>("item_stack_snapshot")
register<NotePitch>("note")
register<Vector3d>("offset")
register<PotionEffectType>("potion_effect_type")
register<Double>("scale") { value -> check(value >= 0) { "Scale may not be negative" } }
register<Vector3d>("velocity")
register<Boolean>("slow_horizontal_velocity")
}
private inline fun <reified V> CatalogTypeRegistryBuilder<ParticleOption<*>>.register(
id: String, noinline valueValidator: (V) -> Unit = {}
): ParticleOption<*> = register(LanternParticleOption(NamespacedKey.sponge(id), V::class.java, valueValidator))
| src/main/kotlin/org/lanternpowered/server/registry/type/effect/particle/ParticleOptionRegistry.kt | 4024111856 |
/*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.profile
import org.lanternpowered.api.profile.GameProfile
import org.lanternpowered.api.service.profile.GameProfileService
import org.lanternpowered.api.util.optional.asOptional
import org.lanternpowered.api.util.optional.orNull
import org.spongepowered.api.profile.GameProfileCache
import java.time.Instant
import java.util.Optional
import java.util.UUID
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ConcurrentHashMap
import java.util.stream.Stream
class LanternGameProfileCache(
private val service: GameProfileService
) : GameProfileCache {
private val byUniqueId = ConcurrentHashMap<UUID, GameProfile>()
override fun getProfiles(): Collection<GameProfile> {
TODO("Not yet implemented")
}
override fun getOrLookupByName(name: String): Optional<GameProfile> {
TODO("Not yet implemented")
}
fun getOrLookupByNameAsync(name: String): CompletableFuture<GameProfile?> {
val cachedProfile = this.getByName(name).orNull()
if (cachedProfile != null)
return CompletableFuture.completedFuture(cachedProfile)
return this.service.getBasicProfile(name).thenApply { profile ->
if (profile != null)
this.add(profile)
profile
}
}
fun lookupByNameAsync(name: String): CompletableFuture<GameProfile?> =
this.service.getBasicProfile(name)
override fun clear() {
TODO("Not yet implemented")
}
override fun getById(uniqueId: UUID): Optional<GameProfile> {
TODO("Not yet implemented")
}
override fun lookupByIds(uniqueIds: Iterable<UUID>): Map<UUID, Optional<GameProfile>> {
TODO("Not yet implemented")
}
override fun getByNames(names: Iterable<String>): Map<String, Optional<GameProfile>> {
TODO("Not yet implemented")
}
override fun lookupByName(name: String): Optional<GameProfile> =
this.lookupByNameAsync(name).get().asOptional()
override fun streamProfiles(): Stream<GameProfile> {
TODO("Not yet implemented")
}
override fun remove(profile: GameProfile): Boolean {
TODO("Not yet implemented")
}
override fun remove(profiles: Iterable<GameProfile>): Collection<GameProfile> {
TODO("Not yet implemented")
}
override fun getByIds(uniqueIds: Iterable<UUID>): Map<UUID, Optional<GameProfile>> {
TODO("Not yet implemented")
}
override fun lookupByNames(names: Iterable<String>): Map<String, Optional<GameProfile>> {
TODO("Not yet implemented")
}
override fun getByName(name: String?): Optional<GameProfile> {
TODO("Not yet implemented")
}
override fun getOrLookupByIds(uniqueIds: Iterable<UUID>): Map<UUID, Optional<GameProfile>> {
TODO("Not yet implemented")
}
override fun add(profile: GameProfile, overwrite: Boolean, expiry: Instant?): Boolean {
TODO("Not yet implemented")
}
override fun getOrLookupByNames(names: Iterable<String>): Map<String, Optional<GameProfile>> {
TODO("Not yet implemented")
}
override fun fillProfile(profile: GameProfile, signed: Boolean): Optional<GameProfile> {
TODO("Not yet implemented")
}
override fun match(name: String): Collection<GameProfile> {
TODO("Not yet implemented")
}
override fun streamOfMatches(name: String): Stream<GameProfile> {
TODO("Not yet implemented")
}
override fun lookupById(uniqueId: UUID): Optional<GameProfile> {
TODO("Not yet implemented")
}
override fun getOrLookupById(uniqueId: UUID): Optional<GameProfile> {
TODO("Not yet implemented")
}
fun getOrLookupByIdAsync(uniqueId: UUID): CompletableFuture<GameProfile?> {
TODO("Not yet implemented")
}
}
| src/main/kotlin/org/lanternpowered/server/profile/LanternGameProfileCache.kt | 2514470784 |
/*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
@file:Suppress("NOTHING_TO_INLINE")
package org.lanternpowered.api.util.gson
import com.google.gson.Gson
import com.google.gson.JsonElement
import com.google.gson.JsonNull
import org.lanternpowered.api.util.type.TypeToken
import java.io.Reader
import kotlin.reflect.KClass
import kotlin.reflect.KType
import kotlin.reflect.jvm.javaType
fun Gson.fromJson(json: String, type: KType): Any = fromJson(json, type.javaType)
fun Gson.fromJson(json: Reader, type: KType): Any = fromJson(json, type.javaType)
fun Gson.fromJson(json: JsonElement, type: KType): Any = fromJson(json, type.javaType)
fun <T : Any> Gson.fromJson(json: String, type: KClass<T>): T = fromJson(json, type.java)
fun <T : Any> Gson.fromJson(json: Reader, type: KClass<T>): T = fromJson(json, type.java)
fun <T : Any> Gson.fromJson(json: JsonElement, type: KClass<T>): T = fromJson(json, type.java)
fun <T> Gson.fromJson(json: String, type: TypeToken<T>): T = fromJson(json, type.type)
fun <T> Gson.fromJson(json: Reader, type: TypeToken<T>): T = fromJson(json, type.type)
fun <T> Gson.fromJson(json: JsonElement, type: TypeToken<T>): T = fromJson(json, type.type)
inline fun <reified T> Gson.fromJson(json: String): T = fromJson(json, object : TypeToken<T>() {})
inline fun <reified T> Gson.fromJson(json: Reader): T = fromJson(json, object : TypeToken<T>() {})
inline fun <reified T> Gson.fromJson(json: JsonElement): T = fromJson(json, object : TypeToken<T>() {})
private val gson = Gson()
/**
* Parses the [String] as a [JsonElement].
*/
fun String?.parseJson(): JsonElement = if (this == null) JsonNull.INSTANCE else gson.fromJson(this)
| src/main/kotlin/org/lanternpowered/api/util/gson/Gson.kt | 2984179246 |
package org.illegaller.ratabb.hishoot2i.ui.main
import androidx.annotation.ColorInt
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import core.CoreProcess
import dagger.hilt.android.lifecycle.HiltViewModel
import entity.BackgroundMode
import entity.ImageOption
import entity.ImageSourcePath
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.merge
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.illegaller.ratabb.hishoot2i.data.pref.BackgroundToolPref
import org.illegaller.ratabb.hishoot2i.data.pref.BadgeToolPref
import org.illegaller.ratabb.hishoot2i.data.pref.ScreenToolPref
import org.illegaller.ratabb.hishoot2i.data.pref.TemplateToolPref
import org.illegaller.ratabb.hishoot2i.data.source.TemplateSource
import org.illegaller.ratabb.hishoot2i.ui.ARG_BACKGROUND_PATH
import org.illegaller.ratabb.hishoot2i.ui.ARG_SCREEN1_PATH
import org.illegaller.ratabb.hishoot2i.ui.ARG_SCREEN2_PATH
import template.Template
import javax.inject.Inject
@ExperimentalCoroutinesApi
@HiltViewModel
class MainViewModel @Inject constructor(
private val coreProcess: CoreProcess,
private val templateSource: TemplateSource,
private val backgroundToolPref: BackgroundToolPref,
private val badgeToolPref: BadgeToolPref,
private val screenToolPref: ScreenToolPref,
private val templateToolPref: TemplateToolPref,
private val savedStateHandle: SavedStateHandle
) : ViewModel() {
private var lastTemplateId: String? = null
private var lastTemplate: Template? = null
private val isHaveLastTemplate: Boolean
get() = lastTemplateId != null && lastTemplate != null &&
lastTemplateId == templateToolPref.templateCurrentId
private val _uiState = MutableLiveData<MainView>()
internal val uiState: LiveData<MainView>
get() = _uiState
private val sourcePath = ImageSourcePath()
init {
preferenceChanges() //
sourcePath.background = savedStateHandle.get(ARG_BACKGROUND_PATH)
sourcePath.screen1 = savedStateHandle.get(ARG_SCREEN1_PATH)
sourcePath.screen2 = savedStateHandle.get(ARG_SCREEN2_PATH)
}
override fun onCleared() {
lastTemplate = null
lastTemplateId = null
}
fun resume() {
lastTemplateId?.let {
if (it != templateToolPref.templateCurrentId) {
render()
}
}
}
private fun currentTemplate(): Template = if (isHaveLastTemplate) lastTemplate!! else {
templateSource.findByIdOrDefault(templateToolPref.templateCurrentId).also {
lastTemplate = it
lastTemplateId = it.id
}
}
fun render() {
viewModelScope.launch {
_uiState.value = Loading(false)
runCatching { withContext(IO) { coreProcess.preview(currentTemplate(), sourcePath) } }
.fold({ _uiState.value = Success(it) }, { _uiState.value = Fail(it, false) })
}
}
fun save() {
viewModelScope.launch {
_uiState.value = Loading(true)
runCatching { withContext(IO) { coreProcess.save(currentTemplate(), sourcePath) } }
.fold({ _uiState.value = Success(it) }, { _uiState.value = Fail(it, true) })
}
}
fun backgroundColorPipette(@ColorInt color: Int) {
if (backgroundToolPref.backgroundColorInt != color) {
backgroundToolPref.backgroundColorInt = color
}
}
fun changeScreen1(path: String?) {
if (path == null) return
sourcePath.screen1 = path
savedStateHandle.set(ARG_SCREEN1_PATH, path)
render()
}
fun changeScreen2(path: String?) {
if (path == null) return
sourcePath.screen2 = path
savedStateHandle.set(ARG_SCREEN2_PATH, path)
render()
}
fun changeBackground(path: String?) {
if (path == null) return
sourcePath.background = path
savedStateHandle.set(ARG_BACKGROUND_PATH, path)
if (backgroundToolPref.backgroundMode.isImage) render()
else backgroundToolPref.backgroundMode = BackgroundMode.IMAGE
}
@ExperimentalCoroutinesApi
private fun preferenceChanges() {
(
screenToolPref.mainFlow + badgeToolPref.mainFlow +
templateToolPref.mainFlow + backgroundToolPref.mainFlow
)
.merge()
.filter { (it as? ImageOption)?.isManualCrop != true }
.onEach { render() }
.catch { _uiState.value = Fail(it, false) }
.launchIn(viewModelScope)
}
}
| app/src/main/java/org/illegaller/ratabb/hishoot2i/ui/main/MainViewModel.kt | 44316869 |
package com.orhanobut.android.dialogplus
import android.app.Activity
import android.view.LayoutInflater
import android.view.View
import android.widget.ArrayAdapter
import android.widget.LinearLayout
import android.widget.ListView
import com.orhanobut.dialogplus.HolderAdapter
import com.orhanobut.dialogplus.ListHolder
import com.orhanobut.dialogplus.R
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.fail
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class ListHolderTest {
private val context = Robolectric.setupActivity(Activity::class.java)
private val listHolder: ListHolder
get() {
val holder = ListHolder()
val layoutInflater = LayoutInflater.from(context)
holder.getView(layoutInflater, LinearLayout(context))
return holder
}
@Test fun init() {
assertThat(listHolder).isInstanceOf(HolderAdapter::class.java)
assertThat(listHolder).isNotNull()
}
@Test fun testViewInflation() {
val holder = ListHolder()
val layoutInflater = LayoutInflater.from(context)
val view = holder.getView(layoutInflater, LinearLayout(context))
assertThat(view).isNotNull()
assertThat(holder.inflatedView.id).isEqualTo(R.id.dialogplus_list)
val listView = holder.inflatedView as ListView
assertThat(listView.onItemClickListener).isInstanceOf(ListHolder::class.java)
}
@Test fun testFooter() {
val holder = listHolder
assertThat(holder.footer).isNull()
val footer = LinearLayout(context)
holder.addFooter(footer)
assertThat(holder.footer).isEqualTo(footer)
}
@Test fun testHeader() {
val holder = listHolder
assertThat(holder.header).isNull()
val header = LinearLayout(context)
holder.addHeader(header)
assertThat(holder.header).isEqualTo(header)
}
@Test fun testOnItemClickWithoutItemListenerAndAdapter() {
val holder = listHolder
val listView = holder.inflatedView as ListView
try {
listView.performItemClick(null, 0, 0)
} catch (e: Exception) {
fail("it should not crash")
}
}
@Test fun testOnItemClickWithoutItemListenerOnly() {
val holder = listHolder
val listView = holder.inflatedView as ListView
//with adapter set
val adapter = ArrayAdapter(
context, android.R.layout.simple_list_item_1,
arrayOf("test")
)
holder.setAdapter(adapter)
try {
listView.performItemClick(null, 0, 0)
} catch (e: Exception) {
fail("it should not crash")
}
}
@Test fun testOnItemClick() {
val holder = listHolder
val listView = holder.inflatedView as ListView
//with adapter set
val adapter = ArrayAdapter(
context, android.R.layout.simple_list_item_1,
arrayOf("test")
)
holder.setAdapter(adapter)
//set listener
holder.setOnItemClickListener { item, view, position ->
assertThat(item.toString()).isEqualTo("test")
assertThat(position).isEqualTo(0)
assertThat(view).isEqualTo(listView)
}
listView.performItemClick(listView, 0, 0)
}
@Test fun doNotCountHeaderForPositionCalculation() {
val holder = listHolder
holder.addHeader(View(context))
val listView = holder.inflatedView as ListView
//with adapter set
val adapter = ArrayAdapter(
context, android.R.layout.simple_list_item_1,
arrayOf("test")
)
holder.setAdapter(adapter)
//set listener
holder.setOnItemClickListener { item, view, position ->
assertThat(item.toString()).isEqualTo("test")
assertThat(position).isEqualTo(0)
assertThat(view).isEqualTo(listView)
}
listView.performItemClick(listView, 1, 0)
}
}
| dialogplus/src/test/java/com/orhanobut/android/dialogplus/ListHolderTest.kt | 2104688516 |
/*
* Copyright (c) 2015 PocketHub
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.pockethub.android.ui.gist
import android.content.Intent
import android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP
import android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP
import android.os.Bundle
import android.util.Log
import android.view.MenuItem
import com.github.pockethub.android.Intents.Builder
import com.github.pockethub.android.Intents.EXTRA_GIST
import com.github.pockethub.android.Intents.EXTRA_GIST_ID
import com.github.pockethub.android.Intents.EXTRA_GIST_IDS
import com.github.pockethub.android.Intents.EXTRA_POSITION
import com.github.pockethub.android.R
import com.github.pockethub.android.core.OnLoadListener
import com.github.pockethub.android.core.gist.GistStore
import com.github.pockethub.android.rx.AutoDisposeUtils
import com.github.pockethub.android.rx.RxProgress
import com.github.pockethub.android.ui.base.BaseActivity
import com.github.pockethub.android.ui.ConfirmDialogFragment
import com.github.pockethub.android.ui.DialogResultListener
import com.github.pockethub.android.ui.MainActivity
import com.github.pockethub.android.ui.helpers.PagerHandler
import com.github.pockethub.android.ui.item.gist.GistItem
import com.github.pockethub.android.ui.user.UriLauncherActivity
import com.github.pockethub.android.util.ToastUtils
import com.meisolsson.githubsdk.core.ServiceGenerator
import com.meisolsson.githubsdk.model.Gist
import com.meisolsson.githubsdk.service.gists.GistService
import com.xwray.groupie.Item
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_pager.*
import java.io.Serializable
import javax.inject.Inject
/**
* Activity to display a collection of Gists in a pager
*/
class GistsViewActivity : BaseActivity(), DialogResultListener, OnLoadListener<Gist> {
@Inject
lateinit var store: GistStore
private var gists: Array<String>? = null
private var gist: Gist? = null
private var initialPosition: Int = 0
private var pagerHandler: PagerHandler<GistsPagerAdapter>? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_pager)
gists = intent.getStringArrayExtra(EXTRA_GIST_IDS)
gist = intent.getParcelableExtra(EXTRA_GIST)
initialPosition = intent.getIntExtra(EXTRA_POSITION, -1)
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
// Support opening this activity with a single Gist that may be present
// in the intent but not currently present in the store
if (gists == null && gist != null) {
if (gist!!.createdAt() != null) {
val stored = store.getGist(gist!!.id())
if (stored == null) {
store.addGist(gist)
}
}
gists = arrayOf(gist!!.id()!!)
}
val adapter = GistsPagerAdapter(this, gists)
pagerHandler = PagerHandler(this, vp_pages, adapter)
lifecycle.addObserver(pagerHandler!!)
pagerHandler!!.onPagedChanged = this::onPageChanged
vp_pages.scheduleSetItem(initialPosition, pagerHandler)
}
override fun onDestroy() {
super.onDestroy()
lifecycle.removeObserver(pagerHandler!!)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
finish()
val intent = Intent(this, MainActivity::class.java)
intent.addFlags(FLAG_ACTIVITY_CLEAR_TOP or FLAG_ACTIVITY_SINGLE_TOP)
startActivity(intent)
return true
}
R.id.m_delete -> {
val gistId = gists!![vp_pages.currentItem]
val args = Bundle()
args.putString(EXTRA_GIST_ID, gistId)
ConfirmDialogFragment.show(this, REQUEST_CONFIRM_DELETE,
getString(R.string.confirm_gist_delete_title),
getString(R.string.confirm_gist_delete_message), args)
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
override fun onDialogResult(requestCode: Int, resultCode: Int, arguments: Bundle) {
if (REQUEST_CONFIRM_DELETE == requestCode && RESULT_OK == resultCode) {
val gistId = arguments.getString(EXTRA_GIST_ID)
ServiceGenerator.createService(this, GistService::class.java)
.deleteGist(gistId)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.compose(RxProgress.bindToLifecycle(this, R.string.deleting_gist))
.`as`(AutoDisposeUtils.bindToLifecycle(this))
.subscribe({ response ->
setResult(RESULT_OK)
finish()
}, { e ->
Log.d(TAG, "Exception deleting Gist", e)
ToastUtils.show(this, e.message)
})
return
}
pagerHandler!!.adapter
.onDialogResult(vp_pages.currentItem, requestCode, resultCode, arguments)
}
private fun onPageChanged(position: Int) {
val gistId = gists!![position]
val gist = store.getGist(gistId)
updateActionBar(gist, gistId)
}
override fun startActivity(intent: Intent) {
val converted = UriLauncherActivity.convert(intent)
if (converted != null) {
super.startActivity(converted)
} else {
super.startActivity(intent)
}
}
private fun updateActionBar(gist: Gist?, gistId: String) {
val actionBar = supportActionBar!!
when {
gist == null -> {
actionBar.subtitle = null
actionBar.setLogo(null)
}
gist.owner() != null -> {
actionBar.subtitle = gist.owner()!!.login()
}
else -> {
actionBar.setSubtitle(R.string.anonymous)
actionBar.setLogo(null)
}
}
actionBar.title = getString(R.string.gist_title) + gistId
}
override fun loaded(gist: Gist) {
if (gists!![vp_pages.currentItem] == gist.id()) {
updateActionBar(gist, gist.id()!!)
}
}
companion object {
private val REQUEST_CONFIRM_DELETE = 1
private val TAG = "GistsViewActivity"
/**
* Create an intent to show a single gist
*
* @param gist
* @return intent
*/
fun createIntent(gist: Gist): Intent {
return Builder("gists.VIEW").gist(gist).add(EXTRA_POSITION, 0)
.toIntent()
}
/**
* Create an intent to show gists with an initial selected Gist
*
* @param items
* @param position
* @return intent
*/
fun createIntent(items: List<Item<*>>, position: Int): Intent {
val ids = items.map { (it as GistItem).gist.id() }.toTypedArray()
return Builder("gists.VIEW")
.add(EXTRA_GIST_IDS, ids as Serializable)
.add(EXTRA_POSITION, position).toIntent()
}
}
}
| app/src/main/java/com/github/pockethub/android/ui/gist/GistsViewActivity.kt | 1275529852 |
// Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.kingdom.service.api.v2alpha
import io.grpc.BindableService
import io.grpc.Context
import io.grpc.Contexts
import io.grpc.Metadata
import io.grpc.ServerCall
import io.grpc.ServerCallHandler
import io.grpc.ServerInterceptor
import io.grpc.ServerInterceptors
import io.grpc.ServerServiceDefinition
import io.grpc.Status
import io.grpc.StatusException
import java.security.GeneralSecurityException
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
import org.wfanet.measurement.api.AccountConstants
import org.wfanet.measurement.api.v2alpha.AccountKey
import org.wfanet.measurement.api.v2alpha.AccountPrincipal
import org.wfanet.measurement.api.v2alpha.withPrincipal
import org.wfanet.measurement.common.grpc.SuspendableServerInterceptor
import org.wfanet.measurement.common.identity.externalIdToApiId
import org.wfanet.measurement.internal.kingdom.Account
import org.wfanet.measurement.internal.kingdom.AccountsGrpcKt.AccountsCoroutineStub
import org.wfanet.measurement.internal.kingdom.authenticateAccountRequest
/** gRPC [ServerInterceptor] to check [Account] credentials coming in from a request. */
class AccountAuthenticationServerInterceptor(
private val internalAccountsClient: AccountsCoroutineStub,
private val redirectUri: String,
coroutineContext: CoroutineContext = EmptyCoroutineContext
) : SuspendableServerInterceptor(coroutineContext) {
override suspend fun <ReqT : Any, RespT : Any> interceptCallSuspending(
call: ServerCall<ReqT, RespT>,
headers: Metadata,
next: ServerCallHandler<ReqT, RespT>
): ServerCall.Listener<ReqT> {
var context = Context.current()
val idToken =
headers.get(AccountConstants.ID_TOKEN_METADATA_KEY)
?: return Contexts.interceptCall(context, call, headers, next)
context = context.withValue(AccountConstants.CONTEXT_ID_TOKEN_KEY, idToken)
try {
val account = authenticateAccountCredentials(idToken)
context =
context
.withPrincipal(AccountPrincipal(AccountKey(externalIdToApiId(account.externalAccountId))))
.withValue(AccountConstants.CONTEXT_ACCOUNT_KEY, account)
} catch (e: GeneralSecurityException) {
call.close(Status.UNAUTHENTICATED.withCause(e), headers)
} catch (e: StatusException) {
val status =
when (e.status.code) {
Status.Code.NOT_FOUND -> {
// The request might not require authentication, so this is fine.
Status.OK
}
Status.Code.CANCELLED -> Status.CANCELLED
Status.Code.DEADLINE_EXCEEDED -> Status.DEADLINE_EXCEEDED
else -> Status.UNKNOWN
}
if (!status.isOk) {
call.close(status, headers)
}
}
return Contexts.interceptCall(context, call, headers, next)
}
private suspend fun authenticateAccountCredentials(idToken: String): Account {
val openIdConnectIdentity =
AccountsService.validateIdToken(
idToken = idToken,
redirectUri = redirectUri,
internalAccountsStub = internalAccountsClient
)
return internalAccountsClient.authenticateAccount(
authenticateAccountRequest { identity = openIdConnectIdentity }
)
}
}
fun BindableService.withAccountAuthenticationServerInterceptor(
internalAccountsClient: AccountsCoroutineStub,
redirectUri: String
): ServerServiceDefinition =
ServerInterceptors.intercept(
this,
AccountAuthenticationServerInterceptor(internalAccountsClient, redirectUri)
)
fun ServerServiceDefinition.withAccountAuthenticationServerInterceptor(
internalAccountsClient: AccountsCoroutineStub,
redirectUri: String
): ServerServiceDefinition =
ServerInterceptors.intercept(
this,
AccountAuthenticationServerInterceptor(internalAccountsClient, redirectUri)
)
/** Executes [block] with [Account] installed in a new [Context]. */
fun <T> withAccount(account: Account, block: () -> T): T {
return Context.current().withAccount(account).call(block)
}
fun Context.withAccount(account: Account): Context {
return withValue(AccountConstants.CONTEXT_ACCOUNT_KEY, account)
}
| src/main/kotlin/org/wfanet/measurement/kingdom/service/api/v2alpha/AccountAuthenticationServerInterceptor.kt | 2255119729 |
package com.twitter.mk_melics.sojobus.holder
import android.view.View
import java.util.*
class GezanTakatukiBusDetailHolder(itemView: View) : BaseBusDetailHolder(itemView) {
override fun onBind() {
Title.text="下山(JR高槻駅北)"
SubTitle.text="関西大学発"
var c = GregorianCalendar()
c.set(Calendar.HOUR_OF_DAY,0)
c.set(Calendar.MINUTE,0)
show(Text,Manager.toTakatukiFromRapyuta(-1,c))
}
} | app/src/main/kotlin/com/twitter/mk_melics/sojobus/holder/GezanTakatukiBusDetailHolder.kt | 4069448738 |
package nl.hannahsten.texifyidea.completion.pathcompletion
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiFile
import nl.hannahsten.texifyidea.index.LatexIncludesIndex
import nl.hannahsten.texifyidea.lang.commands.LatexGenericRegularCommand
import nl.hannahsten.texifyidea.psi.LatexCommands
import nl.hannahsten.texifyidea.psi.LatexNormalText
import nl.hannahsten.texifyidea.util.childrenOfType
import nl.hannahsten.texifyidea.util.files.*
import nl.hannahsten.texifyidea.util.magic.cmd
import java.io.File
/**
* Autocompletion roots based on graphicspaths.
*/
class LatexGraphicsPathProvider : LatexPathProviderBase() {
override fun selectScanRoots(file: PsiFile): ArrayList<VirtualFile> {
val paths = getProjectRoots()
val rootDirectory = file.findRootFile().containingDirectory.virtualFile
getGraphicsPathsInFileSet(file).forEach {
paths.add(rootDirectory.findVirtualFileByAbsoluteOrRelativePath(it) ?: return@forEach)
}
return paths
}
/**
* When using \includegraphics from graphicx package, a path prefix can be set with \graphicspath.
* @return Graphicspaths defined in the fileset.
*/
fun getGraphicsPathsInFileSet(file: PsiFile): List<String> {
val graphicsPaths = mutableListOf<String>()
val graphicsPathCommands = file.commandsInFileSet().filter { it.name == LatexGenericRegularCommand.GRAPHICSPATH.cmd }
// Is a graphicspath defined?
if (graphicsPathCommands.isNotEmpty()) {
// Only last defined one counts
graphicsPathCommands.last().getGraphicsPaths().forEach { graphicsPaths.add(it) }
}
return graphicsPaths
}
/**
* This function is used in [InputFileReference#resolve], which is also used to create the file set, so we should
* not use the file set here (to avoid an infinite loop). Instead, we start searching the file of the given command
* for graphics paths. Then look at all commands that include the file of the given command and check the files of
* those commands for graphics paths.
*/
fun getGraphicsPathsWithoutFileSet(command: LatexCommands): List<String> {
fun graphicsPathsInFile(file: PsiFile): List<String> = file.commandsInFile()
.filter { it.name == "\\graphicspath" }
.flatMap { it.getGraphicsPaths() }
// First find all graphicspaths commands in the file of the given command
val graphicsPaths = graphicsPathsInFile(command.containingFile).toMutableList()
val allIncludeCommands = LatexIncludesIndex.getItems(command.project)
// Commands which may include the current file (this is an overestimation, better would be to check for RequiredFileArguments)
var includingCommands = allIncludeCommands.filter { includeCommand -> includeCommand.requiredParameters.any { it.contains(command.containingFile.name.removeFileExtension()) } }
// Avoid endless loop (in case of a file inclusion loop)
val maxDepth = allIncludeCommands.size
var counter = 0
// I think it's a kind of reversed BFS
while (includingCommands.isNotEmpty() && counter < maxDepth) {
val handledFiles = mutableListOf<PsiFile>()
val newIncludingCommands = mutableListOf<LatexCommands>()
for (includingCommand in includingCommands) {
// Search the file of the command that includes the current file for graphics paths.
graphicsPaths.addAll(graphicsPathsInFile(includingCommand.containingFile))
// Find files/commands to search next
val file = includingCommand.containingFile
if (file !in handledFiles) {
val commandsIncludingThisFile = allIncludeCommands.filter { includeCommand -> includeCommand.requiredParameters.any { it.contains(file.name) } }
newIncludingCommands.addAll(commandsIncludingThisFile)
handledFiles.add(file)
}
}
includingCommands = newIncludingCommands
counter++
}
return graphicsPaths
}
/**
* Get all the graphics paths defined by one \graphicspaths command.
*/
private fun LatexCommands.getGraphicsPaths(): List<String> {
if (name != "\\graphicspath") return emptyList()
return parameterList.mapNotNull { it.requiredParam }.first()
// Each graphics path is in a group.
.childrenOfType(LatexNormalText::class)
.map { it.text }
// Relative paths (not starting with /) have to be appended to the directory of the file of the given command.
.map { if (it.startsWith('/')) it else containingFile.containingDirectory.virtualFile.path + File.separator + it }
}
override fun searchFolders(): Boolean = true
override fun searchFiles(): Boolean = true
} | src/nl/hannahsten/texifyidea/completion/pathcompletion/LatexGraphicsPathProvider.kt | 3538539081 |
/*
* Copyright (C) 2015 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.api.entity
import net.simonvt.cathode.api.enumeration.ItemType
data class Like(
val liked_at: IsoTime,
val type: ItemType,
val comment: Comment? = null,
val list: CustomList? = null
)
| trakt-api/src/main/java/net/simonvt/cathode/api/entity/Like.kt | 1307519180 |
package nl.hannahsten.texifyidea.run.bibtex.logtab.messagehandlers.warnings
import nl.hannahsten.texifyidea.run.bibtex.logtab.BibtexLogMagicRegex
import nl.hannahsten.texifyidea.run.bibtex.logtab.BibtexLogMessage
import nl.hannahsten.texifyidea.run.bibtex.logtab.BibtexLogMessageType
import nl.hannahsten.texifyidea.run.bibtex.logtab.BibtexMessageHandler
/**
* Handle biber warning messages which do have information about the line number.
*/
object BiberWarningBibtexSubsystemMessageHandler : BibtexMessageHandler() {
override fun findMessage(window: List<String>, currentFile: String): BibtexLogMessage? {
BibtexLogMagicRegex.biberWarningBibtexSubsystem.find(window.lastOrNull() ?: "")?.apply {
return BibtexLogMessage(groups["message"]?.value ?: "", currentFile, groups["line"]?.value?.toInt(), BibtexLogMessageType.WARNING)
}
return null
}
} | src/nl/hannahsten/texifyidea/run/bibtex/logtab/messagehandlers/warnings/BiberWarningBibtexSubsystemMessageHandler.kt | 2556807064 |
package doit.study.droid.data.local.entity
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.PrimaryKey
@Entity(
foreignKeys = [
ForeignKey(
entity = Question::class,
parentColumns = ["id"],
childColumns = ["questionId"]
),
ForeignKey(
entity = Tag::class,
parentColumns = ["id"],
childColumns = ["tagId"]
)
],
indices = [
Index("questionId"),
Index("tagId")
]
)
data class QuestionTagJoin(
@PrimaryKey(autoGenerate = true)
val id: Int = 0,
val questionId: Int,
val tagId: Int
)
| app/src/main/java/doit/study/droid/data/local/entity/QuestionTagJoin.kt | 2965592468 |
/*
Copyright 2018 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.androidstudiopoet.models
import com.google.androidstudiopoet.utils.joinPath
class AndroidBuildBazelBlueprint(val isApplication: Boolean,
moduleRoot: String,
val packageName: String,
additionalDependencies: Set<Dependency>,
val name: String) {
val libraries: Set<GmavenBazelDependency> = createSetOfLibraries()
val dependencies = additionalDependencies + libraries
val path = moduleRoot.joinPath("BUILD.bazel")
private fun createSetOfLibraries(): Set<GmavenBazelDependency> {
return mutableSetOf(
GmavenBazelDependency("com.android.support:appcompat-v7:aar:28.0.0"),
GmavenBazelDependency("com.android.support.constraint:constraint-layout:aar:1.1.3"),
GmavenBazelDependency("com.android.support:multidex:aar:1.0.3"),
GmavenBazelDependency("com.android.support.test:runner:aar:1.0.2"),
GmavenBazelDependency("com.android.support.test.espresso:espresso-core:aar:3.0.2"))
}
}
| aspoet/src/main/kotlin/com/google/androidstudiopoet/models/AndroidBuildBazelBlueprint.kt | 1365471803 |
/*
* 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 org.jetbrains.intellij.build.images
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.util.text.StringUtil
import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes
import org.jetbrains.jps.model.module.JpsModule
import org.jetbrains.jps.model.module.JpsModuleSourceRoot
import java.io.File
import java.util.*
import java.util.regex.Matcher
import java.util.regex.Pattern
internal class ImagePaths(val id: String, val sourceRoot: JpsModuleSourceRoot, val used: Boolean, val deprecated: Boolean) {
var files: MutableMap<ImageType, File> = HashMap()
var ambiguous: Boolean = false
val file: File? get() = files[ImageType.BASIC]
val presentablePath: File get() = file ?: files.values.first() ?: File("<unknown>")
}
internal class ImageCollector(val projectHome: File, val iconsOnly: Boolean = true, val ignoreSkipTag: Boolean = false) {
private val result = HashMap <String, ImagePaths>()
private val usedIconsRobots: MutableSet<File> = HashSet()
fun collect(module: JpsModule): List<ImagePaths> {
module.sourceRoots.forEach {
processRoot(it)
}
return result.values.toList()
}
fun printUsedIconRobots() {
usedIconsRobots.forEach {
println("Found icon-robots: $it")
}
}
private fun processRoot(sourceRoot: JpsModuleSourceRoot) {
val root = sourceRoot.file
if (!root.exists()) return
if (!JavaModuleSourceRootTypes.PRODUCTION.contains(sourceRoot.rootType)) return
val iconsRoot = downToRoot(root)
if (iconsRoot == null) return
val rootRobotData = upToProjectHome(root)
if (rootRobotData.isSkipped(root)) return
val robotData = rootRobotData.fork(iconsRoot, root)
processDirectory(iconsRoot, sourceRoot, robotData, emptyList<String>())
}
private fun processDirectory(dir: File, sourceRoot: JpsModuleSourceRoot, robotData: IconRobotsData, prefix: List<String>) {
dir.children.forEach { file ->
if (robotData.isSkipped(file)) return@forEach
if (file.isDirectory) {
val root = sourceRoot.file
val childRobotData = robotData.fork(file, root)
val childPrefix = prefix + file.name
processDirectory(file, sourceRoot, childRobotData, childPrefix)
}
else if (isImage(file, iconsOnly)) {
processImageFile(file, sourceRoot, robotData, prefix)
}
}
}
private fun processImageFile(file: File, sourceRoot: JpsModuleSourceRoot, robotData: IconRobotsData, prefix: List<String>) {
val nameWithoutExtension = FileUtil.getNameWithoutExtension(file.name)
val type = ImageType.fromName(nameWithoutExtension)
val id = type.getBasicName((prefix + nameWithoutExtension).joinToString("/"))
val skipped = robotData.isSkipped(file)
val used = robotData.isUsed(file)
val deprecated = robotData.isDeprecated(file)
if (skipped) return
val iconPaths = result.computeIfAbsent(id, { ImagePaths(id, sourceRoot, used, deprecated) })
if (type !in iconPaths.files) {
iconPaths.files[type] = file
}
else {
iconPaths.ambiguous = true
}
}
private fun upToProjectHome(dir: File): IconRobotsData {
if (FileUtil.filesEqual(dir, projectHome)) return IconRobotsData()
val parent = dir.parentFile ?: return IconRobotsData()
return upToProjectHome(parent).fork(parent, projectHome)
}
private fun downToRoot(dir: File): File? {
val answer = downToRoot(dir, dir, null, IconRobotsData())
return if (answer == null || answer.isDirectory) answer else answer.parentFile
}
private fun downToRoot(root: File, file: File, common: File?, robotData: IconRobotsData): File? {
if (robotData.isSkipped(file)) return common
if (file.isDirectory) {
val childRobotData = robotData.fork(file, root)
var childCommon = common
file.children.forEach {
childCommon = downToRoot(root, it, childCommon, childRobotData)
}
return childCommon
}
else if (isImage(file, iconsOnly)) {
if (common == null) return file
return FileUtil.findAncestor(common, file)
}
else {
return common
}
}
private inner class IconRobotsData(private val parent: IconRobotsData? = null) {
private val skip: MutableSet<Matcher> = HashSet()
private val used: MutableSet<Matcher> = HashSet()
private val deprecated: MutableSet<Matcher> = HashSet()
fun isSkipped(file: File): Boolean = !ignoreSkipTag && (matches(file, skip) || parent?.isSkipped(file) ?: false)
fun isUsed(file: File): Boolean = matches(file, used) || parent?.isUsed(file) ?: false
fun isDeprecated(file: File): Boolean = matches(file, deprecated) || parent?.isDeprecated(file) ?: false
fun fork(dir: File, root: File): IconRobotsData {
val robots = File(dir, "icon-robots.txt")
if (!robots.exists()) return this
usedIconsRobots.add(robots)
val answer = IconRobotsData(this)
parse(robots,
Pair("skip:", { value -> compilePattern(answer.skip, dir, root, value) }),
Pair("used:", { value -> compilePattern(answer.used, dir, root, value) }),
Pair("deprecated:", { value -> compilePattern(answer.deprecated, dir, root, value) }),
Pair("name:", { value -> }), // ignore
Pair("#", { value -> }) // comment
)
return answer
}
private fun parse(robots: File, vararg handlers: Pair<String, (String) -> Unit>) {
robots.forEachLine { line ->
if (line.isBlank()) return@forEachLine
for (h in handlers) {
if (line.startsWith(h.first)) {
h.second(StringUtil.trimStart(line, h.first))
return@forEachLine
}
}
throw Exception("Can't parse $robots. Line: $line")
}
}
private fun compilePattern(set: MutableSet<Matcher>, dir: File, root: File, value: String) {
var pattern = value.trim()
if (pattern.startsWith("/")) {
pattern = root.absolutePath + pattern
}
else {
pattern = dir.absolutePath + '/' + pattern
}
val regExp = FileUtil.convertAntToRegexp(pattern, false)
try {
set.add(Pattern.compile(regExp).matcher(""))
}
catch (e: Exception) {
throw Exception("Cannot compile pattern: $pattern. Built on based in $dir/icon-robots.txt")
}
}
private fun matches(file: File, matcher: Set<Matcher>): Boolean {
val path = file.absolutePath.replace('\\', '/')
val pathWithoutExtension = FileUtilRt.getNameWithoutExtension(path)
val extension = FileUtilRt.getExtension(path)
val basicPathWithoutExtension = ImageType.stripSuffix(pathWithoutExtension)
val basicPath = basicPathWithoutExtension + if (extension.isNotEmpty()) "." + extension else ""
return matcher.any { it.reset(basicPath).matches() }
}
}
} | platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/ImageCollector.kt | 1809513243 |
package com.lasthopesoftware.bluewater.shared.policies.caching
import com.lasthopesoftware.bluewater.shared.policies.ApplyExecutionPolicies
import com.namehillsoftware.handoff.promises.Promise
class CachingPolicyFactory : ApplyExecutionPolicies {
override fun <Input : Any, Output> applyPolicy(function: (Input) -> Promise<Output>): (Input) -> Promise<Output> {
val functionCache = PermanentPromiseFunctionCache<Input, Output>()
return { input -> functionCache.getOrAdd(input, function) }
}
override fun <In1 : Any, In2 : Any, Output> applyPolicy(function: (In1, In2) -> Promise<Output>): (In1, In2) -> Promise<Output> {
val functionCache = PermanentPromiseFunctionCache<Pair<In1, In2>, Output>()
return { in1, in2 -> functionCache.getOrAdd(Pair(in1, in2)) { (in1, in2) -> function(in1, in2) } }
}
}
| projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/shared/policies/caching/CachingPolicyFactory.kt | 780972297 |
package za.org.grassroot2.presenter.fragment
import timber.log.Timber
import javax.inject.Inject
import za.org.grassroot2.database.DatabaseService
import za.org.grassroot2.model.Group
import za.org.grassroot2.model.enums.GrassrootEntityType
import za.org.grassroot2.view.FragmentView
class ItemCalledPresenter @Inject
constructor(private val databaseService: DatabaseService) : BaseFragmentPresenter<ItemCalledPresenter.MeetingCalledView>() {
fun loadGroupData(groupUid: String, type: GrassrootEntityType) {
disposableOnDetach(databaseService.load(Group::class.java, groupUid)
.subscribe({ group -> view.showDescription(group.memberCount, type) }, { Timber.e(it) }))
}
override fun onViewCreated() {}
interface MeetingCalledView : FragmentView {
fun showDescription(memberCount: Int?, type: GrassrootEntityType)
}
}
| app/src/main/java/za/org/grassroot2/presenter/fragment/ItemCalledPresenter.kt | 1711236656 |
package com.lasthopesoftware.bluewater.client.connection.selected
import java.util.concurrent.locks.ReentrantLock
class SelectedConnectionReservation : AutoCloseable {
companion object {
private val lock = ReentrantLock()
}
init { lock.lock() }
override fun close() = lock.unlock()
}
| projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/connection/selected/SelectedConnectionReservation.kt | 3945141057 |
/*
BusTO - Data components
Copyright (C) 2022 Fabio Mazza
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 it.reyboz.bustorino.data.gtfs
import androidx.room.*
import it.reyboz.bustorino.backend.Stop
@Entity(tableName = MatoPattern.TABLE_NAME,
foreignKeys = [
ForeignKey(entity = GtfsRoute::class,
parentColumns = [GtfsRoute.COL_ROUTE_ID],
childColumns = [MatoPattern.COL_ROUTE_ID],
onDelete = ForeignKey.CASCADE,
)
]
)
data class MatoPattern(
@ColumnInfo(name= COL_NAME)
val name: String,
@ColumnInfo(name= COL_CODE)
@PrimaryKey
val code: String,
@ColumnInfo(name= COL_SEMANTIC_HASH)
val semanticHash: String,
@ColumnInfo(name= COL_DIRECTION_ID)
val directionId: Int,
@ColumnInfo(name= COL_ROUTE_ID)
val routeGtfsId: String,
@ColumnInfo(name= COL_HEADSIGN)
var headsign: String?,
@ColumnInfo(name= COL_GEOMETRY_POLY)
val patternGeometryPoly: String,
@ColumnInfo(name= COL_GEOMETRY_LENGTH)
val patternGeometryLength: Int,
@Ignore
val stopsGtfsIDs: ArrayList<String>
):GtfsTable{
@Ignore
val servingStops= ArrayList<Stop>(4)
constructor(
name: String, code:String,
semanticHash: String, directionId: Int,
routeGtfsId: String, headsign: String?,
patternGeometryPoly: String, patternGeometryLength: Int
): this(name, code, semanticHash, directionId, routeGtfsId, headsign, patternGeometryPoly, patternGeometryLength, ArrayList<String>(4))
companion object{
const val TABLE_NAME="mato_patterns"
const val COL_NAME="pattern_name"
const val COL_CODE="pattern_code"
const val COL_ROUTE_ID="pattern_route_id"
const val COL_SEMANTIC_HASH="pattern_hash"
const val COL_DIRECTION_ID="pattern_direction_id"
const val COL_HEADSIGN="pattern_headsign"
const val COL_GEOMETRY_POLY="pattern_polyline"
const val COL_GEOMETRY_LENGTH="pattern_polylength"
val COLUMNS = arrayOf(
COL_NAME,
COL_CODE,
COL_ROUTE_ID,
COL_SEMANTIC_HASH,
COL_DIRECTION_ID,
COL_HEADSIGN,
COL_GEOMETRY_POLY,
COL_GEOMETRY_LENGTH
)
}
override fun getColumns(): Array<String> {
return COLUMNS
}
}
//DO NOT USE EMBEDDED!!! -> copies all data
@Entity(tableName=PatternStop.TABLE_NAME,
primaryKeys = [
PatternStop.COL_PATTERN_ID,
PatternStop.COL_STOP_GTFS,
PatternStop.COL_ORDER
],
foreignKeys = [
ForeignKey(entity = MatoPattern::class,
parentColumns = [MatoPattern.COL_CODE],
childColumns = [PatternStop.COL_PATTERN_ID],
onDelete = ForeignKey.CASCADE
)
]
)
data class PatternStop(
@ColumnInfo(name= COL_PATTERN_ID)
val patternId: String,
@ColumnInfo(name=COL_STOP_GTFS)
val stopGtfsId: String,
@ColumnInfo(name=COL_ORDER)
val order: Int,
){
companion object{
const val TABLE_NAME="patterns_stops"
const val COL_PATTERN_ID="pattern_gtfs_id"
const val COL_STOP_GTFS="stop_gtfs_id"
const val COL_ORDER="stop_order"
}
}
data class MatoPatternWithStops(
@Embedded val pattern: MatoPattern,
@Relation(
parentColumn = MatoPattern.COL_CODE,
entityColumn = PatternStop.COL_PATTERN_ID,
)
var stopsIndices: List<PatternStop>)
{
init {
stopsIndices = stopsIndices.sortedBy { p-> p.order }
}
} | src/it/reyboz/bustorino/data/gtfs/MatoPattern.kt | 3000145145 |
package com.nextfaze.devfun.compiler
import com.squareup.kotlinpoet.CodeBlock
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.TypeName
import com.squareup.kotlinpoet.WildcardTypeName.Companion.STAR
import com.squareup.kotlinpoet.WildcardTypeName.Companion.subtypeOf
import com.squareup.kotlinpoet.WildcardTypeName.Companion.supertypeOf
import com.squareup.kotlinpoet.asTypeName
import javax.lang.model.element.AnnotationMirror
import javax.lang.model.element.AnnotationValue
import javax.lang.model.element.Element
import javax.lang.model.element.Modifier
import javax.lang.model.element.Name
import javax.lang.model.element.TypeElement
import javax.lang.model.type.ArrayType
import javax.lang.model.type.DeclaredType
import javax.lang.model.type.ExecutableType
import javax.lang.model.type.NoType
import javax.lang.model.type.NullType
import javax.lang.model.type.PrimitiveType
import javax.lang.model.type.TypeMirror
import javax.lang.model.type.TypeVariable
import javax.lang.model.type.WildcardType
import javax.lang.model.util.Elements
import kotlin.reflect.KCallable
import kotlin.reflect.KClass
internal inline val Element.isPublic get() = modifiers.contains(Modifier.PUBLIC)
internal inline val Element.isStatic get() = modifiers.contains(Modifier.STATIC)
internal inline val Element.isProperty get() = isStatic && simpleName.endsWith("\$annotations")
internal inline val TypeMirror.isPrimitive get() = kind.isPrimitive
internal val TypeMirror.isClassPublic: Boolean
get() {
return when (this) {
is PrimitiveType -> true
is DeclaredType -> (asElement() as TypeElement).isClassPublic && typeArguments.all { it.isClassPublic } && asElement().enclosingElement.asType().isClassPublic
is ExecutableType -> returnType.isClassPublic && parameterTypes.all { it.isClassPublic } && typeVariables.all { it.isClassPublic }
is ArrayType -> componentType.isClassPublic
is WildcardType -> extendsBound?.isClassPublic != false && superBound?.isClassPublic != false
is TypeVariable -> upperBound?.isClassPublic != false && lowerBound?.isClassPublic != false
is NoType -> true
is NullType -> true
else -> throw RuntimeException("isClassPublic not implemented for $this (${this::class})")
}
}
internal inline val TypeElement.isClassPublic: Boolean
get() {
var element = this
while (true) {
if (!element.isPublic) return false
element = element.enclosingElement as? TypeElement ?: return true // hit package
}
}
internal inline operator fun <reified T : Any> AnnotationMirror.get(callable: KCallable<T>) =
elementValues.filter { it.key.simpleName.toString() == callable.name }.values.singleOrNull()?.value as T?
internal inline operator fun <reified T : Any> AnnotationMirror.get(name: String): T? {
val v = elementValues.filter { it.key.simpleName.toString() == name }.values.singleOrNull()?.value
return if (v is List<*>) {
when {
T::class == IntArray::class -> v.map { (it as AnnotationValue).value as Int }.toTypedArray().toIntArray() as T
T::class == Array<String>::class -> v.map { (it as AnnotationValue).value as String }.toTypedArray() as T
else -> throw NotImplementedError("$this.get($name) for ${T::class} not implemented.")
}
} else {
v as T?
}
}
internal inline operator fun <reified T : Annotation> AnnotationMirror.get(callable: KCallable<T>) =
elementValues.filter { it.key.simpleName.toString() == callable.name }.values.singleOrNull()?.value as AnnotationMirror?
internal operator fun <K : KClass<*>> AnnotationMirror.get(
callable: KCallable<K>,
orDefault: (() -> DeclaredType?)? = null
): DeclaredType? {
val entry = elementValues.filter { it.key.simpleName.toString() == callable.name }.entries.singleOrNull() ?: return orDefault?.invoke()
return (entry.value.value ?: orDefault?.invoke()) as DeclaredType?
}
internal fun Name.stripInternal() = toString().substringBefore("\$")
internal fun CharSequence.escapeDollar() = toString().replace("\$", "\\\$")
internal val TypeMirror.isPublic: Boolean
get() = when (this) {
is PrimitiveType -> true
is ArrayType -> this.componentType.isPublic
is TypeVariable -> this.upperBound.isPublic
is DeclaredType -> this.asElement().isPublic && this.typeArguments.all { it.isPublic } && this.asElement().enclosingElement.asType().isPublic
is WildcardType -> this.extendsBound?.isPublic ?: true && this.superBound?.isPublic ?: true
is ExecutableType -> returnType.isPublic && parameterTypes.all { it.isPublic } && typeVariables.all { it.isPublic }
is NoType -> true
else -> throw NotImplementedError("TypeMirror.isPublic not implemented for this=$this (${this::class})")
}
internal fun Element.getAnnotation(typeElement: TypeElement): AnnotationMirror? =
annotationMirrors.singleOrNull { it.annotationType.toString() == typeElement.qualifiedName.toString() }
internal fun TypeMirror.toKClassBlock(
kotlinClass: Boolean = true,
isKtFile: Boolean = false,
castIfNotPublic: TypeName? = null,
elements: Elements
): CodeBlock {
if (!isKtFile && isClassPublic) {
val suffix = when {
kotlinClass -> ""
isPrimitiveObject -> ".javaObjectType"
else -> ".java"
}
fun TypeMirror.toType(): TypeName =
when (this) {
is PrimitiveType -> asTypeName()
is DeclaredType -> className
is ArrayType -> when {
componentType.isPrimitive -> (componentType as PrimitiveType).arrayTypeName
else -> TypeNames.array.parameterizedBy(componentType.toType())
}
else -> throw NotImplementedError("TypeMirror.toTypeName not implemented for this=$this (${this::class})")
}
return CodeBlock.of("%T::class$suffix", toType())
}
return when (this) {
is DeclaredType -> {
val suffix = if (kotlinClass) ".kotlin" else ""
val type = asElement() as TypeElement
val binaryName = elements.getBinaryName(type).escapeDollar()
if (castIfNotPublic != null) {
CodeBlock.of("Class.forName(\"$binaryName\")$suffix as %T", castIfNotPublic)
} else {
CodeBlock.of("Class.forName(\"$binaryName\")$suffix")
}
}
is ArrayType -> CodeBlock.of(
"java.lang.reflect.Array.newInstance(%L, 0)::class",
componentType.toKClassBlock(kotlinClass = false, elements = elements)
)
else -> throw NotImplementedError("TypeMirror.toCodeBlock not implemented for this=$this (${this::class})")
}
}
private val TypeMirror.isPrimitiveObject
get() = this is DeclaredType &&
when (toString()) {
"java.lang.Boolean",
"java.lang.Character",
"java.lang.Byte",
"java.lang.Short",
"java.lang.Integer",
"java.lang.Float",
"java.lang.Long",
"java.lang.Double",
"java.lang.Void" -> true
else -> false
}
internal fun TypeMirror.toTypeName(subtypeArrayVariance: Boolean = false): TypeName = when (this) {
is PrimitiveType -> asTypeName()
is ArrayType -> when {
componentType.isPrimitive -> (componentType as PrimitiveType).arrayTypeName
// We need this when getting the typeName for use as a property return type as we can't actually know the
// variance because we see it as Java "ArrayType[]", not Kotlin "Array<VARIANCE Type>".
// Thus by using "out" in the property's return type, it will always be accepted (though could technically be wrong under certain circumstances)
subtypeArrayVariance -> TypeNames.array.parameterizedBy(subtypeOf(componentType.toTypeName(subtypeArrayVariance)))
else -> TypeNames.array.parameterizedBy(componentType.toTypeName(subtypeArrayVariance))
}
is DeclaredType -> when {
typeArguments.isEmpty() -> className
else -> className.parameterizedBy(*typeArguments.map { it.toTypeName(subtypeArrayVariance) }.toTypedArray())
}
is WildcardType -> extendsBound?.toTypeName(subtypeArrayVariance)?.let { subtypeOf(it) }
?: superBound?.toTypeName(subtypeArrayVariance)?.let { supertypeOf(it) }
?: STAR
is TypeVariable -> upperBound?.toTypeName(subtypeArrayVariance) ?: lowerBound?.toTypeName(subtypeArrayVariance) ?: STAR
else -> throw NotImplementedError("TypeMirror.toTypeName not implemented for this=$this (${this::class})")
}
internal fun TypeName.toCodeBlock() = CodeBlock.of("%T", this)
| devfun-compiler/src/main/java/com/nextfaze/devfun/compiler/AptUtil.kt | 178789301 |
/*
* Copyright 2018-2021 Andrei Heidelbacher <[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 org.chronolens.coupling
import org.chronolens.core.cli.Subcommand
import org.chronolens.core.cli.restrictTo
import org.chronolens.core.model.sourcePath
import org.chronolens.core.repository.Transaction
import org.chronolens.core.serialization.JsonModule
import org.chronolens.coupling.Graph.Subgraph
import java.io.File
internal class DivergentChangeCommand : Subcommand() {
override val help: String get() = """
Loads the persisted repository, builds the temporal coupling graphs for
the analyzed source files, detects the Divergent Change instances,
reports the results to the standard output and dumps the coupling graphs
for each source file in the '.chronolens/divergent-change' directory.
"""
private val maxChangeSet by option<Int>()
.help("the maximum number of changed files in a revision")
.defaultValue(100).restrictTo(min = 1)
private val minRevisions by option<Int>().help(
"the minimum number of revisions of a method or coupling relation"
).defaultValue(5).restrictTo(min = 1)
private val minCoupling by option<Double>()
.help("the minimum temporal coupling between two methods")
.defaultValue(0.1).restrictTo(min = 0.0)
private val minBlobDensity by option<Double>().help(
"the minimum average degree (sum of coupling) of methods in a blob"
).defaultValue(2.5).restrictTo(min = 0.0)
private val maxAntiCoupling by option<Double>().help(
"the maximum degree (sum of coupling) of a method in an anti-blob"
).defaultValue(0.5).restrictTo(min = 0.0)
private val minAntiBlobSize by option<Int>()
.help("the minimum size of an anti-blob")
.defaultValue(10).restrictTo(min = 1)
private val minMetricValue by option<Int>().help(
"""ignore source files that have less blobs / anti-blobs than the
specified limit"""
).defaultValue(0).restrictTo(min = 0)
private fun TemporalContext.aggregateGraphs(): List<Graph> {
val idsByFile = ids.groupBy(String::sourcePath)
return idsByFile.keys.map { path ->
val ids = idsByFile[path].orEmpty().toSet()
buildGraphFrom(path, ids)
}
}
private fun analyze(history: Sequence<Transaction>): Report {
val analyzer = HistoryAnalyzer(maxChangeSet, minRevisions, minCoupling)
val temporalContext = analyzer.analyze(history)
val graphs = temporalContext.aggregateGraphs()
val coloredGraphs = mutableListOf<ColoredGraph>()
val files = mutableListOf<FileReport>()
for (graph in graphs) {
val blobs = graph.findBlobs(minBlobDensity)
val antiBlob = graph.findAntiBlob(maxAntiCoupling, minAntiBlobSize)
coloredGraphs += graph.colorNodes(blobs, antiBlob)
files += FileReport(graph.label, blobs, antiBlob)
}
files.sortByDescending(FileReport::value)
return Report(files, coloredGraphs)
}
override fun run() {
val repository = load()
val report = analyze(repository.getHistory())
val files = report.files.filter { it.value >= minMetricValue }
JsonModule.serialize(System.out, files)
val directory = File(".chronolens", "divergent-change")
for (coloredGraph in report.coloredGraphs) {
val graphDirectory = File(directory, coloredGraph.graph.label)
graphDirectory.mkdirs()
val graphFile = File(graphDirectory, "graph.json")
graphFile.outputStream().use { out ->
JsonModule.serialize(out, coloredGraph)
}
}
}
data class Report(
val files: List<FileReport>,
val coloredGraphs: List<ColoredGraph>,
)
data class FileReport(
val file: String,
val blobs: List<Subgraph>,
val antiBlob: Subgraph?,
) {
val responsibilities: Int = blobs.size + if (antiBlob != null) 1 else 0
val category: String = "SOLID Breakers"
val name: String = "Single Responsibility Breakers"
val value: Int = responsibilities
}
}
private fun Graph.colorNodes(
blobs: List<Subgraph>,
antiBlob: Subgraph?,
): ColoredGraph {
val groups = blobs.map(Subgraph::nodes) + listOfNotNull(antiBlob?.nodes)
return colorNodes(groups)
}
| analyzers/chronolens-coupling/src/main/kotlin/org/chronolens/coupling/DivergentChangeCommand.kt | 1463039082 |
package com.aglushkov.repository.livedata
import androidx.lifecycle.LiveData
class NonNullLiveData<T>(value: T) : LiveData<T>() {
init {
setValue(value)
}
} | repository/src/main/java/com/aglushkov/repository/livedata/NonNullLiveData.kt | 2634732098 |
package com.jawnnypoo.geotune.viewHolder
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.SwitchCompat
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.PopupMenu
import android.widget.TextView
import com.commit451.addendum.recyclerview.bindView
import com.jawnnypoo.geotune.R
import com.jawnnypoo.geotune.data.GeoTune
class GeoTuneViewHolder(view: View) : RecyclerView.ViewHolder(view) {
companion object {
fun inflate(parent: ViewGroup): GeoTuneViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_geofence, parent, false)
return GeoTuneViewHolder(view)
}
}
val card: View by bindView(R.id.card_view)
val name: TextView by bindView(R.id.geotune_name)
val tune: TextView by bindView(R.id.geotune_tune)
val datSwitch: SwitchCompat by bindView(R.id.geotune_switch)
val overflow: ImageView by bindView(R.id.geotune_overflow)
val popupMenu=PopupMenu(view.context, overflow)
init {
popupMenu.menuInflater.inflate(R.menu.geotune_menu, popupMenu.menu)
overflow.setOnClickListener { popupMenu.show() }
}
fun bind(geoTune: GeoTune) {
name.text = geoTune.name
if (geoTune.tuneUri == null) {
tune.text = itemView.context.getString(R.string.default_notification_tone)
} else {
if (geoTune.tuneName == null) {
tune.text = ""
} else {
tune.text = geoTune.tuneName
}
}
datSwitch.isChecked = geoTune.isActive
}
}
| app/src/main/java/com/jawnnypoo/geotune/viewHolder/GeoTuneViewHolder.kt | 2842343277 |
package com.andela.checksmarter.utilities
import com.andela.checksmarter.model.CheckSmarterDup
import com.andela.checksmarter.model.CheckSmarterJava
import com.andela.checksmarter.model.CheckSmarterTaskDup
import com.andela.checksmarter.model.CheckSmarterTaskJava
import io.realm.Realm
/**
* Created by CodeKenn on 21/04/16.
*/
class Exchange {
fun getParcelableCheckSmarter(checkSmarter: CheckSmarterJava): CheckSmarterDup {
var newCheckSmarter = CheckSmarterDup()
newCheckSmarter.id = checkSmarter.id
newCheckSmarter.title = checkSmarter.title
newCheckSmarter.isCheck = checkSmarter.isCheck
newCheckSmarter.isAlarm = checkSmarter.isAlarm
newCheckSmarter.alarmValue = checkSmarter.alarmValue
newCheckSmarter.timeValue = checkSmarter.timeValue
checkSmarter.tasks.forEach {
var newCheckSmarterTask = CheckSmarterTaskDup()
newCheckSmarterTask.id = it.id
newCheckSmarterTask.title = it.title
newCheckSmarterTask.isCheck = it.isCheck
newCheckSmarter.tasks.add(newCheckSmarterTask)
}
return newCheckSmarter
}
fun getRealmCheckSmarter(checkSmarter: CheckSmarterDup): CheckSmarterJava {
var newCheckSmarter = CheckSmarterJava()
newCheckSmarter.id = checkSmarter.id
newCheckSmarter.title = checkSmarter.title
newCheckSmarter.isCheck = checkSmarter.isCheck
newCheckSmarter.isAlarm = checkSmarter.isAlarm
newCheckSmarter.alarmValue = checkSmarter.alarmValue
newCheckSmarter.timeValue = checkSmarter.timeValue
checkSmarter.tasks.forEach {
var newCheckSmarterTask = CheckSmarterTaskJava()
newCheckSmarterTask.id = it.id
newCheckSmarterTask.title = it.title
newCheckSmarterTask.isCheck = it.isCheck
newCheckSmarter.tasks.add(newCheckSmarterTask)
}
return newCheckSmarter
}
} | app/src/main/kotlin/com/andela/checksmarter/utilities/Exchange.kt | 2755281585 |
/*
* Copyright (C) 2017 Andrzej Ressel ([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 <https://www.gnu.org/licenses/>.
*/
package com.jereksel.libresubstratum.views
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.DragEvent
import android.view.MotionEvent
import android.view.View
import android.widget.SeekBar
class ColorView: View {
constructor(context: Context?) : super(context)
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes)
val paint = Paint()
var colors = listOf<Int>()
//For edit mode
val rainbow = listOf(
Color.RED,
Color.parseColor("#FF7F00"),
Color.YELLOW,
Color.GREEN,
Color.BLUE,
Color.parseColor("#4B0082"),
Color.parseColor("#8F00FF")
)
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
val colors = if (isInEditMode) {
rainbow
} else if(!colors.isEmpty()) {
colors
} else {
listOf(Color.TRANSPARENT)
}
val blockSize = width/colors.size.toFloat()
colors.forEachIndexed { index, color ->
val start = index*blockSize
val end = (index + 1)*blockSize
paint.color = color
canvas.drawRect(start, 0f, end, height.toFloat(), paint)
}
//
// SeekBar(context).draw(canvas)
}
override fun onTouchEvent(event: MotionEvent) = true
override fun onDragEvent(event: DragEvent?) = true
} | app/src/main/kotlin/com/jereksel/libresubstratum/views/ColorView.kt | 3522734492 |
package com.soywiz.vitaorganizer.i18n
import com.soywiz.vitaorganizer.TextFormatter
import org.junit.Assert
import org.junit.Test
class TextFormatterTest {
@Test
fun testFormat() {
Assert.assertEquals(
"hello 1 %a% hello",
TextFormatter.format("hello %test% %a% %b%", mapOf("test" to 1, "b" to "hello"))
)
//Assert.assertEquals(1, 2)
}
} | test/com/soywiz/vitaorganizer/i18n/TextFormatterTest.kt | 3184938765 |
package com.github.pgutkowski.kgraphql.schema.dsl
import com.github.pgutkowski.kgraphql.Context
import com.github.pgutkowski.kgraphql.schema.model.FunctionWrapper
import com.github.pgutkowski.kgraphql.schema.model.InputValueDef
import com.github.pgutkowski.kgraphql.schema.model.PropertyDef
import com.github.pgutkowski.kgraphql.schema.model.TypeDef
import java.lang.IllegalArgumentException
class UnionPropertyDSL<T : Any>(val name : String, block: UnionPropertyDSL<T>.() -> Unit) : LimitedAccessItemDSL<T>(), ResolverDSL.Target {
init {
block()
}
internal lateinit var functionWrapper : FunctionWrapper<Any?>
lateinit var returnType : TypeID
private val inputValues = mutableListOf<InputValueDef<*>>()
private fun resolver(function: FunctionWrapper<Any?>): ResolverDSL {
functionWrapper = function
return ResolverDSL(this)
}
fun resolver(function: (T) -> Any?) = resolver(FunctionWrapper.on(function, true))
fun <E>resolver(function: (T, E) -> Any?) = resolver(FunctionWrapper.on(function, true))
fun <E, W>resolver(function: (T, E, W) -> Any?) = resolver(FunctionWrapper.on(function, true))
fun <E, W, Q>resolver(function: (T, E, W, Q) -> Any?) = resolver(FunctionWrapper.on(function, true))
fun <E, W, Q, A>resolver(function: (T, E, W, Q, A) -> Any?) = resolver(FunctionWrapper.on(function, true))
fun <E, W, Q, A, S>resolver(function: (T, E, W, Q, A, S) -> Any?) = resolver(FunctionWrapper.on(function, true))
fun accessRule(rule: (T, Context) -> Exception?){
val accessRuleAdapter: (T?, Context) -> Exception? = { parent, ctx ->
if (parent != null) rule(parent, ctx) else IllegalArgumentException("Unexpected null parent of kotlin property")
}
this.accessRuleBlock = accessRuleAdapter
}
fun toKQLProperty(union : TypeDef.Union) = PropertyDef.Union<T> (
name = name,
resolver = functionWrapper,
union = union,
description = description,
isDeprecated = isDeprecated,
deprecationReason = deprecationReason,
inputValues = inputValues,
accessRule = accessRuleBlock
)
override fun addInputValues(inputValues: Collection<InputValueDef<*>>) {
this.inputValues.addAll(inputValues)
}
} | src/main/kotlin/com/github/pgutkowski/kgraphql/schema/dsl/UnionPropertyDSL.kt | 1470807665 |
package com.davezhao
import org.junit.Test
import kotlin.test.assertEquals
class HelloTest {
fun getSth(): String {
return "hello"
}
}
| src/test/kotlin/com/davezhao/HelloTest.kt | 2168670167 |
package net.nemerosa.ontrack.service
import net.nemerosa.ontrack.job.*
import net.nemerosa.ontrack.model.metrics.MetricsReexportJobProvider
import net.nemerosa.ontrack.model.structure.RunInfoService
import net.nemerosa.ontrack.model.support.JobProvider
import net.nemerosa.ontrack.model.support.RestorationJobs
import org.springframework.stereotype.Component
/**
* Job used to re-export all run infos into registered listeners.
*/
@Component
class RunInfoRestorationJob(
private val runInfoService: RunInfoService
): JobProvider, Job, MetricsReexportJobProvider {
override fun getStartingJobs(): Collection<JobRegistration> =
listOf(
JobRegistration(
this,
Schedule.NONE // Manually only
)
)
override fun isDisabled(): Boolean = false
override fun getReexportJobKey(): JobKey = key
override fun getKey(): JobKey =
RestorationJobs.RESTORATION_JOB_TYPE.getKey("run-info-restoration")
override fun getDescription(): String = "Run Info Restoration"
override fun getTask() = JobRun { listener ->
runInfoService.restore {
listener.message(it)
}
}
} | ontrack-service/src/main/java/net/nemerosa/ontrack/service/RunInfoRestorationJob.kt | 3277724983 |
package cn.rieon.idea.plugin.AutoSwitchIm.util
import com.intellij.openapi.diagnostic.Logger
import java.awt.SystemColor.text
import java.io.*
import java.util.*
/**
* @author Rieon Ke <rieon></rieon>@rieon.cn>
* *
* @version 1.0.0
* *
* @since 2017/5/19
*/
object InputSourceUtil {
private var inputSources: ArrayList<Pair<String, String>>? = null
private val LOG = Logger.getInstance(InputSourceUtil::class.java)
private var EXEC_PATH: String? = null
private val EXCLUDE_IME = Arrays.asList(
"com.apple.inputmethod.EmojiFunctionRowItem",
"com.baidu.inputmethod.BaiduIM"
)
init {
try {
val execPath = NativeUtil.getLibPath("/native/ImSelect")
if (execPath == null) {
LOG.error("GET EXEC PATH FAILED")
} else {
EXEC_PATH = execPath
LOG.info("LOADED FORM NATIVE UTILS")
LOG.info("CURRENT EXEC PATH " + execPath)
}
} catch (e: IOException) {
e.printStackTrace()
}
}
private fun nativeGetCurrentInputSource(): String {
return execImSelect("c")
}
private fun nativeSwitchToInputSource(inputSourceName: String): Boolean {
execImSelect("s " + inputSourceName)
return true
}
private fun nativeGetAllInputSources(): String {
return execImSelect("l")
}
internal fun execImSelect(command: String): String {
var c: String? = EXEC_PATH;
if (command.isNotEmpty()) {
c = EXEC_PATH + " -" + command
}
LOG.info("EXEC COMMAND " + c)
var result: Process? = null
try {
result = Runtime.getRuntime().exec(c)
} catch (e: IOException) {
LOG.error("EXEC FAILED!")
e.printStackTrace()
}
if (result != null) {
val text = result.inputStream.bufferedReader().use(BufferedReader::readText)
LOG.info("GET EXEC RESULT " + text)
return text
}
return ""
}
val currentInputSource: String
get() {
LOG.info("GET CURRENT INPUT SOURCE")
return nativeGetCurrentInputSource()
}
fun switchTo(source: String): Boolean {
LOG.info("SWITCH TO INPUT SOURCE " + source)
return nativeSwitchToInputSource(source)
}
internal fun filterInputSource(source: String): Boolean {
return !EXCLUDE_IME.contains(source)
}
val allInputSources: ArrayList<Pair<String, String>>
get() {
LOG.info("GET ALL INPUT SOURCES")
val originalStr = nativeGetAllInputSources()
val pairStrArr = originalStr.split("\\|".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
inputSources = ArrayList<Pair<String, String>>()
pairStrArr
.map { x -> x.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() }
.filter { filterInputSource(it[0]) }
.forEach { inputSources!!.add(Pair(it[0], it[1])) }
return inputSources as ArrayList<Pair<String, String>>
}
}
| src/main/java/cn/rieon/idea/plugin/AutoSwitchIm/util/InputSourceUtil.kt | 4081057111 |
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.kotlin.backend.konan
import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.GroupingMessageCollector
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.konan.CompilerVersion
import org.jetbrains.kotlin.konan.file.File
import org.jetbrains.kotlin.konan.library.defaultResolver
import org.jetbrains.kotlin.konan.parseCompilerVersion
import org.jetbrains.kotlin.konan.target.Distribution
import org.jetbrains.kotlin.konan.target.KonanTarget
import org.jetbrains.kotlin.library.UnresolvedLibrary
import org.jetbrains.kotlin.library.resolver.impl.libraryResolver
import org.jetbrains.kotlin.library.toUnresolvedLibraries
import org.jetbrains.kotlin.util.Logger
import kotlin.system.exitProcess
class KonanLibrariesResolveSupport(
configuration: CompilerConfiguration,
target: KonanTarget,
distribution: Distribution
) {
private val includedLibraryFiles =
configuration.getList(KonanConfigKeys.INCLUDED_LIBRARIES).map { File(it) }
private val librariesToCacheFiles =
configuration.getList(KonanConfigKeys.LIBRARIES_TO_CACHE).map { File(it) } +
configuration.get(KonanConfigKeys.LIBRARY_TO_ADD_TO_CACHE).let {
if (it.isNullOrEmpty()) emptyList() else listOf(File(it))
}
private val libraryNames = configuration.getList(KonanConfigKeys.LIBRARY_FILES)
private val unresolvedLibraries = libraryNames.toUnresolvedLibraries
private val repositories = configuration.getList(KonanConfigKeys.REPOSITORIES)
private val resolverLogger =
object : Logger {
private val collector = configuration.getNotNull(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY)
override fun warning(message: String)= collector.report(CompilerMessageSeverity.STRONG_WARNING, message)
override fun error(message: String) = collector.report(CompilerMessageSeverity.ERROR, message)
override fun log(message: String) = collector.report(CompilerMessageSeverity.LOGGING, message)
override fun fatal(message: String): Nothing {
collector.report(CompilerMessageSeverity.ERROR, message)
(collector as? GroupingMessageCollector)?.flush()
exitProcess(1)
}
}
private val compatibleCompilerVersions: List<CompilerVersion> =
configuration.getList(KonanConfigKeys.COMPATIBLE_COMPILER_VERSIONS).map { it.parseCompilerVersion() }
private val resolver = defaultResolver(
repositories,
libraryNames.filter { it.contains(File.separator) },
target,
distribution,
compatibleCompilerVersions,
resolverLogger
).libraryResolver()
// We pass included libraries by absolute paths to avoid repository-based resolution for them.
// Strictly speaking such "direct" libraries should be specially handled by the resolver, not by KonanConfig.
// But currently the resolver is in the middle of a complex refactoring so it was decided to avoid changes in its logic.
// TODO: Handle included libraries in KonanLibraryResolver when it's refactored and moved into the big Kotlin repo.
internal val resolvedLibraries = run {
val additionalLibraryFiles = includedLibraryFiles + librariesToCacheFiles
resolver.resolveWithDependencies(
unresolvedLibraries + additionalLibraryFiles.map { UnresolvedLibrary(it.absolutePath, null) },
noStdLib = configuration.getBoolean(KonanConfigKeys.NOSTDLIB),
noDefaultLibs = configuration.getBoolean(KonanConfigKeys.NODEFAULTLIBS),
noEndorsedLibs = configuration.getBoolean(KonanConfigKeys.NOENDORSEDLIBS)
)
}
internal val exportedLibraries =
getExportedLibraries(configuration, resolvedLibraries, resolver.searchPathResolver, report = true)
internal val coveredLibraries =
getCoveredLibraries(configuration, resolvedLibraries, resolver.searchPathResolver)
internal val includedLibraries =
getIncludedLibraries(includedLibraryFiles, configuration, resolvedLibraries)
} | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/KonanLibrariesResolveSupport.kt | 2235946403 |
package org.rust.lang.core.resolve
class RsStubOnlyResolveTest : RsResolveTestBase() {
fun testChildMod() = stubOnlyResolve("""
//- main.rs
mod child;
fn main() {
child::foo();
//^ child.rs
}
//- child.rs
pub fn foo() {}
""")
fun testNestedChildMod() = stubOnlyResolve("""
//- main.rs
mod inner {
pub mod child;
}
fn main() {
inner::child::foo();
//^ inner/child.rs
}
//- inner/child.rs
fn foo() {}
""")
fun testModDecl() = stubOnlyResolve("""
//- main.rs
mod foo;
//^ foo.rs
fn main() {}
//- foo.rs
// Empty file
""")
fun testModDecl2() = stubOnlyResolve("""
//- foo/mod.rs
use bar::Bar;
//^ bar.rs
//- main.rs
mod bar;
mod foo;
fn main() {}
//- bar.rs
struct Bar {}
""")
fun testModDeclPath() = stubOnlyResolve("""
//- main.rs
#[path = "bar/baz/foo.rs"]
mod foo;
//^ bar/baz/foo.rs
fn main() {}
//- bar/baz/foo.rs
fn quux() {}
""")
fun testModDeclPathSuper() = stubOnlyResolve("""
//- bar/baz/quux.rs
fn quux() {
super::main();
} //^ main.rs
//- main.rs
#[path = "bar/baz/quux.rs"]
mod foo;
fn main(){}
""")
fun testModRelative() = stubOnlyResolve("""
//- main.rs
mod sub;
fn main() {
sub::foobar::quux();
} //^ foo.rs
//- sub.rs
#[path="./foo.rs"]
pub mod foobar;
//- foo.rs
fn quux() {}
""")
fun testModRelative2() = stubOnlyResolve("""
//- main.rs
mod sub;
fn main() {
sub::foobar::quux();
} //^ foo.rs
//- sub/mod.rs
#[path="../foo.rs"]
pub mod foobar;
//- foo.rs
pub fn quux() {}
""")
fun testUseFromChild() = stubOnlyResolve("""
//- main.rs
use child::{foo};
mod child;
fn main() {
foo();
} //^ child.rs
//- child.rs
pub fn foo() {}
""")
fun testUseGlobalPath() {
stubOnlyResolve("""
//- foo.rs
fn main() {
::bar::hello();
} //^ bar.rs
//- lib.rs
mod foo;
pub mod bar;
//- bar.rs
pub fn hello() {}
""")
}
// We resolve mod_decls even if the parent module does not own a directory and mod_decl should not be allowed.
// This way, we don't need to know the set of crate roots for resolve, which helps indexing.
// The `mod_decl not allowed here` error is then reported by an annotator.
fun testModDeclNotOwn() = stubOnlyResolve("""
//- foo.rs
pub mod bar;
mod foo {
pub use super::bar::baz;
//^ bar.rs
}
//- bar.rs
pub fn baz() {}
//- main.rs
// Empty file
""")
fun testModDeclWrongPath() = stubOnlyResolve("""
//- main.rs
#[path = "foo/bar/baz/rs"]
mod foo;
//^ unresolved
fn main() {}
""")
fun testModDeclCycle() = stubOnlyResolve("""
//- foo.rs
use quux;
//^ unresolved
#[path="bar.rs"]
mod bar;
//- baz.rs
#[path="foo.rs"]
mod foo;
//- bar.rs
#[path="baz.rs"]
mod baz;
""")
fun testFunctionType() = stubOnlyResolve("""
//- main.rs
mod foo;
struct S { field: u32, }
fn main() { foo::id(S { field: 92 }).field }
//^ main.rs
//- foo.rs
use super::S;
pub fn id(x: S) -> S { x }
""")
fun `test tuple struct`() = stubOnlyResolve("""
//- main.rs
mod foo;
use foo::S;
fn f(s: S) { s.0.bar() }
//^ foo.rs
//- foo.rs
struct S(Bar);
struct Bar;
impl Bar { fn bar(self) {} }
""")
fun `test method call`() = stubOnlyResolve("""
//- main.rs
mod aux;
use aux::S;
fn main() {
let s: S = S;
s.foo();
//^ aux.rs
}
//- aux.rs
pub struct S;
impl S {
pub fn foo(&self) { }
}
""")
fun `test method call on enum`() = stubOnlyResolve("""
//- main.rs
mod aux;
use aux::S;
fn main() {
let s: S = S::X;
s.foo();
//^ aux.rs
}
//- aux.rs
enum S { X }
impl S {
fn foo(&self) { }
}
""")
}
| src/test/kotlin/org/rust/lang/core/resolve/RsStubOnlyResolveTest.kt | 3973439786 |
/*
* Copyright 2018 Google LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.plaidapp.designernews.data.users
import io.plaidapp.core.data.Result
import io.plaidapp.core.designernews.data.users.model.User
import java.io.IOException
/**
* Class that requests users from the remote data source and caches them, in memory.
*/
class UserRepository(private val dataSource: UserRemoteDataSource) {
private val cachedUsers = mutableMapOf<Long, User>()
suspend fun getUsers(ids: Set<Long>): Result<Set<User>> {
// find the ids in the cached users first and only request the ones that we don't have yet
val notCachedUsers = ids.filterNot { cachedUsers.containsKey(it) }
if (notCachedUsers.isNotEmpty()) {
getAndCacheUsers(notCachedUsers)
}
// compute the list of users requested
val users = ids.mapNotNull { cachedUsers[it] }.toSet()
if (users.isNotEmpty()) {
return Result.Success(users)
}
return Result.Error(IOException("Unable to get users"))
}
private suspend fun getAndCacheUsers(userIds: List<Long>) {
val result = dataSource.getUsers(userIds)
// save the new users in the cachedUsers
if (result is Result.Success) {
result.data.forEach { cachedUsers[it.id] = it }
}
}
}
| designernews/src/main/java/io/plaidapp/designernews/data/users/UserRepository.kt | 487304171 |
package io.mockk.impl.recording
import io.mockk.impl.instantiation.AbstractInstantiator
import io.mockk.impl.instantiation.AnyValueGenerator
import io.mockk.core.ValueClassSupport.boxedClass
import java.util.*
import kotlin.reflect.KClass
import kotlin.reflect.full.cast
import kotlin.reflect.full.primaryConstructor
import kotlin.reflect.jvm.isAccessible
class JvmSignatureValueGenerator(val rnd: Random) : SignatureValueGenerator {
override fun <T : Any> signatureValue(
cls: KClass<T>,
anyValueGeneratorProvider: () -> AnyValueGenerator,
instantiator: AbstractInstantiator,
): T {
if (cls.isValue) {
val valueCls = cls.boxedClass
val valueSig = signatureValue(valueCls, anyValueGeneratorProvider, instantiator)
val constructor = cls.primaryConstructor!!.apply { isAccessible = true }
return constructor.call(valueSig)
}
return cls.cast(instantiate(cls, anyValueGeneratorProvider, instantiator))
}
private fun <T : Any> instantiate(
cls: KClass<T>,
anyValueGeneratorProvider: () -> AnyValueGenerator,
instantiator: AbstractInstantiator
): Any = when (cls) {
Boolean::class -> rnd.nextBoolean()
Byte::class -> rnd.nextInt().toByte()
Short::class -> rnd.nextInt().toShort()
Character::class -> rnd.nextInt().toChar()
Integer::class -> rnd.nextInt()
Long::class -> rnd.nextLong()
Float::class -> rnd.nextFloat()
Double::class -> rnd.nextDouble()
String::class -> rnd.nextLong().toString(16)
else ->
if (cls.isSealed) {
cls.sealedSubclasses.firstNotNullOfOrNull {
instantiate(it, anyValueGeneratorProvider, instantiator)
} ?: error("Unable to create proxy for sealed class $cls, available subclasses: ${cls.sealedSubclasses}")
} else {
@Suppress("UNCHECKED_CAST")
anyValueGeneratorProvider().anyValue(cls, isNullable = false) {
instantiator.instantiate(cls)
} as T
}
}
}
| modules/mockk/src/jvmMain/kotlin/io/mockk/impl/recording/JvmSignatureValueGenerator.kt | 903156099 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.fabric.reference
import com.demonwav.mcdev.util.manipulator
import com.demonwav.mcdev.util.reference.InspectionReference
import com.intellij.json.psi.JsonStringLiteral
import com.intellij.openapi.util.TextRange
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementResolveResult
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiModifier
import com.intellij.psi.PsiPolyVariantReference
import com.intellij.psi.PsiReference
import com.intellij.psi.PsiReferenceBase
import com.intellij.psi.PsiReferenceProvider
import com.intellij.psi.ResolveResult
import com.intellij.util.IncorrectOperationException
import com.intellij.util.ProcessingContext
object EntryPointReference : PsiReferenceProvider() {
override fun getReferencesByElement(element: PsiElement, context: ProcessingContext): Array<PsiReference> {
if (element !is JsonStringLiteral) {
return PsiReference.EMPTY_ARRAY
}
val manipulator = element.manipulator ?: return PsiReference.EMPTY_ARRAY
val range = manipulator.getRangeInElement(element)
val text = element.text.substring(range.startOffset, range.endOffset)
val methodParts = text.split("::", limit = 2)
val clazzParts = methodParts[0].split("$", limit = 0)
val references = mutableListOf<Reference>()
var cursor = -1
var innerClassDepth = -1
for (clazzPart in clazzParts) {
cursor++
innerClassDepth++
references.add(
Reference(
element,
range.cutOut(TextRange.from(cursor, clazzPart.length)),
innerClassDepth,
false
)
)
cursor += clazzPart.length
}
if (methodParts.size == 2) {
cursor += 2
references.add(
Reference(
element,
range.cutOut(TextRange.from(cursor, methodParts[1].length)),
innerClassDepth,
true
)
)
}
return references.toTypedArray()
}
private fun resolveReference(
element: JsonStringLiteral,
innerClassDepth: Int,
isMethodReference: Boolean
): Array<PsiElement> {
val strReference = element.value
val methodParts = strReference.split("::", limit = 2)
// split at dollar sign for inner class evaluation
val clazzParts = methodParts[0].split("$", limit = 0)
// this case should only happen if someone misuses the method, better protect against it anyways
if (innerClassDepth >= clazzParts.size ||
innerClassDepth + 1 < clazzParts.size &&
isMethodReference
) throw IncorrectOperationException("Invalid reference")
var clazz = JavaPsiFacade.getInstance(element.project).findClass(clazzParts[0], element.resolveScope)
?: return PsiElement.EMPTY_ARRAY
// if class is inner class, then a dot "." was used as separator instead of a dollar sign "$", this does not work to reference an inner class
if (clazz.parent is PsiClass) return PsiElement.EMPTY_ARRAY
// walk inner classes
for (inner in clazzParts.drop(1).take(innerClassDepth)) {
// we don't want any dots "." in the names of the inner classes
if (inner.contains('.')) return PsiElement.EMPTY_ARRAY
clazz = clazz.findInnerClassByName(inner, false) ?: return PsiElement.EMPTY_ARRAY
}
return if (isMethodReference) {
if (methodParts.size == 1) {
throw IncorrectOperationException("Invalid reference")
}
clazz.methods.filter { method ->
method.name == methodParts[1] &&
method.hasModifierProperty(PsiModifier.PUBLIC) &&
method.hasModifierProperty(PsiModifier.STATIC)
}.toTypedArray()
} else {
arrayOf(clazz)
}
}
fun isEntryPointReference(reference: PsiReference) = reference is Reference
private class Reference(
element: JsonStringLiteral,
range: TextRange,
private val innerClassDepth: Int,
private val isMethodReference: Boolean
) :
PsiReferenceBase<JsonStringLiteral>(element, range),
PsiPolyVariantReference,
InspectionReference {
override val description = "entry point '%s'"
override val unresolved = resolve() == null
override fun multiResolve(incompleteCode: Boolean): Array<ResolveResult> {
return resolveReference(element, innerClassDepth, isMethodReference)
.map { PsiElementResolveResult(it) }.toTypedArray()
}
override fun resolve(): PsiElement? {
val results = multiResolve(false)
return if (results.size == 1) {
results[0].element
} else {
null
}
}
override fun bindToElement(newTarget: PsiElement): PsiElement? {
val manipulator = element.manipulator ?: return null
val range = manipulator.getRangeInElement(element)
val text = element.text.substring(range.startOffset, range.endOffset)
val parts = text.split("::", limit = 2)
if (isMethodReference) {
val targetMethod = newTarget as? PsiMethod
?: throw IncorrectOperationException("Cannot target $newTarget")
if (parts.size == 1) {
throw IncorrectOperationException("Invalid reference")
}
val methodRange = range.cutOut(TextRange.from(parts[0].length + 2, parts[1].length))
return manipulator.handleContentChange(element, methodRange, targetMethod.name)
} else {
val targetClass = newTarget as? PsiClass
?: throw IncorrectOperationException("Cannot target $newTarget")
val classRange = if (parts.size == 1) {
range
} else {
range.cutOut(TextRange.from(0, parts[0].length))
}
return manipulator.handleContentChange(element, classRange, targetClass.qualifiedName)
}
}
}
}
| src/main/kotlin/platform/fabric/reference/EntryPointReference.kt | 2712170300 |
package com.johnguant.redditthing.redditapi
import com.johnguant.redditthing.redditapi.model.OAuthToken
import retrofit2.Call
import retrofit2.http.Field
import retrofit2.http.FormUrlEncoded
import retrofit2.http.POST
interface AuthService {
@FormUrlEncoded
@POST("https://www.reddit.com/api/v1/access_token")
fun accessToken(@Field("grant_type") grantType: String,
@Field("code") code: String,
@Field("redirect_uri") redirectUri: String): Call<OAuthToken>
@FormUrlEncoded
@POST("https://www.reddit.com/api/v1/access_token")
fun deviceAccessToken(@Field("grant_type") grantType: String,
@Field("device_id") deviceId: String): Call<OAuthToken>
@FormUrlEncoded
@POST("https://www.reddit.com/api/v1/access_token")
fun refreshAccessToken(@Field("grant_type") grantType: String,
@Field("refresh_token") refreshToken: String): Call<OAuthToken>
}
| app/src/main/java/com/johnguant/redditthing/redditapi/AuthService.kt | 1554519828 |
package com.zepp.www.searchfilter
// Created by xubinggui on 01/11/2016.
// _ooOoo_
// o8888888o
// 88" . "88
// (| -_- |)
// O\ = /O
// ____/`---'\____
// . ' \\| |// `.
// / \\||| : |||// \
// / _||||| -:- |||||- \
// | | \\\ - /// | |
// | \_| ''\---/'' | |
// \ .-\__ `-` ___/-. /
// ___`. .' /--.--\ `. . __
// ."" '< `.___\_<|>_/___.' >'"".
// | | : `- \`.;`\ _ /`;.`/ - ` : | |
// \ \ `-. \_ __\ /__ _/ .-` / /
// ======`-.____`-.___\_____/___.-`____.-'======
// `=---='
//
// .............................................
// 佛祖镇楼 BUG辟易
object Constant {
val ANIMATION_DURATION: Long = 400
} | SearchFilter/app/src/main/java/com/zepp/www/searchfilter/Constant.kt | 2856921638 |
package org.ojacquemart.eurobets.firebase.initdb.country
import org.ojacquemart.eurobets.firebase.initdb.i18n.I18n
class CountryFinder {
private val countries = CountriesJsonFileLoader().load()
private val countriesByEnglishCountryName = countries.countries.associateBy({ it.i18n.en }, { it })
fun find(countryName: String): Country {
return countriesByEnglishCountryName.getOrElse(countryName.trim(), { Country(I18n(countryName, countryName), "???") })
}
}
| src/main/kotlin/org/ojacquemart/eurobets/firebase/initdb/country/CountryFinder.kt | 2004652519 |
/*
* Copyright (C) 2017 Artem Hluhovskyi
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
@file:JvmName("SQLiteDatabaseUtils")
package com.dewarder.akommons.database
import android.content.ContentValues
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
inline fun <R> SQLiteDatabase.use(block: (SQLiteDatabase) -> R): R {
var closed = false
try {
return block(this)
} catch (e: Exception) {
closed = true
try {
close()
} catch (closeException: Exception) {
}
throw e
} finally {
if (!closed) {
close()
}
}
}
fun SQLiteDatabase.executeQuery(
table: String,
columns: Array<String>? = null,
selection: String? = null,
selectionArgs: Array<String>? = null,
groupBy: String? = null,
having: String? = null,
orderBy: String? = null,
limit: String? = null
): Cursor = query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit)
fun SQLiteDatabase.executeInsert(
table: String,
nullColumnHack: String? = null,
values: ContentValues
): Long = insert(table, nullColumnHack, values)
fun SQLiteDatabase.executeUpdate(
table: String,
values: ContentValues,
whereClause: String? = null,
whereArgs: Array<String>? = null
): Long = update(table, values, whereClause, whereArgs).toLong()
fun SQLiteDatabase.executeDelete(
table: String,
whereClause: String? = null,
whereArgs: Array<String>? = null
): Long = delete(table, whereClause, whereArgs).toLong() | akommons/src/main/java/com/dewarder/akommons/database/SQLiteDatabase.kt | 3799334452 |
/*
* 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.jetbrains.python
import com.intellij.psi.PsiManager
import com.jetbrains.python.fixtures.PyTestCase
import com.jetbrains.python.psi.LanguageLevel
import com.jetbrains.python.psi.PyFile
import junit.framework.TestCase
/**
* @author traff
*/
class PyUnifiedStubsTest : PyTestCase() {
override fun getTestDataPath(): String {
return PythonTestUtil.getTestDataPath()
}
fun testExecPy3() {
for (level in LanguageLevel.SUPPORTED_LEVELS) {
runWithLanguageLevel(level) {
val vf = myFixture.copyFileToProject("psi/${getTestName(false)}.py")
val file = PsiManager.getInstance(myFixture.project).findFile(vf) as PyFile
TestCase.assertEquals("Python $level", "exec", file.topLevelFunctions[0].name)
}
}
}
} | python/testSrc/com/jetbrains/python/PyUnifiedStubsTest.kt | 711894849 |
package co.nums.intellij.aem.htl.file
import co.nums.intellij.aem.extensions.isHtlFile
import co.nums.intellij.aem.htl.HtlLanguage
import co.nums.intellij.aem.settings.aemSettings
import com.intellij.lang.Language
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.LanguageSubstitutor
class HtlLanguageSubstitutor : LanguageSubstitutor() {
override fun getLanguage(file: VirtualFile, project: Project): Language? =
if (project.aemSettings?.aemSupportEnabled == true && file.isHtlFile(project)) HtlLanguage
else null
}
| src/main/kotlin/co/nums/intellij/aem/htl/file/HtlLanguageSubstitutor.kt | 2003371941 |
/*
* Copyright (C) 2022 panpf <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.panpf.sketch.decode
import android.graphics.drawable.Drawable
import androidx.annotation.WorkerThread
import com.github.panpf.sketch.ComponentRegistry
import com.github.panpf.sketch.Sketch
import com.github.panpf.sketch.decode.internal.EngineDrawableDecodeInterceptor
import com.github.panpf.sketch.fetch.FetchResult
import com.github.panpf.sketch.request.ImageRequest
import com.github.panpf.sketch.request.internal.RequestContext
/**
* Intercept the execution of [Drawable] decode, you can change the output, register to [ComponentRegistry] to take effect
*/
interface DrawableDecodeInterceptor {
/**
* If the current BitmapDecodeInterceptor will change the DrawableDecodeResult,
* and may only work on part [ImageRequest],
* provide a valid key to build request key and cache key
*/
val key: String?
/**
* For sorting, larger values go lower in the list. It ranges from 0 to 100. It's usually zero.
* Convention 51-100 is the exclusive range for sketch. [EngineDrawableDecodeInterceptor] is 100
*/
val sortWeight: Int
@WorkerThread
suspend fun intercept(chain: Chain): DrawableDecodeResult
interface Chain {
val sketch: Sketch
val request: ImageRequest
val requestContext: RequestContext
val fetchResult: FetchResult?
/**
* Continue executing the chain.
*/
@WorkerThread
suspend fun proceed(): DrawableDecodeResult
}
} | sketch/src/main/java/com/github/panpf/sketch/decode/DrawableDecodeInterceptor.kt | 55854508 |
/*
* Copyright (C) 2022 panpf <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.panpf.sketch.test.decode.internal
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.github.panpf.sketch.decode.internal.ImageFormat
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class ImageFormatTest {
@Test
fun testMimeType() {
Assert.assertEquals("image/jpeg", ImageFormat.JPEG.mimeType)
Assert.assertEquals("image/png", ImageFormat.PNG.mimeType)
Assert.assertEquals("image/webp", ImageFormat.WEBP.mimeType)
Assert.assertEquals("image/gif", ImageFormat.GIF.mimeType)
Assert.assertEquals("image/bmp", ImageFormat.BMP.mimeType)
Assert.assertEquals("image/heic", ImageFormat.HEIC.mimeType)
Assert.assertEquals("image/heif", ImageFormat.HEIF.mimeType)
}
@Test
fun testMimeTypeToImageFormat() {
Assert.assertEquals(ImageFormat.JPEG, ImageFormat.parseMimeType("image/jpeg"))
Assert.assertEquals(ImageFormat.JPEG, ImageFormat.parseMimeType("IMAGE/JPEG"))
Assert.assertEquals(ImageFormat.PNG, ImageFormat.parseMimeType("image/png"))
Assert.assertEquals(ImageFormat.PNG, ImageFormat.parseMimeType("IMAGE/PNG"))
Assert.assertEquals(ImageFormat.WEBP, ImageFormat.parseMimeType("image/webp"))
Assert.assertEquals(ImageFormat.WEBP, ImageFormat.parseMimeType("IMAGE/WEBP"))
Assert.assertEquals(ImageFormat.GIF, ImageFormat.parseMimeType("image/gif"))
Assert.assertEquals(ImageFormat.GIF, ImageFormat.parseMimeType("IMAGE/GIF"))
Assert.assertEquals(ImageFormat.BMP, ImageFormat.parseMimeType("image/bmp"))
Assert.assertEquals(ImageFormat.BMP, ImageFormat.parseMimeType("IMAGE/BMP"))
Assert.assertEquals(ImageFormat.HEIC, ImageFormat.parseMimeType("image/heic"))
Assert.assertEquals(ImageFormat.HEIC, ImageFormat.parseMimeType("IMAGE/HEIC"))
Assert.assertEquals(ImageFormat.HEIF, ImageFormat.parseMimeType("image/heif"))
Assert.assertEquals(ImageFormat.HEIF, ImageFormat.parseMimeType("IMAGE/HEIF"))
Assert.assertNull(ImageFormat.parseMimeType("image/jpeg1"))
Assert.assertNull(ImageFormat.parseMimeType("IMAGE/JPEG1"))
}
} | sketch/src/androidTest/java/com/github/panpf/sketch/test/decode/internal/ImageFormatTest.kt | 2306515815 |
package world.player.skill.crafting.battlestaffCrafting
import io.luna.game.model.item.Item
/**
* An enum representing battlestaves that can be made.
*/
enum class Battlestaff(val staff: Int,
val level: Int,
val orb: Int,
val exp: Double) {
WATER(staff = 1395,
level = 54,
orb = 571,
exp = 100.0),
EARTH(staff = 1399,
level = 58,
orb = 575,
exp = 112.5),
FIRE(staff = 1393,
level = 62,
orb = 569,
exp = 125.0),
AIR(staff = 1397,
level = 66,
orb = 573,
exp = 137.5);
companion object {
/**
* The battlestaff identifier.
*/
const val BATTLESTAFF = 1391
/**
* The battlestaff item.
*/
val BATTLESTAFF_ITEM = Item(BATTLESTAFF)
/**
* Mappings of [Battlestaff.orb] to [Battlestaff].
*/
val ORB_TO_BATTLESTAFF = values().associateBy { it.orb }
}
/**
* The staff item.
*/
val staffItem = Item(staff)
/**
* The orb item.
*/
val orbItem = Item(orb)
} | plugins/world/player/skill/crafting/battlestaffCrafting/Battlestaff.kt | 1703129154 |
package com.tamsiree.rxdemo.activity
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import com.tamsiree.rxdemo.R
import com.tamsiree.rxdemo.tools.EvaluatorARGB.Companion.instance
import com.tamsiree.rxkit.RxDeviceTool
import com.tamsiree.rxui.activity.ActivityBase
import com.tamsiree.rxui.view.loadingview.SpinKitView
import com.tamsiree.rxui.view.loadingview.SpriteFactory
import com.tamsiree.rxui.view.loadingview.Style
/**
* @author tamsiree
*/
class ActivityLoadingDetail : ActivityBase() {
var colors = intArrayOf(
Color.parseColor("#D55400"),
Color.parseColor("#2B3E51"),
Color.parseColor("#00BD9C"),
Color.parseColor("#227FBB"),
Color.parseColor("#7F8C8D"),
Color.parseColor("#FFCC5C"),
Color.parseColor("#D55400"),
Color.parseColor("#1AAF5D"))
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_loading_detail)
RxDeviceTool.setPortrait(this)
}
override fun initView() {
val viewPager = findViewById<ViewPager>(R.id.view_pager)
viewPager.offscreenPageLimit = 0
viewPager.adapter = object : PagerAdapter() {
override fun getCount(): Int {
return Style.values().size
}
override fun isViewFromObject(view: View, `object`: Any): Boolean {
return view === `object`
}
override fun instantiateItem(container: ViewGroup, position: Int): Any {
@SuppressLint("InflateParams") val view = LayoutInflater.from(container.context).inflate(R.layout.item_pager, null)
val spinKitView: SpinKitView = view.findViewById(R.id.spin_kit)
val name = view.findViewById<TextView>(R.id.name)
val style = Style.values()[position]
name.text = style.name
val drawable = SpriteFactory.create(style)
spinKitView.setIndeterminateDrawable(drawable!!)
container.addView(view)
return view
}
override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
container.removeView(`object` as View)
}
}
viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
val color = instance.evaluate(positionOffset,
colors[position % colors.size],
colors[(position + 1) % colors.size]) as Int
window.decorView.setBackgroundColor(color)
}
override fun onPageSelected(position: Int) {
window.decorView.setBackgroundColor(colors[position % colors.size])
}
override fun onPageScrollStateChanged(state: Int) {}
})
viewPager.currentItem = intent.getIntExtra("position", 0)
}
override fun initData() {
}
companion object {
fun start(context: Context, position: Int) {
val intent = Intent(context, ActivityLoadingDetail::class.java)
intent.putExtra("position", position)
context.startActivity(intent)
}
}
} | RxDemo/src/main/java/com/tamsiree/rxdemo/activity/ActivityLoadingDetail.kt | 1150344934 |
package dolvic.gw2.api.mechanics
data class TrainingTrack(
val cost: Int,
val type: TrackType,
val id: Int
)
| types/src/main/kotlin/dolvic/gw2/api/mechanics/TrainingTrack.kt | 3435902239 |
package com.sapuseven.untis.dialogs
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.preference.PreferenceDialogFragmentCompat
import ca.antonious.materialdaypicker.MaterialDayPicker
import ca.antonious.materialdaypicker.SelectionMode
import ca.antonious.materialdaypicker.SelectionState
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.sapuseven.untis.R
import com.sapuseven.untis.preferences.WeekRangePickerPreference
class WeekRangePickerPreferenceDialog(private val onCloseListener: ((positiveResult: Boolean, selectedDays: Int) -> Unit)? = null) : PreferenceDialogFragmentCompat() {
private lateinit var picker: MaterialDayPicker
companion object {
fun newInstance(key: String, onCloseListener: ((positiveResult: Boolean, selectedDays: Int) -> Unit)?): WeekRangePickerPreferenceDialog {
val fragment = WeekRangePickerPreferenceDialog(onCloseListener)
val bundle = Bundle(1)
bundle.putString(ARG_KEY, key)
fragment.arguments = bundle
return fragment
}
}
override fun onCreateDialogView(context: Context?): View {
val root = super.onCreateDialogView(context)
picker = root.findViewById(R.id.day_picker)
picker.apply {
selectionMode = RangeSelectionMode(this)
val savedDays = preference.getPersistedStringSet(emptySet()).toList().map { MaterialDayPicker.Weekday.valueOf(it) }
setSelectedDays(if (savedDays.size == 1) listOf(savedDays.first()) else listOfNotNull(savedDays.minOrNull(), savedDays.maxOrNull()))
}
return root
}
override fun onDialogClosed(positiveResult: Boolean) {
if (positiveResult) preference.persistStringSet(picker.selectedDays.map { it.name }.toSet())
(preference as? WeekRangePickerPreference)?.refreshSummary()
onCloseListener?.invoke(positiveResult, picker.selectedDays.size)
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val builder = MaterialAlertDialogBuilder(requireContext())
.setTitle(preference.dialogTitle)
.setView(onCreateDialogView(context))
.setPositiveButton(preference.positiveButtonText, this)
.setNegativeButton(preference.negativeButtonText, this)
.setNeutralButton(R.string.all_reset) { dialog, _ ->
preference.persistStringSet(emptySet())
onCloseListener?.invoke(true, 0)
dialog.dismiss()
}
return builder.create()
}
class RangeSelectionMode(private val materialDayPicker: MaterialDayPicker) : SelectionMode {
override fun getSelectionStateAfterSelecting(lastSelectionState: SelectionState, dayToSelect: MaterialDayPicker.Weekday): SelectionState {
return createRangedSelectionState(
lastSelectionState = lastSelectionState,
dayPressed = dayToSelect
)
}
override fun getSelectionStateAfterDeselecting(lastSelectionState: SelectionState, dayToDeselect: MaterialDayPicker.Weekday): SelectionState {
return createRangedSelectionState(
lastSelectionState = lastSelectionState,
dayPressed = dayToDeselect
)
}
private fun createRangedSelectionState(lastSelectionState: SelectionState, dayPressed: MaterialDayPicker.Weekday): SelectionState {
val previouslySelectedDays = lastSelectionState.selectedDays
val orderedWeekdays = MaterialDayPicker.Weekday.getOrderedDaysOfWeek(materialDayPicker.locale)
val ordinalsOfPreviouslySelectedDays = previouslySelectedDays.map { orderedWeekdays.indexOf(it) }
val ordinalOfFirstDayInPreviousRange = ordinalsOfPreviouslySelectedDays.minOrNull()
val ordinalOfLastDayInPreviousRange = ordinalsOfPreviouslySelectedDays.maxOrNull()
val ordinalOfSelectedDay = orderedWeekdays.indexOf(dayPressed)
return when {
ordinalOfFirstDayInPreviousRange == null || ordinalOfLastDayInPreviousRange == null -> {
// We had no previous selection so just return the day pressed as the selection.
SelectionState.withSingleDay(dayPressed)
}
ordinalOfFirstDayInPreviousRange == ordinalOfLastDayInPreviousRange && ordinalOfFirstDayInPreviousRange == ordinalOfSelectedDay -> {
// User pressed the only day in the range selection. Return an empty selection.
SelectionState()
}
ordinalOfSelectedDay == ordinalOfFirstDayInPreviousRange || ordinalOfSelectedDay == ordinalOfLastDayInPreviousRange -> {
// User pressed the first or last item in range. Just deselect that item.
lastSelectionState.withDayDeselected(dayPressed)
}
ordinalOfSelectedDay < ordinalOfFirstDayInPreviousRange -> {
// User pressed a day on the left of the previous date range. Grow the starting point of the range to that.
SelectionState(selectedDays = orderedWeekdays.subList(ordinalOfSelectedDay, ordinalOfLastDayInPreviousRange + 1))
}
else -> {
// User pressed a day on the right of the start of the date range. Update the ending point to that position.
SelectionState(selectedDays = orderedWeekdays.subList(ordinalOfFirstDayInPreviousRange, ordinalOfSelectedDay + 1))
}
}
}
}
}
| app/src/main/java/com/sapuseven/untis/dialogs/WeekRangePickerPreferenceDialog.kt | 3646057169 |
/*
* Copyright (c) 2017 by Nicolas Märchy
*
* This file is part of Sporttag PSA.
*
* Sporttag PSA 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.
*
* Sporttag PSA 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 Sporttag PSA. If not, see <http://www.gnu.org/licenses/>.
*
* Diese Datei ist Teil von Sporttag PSA.
*
* Sporttag PSA ist Freie Software: Sie können es unter den Bedingungen
* der GNU General Public License, wie von der Free Software Foundation,
* Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren
* veröffentlichten Version, weiterverbreiten und/oder modifizieren.
*
* Sporttag PSA wird in der Hoffnung, dass es nützlich sein wird, aber
* OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite
* Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK.
* Siehe die GNU General Public License für weitere Details.
*
* Sie sollten eine Kopie der GNU General Public License zusammen mit diesem
* Programm erhalten haben. Wenn nicht, siehe <http://www.gnu.org/licenses/>.
*
*
*/
package ch.schulealtendorf.psa.service.standard.entity
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id
import javax.persistence.Table
import javax.validation.constraints.NotNull
import javax.validation.constraints.Size
/**
* @author nmaerchy
* @since 1.0.0
*/
@Entity
@Table(name = "COACH")
data class CoachEntity(
@Id
@NotNull
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Int? = null,
@NotNull
@Size(min = 1, max = 100)
var name: String = ""
)
| app/psa-runtime-service/psa-service-standard/src/main/kotlin/ch/schulealtendorf/psa/service/standard/entity/CoachEntity.kt | 1978209143 |
package com.bl_lia.kirakiratter.data.repository.datasource.auth
import io.reactivex.Completable
import io.reactivex.Maybe
import io.reactivex.Single
import com.bl_lia.kirakiratter.domain.entity.AuthInfo
import com.bl_lia.kirakiratter.domain.value_object.AccessToken
import com.bl_lia.kirakiratter.domain.value_object.AppCredentials
interface AuthDataStore {
fun authInfo(): Single<AuthInfo>
fun reset(authInfo: AuthInfo): Completable
fun authenticateApp(clientName: String, redirectUri: String, scopes: String, website: String): Single<AppCredentials>
fun accessToken(code: String): Maybe<AccessToken>
fun logout(): Completable
} | app/src/main/kotlin/com/bl_lia/kirakiratter/data/repository/datasource/auth/AuthDataStore.kt | 2476247230 |
package com.stripe.android.payments.core.injection
import com.stripe.android.model.StripeIntent.NextActionData
import com.stripe.android.payments.core.authentication.PaymentAuthenticator
import dagger.MapKey
import javax.inject.Qualifier
import kotlin.reflect.KClass
/**
* [Qualifier] for the multibinding map between [NextActionData] and [PaymentAuthenticator].
*/
@Qualifier
annotation class IntentAuthenticatorMap
/**
* [MapKey] for the [IntentAuthenticatorMap], encapsulating the [NextActionData] class type.
*/
@MapKey
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
annotation class IntentAuthenticatorKey(val value: KClass<out NextActionData>)
| payments-core/src/main/java/com/stripe/android/payments/core/injection/AuthenticationAnnotations.kt | 1182941355 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.demos.focus
import android.annotation.SuppressLint
import androidx.compose.foundation.border
import androidx.compose.foundation.focusable
import androidx.compose.foundation.layout.Arrangement.SpaceEvenly
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.size
import androidx.compose.material.Switch
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.focus.FocusRequester.Companion.Cancel
import androidx.compose.ui.focus.FocusRequester.Companion.Default
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color.Companion.Black
import androidx.compose.ui.graphics.Color.Companion.Red
import androidx.compose.ui.unit.dp
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun CancelFocusDemo() {
Column {
Text("Use the arrow keys to move focus left/right/up/down.")
}
Column(Modifier.fillMaxSize(), SpaceEvenly) {
var blockFocusMove by remember { mutableStateOf(false) }
Row {
Text("Cancel focus moves between 3 and 4")
Switch(checked = blockFocusMove, onCheckedChange = { blockFocusMove = !blockFocusMove })
}
Row(Modifier.fillMaxWidth(), SpaceEvenly) {
Text("1", Modifier.focusableWithBorder())
Text("2", Modifier.focusableWithBorder())
}
Row(Modifier.fillMaxWidth(), SpaceEvenly) {
Text(
text = "3",
modifier = Modifier
.focusProperties { if (blockFocusMove) { right = Cancel } }
.focusableWithBorder()
)
Text(
text = "4",
modifier = Modifier
.focusProperties { left = if (blockFocusMove) Cancel else Default }
.focusableWithBorder()
)
}
}
}
@SuppressLint("ModifierInspectorInfo")
private fun Modifier.focusableWithBorder() = composed {
var color by remember { mutableStateOf(Black) }
Modifier
.size(50.dp)
.border(1.dp, color)
.onFocusChanged { color = if (it.isFocused) Red else Black }
.focusable()
}
| compose/ui/ui/integration-tests/ui-demos/src/main/java/androidx/compose/ui/demos/focus/CancelFocusDemo.kt | 2209674383 |
package de.sudoq.model.persistence
interface IRepo<T> {
fun create(): T
fun read(id: Int): T
fun update(t: T): T
fun delete(id: Int)
fun ids(): List<Int>
} | sudoq-app/sudoqmodel/src/main/kotlin/de/sudoq/model/persistence/IRepo.kt | 4194156948 |
/*
* Copyright 2019 Peter Kenji Yamanaka
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.pyamsoft.padlock
import android.annotation.SuppressLint
import android.content.Context
import androidx.annotation.CheckResult
object Injector {
const val name: String = "com.pyamsoft.padlock.INJECTOR"
@JvmStatic
@CheckResult
@SuppressLint("WrongConstant")
fun <T : Any> obtain(context: Context): T {
val service: Any? = context.getSystemService(name)
if (service == null) {
throw IllegalStateException("No service found for: $name")
} else {
@Suppress("UNCHECKED_CAST")
return service as T
}
}
}
| padlock/src/main/java/com/pyamsoft/padlock/Injector.kt | 3669315847 |
package me.ebonjaeger.novusbroadcast.commands
import co.aikar.commands.BaseCommand
import co.aikar.commands.annotation.CommandAlias
import co.aikar.commands.annotation.CommandCompletion
import co.aikar.commands.annotation.CommandPermission
import co.aikar.commands.annotation.Default
import co.aikar.commands.annotation.Description
import co.aikar.commands.annotation.Subcommand
import me.ebonjaeger.novusbroadcast.MessageList
import me.ebonjaeger.novusbroadcast.NovusBroadcast
import org.bukkit.ChatColor
import org.bukkit.command.CommandSender
@CommandAlias("novusbroadcast|nb")
class ListCommand(private val plugin: NovusBroadcast) : BaseCommand()
{
private val PAGE_SIZE = 5
@Subcommand("list")
@CommandCompletion("@messageLists")
@CommandPermission("novusbroadcast.list")
@Description("Shows all messages in a list.")
fun onListMessages(sender: CommandSender, listName: String, @Default("1") page: Int)
{
val messageList = plugin.messageLists[listName]
if (messageList == null)
{
sender.sendMessage("${ChatColor.RED}» ${ChatColor.GRAY}No list with name '$listName' found!")
return
}
if (messageList.messages.isNullOrEmpty())
{
sender.sendMessage("${ChatColor.RED}» ${ChatColor.GRAY}This list has no messages in it!")
return
}
val pages = (messageList.messages.size + PAGE_SIZE - 1) / PAGE_SIZE
if (page < 1 || page > pages)
{
sender.sendMessage("${ChatColor.RED}» ${ChatColor.GRAY}Page '$page' does not exist!")
return
}
val list = buildList(messageList, page, pages)
sender.sendMessage(list)
}
private fun buildList(messageList: MessageList, page: Int, totalPages: Int): String
{
val startIndex = (page - 1) * PAGE_SIZE
var endIndex = startIndex + PAGE_SIZE
if (endIndex >= messageList.messages.size)
{
endIndex = messageList.messages.size - 1
}
val sb = StringBuilder()
sb.append("${ChatColor.GRAY}${ChatColor.STRIKETHROUGH} ---------------${ChatColor.BLUE} Page ${ChatColor.WHITE}$page/$totalPages ${ChatColor.GRAY}${ChatColor.STRIKETHROUGH}--------------- \n")
for (i in startIndex..endIndex)
{
sb.append("${ChatColor.WHITE}$i${ChatColor.GRAY}: ${ChatColor.WHITE}${messageList.messages[i]}\n")
}
sb.append("${ChatColor.GRAY}${ChatColor.STRIKETHROUGH} ---------------------------------------------------- \n")
return sb.toString()
}
} | src/main/kotlin/me/ebonjaeger/novusbroadcast/commands/ListCommand.kt | 1540921675 |
package io.fdeitylink.kbagel
import java.util.stream.Collectors
import java.nio.file.Paths
import java.nio.file.Files
import java.nio.charset.Charset
import java.io.IOException
import kotlin.system.exitProcess
internal object KBagel {
private const val scanParseErrorCode = 65
private const val runtimeErrorCode = 70
private val interpreter = Interpreter(Reporter)
@JvmStatic
fun main(args: Array<String>) = when {
args.size > 1 -> println("Usage: kbagel [script]")
args.size == 1 -> runFile(args[0])
else -> runPrompt()
}
@Throws(IOException::class)
private fun runFile(path: String) {
run(Files.lines(Paths.get(path), Charset.defaultCharset()).use { it.collect(Collectors.joining("\n")) })
if (Reporter.hadScanParseError) {
exitProcess(scanParseErrorCode)
}
if (Reporter.hadRuntimeError) {
exitProcess(runtimeErrorCode)
}
}
@Throws(IOException::class)
private fun runPrompt() {
print("> ")
System.`in`.reader().buffered().use {
it.lines().forEach {
run(it)
//Even if the user made an error, it shouldn't kill the REPL session
Reporter.hadScanParseError = false
print("> ")
}
}
}
private fun run(source: String) {
val stmts = Parser(Scanner(source, Reporter).tokens, Reporter).parsed
if (Reporter.hadScanParseError) {
return
}
interpreter.interpret(stmts)
}
private object Reporter : ErrorReporter() {
//The setter visibility modifiers allows the KBagel object to access the member variables
@Suppress("RedundantVisibilityModifier", "RedundantSetter")
override var hadScanParseError = false
public set
override var hadRuntimeError = false
override fun report(line: Int, message: String, location: String) {
System.err.println("[line $line] Error $location: $message")
hadScanParseError = true
}
override fun report(err: BagelRuntimeError) {
System.err.println("${err.message}\n[line ${err.token.line}]")
hadRuntimeError = true
}
}
} | kbagel/src/main/kotlin/io/fdeitylink/kbagel/KBagel.kt | 552135490 |
package br.com.wakim.mvp_starter.extensions
import android.net.ConnectivityManager
val ConnectivityManager.isConnected: Boolean
get() = activeNetworkInfo?.isConnected ?: false | app/src/main/kotlin/br/com/wakim/mvp_starter/extensions/ContextExtensions.kt | 596925513 |
/**
* Shorthands for creating common objects like vectors and resource locations. These functions are available in Java
* as static members of the `Shorthand` class. e.g.
*
* ```java
* import com.teamwizardry.librarianlib.core.util.Shorthand.vec
* ```
*/
@file:JvmName("Shorthand")
package com.teamwizardry.librarianlib.core.util
import com.teamwizardry.librarianlib.math.Rect2d
import com.teamwizardry.librarianlib.math.Vec2d
import com.teamwizardry.librarianlib.math.Vec2i
import net.minecraft.util.Identifier
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.Vec3d
import net.minecraft.util.math.Vec3i
// Vec2d:
/**
* Get [Vec2d] instances, selecting from a pool of small integer instances when possible. This can vastly reduce the
* number of Vec2d allocations when they are used as intermediates, e.g. when adding one Vec2d to another to offset
* it, this allocates no objects: `Shorthand.vec(1, 0)`
*/
public fun vec(x: Double, y: Double): Vec2d = Vec2d.getPooled(x, y)
/**
* Get [Vec2d] instances, selecting from a pool of small integer instances when possible. This can vastly reduce the
* number of Vec2d allocations when they are used as intermediates, e.g. when adding one Vec2d to another to offset it,
* this allocates no objects: `vec(1, 0)`
*
* This method exists for ease of use in kotlin, where numbers aren't implicitly coerced.
*/
@JvmSynthetic
@Suppress("NOTHING_TO_INLINE")
public inline fun vec(x: Number, y: Number): Vec2d = vec(x.toDouble(), y.toDouble())
// Vec2i:
/**
* Get [Vec2i] instances, selecting from a pool of small value instances when possible. This can vastly reduce the
* number of Vec2i allocations when they are used as intermediates, e.g. when adding one Vec2i to another to offset
* it, this allocates no objects: `Shorthand.ivec(1, 0)`
*/
public fun ivec(x: Int, y: Int): Vec2i = Vec2i.getPooled(x, y)
// Vec3d:
/**
* Get [Vec3d] instances, selecting from a pool of small integer instances when possible. This can vastly reduce the
* number of Vec3d allocations when they are used as intermediates, e.g. when adding one Vec3d to another to offset
* it, this allocates no objects: `Shorthand.vec(1, 0, 0)`
*/
public fun vec(x: Double, y: Double, z: Double): Vec3d = Vec3dPool.getPooled(x, y, z)
/**
* Get [Vec3d] instances, selecting from a pool of small integer instances when possible. This can vastly reduce the
* number of Vec3d allocations when they are used as intermediates, e.g. when adding one Vec3d to another to offset
* it, this allocates no objects: `Shorthand.vec(1, 0, 0)`
*/
public fun vec(pos: BlockPos): Vec3d = vec(pos.x.toDouble(), pos.y.toDouble(), pos.z.toDouble())
/**
* Get [Vec3d] instances, selecting from a pool of small integer instances when possible. This can vastly reduce the
* number of Vec3d allocations when they are used as intermediates, e.g. when adding one Vec3d to another to offset it,
* this allocates no objects: `vec(1, 0, 0)`
*
* This method exists for ease of use in kotlin, where numbers aren't implicitly coerced.
*/
@JvmSynthetic
@Suppress("NOTHING_TO_INLINE")
public inline fun vec(x: Number, y: Number, z: Number): Vec3d = vec(x.toDouble(), y.toDouble(), z.toDouble())
// Vec3i:
/**
* Get [Vec3i] instances, selecting from a pool of small integer instances when possible. This can vastly reduce the
* number of Vec3i allocations when they are used as intermediates, e.g. when adding one Vec3i to another to offset
* it, this allocates no objects: `Shorthand.ivec(1, 0, 0)`
*/
public fun ivec(x: Int, y: Int, z: Int): Vec3i = Vec3iPool.getPooled(x, y, z)
// BlockPos:
/**
* Get [BlockPos] instances, selecting from a pool of small integer instances when possible. This can vastly reduce
* the number of BlockPos allocations when they are used as intermediates, e.g. when adding one BlockPos to another
* to offset it, this allocates no objects: `Shorthand.block(1, 0, 0)`
*/
public fun block(x: Int, y: Int, z: Int): BlockPos = BlockPosPool.getPooled(x, y, z)
/**
* Get [BlockPos] instances, selecting from a pool of small integer instances when possible. This can vastly reduce
* the number of BlockPos allocations when they are used as intermediates, e.g. when adding one BlockPos to another
* to offset it, this allocates no objects: `Shorthand.block(1, 0, 0)`
*/
public fun block(vec: Vec3d): BlockPos = BlockPosPool.getPooled(vec.x.toInt(), vec.y.toInt(), vec.z.toInt())
/**
* Get [BlockPos] instances, selecting from a pool of small integer instances when possible. This can vastly reduce
* the number of BlockPos allocations when they are used as intermediates, e.g. when adding one BlockPos to another
* to offset it, this allocates no objects: `Shorthand.block(1, 0, 0)`
*/
public fun block(vec: Vec3i): BlockPos = BlockPosPool.getPooled(vec.x, vec.y, vec.z)
// Rect2d:
/**
* Convenience method for creating a [Rect2d] instance. This does not do any pooling like the vectors do, but is
* more convenient than `new Rect2d(...)`
*/
public fun rect(x: Double, y: Double, width: Double, height: Double): Rect2d = Rect2d(x, y, width, height)
/**
* Convenience method for creating a [Rect2d] instance. This does not do any pooling like the vectors do, but is
* more convenient than `new Rect2d(...)`
*/
public fun rect(pos: Vec2d, size: Vec2d): Rect2d = Rect2d(pos, size)
/**
* Convenience function for creating [Rect2d]s in Kotlin without needing to explicitly convert parameters to doubles.
*/
@JvmSynthetic
@Suppress("NOTHING_TO_INLINE")
public inline fun rect(x: Number, y: Number, width: Number, height: Number): Rect2d = rect(x.toDouble(), y.toDouble(), width.toDouble(), height.toDouble())
// Internal:
private object Vec3dPool {
private val poolBits = 5
private val poolMask = (1 shl poolBits) - 1
private val poolMax = (1 shl poolBits - 1) - 1
private val poolMin = -(1 shl poolBits - 1)
private val pool = Array(1 shl poolBits * 3) {
val x = (it shr poolBits * 2) + poolMin
val y = (it shr poolBits and poolMask) + poolMin
val z = (it and poolMask) + poolMin
Vec3d(x.toDouble(), y.toDouble(), z.toDouble())
}
@JvmStatic
fun getPooled(x: Double, y: Double, z: Double): Vec3d {
val xi = x.toInt()
val yi = y.toInt()
val zi = z.toInt()
if (xi.toDouble() == x && xi in poolMin..poolMax &&
yi.toDouble() == y && yi in poolMin..poolMax &&
zi.toDouble() == z && zi in poolMin..poolMax) {
return pool[
((xi - poolMin) shl poolBits * 2) or ((yi - poolMin) shl poolBits) or (zi - poolMin)
]
}
return Vec3d(x, y, z)
}
}
private object Vec3iPool {
private val poolBits = 5
private val poolMask = (1 shl poolBits) - 1
private val poolMax = (1 shl poolBits - 1) - 1
private val poolMin = -(1 shl poolBits - 1)
private val pool = Array(1 shl poolBits * 3) {
val x = (it shr poolBits * 2) + poolMin
val y = (it shr poolBits and poolMask) + poolMin
val z = (it and poolMask) + poolMin
Vec3i(x, y, z)
}
@JvmStatic
fun getPooled(x: Int, y: Int, z: Int): Vec3i {
if (x in poolMin..poolMax &&
y in poolMin..poolMax &&
z in poolMin..poolMax) {
return pool[
((x - poolMin) shl poolBits * 2) or ((y - poolMin) shl poolBits) or (z - poolMin)
]
}
return Vec3i(x, y, z)
}
}
private object BlockPosPool {
private val poolBits = 5
private val poolMask = (1 shl poolBits) - 1
private val poolMax = (1 shl poolBits - 1) - 1
private val poolMin = -(1 shl poolBits - 1)
private val pool = Array(1 shl poolBits * 3) {
val x = (it shr poolBits * 2) + poolMin
val y = (it shr poolBits and poolMask) + poolMin
val z = (it and poolMask) + poolMin
BlockPos(x, y, z)
}
@JvmStatic
fun getPooled(x: Int, y: Int, z: Int): BlockPos {
if (x in poolMin..poolMax &&
y in poolMin..poolMax &&
z in poolMin..poolMax) {
return pool[
((x - poolMin) shl poolBits * 2) or ((y - poolMin) shl poolBits) or (z - poolMin)
]
}
return BlockPos(x, y, z)
}
} | modules/core/src/main/kotlin/com/teamwizardry/librarianlib/core/util/Shorthand.kt | 2137625269 |
package org.hexworks.mixite.core.internal.impl.layoutstrategy
import org.hexworks.mixite.core.api.CubeCoordinate
import org.hexworks.mixite.core.api.HexagonOrientation
import org.hexworks.mixite.core.api.HexagonalGridBuilder
import org.hexworks.mixite.core.api.contract.SatelliteData
import kotlin.math.abs
import kotlin.math.floor
import kotlin.math.max
import kotlin.math.round
class HexagonalGridLayoutStrategy : GridLayoutStrategy() {
override fun fetchGridCoordinates(builder: HexagonalGridBuilder<out SatelliteData>): Iterable<CubeCoordinate> {
val coords = ArrayList<CubeCoordinate>()
val gridSize = builder.getGridHeight()
var startX = if (HexagonOrientation.FLAT_TOP.equals(builder.getOrientation())) floor(gridSize / 2.0).toInt() else round(gridSize / 4.0).toInt()
val hexRadius = floor(gridSize / 2.0).toInt()
val minX = startX - hexRadius
var y = 0
while (y < gridSize) {
val distanceFromMid = abs(hexRadius - y)
for (x in max(startX, minX)..max(startX, minX) + hexRadius + hexRadius - distanceFromMid) {
val gridZ = if (HexagonOrientation.FLAT_TOP.equals(builder.getOrientation())) y - floor(gridSize / 4.0).toInt() else y
coords.add(CubeCoordinate.fromCoordinates(x, gridZ))
}
startX--
y++
}
return coords
}
override fun checkParameters(gridHeight: Int, gridWidth: Int): Boolean {
val superResult = checkCommonCase(gridHeight, gridWidth)
val result = gridHeight == gridWidth && abs(gridHeight % 2) == 1
return result && superResult
}
}
| mixite.core/core/src/main/kotlin/org/hexworks/mixite/core/internal/impl/layoutstrategy/HexagonalGridLayoutStrategy.kt | 1239419840 |
package com.mcgars.basekitk.features.base
import android.app.Application
import com.mcgars.basekitk.config.KitConfiguration
/**
* Created by gars on 03.08.17.
*/
abstract class BaseKitApplication : Application(), KitConfiguration {
} | basekitk/src/main/kotlin/com/mcgars/basekitk/features/base/BaseKitApplication.kt | 4055093530 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.credentials.exceptions.publickeycredential
import androidx.annotation.VisibleForTesting
/**
* During the create public key credential flow, this is returned when an authenticator response
* exception contains and abort-err from the fido spec, indicating the operation was aborted. The
* fido spec can be found [here](https://webidl.spec.whatwg.org/#idl-DOMException).
*
* @see CreatePublicKeyCredentialException
*
* @hide
*/
class CreatePublicKeyCredentialAbortException @JvmOverloads constructor(
errorMessage: CharSequence? = null
) : CreatePublicKeyCredentialException(
TYPE_CREATE_PUBLIC_KEY_CREDENTIAL_ABORT_EXCEPTION,
errorMessage) {
/** @hide */
companion object {
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
const val TYPE_CREATE_PUBLIC_KEY_CREDENTIAL_ABORT_EXCEPTION: String =
"androidx.credentials.TYPE_CREATE_PUBLIC_KEY_CREDENTIAL" +
"_ABORT_EXCEPTION"
}
} | credentials/credentials/src/main/java/androidx/credentials/exceptions/publickeycredential/CreatePublicKeyCredentialAbortException.kt | 2954541151 |
/*
* Copyright 2020 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.app.playhvz.firebase.classmodels
/** Android data model representing Firebase Group documents. */
class Group {
var id: String? = null
// Name of group
var name: String? = null
var managed: Boolean = false
var owners = listOf<String>()
var settings: Settings = Settings()
var members = listOf<String>()
class Settings {
var canAddSelf: Boolean = true
var canAddOthers: Boolean = true
var canRemoveSelf: Boolean = true
var canRemoveOthers: Boolean = true
var autoAdd: Boolean = false
var autoRemove: Boolean = false
var allegianceFilter: String = ""
}
} | Android/ghvzApp/app/src/main/java/com/app/playhvz/firebase/classmodels/Group.kt | 1072393123 |
package io.mockk.impl.verify
import io.mockk.Invocation
import io.mockk.MockKGateway
import io.mockk.MockKGateway.VerificationParameters
import io.mockk.RecordedCall
import io.mockk.impl.log.SafeToString
import io.mockk.impl.stub.StubRepository
import io.mockk.impl.verify.VerificationHelpers.allInvocations
import io.mockk.impl.verify.VerificationHelpers.reportCalls
class AllCallsCallVerifier(
stubRepo: StubRepository,
safeToString: SafeToString
) : UnorderedCallVerifier(stubRepo, safeToString) {
override fun verify(
verificationSequence: List<RecordedCall>,
params: VerificationParameters
): MockKGateway.VerificationResult {
val result = super.verify(verificationSequence, params)
if (result.matches) {
val allInvocations = verificationSequence.allInvocations(stubRepo)
val nonMatchingInvocations = allInvocations
.filter { invoke -> doesNotMatchAnyCalls(verificationSequence, invoke) }
if (nonMatchingInvocations.isNotEmpty()) {
return MockKGateway.VerificationResult.Failure(safeToString.exec {
"some calls were not matched: $nonMatchingInvocations" + reportCalls(verificationSequence, allInvocations)
})
}
}
return result
}
private fun doesNotMatchAnyCalls(calls: List<RecordedCall>, invoke: Invocation) =
!calls.any { call -> call.matcher.match(invoke) }
} | mockk/common/src/main/kotlin/io/mockk/impl/verify/AllCallsCallVerifier.kt | 573960849 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.system.templates
import org.lwjgl.generator.*
val MemoryAccessJNI = "MemoryAccessJNI".nativeClass(packageName = "org.lwjgl.system") {
nativeImport(
"<stdlib.h>",
"<stdint.h>"
)
val primitives = arrayOf(
Triple(int8_t, "Byte", "a byte value"),
Triple(int16_t, "Short", "a short value"),
Triple(int32_t, "Int", "an int value"),
Triple(int64_t, "Long", "a long value"),
Triple(float, "Float", "a float value"),
Triple(double, "Double", "a double value"),
Triple(intptr_t, "Address", "a pointer address")
)
nativeDirective(
"""#ifdef LWJGL_WINDOWS
__pragma(warning(disable : 4711))
static void* aligned_alloc(size_t alignment, size_t size) {
return _aligned_malloc(size, alignment);
}
#define aligned_free _aligned_free
#else
#ifndef __USE_ISOC11
static void* aligned_alloc(size_t alignment, size_t size) {
void *p = NULL;
posix_memalign(&p, alignment, size);
return p;
}
#endif
#define aligned_free free
#endif
// -----------
${primitives
.asSequence()
.map {
val (type, name) = it
"static inline ${type.name} get$name(void *ptr) { return *(${type.name} *)ptr; }"
}
.joinToString("\n")}
// -----------
${primitives
.asSequence()
.map {
val (type, name) = it
"static inline void put$name(void *ptr, ${type.name} value) { *(${type.name} *)ptr = value; }"
}
.joinToString("\n")}
// -----------""")
access = Access.INTERNAL
documentation = "Memory access utilities."
arrayOf(
"malloc",
"calloc",
"realloc",
"free",
"aligned_alloc",
"aligned_free"
).forEach {
macro..(Address..voidptr)(
it,
"Returns the address of the stdlib $it function."
)
}
for ((type, name, msg) in primitives)
type(
"get$name",
"Reads $msg from the specified memory address.",
voidptr.IN("ptr", "the memory address to read")
)
for ((type, name, msg) in primitives)
void(
"put$name",
"Writes $msg to the specified memory address.",
voidptr.IN("ptr", "the memory address to write"),
type.IN("value", "the value to write")
)
} | modules/templates/src/main/kotlin/org/lwjgl/system/templates/MemoryAccessJNI.kt | 3126677899 |
package com.dropbox.android.sample
import android.app.Application
import com.dropbox.android.external.fs3.Persister
import com.dropbox.android.external.store4.Store
import com.dropbox.android.sample.data.model.Post
import okio.BufferedSource
import java.io.IOException
class SampleApp : Application() {
lateinit var roomStore: Store<String, List<Post>>
lateinit var storeMultiParam: Store<Pair<String, RedditConfig>, List<Post>>
lateinit var configStore: Store<Unit, RedditConfig>
lateinit var persister: Persister<BufferedSource, Pair<String, String>>
override fun onCreate() {
super.onCreate()
initPersister()
roomStore = Graph.provideRoomStore(this)
storeMultiParam = Graph.provideRoomStoreMultiParam(this)
configStore = Graph.provideConfigStore(this)
}
private fun initPersister() {
try {
persister = Graph.newPersister(this.cacheDir)
} catch (exception: IOException) {
throw RuntimeException(exception)
}
}
}
| app/src/main/java/com/dropbox/android/sample/SampleApp.kt | 3472816955 |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.android.libraries.car.connectionservice
import com.google.android.libraries.car.trustagent.util.logi
import java.util.UUID
// LINT.IfChange
/** Logs events that are expected by automated test. */
object EventLog {
private const val TAG = "ConnectionEvent"
fun onServiceStarted() {
logi(TAG, "Service has been started.")
}
fun onServiceStopped() {
logi(TAG, "Service has been stopped.")
}
fun onCarConnected(deviceId: UUID) {
logi(TAG, "Car of $deviceId has connected.")
}
fun onStartForeground() {
logi(TAG, "Service has started running in the foreground.")
}
fun onStopForeground() {
logi(TAG, "Service has stopped running in the foreground.")
}
}
// LINT.ThenChange(//depot/google3/java/com/google/android/libraries/automotive/multidevice/testing/python_aae/tests/companion_android_longevity_test.py)
| connectionservice/src/com/google/android/libraries/car/connectionservice/EventLog.kt | 1017175339 |
package fr.jaydeer.chat.actor
interface Actor {
} | src/main/kotlin/fr/jaydeer/chat/actor/Actor.kt | 2121646867 |
package one.codehz.container
import android.app.Activity
import android.os.Bundle
import android.os.Handler
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import one.codehz.container.ext.get
import one.codehz.container.ext.vActivityManager
import one.codehz.container.ext.virtualCore
import one.codehz.container.models.AppModel
class VLoadingActivity : Activity() {
val iconView by lazy<ImageView> { this[R.id.icon] }
val titleView by lazy<TextView> { this[R.id.title] }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.loading_page)
val package_name = intent.data.path.substring(1)
val userId = intent.data.fragment?.toInt() ?: 0
val model = AppModel(this, virtualCore.findApp(package_name))
iconView.setImageDrawable(model.icon)
titleView.text = model.name
val target = virtualCore.getLaunchIntent(package_name, userId)
if (target == null) {
Toast.makeText(this, getString(R.string.null_launch_intent), Toast.LENGTH_SHORT).show()
return finishAfterTransition()
}
virtualCore.setLoadingPage(target, this)
if (intent.data.getQueryParameter("delay") != null)
Handler().postDelayed({
vActivityManager.startActivity(target, userId)
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
}, 50)
else if (!virtualCore.isAppRunning(package_name, userId))
Handler().postDelayed({
vActivityManager.startActivity(target, userId)
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
}, 100)
else
vActivityManager.startActivity(target, userId)
}
} | app/src/main/java/one/codehz/container/VLoadingActivity.kt | 2476247309 |
package org.ccci.gto.support.androidx.annotation
actual enum class RestrictToScope { TESTS, SUBCLASSES }
| gto-support-androidx-annotation/src/jsMain/kotlin/org/ccci/gto/support/androidx/annotation/RestrictToScope.js.kt | 729796087 |
package ru.fantlab.android.ui.widgets.filepicker.utils
import ru.fantlab.android.ui.widgets.filepicker.model.DialogConfigs
import ru.fantlab.android.ui.widgets.filepicker.model.DialogProperties
import java.io.File
import java.io.FileFilter
import java.util.*
class ExtensionFilter(properties: DialogProperties) : FileFilter {
private val validExtensions: Array<String>
private val properties: DialogProperties
override fun accept(file: File): Boolean {
if (file.isDirectory && file.canRead()) {
return true
} else if (properties.selection_type == DialogConfigs.DIR_SELECT) {
return false
} else {
val name = file.name.toLowerCase(Locale.getDefault())
for (ext in validExtensions) {
if (name.endsWith(ext)) {
return true
}
}
}
return false
}
init {
if (properties.extensions != null) {
validExtensions = properties.extensions!!
} else {
validExtensions = arrayOf("")
}
this.properties = properties
}
} | app/src/main/kotlin/ru/fantlab/android/ui/widgets/filepicker/utils/ExtensionFilter.kt | 3252573034 |
package ru.fantlab.android.ui.modules.bookcases.selector
import android.os.Bundle
import android.view.View
import io.reactivex.Single
import io.reactivex.functions.Consumer
import ru.fantlab.android.data.dao.model.*
import ru.fantlab.android.data.dao.response.*
import ru.fantlab.android.helper.BundleConstant
import ru.fantlab.android.provider.rest.DataManager
import ru.fantlab.android.provider.rest.getBookcaseInclusionsPath
import ru.fantlab.android.provider.storage.DbProvider
import ru.fantlab.android.ui.base.mvp.presenter.BasePresenter
class BookcasesSelectorPresenter : BasePresenter<BookcasesSelectorMvp.View>(),
BookcasesSelectorMvp.Presenter {
private var bookcaseType: String = ""
private var entityId: Int = 0
override fun onFragmentCreated(bundle: Bundle) {
bookcaseType = bundle.getString(BundleConstant.EXTRA_TWO)
entityId = bundle.getInt(BundleConstant.EXTRA_THREE)
getBookcases(bookcaseType, entityId, false)
}
override fun getBookcases(bookcaseType: String, entityId: Int, force: Boolean) {
makeRestCall(
getBookcasesInternal(bookcaseType, entityId, force).toObservable(),
Consumer { bookcasesInclusions ->
sendToView {
val inclusions: ArrayList<BookcaseSelection> = ArrayList()
bookcasesInclusions!!.map { inclusions.add(BookcaseSelection(it, it.itemAdded == 1)) }
it.onInitViews(inclusions)
}
}
)
}
private fun getBookcasesInternal(bookcaseType: String, entityId: Int, force: Boolean) =
getBookcasesFromServer(bookcaseType, entityId)
.onErrorResumeNext { throwable ->
if (!force) {
getBookcasesFromDb(bookcaseType, entityId)
} else {
throw throwable
}
}
private fun getBookcasesFromServer(bookcaseType: String, entityId: Int): Single<ArrayList<BookcaseInclusion>> =
DataManager.getBookcaseInclusions(bookcaseType, entityId)
.map { getBookcases(it) }
private fun getBookcasesFromDb(bookcaseType: String, entityId: Int): Single<ArrayList<BookcaseInclusion>> =
DbProvider.mainDatabase
.responseDao()
.get(getBookcaseInclusionsPath(bookcaseType, entityId))
.map { it.response }
.map { BookcaseInclusionResponse.Deserializer().deserialize(it) }
.map { getBookcases(it) }
private fun getBookcases(response: BookcaseInclusionResponse): ArrayList<BookcaseInclusion> {
val inclusions = ArrayList<BookcaseInclusion>()
response.items.map { inclusions.add(BookcaseInclusion(it.bookcaseId, it.bookcaseName, it.itemAdded, bookcaseType)) }
return inclusions
}
override fun onItemClick(position: Int, v: View?, item: BookcaseSelection) {
sendToView { it.onItemClicked(item, position) }
}
override fun onItemLongClick(position: Int, v: View?, item: BookcaseSelection) {
// TODO("not implemented")
}
override fun onItemSelected(position: Int, v: View?, item: BookcaseSelection) {
sendToView { it.onItemSelected(item, position) }
}
override fun includeItem(bookcaseId: Int, entityId: Int, include: Boolean) {
makeRestCall(
DataManager.includeItemToBookcase(bookcaseId, entityId, if (include) "add" else "delete").toObservable(),
Consumer { response ->
val result = BookcaseItemIncludedResponse.Parser().parse(response)
if (result == null) {
sendToView { it.showErrorMessage(response) }
} else {
sendToView { it.onItemSelectionUpdated() }
}
}
)
}
} | app/src/main/kotlin/ru/fantlab/android/ui/modules/bookcases/selector/BookcasesSelectorPresenter.kt | 4025443851 |
package ru.fantlab.android.ui.modules.search.awards
import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.annotation.StringRes
import com.evernote.android.state.State
import kotlinx.android.synthetic.main.micro_grid_refresh_list.*
import kotlinx.android.synthetic.main.state_layout.*
import ru.fantlab.android.R
import ru.fantlab.android.data.dao.model.SearchAward
import ru.fantlab.android.helper.InputHelper
import ru.fantlab.android.provider.rest.loadmore.OnLoadMore
import ru.fantlab.android.ui.adapter.SearchAwardsAdapter
import ru.fantlab.android.ui.base.BaseFragment
import ru.fantlab.android.ui.modules.award.AwardPagerActivity
import ru.fantlab.android.ui.modules.search.SearchMvp
class SearchAwardsFragment : BaseFragment<SearchAwardsMvp.View, SearchAwardsPresenter>(),
SearchAwardsMvp.View {
@State var searchQuery = ""
private val onLoadMore: OnLoadMore<String> by lazy { OnLoadMore(presenter, searchQuery) }
private val adapter: SearchAwardsAdapter by lazy { SearchAwardsAdapter(arrayListOf()) }
private var countCallback: SearchMvp.View? = null
override fun onFragmentCreated(view: View, savedInstanceState: Bundle?) {
if (savedInstanceState == null) {
stateLayout.hideProgress()
}
stateLayout.setEmptyText(R.string.no_search_results)
getLoadMore().initialize(presenter.getCurrentPage() - 1, presenter.getPreviousTotal())
stateLayout.setOnReloadListener(this)
refresh.setOnRefreshListener(this)
recycler.setEmptyView(stateLayout, refresh)
adapter.listener = presenter
recycler.adapter = adapter
recycler.addKeyLineDivider()
recycler.addOnScrollListener(getLoadMore())
if (!InputHelper.isEmpty(searchQuery)) {
onRefresh()
}
if (InputHelper.isEmpty(searchQuery)) {
stateLayout.showEmptyState()
}
fastScroller.attachRecyclerView(recycler)
}
override fun onAttach(context: Context) {
super.onAttach(context)
if (context is SearchMvp.View) {
countCallback = context
}
}
override fun onDetach() {
countCallback = null
super.onDetach()
}
override fun onDestroyView() {
recycler.removeOnScrollListener(getLoadMore())
super.onDestroyView()
}
override fun providePresenter(): SearchAwardsPresenter = SearchAwardsPresenter()
override fun onNotifyAdapter(items: ArrayList<SearchAward>, page: Int) {
hideProgress()
if (items.isEmpty()) {
adapter.clear()
stateLayout.showEmptyState()
return
}
if (page <= 1) {
adapter.insertItems(items)
} else {
adapter.addItems(items)
}
}
override fun onSetTabCount(count: Int) {
countCallback?.onSetCount(count, 3)
}
override fun onSetSearchQuery(query: String) {
this.searchQuery = query
getLoadMore().reset()
adapter.clear()
if (!InputHelper.isEmpty(query)) {
recycler.removeOnScrollListener(getLoadMore())
recycler.addOnScrollListener(getLoadMore())
onRefresh()
}
}
override fun onQueueSearch(query: String) {
onSetSearchQuery(query)
}
override fun getLoadMore(): OnLoadMore<String> {
onLoadMore.parameter = searchQuery
return onLoadMore
}
override fun onItemClicked(item: SearchAward) {
val name = if (item.rusName.isNotEmpty()) {
if (item.name.isNotEmpty()) {
String.format("%s / %s", item.rusName, item.name)
} else {
item.name
}
} else {
item.name
}
AwardPagerActivity.startActivity(context!!, item.id, name, 0)
}
override fun fragmentLayout(): Int = R.layout.micro_grid_refresh_list
override fun onRefresh() {
if (searchQuery.isEmpty()) {
refresh.isRefreshing = false
return
}
presenter.onCallApi(1, searchQuery)
}
override fun onClick(v: View?) {
onRefresh()
}
override fun hideProgress() {
refresh.isRefreshing = false
stateLayout.hideProgress()
}
override fun showProgress(@StringRes resId: Int, cancelable: Boolean) {
refresh.isRefreshing = true
stateLayout.showProgress()
}
override fun showErrorMessage(msgRes: String?) {
callback?.showErrorMessage(msgRes)
}
override fun showMessage(titleRes: Int, msgRes: Int) {
showReload()
super.showMessage(titleRes, msgRes)
}
private fun showReload() {
hideProgress()
stateLayout.showReload(adapter.itemCount)
}
} | app/src/main/kotlin/ru/fantlab/android/ui/modules/search/awards/SearchAwardsFragment.kt | 2131700701 |
package com.eden.orchid.api.resources.thumbnails
import com.eden.orchid.api.theme.assets.AssetPage
import com.eden.orchid.api.theme.permalinks.PermalinkStrategy
interface Renameable {
fun rename(page: AssetPage, permalinkStrategy: PermalinkStrategy, permalink: String, usePrettyUrl: Boolean)
}
| OrchidCore/src/main/kotlin/com/eden/orchid/api/resources/thumbnails/Renameable.kt | 3440926534 |
package com.hana053.micropost.pages.main
import com.hana053.micropost.pages.Presenter
import com.hana053.micropost.service.Navigator
import com.hana053.micropost.shared.posts.PostListAdapter
import rx.subjects.PublishSubject
class MainPresenter(
override val view: MainView,
private val mainService: MainService,
private val postListAdapter: PostListAdapter,
private val navigator: Navigator
) : Presenter<MainView> {
val newPostSubmittedSubject: PublishSubject<Void> = PublishSubject.create()
override fun bind() {
mainService.loadNextFeed()
.bindToLifecycle()
.withProgressDialog()
.subscribe()
view.swipeRefreshes
.bindToLifecycle()
.flatMap { mainService.loadNextFeed() }
.subscribe { view.swipeRefreshing.call(false) }
view.scrollsToBottom
.bindToLifecycle()
.flatMap {
mainService.loadPrevFeed()
.withProgressDialog()
}
.subscribe()
view.newMicropostClicks
.bindToLifecycle()
.subscribe { navigator.navigateToMicropostNew() }
postListAdapter.avatarClicksSubject
.bindToLifecycle()
.subscribe { navigator.navigateToUserShow(it.id) }
newPostSubmittedSubject
.bindToLifecycle()
.flatMap {
mainService.loadNextFeed()
.withProgressDialog()
}
.subscribe()
}
} | app/src/main/kotlin/com/hana053/micropost/pages/main/MainPresenter.kt | 77345978 |
package BitcoinABC.buildTypes
import jetbrains.buildServer.configs.kotlin.v2017_2.*
import jetbrains.buildServer.configs.kotlin.v2017_2.buildSteps.script
import jetbrains.buildServer.configs.kotlin.v2017_2.triggers.vcs
object BitcoinABCMasterLinux : BuildType({
uuid = "186070e4-1abd-4bf6-80a9-6e69c9eb299c"
id = "BitcoinABCMasterLinux"
name = "Bitcoin-ABC Master"
enablePersonalBuilds = false
artifactRules = """
+:output/**/*
+:build/tmp/**/*
+:build/ibd/debug.log
+:build/core
""".trimIndent()
vcs {
root(BitcoinABC.vcsRoots.BitcoinABCGit)
checkoutMode = CheckoutMode.ON_AGENT
cleanCheckout = true
}
steps {
script {
scriptContent = "./contrib/teamcity/build.sh"
}
}
triggers {
vcs {
// Run every commit
perCheckinTriggering = true
enableQueueOptimization = false
}
}
features {
feature {
// Parse test reports
type = "xml-report-plugin"
param("xmlReportParsing.reportType", "junit")
param("xmlReportParsing.reportDirs", "+:build/test_bitcoin.xml")
}
}
})
| .teamcity/BitcoinABC/buildTypes/BitcoinABCMasterLinux.kt | 1172091684 |
/*
* Copyright 2016 Shinya Mochida
*
* Licensed under the Apache License,Version2.0(the"License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,software
* Distributed under the License is distributed on an"AS IS"BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mikeneck.example.java.lang
import org.mikeneck.kuickcheck.Property
import org.mikeneck.kuickcheck.boolean
import org.mikeneck.kuickcheck.forAll
object BooleanCheck {
@Property
val materialImplication = forAll(boolean, boolean).satisfy { p, q -> (p && q) `→` p }
infix fun Boolean.`→`(other: Boolean): Boolean = !this || other
}
| example/src/test/kotlin/org/mikeneck/example/java/lang/BooleanCheck.kt | 644160599 |
/*
* Copyright (C) 2016 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.xquery.ast.xquery
/**
* An XQuery 1.0 `CopyNamespacesDecl` node in the XQuery AST.
*
* The `PreserveMode` and `InheritMode` grammar constructs
* are not explicitly generated.
*/
interface XQueryCopyNamespacesDecl : XQuerySetter
| src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/ast/xquery/XQueryCopyNamespacesDecl.kt | 2996973367 |
package com.themovielist.ui.movieimageview
import android.content.Context
import android.support.design.widget.Snackbar
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.FrameLayout
import com.themovielist.PopularMovieApplication
import com.themovielist.R
import com.themovielist.event.FavoriteMovieEvent
import com.themovielist.injector.components.DaggerFragmentComponent
import com.themovielist.model.MovieModel
import com.themovielist.model.view.MovieImageViewModel
import com.themovielist.moviedetail.MovieDetailActivity
import com.themovielist.util.setDisplay
import kotlinx.android.synthetic.main.movie_image_view.view.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import timber.log.Timber
import javax.inject.Inject
class MovieImageView constructor(context: Context, attributeSet: AttributeSet) : FrameLayout(context, attributeSet), MovieImageViewContract.View {
@Inject
lateinit var mPresenter: MovieImageViewPresenter
private var mIsFavoritingManually = false
init {
injectDependencies()
/*
* For some F3cking unknown reason, I was unable to change the SimpleDraweeView width/height/aspectRatio on runtime, turning this component useless.
* I had to pass the layout by parameter (changing the width/height/aspectRatio of the SimpleDraweeView on the XML. Sad :/
* */
val simpleDraweeViewLayout = getSimpleDraweeView(attributeSet)
LayoutInflater.from(context).inflate(simpleDraweeViewLayout, this)
mfbMovieImageViewFavorite.setOnFavoriteChangeListener { _, _ ->
if (mIsFavoritingManually) {
return@setOnFavoriteChangeListener
}
mPresenter.toggleMovieFavorite()
}
sdvMovieImageView.setOnClickListener { mPresenter.showMovieDetail() }
}
private fun getSimpleDraweeView(attributeSet: AttributeSet): Int {
val typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.MovieImageView)
val layoutResId = typedArray.getResourceId(R.styleable.MovieImageView_simpleDraweeView, R.layout.movie_image_view)
typedArray.recycle()
return layoutResId
}
private fun injectDependencies() {
val applicationComponent = PopularMovieApplication.getApplicationComponent(context)
DaggerFragmentComponent.builder()
.applicationComponent(applicationComponent)
.build()
.inject(this)
mPresenter.setView(this)
}
fun setImageURI(posterUrl: String?) {
sdvMovieImageView.setImageURI(posterUrl)
ivMovieItemEmptyImage.setDisplay(posterUrl == null)
}
fun setMovieImageViewModel(movieImageViewModel: MovieImageViewModel) {
mPresenter.setMovieImageViewModel(movieImageViewModel)
}
override fun openMovieDetail(movieModel: MovieModel) {
val intent = MovieDetailActivity.getDefaultIntent(context, movieModel)
context.startActivity(intent)
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
EventBus.getDefault().register(this)
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
EventBus.getDefault().unregister(this)
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onFavoriteMovieEvent(favoriteMovieEvent: FavoriteMovieEvent) {
mPresenter.onFavoriteMovieEvent(favoriteMovieEvent.movie, favoriteMovieEvent.favorite)
}
override fun toggleMovieFavorite(favourite: Boolean) {
mIsFavoritingManually = true
mfbMovieImageViewFavorite.isFavorite = favourite
mIsFavoritingManually = false
}
override fun showErrorFavoriteMovie(error: Throwable) {
Timber.e(error, "An error occurred while tried to favorite the movie: ${error.message}")
Snackbar.make(rootView, context.getString(R.string.error_add_favorite_movie), Snackbar.LENGTH_LONG)
}
override fun toggleMovieFavouriteEnabled(enabled: Boolean) {
mfbMovieImageViewFavorite.isEnabled = enabled
}
override fun showMovieInfo(movieImageViewModel: MovieImageViewModel) {
tvMovieImageViewName.text = movieImageViewModel.movieModel.title
toggleMovieFavorite(movieImageViewModel.isFavorite)
}
}
| app/src/main/java/com/themovielist/ui/movieimageview/MovieImageView.kt | 251221459 |
package com.habitrpg.android.habitica.ui.fragments
import android.os.Bundle
import androidx.fragment.app.testing.launchFragmentInContainer
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.databinding.FragmentStatsBinding
import com.habitrpg.shared.habitica.models.tasks.Attribute
import io.github.kakaocup.kakao.common.views.KView
import io.github.kakaocup.kakao.screen.Screen
import io.github.kakaocup.kakao.text.KButton
import io.mockk.every
import io.mockk.spyk
import io.mockk.verify
import io.reactivex.rxjava3.core.Flowable
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
class StatsScreen : Screen<StatsScreen>() {
val strengthStatsView = KView { withId(R.id.strengthStatsView) }
val strengthAllocateButton = KButton {
withId(R.id.allocateButton)
isDescendantOfA { withId(R.id.strengthStatsView) }
}
val intelligenceStatsView = KView { withId(R.id.intelligenceStatsView) }
val intelligenceAllocateButton = KButton {
withId(R.id.allocateButton)
isDescendantOfA { withId(R.id.intelligenceStatsView) }
}
val constitutionStatsView = KView { withId(R.id.constitutionStatsView) }
val constitutionAllocateButton = KButton {
withId(R.id.allocateButton)
isDescendantOfA { withId(R.id.constitutionStatsView) }
}
val perceptionStatsView = KView { withId(R.id.perceptionStatsView) }
val perceptionAllocateButton = KButton {
withId(R.id.allocateButton)
isDescendantOfA { withId(R.id.perceptionStatsView) }
}
val bulkAllocateButton = KView { withId(R.id.statsAllocationButton) }
}
@LargeTest
@RunWith(AndroidJUnit4::class)
class StatsFragmentTest : FragmentTestCase<StatsFragment, FragmentStatsBinding, StatsScreen>() {
override val screen = StatsScreen()
override fun makeFragment() {
fragment = spyk()
fragment.shouldInitializeComponent = false
}
override fun launchFragment(args: Bundle?) {
scenario = launchFragmentInContainer(args, R.style.MainAppTheme) {
return@launchFragmentInContainer fragment
}
}
@Before
fun setUpUser() {
user.stats?.lvl = 20
user.stats?.points = 30
userState.onNext(user)
every { inventoryRepository.getEquipment(listOf()) } returns Flowable.just(listOf())
}
@Test
fun showStatsTest() {
verify { userRepository.getUser() }
screen {
strengthStatsView.isVisible()
intelligenceStatsView.isVisible()
constitutionStatsView.isVisible()
perceptionStatsView.isVisible()
}
}
@Test
fun showsAllocationButtons() {
verify { userRepository.getUser() }
screen {
strengthAllocateButton.isVisible()
intelligenceAllocateButton.isVisible()
constitutionAllocateButton.isVisible()
perceptionAllocateButton.isVisible()
bulkAllocateButton.isVisible()
bulkAllocateButton.isClickable()
}
}
@Test
fun allocatesOnClick() {
screen {
strengthAllocateButton.click()
verify { userRepository.allocatePoint(Attribute.STRENGTH) }
intelligenceAllocateButton.click()
verify { userRepository.allocatePoint(Attribute.INTELLIGENCE) }
constitutionAllocateButton.click()
verify { userRepository.allocatePoint(Attribute.CONSTITUTION) }
perceptionAllocateButton.click()
verify { userRepository.allocatePoint(Attribute.PERCEPTION) }
}
}
}
| Habitica/src/androidTest/java/com/habitrpg/android/habitica/ui/fragments/StatsFragmentTest.kt | 2451222140 |
@file:Suppress("NOTHING_TO_INLINE")
package uy.klutter.vertx.json
import io.vertx.core.json.Json
import io.vertx.core.json.JsonArray
import io.vertx.core.json.JsonObject
import uy.klutter.core.common.toIsoString
import java.time.temporal.Temporal
/**
* converts a JSON formatted string containing an object into a tree of JsonObject
*/
inline fun jsonObjectFromString(json: String): JsonObject {
return JsonObject(json)
}
/**
* converts a JSON formatted string containing an array into an JsonArray
*/
inline fun jsonArrayFromString(json: String): JsonArray {
return JsonArray(json)
}
/**
* Converts a Map<String, T> into a JsonObject
*/
inline fun <V> jsonObjectFromMap(map: Map<String, V>): JsonObject {
return JsonObject(map)
}
/**
* Converts a List<T> into a JsonArray
*/
inline fun <T> jsonArrayFromList(list: List<T>): JsonArray {
return JsonArray(list)
}
/**
* Converts a POJO into a JsonObject
*/
@Suppress("UNCHECKED_CAST", "PLATFORM_CLASS_MAPPED_TO_KOTLIN")
inline fun jsonObjectFromPojo(something: Any): JsonObject {
return jsonObjectFromMap<Any?>(Json.mapper.convertValue(something, java.util.Map::class.java) as Map<String, Any?>)
}
/**
* A builder function to start creating a JsonObject
*
* ```
* jsonObject {
* put("parm", "value")
* put("field2", 123)
* }
* ```
*/
inline fun jsonObject(init: JsonObject.() -> Unit): JsonObject {
val jsonObject = JsonObject()
jsonObject.init()
return jsonObject
}
/**
* A builder function to start creating a JsonArray
*
* ```
* jsonArray {
* add("value1")
* add("value2")
* }
* ```
*/
inline fun jsonArray(init: JsonArray.() -> Unit): JsonArray {
val jsonArray = JsonArray()
jsonArray.init()
return jsonArray
}
/**
* A builder function to nest JSON objects within other objects
*/
inline fun JsonObject.putObject(name: String, init: JsonObject.() -> Unit): JsonObject {
put(name, jsonObject(init))
return this
}
/**
* A builder function to nest JSON arrays within other objects
*/
inline fun JsonObject.putArray(name: String, init: JsonArray.() -> Unit): JsonObject {
put(name, jsonArray(init))
return this
}
/**
* A builder function to nest JSON objects within an array
*/
inline fun JsonArray.addObject(init: JsonObject.() -> Unit): JsonArray {
add(jsonObject(init))
return this
}
/**
* A builder function to nest JSON arrays within an array
*/
inline fun JsonArray.addArray(init: JsonArray.() -> Unit): JsonArray {
add(jsonArray(init))
return this
}
/**
* Put a date into a JsonObject as an ISO formated string
*/
inline fun JsonObject.putDateIsoString(name: String, value: Temporal): JsonObject = put(name, value.toIsoString())
/**
* Put a date into a JsonArray as an ISO formated string
*/
inline fun JsonArray.addDateIsoString(value: Temporal): JsonArray = add(value.toIsoString())
| vertx3/src/main/kotlin/uy/klutter/vertx/json/VertxJson.kt | 1743764587 |
package org.stepik.android.data.calendar.source
import io.reactivex.Completable
import io.reactivex.Single
import org.stepik.android.domain.calendar.model.CalendarEventData
import org.stepik.android.domain.calendar.model.CalendarItem
interface CalendarCacheDataSource {
fun saveCalendarEventData(calendarEventData: CalendarEventData, calendarItem: CalendarItem): Single<Long>
fun getCalendarPrimaryItems(): Single<List<CalendarItem>>
fun removeEventsById(vararg ids: Long): Completable
} | app/src/main/java/org/stepik/android/data/calendar/source/CalendarCacheDataSource.kt | 3902287942 |
package org.stepic.droid.storage.migration
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
object MigrationFrom73To74 : Migration(73, 74) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("CREATE TABLE IF NOT EXISTS `MobileTier` (`id` TEXT NOT NULL, `course` INTEGER NOT NULL, `priceTier` TEXT, `promoTier` TEXT, PRIMARY KEY(`course`))")
db.execSQL("CREATE TABLE IF NOT EXISTS `LightSku` (`id` TEXT NOT NULL, `price` TEXT NOT NULL, PRIMARY KEY(`id`))")
}
} | app/src/main/java/org/stepic/droid/storage/migration/MigrationFrom73To74.kt | 3024595671 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.