repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
thaleslima/GuideApp | app/src/main/java/com/guideapp/ui/views/DividerItemDecoration.kt | 1 | 4544 | package com.guideapp.ui.views
import android.content.Context
import android.content.res.TypedArray
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.PorterDuff
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
class DividerItemDecoration : RecyclerView.ItemDecoration {
private val mDivider: Drawable
private var mOrientation: Int = 0
private var mDividerColor: Int = 0
private var mDividerStyle = DividerStyle.Dark
private var mDividerHeight: Int = 0
private var mMarginLeft: Int = 0
constructor(context: Context, orientation: Int, dividerStyle: DividerStyle) {
val a = context.obtainStyledAttributes(ATTRS)
mDivider = a.getDrawable(0)
this.mDividerStyle = dividerStyle
a.recycle()
setOrientation(orientation)
}
constructor(context: Context, orientation: Int) {
val a = context.obtainStyledAttributes(ATTRS)
mDivider = a.getDrawable(0)
this.mDividerStyle = DividerStyle.Dark
a.recycle()
setOrientation(orientation)
}
constructor(context: Context, orientation: Int, marginLeft: Int) : this(context, orientation) {
this.mMarginLeft = marginLeft
}
enum class DividerStyle {
Light,
Dark,
NoneColor,
Default
}
fun setDeviderColor(color: String) {
mDividerColor = Color.parseColor(color)
}
fun setDeviderColor(color: Int) {
mDividerColor = color
}
fun setDividerHeight(height: Int) {
mDividerHeight = height
}
fun setOrientation(orientation: Int) {
if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) {
throw IllegalArgumentException("invalid orientation")
}
mOrientation = orientation
}
override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State?) {
if (mOrientation == VERTICAL_LIST) {
drawVertical(c, parent)
} else {
drawHorizontal(c, parent)
}
}
fun drawVertical(c: Canvas, parent: RecyclerView) {
val left = parent.paddingLeft + mMarginLeft
val right = parent.width - parent.paddingRight
if (mDividerStyle != DividerStyle.Default) {
when (mDividerStyle) {
DividerItemDecoration.DividerStyle.Dark -> mDividerColor = Color.argb(13, 0, 0, 0)
DividerItemDecoration.DividerStyle.Light -> mDividerColor = Color.WHITE
DividerItemDecoration.DividerStyle.NoneColor -> mDividerColor = Color.TRANSPARENT
else -> mDividerColor = Color.TRANSPARENT
}
mDivider.setColorFilter(mDividerColor, PorterDuff.Mode.SRC_OUT)
}
val childCount = parent.childCount
for (i in 0..childCount - 1) {
val child = parent.getChildAt(i)
val v = RecyclerView(parent.context)
val params = child
.layoutParams as RecyclerView.LayoutParams
val top = child.bottom + params.bottomMargin
val bottom = top + mDivider.intrinsicHeight
mDivider.setBounds(left, top, right, bottom)
mDivider.draw(c)
}
}
fun drawHorizontal(c: Canvas, parent: RecyclerView) {
val top = parent.paddingTop
val bottom = parent.height - parent.paddingBottom
val childCount = parent.childCount
for (i in 0..childCount - 1) {
val child = parent.getChildAt(i)
val params = child
.layoutParams as RecyclerView.LayoutParams
val left = child.right + params.rightMargin
val right = left + mDivider.intrinsicHeight
mDivider.setBounds(left, top, right, bottom)
mDivider.draw(c)
}
}
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView,
state: RecyclerView.State?) {
if (mOrientation == VERTICAL_LIST) {
outRect.set(0, 0, 0, mDivider.intrinsicHeight + mDividerHeight)
} else {
outRect.set(0, 0, mDivider.intrinsicWidth, 0)
}
}
companion object {
val HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL
val VERTICAL_LIST = LinearLayoutManager.VERTICAL
private val ATTRS = intArrayOf(android.R.attr.listDivider)
}
}
| apache-2.0 | 6916bb9b1b64a8381b1559555a472fec | 32.411765 | 99 | 0.639745 | 4.865096 | false | false | false | false |
wax911/android-emojify | emojify/src/main/java/io/wax911/emojify/util/EmojiTree.kt | 1 | 1874 | package io.wax911.emojify.util
import io.wax911.emojify.model.Emoji
import io.wax911.emojify.util.tree.Matches
import io.wax911.emojify.util.tree.Node
class EmojiTree(emojis: Collection<Emoji>) {
private val root = Node()
init {
emojis.forEach { emoji ->
var tree: Node? = root
emoji.unicode.toCharArray().forEach { c ->
if (tree?.hasChild(c) == false)
tree?.addChild(c)
tree = tree?.getChild(c)
}
tree?.emoji = emoji
}
}
/**
* Checks if sequence of chars contain an emoji.
*
* @param sequence Sequence of char that may contain emoji in full or
* partially.
*
* @return
* - [Matches.EXACTLY] if char sequence in its entirety is an emoji
* - [Matches.POSSIBLY] if char sequence matches prefix of an emoji
* - [Matches.IMPOSSIBLE] if char sequence matches no emoji or prefix of an emoji
*/
fun isEmoji(sequence: CharArray?): Matches {
if (sequence == null)
return Matches.POSSIBLY
var tree: Node? = root
sequence.forEach { c ->
if (tree?.hasChild(c) == false)
return Matches.IMPOSSIBLE
tree = tree?.getChild(c)
}
return if (tree?.isEndOfEmoji == true)
Matches.EXACTLY
else Matches.POSSIBLY
}
/**
* Finds Emoji instance from emoji unicode
*
* @param unicode unicode of emoji to get
*
* @return Emoji instance if unicode matches and emoji, null otherwise.
*/
fun getEmoji(unicode: String): Emoji? {
var tree: Node? = root
unicode.toCharArray().forEach { c ->
if (tree?.hasChild(c) == false)
return null
tree = tree?.getChild(c)
}
return tree?.emoji
}
}
| mit | 223408f3b759c7d7e8191e2406670b0b | 26.970149 | 85 | 0.562433 | 4.298165 | false | false | false | false |
etesync/android | app/src/main/java/com/etesync/syncadapter/ui/CollectionMembersListFragment.kt | 1 | 5704 | package com.etesync.syncadapter.ui
import android.accounts.Account
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.ListFragment
import com.etesync.syncadapter.*
import com.etesync.journalmanager.JournalManager
import com.etesync.syncadapter.model.CollectionInfo
import com.etesync.syncadapter.model.JournalEntity
import com.etesync.syncadapter.model.JournalModel
import com.etesync.syncadapter.model.MyEntityDataStore
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread
import java.util.concurrent.Future
class CollectionMembersListFragment : ListFragment(), AdapterView.OnItemClickListener, Refreshable {
private lateinit var data: MyEntityDataStore
private lateinit var account: Account
private lateinit var info: CollectionInfo
private lateinit var journalEntity: JournalEntity
private var members: List<JournalManager.Member>? = null
private var asyncTask: Future<Unit>? = null
private var emptyTextView: TextView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
data = (context!!.applicationContext as App).data
account = arguments!!.getParcelable(Constants.KEY_ACCOUNT)!!
info = arguments!!.getSerializable(Constants.KEY_COLLECTION_INFO) as CollectionInfo
journalEntity = JournalModel.Journal.fetch(data, info.getServiceEntity(data), info.uid)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.collection_members_list, container, false)
//This is instead of setEmptyText() function because of Google bug
//See: https://code.google.com/p/android/issues/detail?id=21742
emptyTextView = view.findViewById<View>(android.R.id.empty) as TextView
return view
}
override fun refresh() {
asyncTask = doAsync {
try {
val settings = AccountSettings(context!!, account)
val httpClient = HttpClient.Builder(context, settings).build().okHttpClient
val journalsManager = JournalManager(httpClient, settings.uri?.toHttpUrlOrNull()!!)
val journal = JournalManager.Journal.fakeWithUid(journalEntity.uid)
members = journalsManager.listMembers(journal)
uiThread {
setListAdapterMembers(members!!)
}
} catch (e: Exception) {
uiThread {
emptyTextView!!.text = e.localizedMessage
}
}
}
}
private fun setListAdapterMembers(members: List<JournalManager.Member>) {
val context = context
if (context != null) {
val listAdapter = MembersListAdapter(context)
setListAdapter(listAdapter)
listAdapter.addAll(members)
emptyTextView!!.setText(R.string.collection_members_list_empty)
}
}
override fun onResume() {
super.onResume()
if (members != null) {
setListAdapterMembers(members!!)
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
refresh()
listView.onItemClickListener = this
}
override fun onDestroyView() {
super.onDestroyView()
if (asyncTask != null)
asyncTask!!.cancel(true)
}
override fun onItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long) {
val member = listAdapter?.getItem(position) as JournalManager.Member
AlertDialog.Builder(requireActivity())
.setIcon(R.drawable.ic_info_dark)
.setTitle(R.string.collection_members_remove_title)
.setMessage(getString(R.string.collection_members_remove, member.user))
.setPositiveButton(android.R.string.yes) { dialog, which ->
val frag = RemoveMemberFragment.newInstance(account, info, member.user!!)
frag.show(requireFragmentManager(), null)
}
.setNegativeButton(android.R.string.no) { dialog, which -> }.show()
}
internal inner class MembersListAdapter(context: Context) : ArrayAdapter<JournalManager.Member>(context, R.layout.collection_members_list_item) {
override fun getView(position: Int, _v: View?, parent: ViewGroup): View {
var v = _v
if (v == null)
v = LayoutInflater.from(context).inflate(R.layout.collection_members_list_item, parent, false)
val member = getItem(position)
val tv = v!!.findViewById<View>(R.id.title) as TextView
tv.text = member!!.user
val readOnly = v.findViewById<View>(R.id.read_only)
readOnly.visibility = if (member.readOnly) View.VISIBLE else View.GONE
return v
}
}
companion object {
fun newInstance(account: Account, info: CollectionInfo): CollectionMembersListFragment {
val frag = CollectionMembersListFragment()
val args = Bundle(1)
args.putParcelable(Constants.KEY_ACCOUNT, account)
args.putSerializable(Constants.KEY_COLLECTION_INFO, info)
frag.arguments = args
return frag
}
}
}
| gpl-3.0 | e497d40fb264730ca1609cfef330e2cf | 37.026667 | 149 | 0.665673 | 4.883562 | false | false | false | false |
signed/intellij-community | plugins/stats-collector/test/com/intellij/stats/completion/experiment/StatusInfoProviderTest.kt | 1 | 2343 | package com.intellij.stats.completion.experiment
import com.intellij.stats.completion.RequestService
import com.intellij.stats.completion.ResponseData
import com.intellij.testFramework.LightIdeaTestCase
import org.assertj.core.api.Assertions.assertThat
import org.mockito.Matchers
import org.mockito.Mockito.`when`
import org.mockito.Mockito.mock
class StatusInfoProviderTest : LightIdeaTestCase() {
fun newResponse(status: String, salt: String, version: String, url: String) = """
{
"status" : "$status",
"salt" : "$salt",
"experimentVersion" : $version,
"urlForZipBase64Content": "$url"
}
"""
fun `test experiment info is fetched`() {
val response = newResponse("ok", "sdfs", "2", "http://test.jetstat-resty.aws.intellij.net/uploadstats")
val infoProvider = getProvider(response)
infoProvider.updateStatus()
assertThat(infoProvider.getDataServerUrl()).isEqualTo("http://test.jetstat-resty.aws.intellij.net/uploadstats")
assertThat(infoProvider.isServerOk()).isEqualTo(true)
assertThat(infoProvider.getExperimentVersion()).isEqualTo(2)
}
fun `test server is not ok`() {
val response = newResponse("maintance", "sdfs", "2", "http://xxx.xxx")
val infoProvider = getProvider(response)
infoProvider.updateStatus()
assertThat(infoProvider.isServerOk()).isEqualTo(false)
assertThat(infoProvider.getExperimentVersion()).isEqualTo(2)
assertThat(infoProvider.getDataServerUrl()).isEqualTo("http://xxx.xxx")
}
fun `test round to Int`() {
var response = newResponse("maintance", "sdfs", "2.9", "http://xxx.xxx")
var infoProvider = getProvider(response)
infoProvider.updateStatus()
assertThat(infoProvider.getExperimentVersion()).isEqualTo(2)
response = newResponse("maintance", "sdfs", "2.1", "http://xxx.xxx")
infoProvider = getProvider(response)
infoProvider.updateStatus()
assertThat(infoProvider.getExperimentVersion()).isEqualTo(2)
}
private fun getProvider(response: String): StatusInfoProvider {
val requestSender = mock(RequestService::class.java).apply {
`when`(get(Matchers.anyString())).thenReturn(ResponseData(200, response))
}
return StatusInfoProvider(requestSender)
}
} | apache-2.0 | 661c7e7c24fb50dcb8869638f4a5b21c | 35.061538 | 119 | 0.692275 | 4.252269 | false | true | false | false |
vincentvalenlee/XCRM | src/main/kotlin/org/rocfish/domain/views/DefaultViewPort.kt | 1 | 6878 | package org.rocfish.domain.views
import io.vertx.kotlin.core.json.json
import io.vertx.kotlin.core.json.obj
import org.rocfish.IDSpecs
import org.rocfish.domain.ViewPort
import org.rocfish.dao.Searcher
import org.rocfish.domain.ViewPort.Bookmark
import org.rocfish.dao.OptionTargetFactory.Companion.BOOKMARK_CONDITION
import org.rocfish.dao.OptionTargetFactory.Companion.LIMT_FILED_OPTION
import org.rocfish.dao.OptionTargetFactory.Companion.SKIP_FILED_OPTION
import org.rocfish.dao.OptionTargetFactory.Companion.SORT_FIELD_OPTION
import org.slf4j.Logger
import org.slf4j.LoggerFactory
/**
* 默认的viewport实现.
* <p>1.使用一个排序字段(默认为_id),在每次滚动之后,使用一个Bookmark书签记录最后一条记录的位置
* <p>2.初始化时,书签位置为0
* <p>3.如果start > 0,则先将size设置为start,然后调用searcher跳过start记录(按照sort排序),找到start位置的记录,将书签设置为此记录的排序字段的值
* <p>4.使用searcher搜索排序字段值>(大于等于)书签值,且limit为size的记录,设置为current数据集合
* <p>5.书签位置设置为current最后一个记录位置
* <p>6.当发送scroll时(根据方向),使用searcher搜索排序字段大于(或小于)书签,且limit为size的记录,更新current数据集,并更新书签
* <p>7.viewport在web中使用,可以在页面的生命周期中短暂的存储于session中,他并不占用太多的内存。其使用的资源,根据缓存机制而决定
*/
class DefaultViewPort<T:IDSpecs>(val seacher: Searcher<T>, val startMark: Bookmark = Bookmark()): ViewPort<T> {
private var started:Int = 0
private var lastMark:Bookmark = this.startMark //每次scroll后的书签
private var firstMark:Bookmark = this.startMark //每次scroll后的书签
private var size:Int = 10
private var currentResult:List<T> = mutableListOf()
companion object {
val logger: Logger = LoggerFactory.getLogger(DefaultViewPort::class.java)
}
init {
//初始化时,执行1~3步
initLoad()
}
private fun initLoad() {
if (!this.seacher.getOption().containsKey(SORT_FIELD_OPTION)) {
//搜索器没有排序选项,从bookmark上
this.seacher.setOption(SORT_FIELD_OPTION, json {
obj(
"sort" to [email protected],
"desc" to [email protected]
)
})
}
this.seacher.setOption(LIMT_FILED_OPTION, json {
obj(
"limit" to size
)
})
if ([email protected] > 0) {
this.seacher.setOption(SKIP_FILED_OPTION, json {
obj(
"skip" to [email protected] - 1
)
})
}
this.currentResult = this.seacher.result()
resetMark(this.currentResult[0], this.currentResult[this.currentResult.size - 1])
//清除skip选项
clearOption(SKIP_FILED_OPTION)
}
override fun setStart(i: Int) {
started = i
initLoad()
}
override fun setSize(l: Int) {
this.size = l
}
override fun getSize(): Int = this.size
override fun scrollDown(): Boolean {
if (this.lastMark.value == "") {
logger.warn("viewport尚未进行滚动前的初始化,书签字段未设置值,将首先执行init初始化")
initLoad()
}
return try {
//恢复排序选项
this.seacher.setOption(SORT_FIELD_OPTION, json {
obj(
"sort" to [email protected],
"desc" to [email protected]
)
})
//mark选项的field在searcher中,将作为下次向下滚动的起始节点,根据排序,作为大小条件
// [向下滚动:如果为增序,则字段条件为大于起始点值;如果为降序,则字段条件为小于起始点值]
this.seacher.setOption(BOOKMARK_CONDITION, json {
obj (
[email protected] to [email protected]
)
})
this.seacher.setOption(LIMT_FILED_OPTION, json {
obj(
"limit" to size
)
})
this.currentResult = this.seacher.result()
resetMark(this.currentResult[0], this.currentResult[this.currentResult.size - 1])
clearOption(LIMT_FILED_OPTION, BOOKMARK_CONDITION)
true
} catch (e:Exception) {
logger.warn("向下滚动viewport发生错误!", e)
false
}
}
override fun scrollUp(): Boolean {
return try {
if (this.lastMark.value == "") {
logger.warn("viewport尚未进行滚动前的初始化,书签字段未设置值,将首先执行init初始化")
initLoad()
}
//向上滚动,排序取反
this.seacher.setOption(SORT_FIELD_OPTION, json {
obj(
"sort" to [email protected],
"desc" to [email protected]
)
})
// [向上滚动,因为滚动排序已经取反,规则与向下滚动相同]
this.seacher.setOption(BOOKMARK_CONDITION, json {
obj (
[email protected] to [email protected]
)
})
this.seacher.setOption(LIMT_FILED_OPTION, json {
obj(
"limit" to size
)
})
//返回的集合,与原序相反,则结果集反转
this.currentResult = this.seacher.result().asReversed()
resetMark(this.currentResult[0], this.currentResult[this.currentResult.size - 1])
clearOption(LIMT_FILED_OPTION, BOOKMARK_CONDITION, SORT_FIELD_OPTION)
true
} catch (e:Exception) {
logger.warn("向上滚动viewport发生错误!", e)
false
}
}
private fun resetMark(first:T, last:T) {
this.lastMark = Bookmark(this.startMark.field, this.startMark.desc, last.getField(this.startMark.field))
//视口开始书签,排序需要与last相反
this.firstMark = Bookmark(this.startMark.field, !this.startMark.desc, first.getField(this.startMark.field))
}
private fun clearOption(vararg keys:String) {
this.seacher.clearOption(*keys)
}
override fun getCurrent(): List<T> = this.currentResult
}
| apache-2.0 | e2b0f06346e15cd896849344108c2353 | 34.221557 | 116 | 0.593846 | 3.528494 | false | false | false | false |
google-pay/android-quickstart | kotlin/app/src/main/java/com/google/android/gms/samples/wallet/util/PaymentsUtil.kt | 2 | 8552 | /*
* Copyright 2021 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.gms.samples.wallet.util
import android.content.Context
import com.google.android.gms.samples.wallet.Constants
import com.google.android.gms.wallet.PaymentsClient
import com.google.android.gms.wallet.Wallet
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.math.BigDecimal
import java.math.RoundingMode
/**
* Contains helper static methods for dealing with the Payments API.
*
* Many of the parameters used in the code are optional and are set here merely to call out their
* existence. Please consult the documentation to learn more and feel free to remove ones not
* relevant to your implementation.
*/
object PaymentsUtil {
val CENTS = BigDecimal(100)
/**
* Create a Google Pay API base request object with properties used in all requests.
*
* @return Google Pay API base request object.
* @throws JSONException
*/
private val baseRequest = JSONObject().apply {
put("apiVersion", 2)
put("apiVersionMinor", 0)
}
/**
* Gateway Integration: Identify your gateway and your app's gateway merchant identifier.
*
*
* The Google Pay API response will return an encrypted payment method capable of being charged
* by a supported gateway after payer authorization.
*
*
* TODO: Check with your gateway on the parameters to pass and modify them in Constants.java.
*
* @return Payment data tokenization for the CARD payment method.
* @throws JSONException
* See [PaymentMethodTokenizationSpecification](https://developers.google.com/pay/api/android/reference/object.PaymentMethodTokenizationSpecification)
*/
private fun gatewayTokenizationSpecification(): JSONObject {
return JSONObject().apply {
put("type", "PAYMENT_GATEWAY")
put("parameters", JSONObject(Constants.PAYMENT_GATEWAY_TOKENIZATION_PARAMETERS))
}
}
/**
* Card networks supported by your app and your gateway.
*
*
* TODO: Confirm card networks supported by your app and gateway & update in Constants.java.
*
* @return Allowed card networks
* See [CardParameters](https://developers.google.com/pay/api/android/reference/object.CardParameters)
*/
private val allowedCardNetworks = JSONArray(Constants.SUPPORTED_NETWORKS)
/**
* Card authentication methods supported by your app and your gateway.
*
*
* TODO: Confirm your processor supports Android device tokens on your supported card networks
* and make updates in Constants.java.
*
* @return Allowed card authentication methods.
* See [CardParameters](https://developers.google.com/pay/api/android/reference/object.CardParameters)
*/
private val allowedCardAuthMethods = JSONArray(Constants.SUPPORTED_METHODS)
/**
* Describe your app's support for the CARD payment method.
*
*
* The provided properties are applicable to both an IsReadyToPayRequest and a
* PaymentDataRequest.
*
* @return A CARD PaymentMethod object describing accepted cards.
* @throws JSONException
* See [PaymentMethod](https://developers.google.com/pay/api/android/reference/object.PaymentMethod)
*/
// Optionally, you can add billing address/phone number associated with a CARD payment method.
private fun baseCardPaymentMethod(): JSONObject {
return JSONObject().apply {
val parameters = JSONObject().apply {
put("allowedAuthMethods", allowedCardAuthMethods)
put("allowedCardNetworks", allowedCardNetworks)
put("billingAddressRequired", true)
put("billingAddressParameters", JSONObject().apply {
put("format", "FULL")
})
}
put("type", "CARD")
put("parameters", parameters)
}
}
/**
* Describe the expected returned payment data for the CARD payment method
*
* @return A CARD PaymentMethod describing accepted cards and optional fields.
* @throws JSONException
* See [PaymentMethod](https://developers.google.com/pay/api/android/reference/object.PaymentMethod)
*/
private fun cardPaymentMethod(): JSONObject {
val cardPaymentMethod = baseCardPaymentMethod()
cardPaymentMethod.put("tokenizationSpecification", gatewayTokenizationSpecification())
return cardPaymentMethod
}
/**
* An object describing accepted forms of payment by your app, used to determine a viewer's
* readiness to pay.
*
* @return API version and payment methods supported by the app.
* See [IsReadyToPayRequest](https://developers.google.com/pay/api/android/reference/object.IsReadyToPayRequest)
*/
fun isReadyToPayRequest(): JSONObject? {
return try {
baseRequest.apply {
put("allowedPaymentMethods", JSONArray().put(baseCardPaymentMethod()))
}
} catch (e: JSONException) {
null
}
}
/**
* Information about the merchant requesting payment information
*
* @return Information about the merchant.
* @throws JSONException
* See [MerchantInfo](https://developers.google.com/pay/api/android/reference/object.MerchantInfo)
*/
private val merchantInfo: JSONObject =
JSONObject().put("merchantName", "Example Merchant")
/**
* Creates an instance of [PaymentsClient] for use in an [Context] using the
* environment and theme set in [Constants].
*
* @param context from the caller activity.
*/
fun createPaymentsClient(context: Context): PaymentsClient {
val walletOptions = Wallet.WalletOptions.Builder()
.setEnvironment(Constants.PAYMENTS_ENVIRONMENT)
.build()
return Wallet.getPaymentsClient(context, walletOptions)
}
/**
* Provide Google Pay API with a payment amount, currency, and amount status.
*
* @return information about the requested payment.
* @throws JSONException
* See [TransactionInfo](https://developers.google.com/pay/api/android/reference/object.TransactionInfo)
*/
@Throws(JSONException::class)
private fun getTransactionInfo(price: String): JSONObject {
return JSONObject().apply {
put("totalPrice", price)
put("totalPriceStatus", "FINAL")
put("countryCode", Constants.COUNTRY_CODE)
put("currencyCode", Constants.CURRENCY_CODE)
}
}
/**
* An object describing information requested in a Google Pay payment sheet
*
* @return Payment data expected by your app.
* See [PaymentDataRequest](https://developers.google.com/pay/api/android/reference/object.PaymentDataRequest)
*/
fun getPaymentDataRequest(priceCemts: Long): JSONObject {
return baseRequest.apply {
put("allowedPaymentMethods", JSONArray().put(cardPaymentMethod()))
put("transactionInfo", getTransactionInfo(priceCemts.centsToString()))
put("merchantInfo", merchantInfo)
// An optional shipping address requirement is a top-level property of the
// PaymentDataRequest JSON object.
val shippingAddressParameters = JSONObject().apply {
put("phoneNumberRequired", false)
put("allowedCountryCodes", JSONArray(listOf("US", "GB")))
}
put("shippingAddressParameters", shippingAddressParameters)
put("shippingAddressRequired", true)
}
}
}
/**
* Converts cents to a string format accepted by [PaymentsUtil.getPaymentDataRequest].
*/
fun Long.centsToString() = BigDecimal(this)
.divide(PaymentsUtil.CENTS)
.setScale(2, RoundingMode.HALF_EVEN)
.toString()
| apache-2.0 | 9b64dbdca415f56f3f817625d5a6a689 | 36.840708 | 154 | 0.670486 | 4.90086 | false | false | false | false |
bassph/bassph-app-android | app/src/main/java/org/projectbass/bass/ui/main/MainActivity.kt | 1 | 18173 | package org.projectbass.bass.ui.main
import android.Manifest.permission.*
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.content.pm.PackageManager.PERMISSION_GRANTED
import android.graphics.Bitmap
import android.graphics.Color
import android.location.LocationManager
import android.net.ConnectivityManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.text.TextUtils
import android.view.View
import android.widget.*
import butterknife.BindView
import butterknife.OnCheckedChanged
import butterknife.OnClick
import cn.pedant.SweetAlert.SweetAlertDialog
import co.mobiwise.materialintro.shape.Focus
import co.mobiwise.materialintro.shape.FocusGravity
import co.mobiwise.materialintro.shape.ShapeType
import co.mobiwise.materialintro.view.MaterialIntroView
import com.cardiomood.android.controls.gauge.SpeedometerGauge
import com.crashlytics.android.Crashlytics
import com.crashlytics.android.answers.Answers
import com.crashlytics.android.answers.CustomEvent
import com.facebook.share.model.ShareHashtag
import com.facebook.share.model.ShareLinkContent
import com.facebook.share.model.SharePhoto
import com.facebook.share.model.SharePhotoContent
import com.facebook.share.widget.ShareDialog
import com.github.pwittchen.reactivewifi.AccessRequester
import com.google.firebase.analytics.FirebaseAnalytics
import com.hsalf.smilerating.BaseRating
import com.hsalf.smilerating.SmileRating
import jonathanfinerty.once.Once
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.share_results.*
import org.projectbass.bass.R
import org.projectbass.bass.flux.action.DataCollectionActionCreator
import org.projectbass.bass.flux.store.DataCollectionStore
import org.projectbass.bass.model.Data
import org.projectbass.bass.post.api.RestAPI
import org.projectbass.bass.service.job.DataCollectionJob
import org.projectbass.bass.ui.BaseActivity
import org.projectbass.bass.ui.history.HistoryActivity
import org.projectbass.bass.ui.map.MapsActivity
import org.projectbass.bass.utils.AnalyticsUtils
import org.projectbass.bass.utils.SharedPrefUtil
import rx.Observable
import rx.Single
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import java.net.InetAddress
import java.net.URI
import java.util.*
import javax.inject.Inject
/**
* Paul Sydney Orozco (@xtrycatchx) on 4/2/17.
*/
class MainActivity : BaseActivity() {
override val layoutRes: Int = R.layout.activity_main
@BindView(R.id.centerImage) lateinit var centerImage: ImageView
@BindView(R.id.btnMap) lateinit var map: Button
@BindView(R.id.enableAutoMeasure) lateinit var enableAutoMeasure: CheckBox
@Inject lateinit internal var dataCollectionActionCreator: DataCollectionActionCreator
@Inject lateinit internal var dataCollectionStore: DataCollectionStore
@Inject lateinit internal var analyticsUtils: AnalyticsUtils
@Inject lateinit internal var firebaseAnalytics: FirebaseAnalytics
private var pDialog: SweetAlertDialog? = null
private var isAlreadyRunningTest: Boolean = false
private fun requestCoarseLocationPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(arrayOf(ACCESS_COARSE_LOCATION),
PERMISSIONS_REQUEST_CODE_ACCESS_COARSE_LOCATION)
}
}
private fun requestPhoneStatePermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(arrayOf(READ_PHONE_STATE),
PERMISSIONS_REQUEST_READ_PHONE_STATE)
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
when (requestCode) {
PERMISSIONS_REQUEST_CODE_ACCESS_COARSE_LOCATION,
PERMISSIONS_REQUEST_READ_PHONE_STATE -> {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
onCenterImageClicked()
}
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
activityComponent.inject(this)
initUi()
showTutorial()
setupGauge()
initFlux()
isConnected.subscribe({
SharedPrefUtil.retrieveTempData(this)?.let {
it?.let {
postToServer(it)
}
}
}, Crashlytics::logException)
}
private fun setupGauge() {
// Add label converter
speedometer.labelConverter = SpeedometerGauge.LabelConverter { progress, maxProgress ->
return@LabelConverter Math.round(progress).toInt().toString()
}
speedometer.labelTextSize = 40
// configure value range and ticks
speedometer.maxSpeed = 30.0
speedometer.majorTickStep = 5.0
speedometer.minorTicks = 0
speedometer.addColoredRange(0.0, 5.0, Color.RED)
speedometer.addColoredRange(5.0, 10.0, Color.parseColor("#ffa500"))
speedometer.addColoredRange(10.0, 15.0, Color.YELLOW)
speedometer.addColoredRange(15.0, 20.0, Color.parseColor("#90ee90"))
speedometer.setSpeed(0.0, false)
}
private fun initUi() {
enableAutoMeasure.isChecked = SharedPrefUtil.retrieveFlag(this, "auto_measure")
}
private fun showTutorial() {
if (!Once.beenDone(Once.THIS_APP_INSTALL, "tutorial_measure")) {
showMeasureTutorial()
} else if (!Once.beenDone(Once.THIS_APP_SESSION, "tutorial_auto_measure") and
!SharedPrefUtil.retrieveFlag(this, "auto_measure")) {
showAutoMeasureTutorial()
} else if (!Once.beenDone(Once.THIS_APP_INSTALL, "tutorial_map")) {
showMapTutorial()
}
}
private fun showMapTutorial() {
showTutorialOverlay(message = "To view measurement reports, click Map.",
target = map,
focusType = Focus.ALL,
listener = {
Once.markDone("tutorial_map")
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.TUTORIAL_COMPLETE,
Bundle().apply { putBoolean("is_complete", true) })
})
}
private fun showMeasureTutorial() {
showTutorialOverlay(message = "Hi There! To contribute to our data and see your network speed, please click the button in the center.",
target = centerImage,
focusType = Focus.ALL,
listener = {
Once.markDone("tutorial_measure")
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.TUTORIAL_BEGIN,
Bundle().apply { putBoolean("is_complete", false) })
showTutorial()
})
}
private fun showAutoMeasureTutorial() {
showTutorialOverlay(message = "If you want to send us your measurements regularly, please check this box. Let's check this for now to help us gather more data (You can uncheck it).",
target = enableAutoMeasure,
focusType = Focus.ALL,
listener = {
enableAutoMeasure.isChecked = true
Once.markDone("tutorial_auto_measure")
showTutorial()
})
}
fun showTutorialOverlay(target: View, message: String, focusType: Focus = Focus.NORMAL, listener: () -> Unit) {
MaterialIntroView.Builder(this)
.enableDotAnimation(false)
.enableIcon(false)
.setFocusGravity(FocusGravity.CENTER)
.setFocusType(focusType)
.dismissOnTouch(true)
.setTargetPadding(30)
.setDelayMillis(100)
.enableFadeAnimation(true)
.performClick(false)
.setIdempotent(false)
.setInfoText(message)
.setShape(ShapeType.CIRCLE)
.setTarget(target)
.setUsageId(UUID.randomUUID().toString())
.setListener { listener() }
.show()
}
private fun initFlux() {
addSubscriptionToUnsubscribe(dataCollectionStore.observable()
.observeOn(AndroidSchedulers.mainThread())
.subscribe { store ->
when (store.action) {
DataCollectionActionCreator.ACTION_COLLECT_DATA_S -> {
resetView()
store.data?.let {
getCarrierUserSatisfaction(it)
}
}
DataCollectionActionCreator.ACTION_SEND_DATA_S -> showShareResultDialog()
DataCollectionActionCreator.ACTION_SEND_DATA_F -> {
pDialog?.dismiss()
showErrorDialog()
}
DataCollectionActionCreator.ACTION_COLLECT_DATA_F -> {
pDialog?.dismiss()
firebaseAnalytics.logEvent("data_collection_failed", Bundle().apply { putBoolean("is_auto", false) })
resetView()
}
}
}
)
}
private fun getCarrierUserSatisfaction(data: Data) {
SweetAlertDialog(this, SweetAlertDialog.NORMAL_TYPE).apply {
titleText = "How do you feel about your connection?"
confirmText = "Submit"
setCancelable(false)
val smileRatingView = initSmileRatingView()
setConfirmClickListener { dialog ->
data.mood = smileRatingView.rating - 3
dismissWithAnimation()
postToServer(data)
}
setCustomView(smileRatingView)
}.show()
}
fun initSmileRatingView(): SmileRating {
return SmileRating(this).apply {
selectedSmile = BaseRating.OKAY
setNameForSmile(BaseRating.TERRIBLE, "Angry")
setNameForSmile(BaseRating.OKAY, "Meh")
}
}
private fun showErrorDialog() {
AlertDialog.Builder(this)
.setTitle("Error : ${dataCollectionStore.error?.statusCode}")
.setMessage(dataCollectionStore.error?.errorMessage)
.show()
}
private fun showShareResultDialog() {
pDialog?.dismissWithAnimation()
share_results.visibility = View.VISIBLE
val data = dataCollectionStore.data!!
if (data.connectivity != null) {
if (data.connectivity.type == ConnectivityManager.TYPE_WIFI) {
speed.text = "WiFi Speed: "
} else {
speed.text = "Data Speed: "
}
}
if (!TextUtils.isEmpty(data.bandwidth)) {
val bandwidth = data.bandwidth.replace(" Kbps", "").toFloat()
val bandwidthString: String
if (bandwidth < 1024) {
bandwidthString = "$bandwidth Kbps"
speedometer.maxSpeed = 30.0
speedometer.majorTickStep = 5.0
speedometer.minorTicks = 0
speedometer.addColoredRange(20.0, speedometer.maxSpeed, Color.GREEN)
speedometer.setSpeed(1.0, false)
} else {
bandwidthString = "${(Math.round(bandwidth / 1024))} Mbps"
if (Math.round(bandwidth / 1024) > 30) {
speedometer.maxSpeed = Math.round(bandwidth / 1024).toDouble()
speedometer.majorTickStep = 10.0
speedometer.minorTicks = 0
}
speedometer.addColoredRange(20.0, speedometer.maxSpeed, Color.GREEN)
speedometer.setSpeed((bandwidth / 1024).toDouble(), false)
}
speed.text = "${speed.text} $bandwidthString"
}
signal.text = "Signal: " + data.signal
done.setOnClickListener {
// TODO: Don't treat shared prefs as database
SharedPrefUtil.clearTempData(this)
resetView()
}
share.setOnClickListener {
if (ShareDialog.canShow(SharePhotoContent::class.java)) {
share_card.isDrawingCacheEnabled = true
val bitmap = Bitmap.createBitmap(share_card.drawingCache)
share_card.isDrawingCacheEnabled = false
val linkContent = SharePhotoContent.Builder()
.setPhotos(listOf(SharePhoto.Builder().setBitmap(bitmap).setCaption("My BASS Results").build()))
.build()
ShareDialog.show(this@MainActivity, linkContent)
}
SharedPrefUtil.clearTempData(this)
resetView()
}
}
@OnClick(R.id.btnMap)
fun onButtonMapsClicked() {
val intent = Intent(this@MainActivity, MapsActivity::class.java)
startActivity(intent)
}
@OnClick(R.id.btnHistory)
fun onHistoryClicked() {
val intent = Intent(this@MainActivity, HistoryActivity::class.java)
startActivity(intent)
}
@OnClick(R.id.centerImage)
fun onCenterImageClicked() {
if (rippleBackground.isRippleAnimationRunning) {
endTest()
} else {
reportText.visibility = View.INVISIBLE
centerImage.setImageDrawable(ContextCompat.getDrawable(this@MainActivity, R.drawable.signal_on))
rippleBackground.startRippleAnimation()
if (!isAlreadyRunningTest) {
isAlreadyRunningTest = true
runOnUiThreadIfAlive(Runnable { this.beginTest() }, 1000)
}
}
}
@OnCheckedChanged(R.id.enableAutoMeasure)
fun onEnabledMeasure(v: CompoundButton, isChecked: Boolean) {
firebaseAnalytics.logEvent("auto_measure", Bundle().apply { putBoolean("is_auto", isChecked) })
SharedPrefUtil.saveFlag(this, "auto_measure", isChecked)
}
fun beginTest() {
firebaseAnalytics.logEvent("begin_test", Bundle().apply { putBoolean("start", true) })
val fineLocationPermissionNotGranted = ActivityCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) != PERMISSION_GRANTED
val coarseLocationPermissionNotGranted = ActivityCompat.checkSelfPermission(this, ACCESS_COARSE_LOCATION) != PERMISSION_GRANTED
val phoneStatePermissionNotGranted = ActivityCompat.checkSelfPermission(this, READ_PHONE_STATE) != PERMISSION_GRANTED
if (fineLocationPermissionNotGranted && coarseLocationPermissionNotGranted) {
if (fineLocationPermissionNotGranted) {
requestCoarseLocationPermission()
firebaseAnalytics.logEvent("permission_denied", Bundle().apply { putString("permission", ACCESS_FINE_LOCATION) })
}
if (coarseLocationPermissionNotGranted) {
firebaseAnalytics.logEvent("permission_denied", Bundle().apply { putString("permission", ACCESS_COARSE_LOCATION) })
}
isAlreadyRunningTest = false
endTest()
return
}
if (phoneStatePermissionNotGranted) {
isAlreadyRunningTest = false
requestPhoneStatePermission()
endTest()
firebaseAnalytics.logEvent("permission_denied", Bundle().apply { putString("permission", READ_PHONE_STATE) })
return
}
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN) {
val provider = Settings.Secure.getString(contentResolver, Settings.Secure.LOCATION_PROVIDERS_ALLOWED)
if (!provider.contains(LocationManager.GPS_PROVIDER)) {
runOnUiThread { AccessRequester.requestLocationAccess(this) }
isAlreadyRunningTest = false
endTest()
return
}
} else {
if (!AccessRequester.isLocationEnabled(this)) {
runOnUiThread { AccessRequester.requestLocationAccess(this) }
isAlreadyRunningTest = false
endTest()
return
}
}
dataCollectionActionCreator.collectData()
isAlreadyRunningTest = false
Answers.getInstance().logCustom(CustomEvent("Begin Test"))
DataCollectionJob.scheduleJob()
}
fun endTest() {
runOnUiThread { this.resetView() }
}
fun resetView() {
reportText.visibility = View.VISIBLE
share_results.visibility = View.GONE
rippleBackground.stopRippleAnimation()
centerImage.setImageDrawable(ContextCompat.getDrawable(this@MainActivity, R.drawable.signal))
}
fun postToServer(data: Data) {
analyticsUtils.logPostData(data)
data.let {
SharedPrefUtil.saveTempData(this, it)
pDialog = SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE).apply {
progressHelper?.barColor = Color.parseColor("#A5DC86")
titleText = "Loading"
setCancelable(false)
show()
}
dataCollectionActionCreator.sendData(it)
}
}
// TODO: Can be improved
val isConnected: Single<Boolean>
get() = Observable.fromCallable { InetAddress.getByName(URI.create(RestAPI.BASE_URL).host) }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.map { inetAddress -> inetAddress != null }
.toSingle()
override fun onDestroy() {
super.onDestroy()
if (pDialog != null && pDialog!!.isShowing) {
pDialog!!.dismiss()
}
}
companion object {
val PERMISSIONS_REQUEST_CODE_ACCESS_COARSE_LOCATION = 1000
private val PERMISSIONS_REQUEST_READ_PHONE_STATE = 1001
}
}
| agpl-3.0 | 147370917ad2d3e335f500336ceb77d7 | 37.258947 | 190 | 0.625543 | 4.862992 | false | false | false | false |
DevCharly/kotlin-ant-dsl | src/main/kotlin/com/devcharly/kotlin/ant/taskdefs/tar-tarfileset.kt | 1 | 2859 | /*
* Copyright 2016 Karl Tauber
*
* 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.devcharly.kotlin.ant
import org.apache.tools.ant.taskdefs.Tar.TarFileSet
/******************************************************************************
DO NOT EDIT - this file was generated
******************************************************************************/
fun TarFileSet._init(
dir: String?,
file: String?,
includes: String?,
excludes: String?,
includesfile: String?,
excludesfile: String?,
defaultexcludes: Boolean?,
casesensitive: Boolean?,
followsymlinks: Boolean?,
maxlevelsofsymlinks: Int?,
erroronmissingdir: Boolean?,
src: String?,
erroronmissingarchive: Boolean?,
prefix: String?,
fullpath: String?,
encoding: String?,
filemode: String?,
dirmode: String?,
username: String?,
uid: Int?,
group: String?,
gid: Int?,
mode: String?,
preserveleadingslashes: Boolean?,
nested: (KTarFileSet.() -> Unit)?)
{
if (dir != null)
setDir(project.resolveFile(dir))
if (file != null)
setFile(project.resolveFile(file))
if (includes != null)
setIncludes(includes)
if (excludes != null)
setExcludes(excludes)
if (includesfile != null)
setIncludesfile(project.resolveFile(includesfile))
if (excludesfile != null)
setExcludesfile(project.resolveFile(excludesfile))
if (defaultexcludes != null)
setDefaultexcludes(defaultexcludes)
if (casesensitive != null)
setCaseSensitive(casesensitive)
if (followsymlinks != null)
setFollowSymlinks(followsymlinks)
if (maxlevelsofsymlinks != null)
setMaxLevelsOfSymlinks(maxlevelsofsymlinks)
if (erroronmissingdir != null)
setErrorOnMissingDir(erroronmissingdir)
if (src != null)
setSrc(project.resolveFile(src))
if (erroronmissingarchive != null)
setErrorOnMissingArchive(erroronmissingarchive)
if (prefix != null)
setPrefix(prefix)
if (fullpath != null)
setFullpath(fullpath)
if (encoding != null)
setEncoding(encoding)
if (filemode != null)
setFileMode(filemode)
if (dirmode != null)
setDirMode(dirmode)
if (username != null)
setUserName(username)
if (uid != null)
setUid(uid)
if (group != null)
setGroup(group)
if (gid != null)
setGid(gid)
if (mode != null)
setMode(mode)
if (preserveleadingslashes != null)
setPreserveLeadingSlashes(preserveleadingslashes)
if (nested != null)
nested(KTarFileSet(this))
}
| apache-2.0 | 98c131e0763c15045601ffea6624899d | 27.029412 | 79 | 0.693249 | 3.732376 | false | false | false | false |
skydoves/WaterDrink | app/src/main/java/com/skydoves/waterdays/ui/activities/main/SelectDrinkActivity.kt | 1 | 5856 | /*
* Copyright (C) 2016 skydoves
*
* 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.skydoves.waterdays.ui.activities.main
import android.annotation.SuppressLint
import android.content.Context
import android.content.DialogInterface
import android.content.res.Configuration
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.text.InputType
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import com.google.android.material.snackbar.Snackbar
import com.jakewharton.rxbinding2.view.RxView
import com.skydoves.waterdays.R
import com.skydoves.waterdays.compose.BaseActivity
import com.skydoves.waterdays.compose.qualifiers.RequirePresenter
import com.skydoves.waterdays.consts.CapacityDrawable
import com.skydoves.waterdays.models.Capacity
import com.skydoves.waterdays.presenters.SelectDrinkPresenter
import com.skydoves.waterdays.ui.adapters.SelectDrinkAdapter
import com.skydoves.waterdays.ui.viewholders.SelectDrinkViewHolder
import com.skydoves.waterdays.viewTypes.SelectDrinkActivityView
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.activity_select_drink.*
/**
* Created by skydoves on 2016-10-15.
* Updated by skydoves on 2017-09-22.
* Copyright (c) 2017 skydoves rights reserved.
*/
@RequirePresenter(SelectDrinkPresenter::class)
class SelectDrinkActivity : BaseActivity<SelectDrinkPresenter, SelectDrinkActivityView>(), SelectDrinkActivityView {
private lateinit var adapter: SelectDrinkAdapter
@SuppressLint("CheckResult")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_select_drink)
initBaseView(this)
RxView.clicks(findViewById(R.id.selectdrink_btn_add))
.observeOn(AndroidSchedulers.mainThread())
.subscribe { e -> addCapacity() }
RxView.clicks(icon_question)
.observeOn(AndroidSchedulers.mainThread())
.subscribe { Snackbar.make(icon_question, getString(R.string.msg_press_long), Snackbar.LENGTH_LONG).setActionTextColor(Color.WHITE).show() }
RxView.clicks(findViewById(R.id.selectdrink_btn_close))
.observeOn(AndroidSchedulers.mainThread())
.subscribe { finish() }
}
override fun initializeUI() {
adapter = SelectDrinkAdapter(delegate)
selectdrink_rcyv.setAdapter(adapter)
val capacities = presenter.capacityItemList
for (capacity in capacities) {
val amount = capacity.amount
val drawable = ContextCompat.getDrawable(baseContext, CapacityDrawable.getLayout(amount))
adapter.addCapacityItem(Capacity(drawable, amount))
}
if (capacities.isEmpty())
Toast.makeText(baseContext, R.string.msg_require_capacity, Toast.LENGTH_SHORT).show()
}
/**
* recyclerView onTouch listeners delegate
*/
private var delegate: SelectDrinkViewHolder.Delegate = object : SelectDrinkViewHolder.Delegate {
override fun onClick(view: View, capacity: Capacity) {
val duration = 200
Handler().postDelayed({
presenter.addRecrodItem(capacity.amount)
finish()
}, duration.toLong())
}
override fun onLongClick(view: View, capacity: Capacity) {
val alertDlg = AlertDialog.Builder(view.context)
alertDlg.setTitle(getString(R.string.title_alert))
// yes - delete
alertDlg.setPositiveButton(getString(R.string.yes)) { dialog: DialogInterface, which: Int ->
presenter.deleteCapacity(capacity)
adapter.removeDrinkItem(capacity)
Toast.makeText(baseContext, capacity.amount.toString() + "ml " + getString(R.string.msg_delete_capacity), Toast.LENGTH_SHORT).show()
}
// no - cancel
alertDlg.setNegativeButton(getString(R.string.no)) { dialog: DialogInterface, which: Int -> dialog.dismiss() }
alertDlg.setMessage(String.format(getString(R.string.msg_ask_remove_capacity)))
alertDlg.show()
}
}
/**
* add a new water capacity cup
*/
private fun addCapacity() {
val alert = AlertDialog.Builder(this)
alert.setTitle(getString(R.string.title_add_capacity))
val input = EditText(this)
input.inputType = InputType.TYPE_CLASS_NUMBER
input.setRawInputType(Configuration.KEYBOARD_12KEY)
alert.setView(input)
alert.setPositiveButton(getString(R.string.yes)) { dialog: DialogInterface, whichButton: Int ->
try {
val amount = Integer.parseInt(input.text.toString())
if (amount in 1..2999) {
val capacity = Capacity(ContextCompat.getDrawable(baseContext, CapacityDrawable.getLayout(amount)), amount)
presenter.addCapacity(capacity)
adapter.addCapacityItem(capacity)
} else
Toast.makeText(baseContext, R.string.msg_invalid_input, Toast.LENGTH_SHORT).show()
} catch (e: Exception) {
e.printStackTrace()
}
}
alert.setNegativeButton(getString(R.string.no)) { dialog: DialogInterface, whichButton: Int ->
}
alert.show()
val mgr = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
mgr.showSoftInputFromInputMethod(input.applicationWindowToken, InputMethodManager.SHOW_FORCED)
}
}
| apache-2.0 | feff209b01755ab3bfe0620c6dff2776 | 37.27451 | 148 | 0.746243 | 4.299559 | false | false | false | false |
SimonMarquis/FCM-toolbox | app/src/main/java/fr/smarquis/fcm/utils/Singleton.kt | 1 | 600 | package fr.smarquis.fcm.utils
open class Singleton<out T, in A>(creator: (A) -> T) {
private var creator: ((A) -> T)? = creator
@Volatile
private var instance: T? = null
fun instance(arg: A): T {
val i = instance
if (i != null) {
return i
}
return synchronized(this) {
val i2 = instance
if (i2 != null) {
i2
} else {
val created = creator!!(arg)
instance = created
creator = null
created
}
}
}
} | apache-2.0 | bf04e571127650b538dc53df77d8b924 | 20.464286 | 54 | 0.433333 | 4.347826 | false | false | false | false |
jitsi/jitsi-videobridge | jvb/src/main/kotlin/org/jitsi/videobridge/cc/allocation/SingleSourceAllocation.kt | 1 | 15641 | /*
* Copyright @ 2021 - present 8x8, Inc.
* Copyright @ 2021 - Vowel, 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 org.jitsi.videobridge.cc.allocation
import org.jitsi.nlj.MediaSourceDesc
import org.jitsi.nlj.RtpLayerDesc
import org.jitsi.nlj.RtpLayerDesc.Companion.indexString
import org.jitsi.nlj.VideoType
import org.jitsi.utils.logging.DiagnosticContext
import org.jitsi.utils.logging.TimeSeriesLogger
import org.jitsi.utils.logging2.Logger
import org.jitsi.utils.logging2.LoggerImpl
import org.jitsi.videobridge.cc.config.BitrateControllerConfig.Companion.config
import java.lang.Integer.max
import java.time.Clock
/**
* A bitrate allocation that pertains to a specific source. This is the internal representation used in the allocation
* algorithm, as opposed to [SingleAllocation] which is the end result.
*
* @author George Politis
* @author Pawel Domas
*/
internal class SingleSourceAllocation(
val endpointId: String,
val mediaSource: MediaSourceDesc,
/** The constraints to use while allocating bandwidth to this media source. */
val constraints: VideoConstraints,
/** Whether the source is on stage. */
private val onStage: Boolean,
diagnosticContext: DiagnosticContext,
clock: Clock,
val logger: Logger = LoggerImpl(SingleSourceAllocation::class.qualifiedName)
) {
/**
* The immutable list of layers to be considered when allocating bandwidth.
*/
val layers: Layers = selectLayers(mediaSource, onStage, constraints, clock.instant().toEpochMilli())
/**
* The index (into [layers] of the current target layer). It can be improved in the `improve()` step, if there is
* enough bandwidth.
*/
var targetIdx = -1
init {
if (timeSeriesLogger.isTraceEnabled) {
val ratesTimeSeriesPoint = diagnosticContext.makeTimeSeriesPoint("layers_considered")
.addField("remote_endpoint_id", endpointId)
for ((l, bitrate) in layers.layers) {
ratesTimeSeriesPoint.addField(
"${indexString(l.index)}_${l.height}p_${l.frameRate}fps_bps",
bitrate
)
}
timeSeriesLogger.trace(ratesTimeSeriesPoint)
}
}
fun isOnStage() = onStage
fun hasReachedPreferred(): Boolean = targetIdx >= layers.preferredIndex
/**
* Implements an "improve" step, incrementing [.targetIdx] to the next layer if there is sufficient
* bandwidth. Note that this works eagerly up until the "preferred" layer (if any), and as a single step from
* then on.
*
* @param remainingBps the additional bandwidth which is available on top of the bitrate of the current target
* layer.
* @return the bandwidth "consumed" by the method, i.e. the difference between the resulting and initial target
* bitrate. E.g. if the target bitrate goes from 100 to 300 as a result if the method call, it will return 200.
*/
fun improve(remainingBps: Long, allowOversending: Boolean): Long {
val initialTargetBitrate = targetBitrate
val maxBps = remainingBps + initialTargetBitrate
if (layers.isEmpty()) {
return 0
}
if (targetIdx == -1 && layers.preferredIndex > -1 && onStage) {
// Boost on stage participant to preferred, if there's enough bw.
for (i in layers.indices) {
if (i > layers.preferredIndex || maxBps < layers[i].bitrate) {
break
}
targetIdx = i
}
} else {
// Try the next element in the ratedIndices array.
if (targetIdx + 1 < layers.size && layers[targetIdx + 1].bitrate < maxBps) {
targetIdx++
}
}
if (targetIdx > -1) {
// If there's a higher layer available with a lower bitrate, skip to it.
//
// For example, if 1080p@15fps is configured as a better subjective quality than 720p@30fps (i.e. it sits
// on a higher index in the ratedIndices array) and the bitrate that we measure for the 1080p stream is less
// than the bitrate that we measure for the 720p stream, then we "jump over" the 720p stream and immediately
// select the 1080p stream.
//
// TODO further: Should we just prune the list of layers we consider to not include such layers?
for (i in layers.size - 1 downTo targetIdx + 1) {
if (layers[i].bitrate <= layers[targetIdx].bitrate) {
targetIdx = i
}
}
}
// If oversending is allowed, look for a better layer which doesn't exceed maxBps by more than
// `maxOversendBitrate`.
if (allowOversending && layers.oversendIndex >= 0 && targetIdx < layers.oversendIndex) {
for (i in layers.oversendIndex downTo targetIdx + 1) {
if (layers[i].bitrate <= maxBps + config.maxOversendBitrateBps()) {
targetIdx = i
}
}
}
// If the stream is non-scalable enable oversending regardless of maxOversendBitrate
if (allowOversending && targetIdx < 0 && layers.oversendIndex >= 0 && layers.hasOnlyOneLayer()) {
logger.warn(
"Oversending above maxOversendBitrate, layer bitrate " +
"${layers.layers[layers.oversendIndex].bitrate} bps"
)
targetIdx = layers.oversendIndex
}
val resultingTargetBitrate = targetBitrate
return resultingTargetBitrate - initialTargetBitrate
}
/**
* The source is suspended if we've not selected a layer AND the source has active layers.
*
* TODO: this is not exactly correct because it only looks at the layers we consider. E.g. if the receiver set
* a maxHeight=0 constraint for an endpoint, it will appear suspended. This is not critical, because this val is
* only used for logging.
*/
val isSuspended: Boolean
get() = targetIdx == -1 && layers.isNotEmpty() && layers[0].bitrate > 0
/**
* Gets the target bitrate (in bps) for this endpoint allocation, i.e. the bitrate of the currently chosen layer.
*/
val targetBitrate: Long
get() = targetLayer?.bitrate?.toLong() ?: 0
private val targetLayer: LayerSnapshot?
get() = layers.getOrNull(targetIdx)
/**
* Gets the ideal bitrate (in bps) for this endpoint allocation, i.e. the bitrate of the layer the bridge would
* forward if there were no (bandwidth) constraints.
*/
val idealBitrate: Long
get() = layers.idealLayer?.bitrate?.toLong() ?: 0
/**
* Exposed for testing only.
*/
val preferredLayer: RtpLayerDesc?
get() = layers.preferredLayer?.layer
/**
* Exposed for testing only.
*/
val oversendLayer: RtpLayerDesc?
get() = layers.oversendLayer?.layer
/**
* Creates the final immutable result of this allocation. Should be called once the allocation algorithm has
* completed.
*/
val result: SingleAllocation
get() = SingleAllocation(
endpointId,
mediaSource,
targetLayer?.layer,
layers.idealLayer?.layer
)
override fun toString(): String {
return (
"[id=" + endpointId +
" constraints=" + constraints +
" ratedPreferredIdx=" + layers.preferredIndex +
" ratedTargetIdx=" + targetIdx
)
}
/**
* Selects from a list of layers the ones which should be considered when allocating bandwidth, as well as the
* "preferred" and "oversend" layers. Logic specific to screensharing: we prioritize resolution over framerate,
* prioritize the highest layer over other endpoints (by setting the highest layer as "preferred"), and allow
* oversending up to the highest resolution (with low frame rate).
*/
private fun selectLayersForScreensharing(
layers: List<LayerSnapshot>,
constraints: VideoConstraints,
onStage: Boolean
): Layers {
var activeLayers = layers.filter { it.bitrate > 0 }
// No active layers usually happens when the source has just been signaled and we haven't received
// any packets yet. Add the layers here, so one gets selected and we can start forwarding sooner.
if (activeLayers.isEmpty()) activeLayers = layers
// We select all layers that satisfy the constraints.
var selectedLayers =
if (!constraints.heightIsLimited()) {
activeLayers
} else {
activeLayers.filter { it.layer.height <= constraints.maxHeight }
}
// If no layers satisfy the constraints, we use the layers with the lowest resolution.
if (selectedLayers.isEmpty()) {
val minHeight = activeLayers.minOfOrNull { it.layer.height } ?: return Layers.noLayers
selectedLayers = activeLayers.filter { it.layer.height == minHeight }
// This recognizes the structure used with VP9 (multiple encodings with the same resolution and unknown frame
// rate). In this case, we only want the low quality layer. Unless we're on stage, in which case we should
// consider all layers.
if (!onStage && selectedLayers.isNotEmpty() && selectedLayers[0].layer.frameRate < 0) {
selectedLayers = listOf(selectedLayers[0])
}
}
val oversendIdx = if (onStage && config.allowOversendOnStage()) {
val maxHeight = selectedLayers.maxOfOrNull { it.layer.height } ?: return Layers.noLayers
// Of all layers with the highest resolution select the one with lowest bitrate. In case of VP9 the layers
// are not necessarily ordered by bitrate.
val lowestBitrateLayer = selectedLayers.filter { it.layer.height == maxHeight }.minByOrNull { it.bitrate }
?: return Layers.noLayers
selectedLayers.indexOf(lowestBitrateLayer)
} else {
-1
}
return Layers(selectedLayers, selectedLayers.size - 1, oversendIdx)
}
/**
* Selects from the layers of a [MediaSourceContainer] the ones which should be considered when allocating bandwidth for
* an endpoint. Also selects the indices of the "preferred" and "oversend" layers.
*
* @param endpoint the [MediaSourceContainer] that describes the available layers.
* @param constraints the constraints signaled for the endpoint.
* @return the ordered list of [endpoint]'s layers which should be considered when allocating bandwidth, as well as the
* indices of the "preferred" and "oversend" layers.
*/
private fun selectLayers(
/** The endpoint which is the source of the stream(s). */
source: MediaSourceDesc,
onStage: Boolean,
/** The constraints that the receiver specified for [source]. */
constraints: VideoConstraints,
nowMs: Long
): Layers {
if (constraints.maxHeight == 0 || !source.hasRtpLayers()) {
return Layers.noLayers
}
val layers = source.rtpLayers.map { LayerSnapshot(it, it.getBitrateBps(nowMs)) }
return when (source.videoType) {
VideoType.CAMERA -> selectLayersForCamera(layers, constraints)
VideoType.DESKTOP, VideoType.DESKTOP_HIGH_FPS -> selectLayersForScreensharing(layers, constraints, onStage)
else -> Layers.noLayers
}
}
/**
* Selects from a list of layers the ones which should be considered when allocating bandwidth, as well as the
* "preferred" and "oversend" layers. Logic specific to a camera stream: once the "preferred" height is reached we
* require a high frame rate, with preconfigured values for the "preferred" height and frame rate, and we do not allow
* oversending.
*/
private fun selectLayersForCamera(
layers: List<LayerSnapshot>,
constraints: VideoConstraints,
): Layers {
val minHeight = layers.map { it.layer.height }.minOrNull() ?: return Layers.noLayers
val noActiveLayers = layers.none { (_, bitrate) -> bitrate > 0 }
val (preferredHeight, preferredFps) = getPreferred(constraints)
val ratesList: MutableList<LayerSnapshot> = ArrayList()
// Initialize the list of layers to be considered. These are the layers that satisfy the constraints, with
// a couple of exceptions (see comments below).
for (layerSnapshot in layers) {
val layer = layerSnapshot.layer
val lessThanPreferredHeight = layer.height < preferredHeight
val lessThanOrEqualMaxHeight = layer.height <= constraints.maxHeight || !constraints.heightIsLimited()
// If frame rate is unknown, consider it to be sufficient.
val atLeastPreferredFps = layer.frameRate < 0 || layer.frameRate >= preferredFps
if (lessThanPreferredHeight ||
(lessThanOrEqualMaxHeight && atLeastPreferredFps) ||
layer.height == minHeight
) {
// No active layers usually happens when the source has just been signaled and we haven't received
// any packets yet. Add the layers here, so one gets selected and we can start forwarding sooner.
if (noActiveLayers || layerSnapshot.bitrate > 0) {
ratesList.add(layerSnapshot)
}
}
}
val effectivePreferredHeight = max(preferredHeight, minHeight)
val preferredIndex = ratesList.lastIndexWhich { it.layer.height <= effectivePreferredHeight }
return Layers(ratesList, preferredIndex, -1)
}
companion object {
private val timeSeriesLogger = TimeSeriesLogger.getTimeSeriesLogger(BandwidthAllocator::class.java)
}
}
/**
* Returns the index of the last element of this list which satisfies the given predicate, or -1 if no elements do.
*/
private fun <T> List<T>.lastIndexWhich(predicate: (T) -> Boolean): Int {
var lastIndex = -1
forEachIndexed { i, e -> if (predicate(e)) lastIndex = i }
return lastIndex
}
/**
* Gets the "preferred" height and frame rate based on the constraints signaled from the receiver.
*
* For participants with sufficient maxHeight we favor frame rate over resolution. We consider all
* temporal layers for resolutions lower than the preferred, but for resolutions >= preferred, we only
* consider frame rates at least as high as the preferred. In practice this means we consider
* 180p/7.5fps, 180p/15fps, 180p/30fps, 360p/30fps and 720p/30fps.
*/
private fun getPreferred(constraints: VideoConstraints): VideoConstraints {
return if (constraints.maxHeight > 180 || !constraints.heightIsLimited()) {
VideoConstraints(config.onstagePreferredHeightPx(), config.onstagePreferredFramerate())
} else {
VideoConstraints.UNLIMITED
}
}
| apache-2.0 | e29e85d5fb186ea7d261ca9c6d665117 | 43.434659 | 124 | 0.649895 | 4.656445 | false | false | false | false |
collinx/susi_android | app/src/main/java/org/fossasia/susi/ai/rest/responses/susi/SkillData.kt | 2 | 1088 | package org.fossasia.susi.ai.rest.responses.susi
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
import java.io.Serializable
/**
*
* Created by chiragw15 on 16/8/17.
*/
class SkillData: Serializable {
@SerializedName("image")
@Expose
var image: String = ""
@SerializedName("author_url")
@Expose
var authorUrl: String = ""
@SerializedName("examples")
@Expose
var examples: List<String> = ArrayList()
@SerializedName("developer_privacy_policy")
@Expose
var developerPrivacyPolicy: String = ""
@SerializedName("author")
@Expose
var author: String = ""
@SerializedName("skill_name")
@Expose
var skillName: String = ""
@SerializedName("dynamic_content")
@Expose
var dynamicContent: Boolean ?= null
@SerializedName("terms_of_use")
@Expose
var termsOfUse: String = ""
@SerializedName("descriptions")
@Expose
var descriptions: String = ""
@SerializedName("skill_rating")
@Expose
var skillRating: SkillRating ?= null
} | apache-2.0 | 14e128831c16175471a9e7127ce686e3 | 19.942308 | 49 | 0.66636 | 4.10566 | false | false | false | false |
robinverduijn/gradle | subprojects/instant-execution/src/main/kotlin/org/gradle/instantexecution/serialization/codecs/TaskNodeCodec.kt | 1 | 12867 | /*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.instantexecution.serialization.codecs
import org.gradle.api.GradleException
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.internal.GeneratedSubclasses
import org.gradle.api.internal.TaskInputsInternal
import org.gradle.api.internal.TaskOutputsInternal
import org.gradle.api.internal.project.ProjectState
import org.gradle.api.internal.project.ProjectStateRegistry
import org.gradle.api.internal.provider.Providers
import org.gradle.api.internal.tasks.properties.InputFilePropertyType
import org.gradle.api.internal.tasks.properties.InputParameterUtils
import org.gradle.api.internal.tasks.properties.OutputFilePropertyType
import org.gradle.api.internal.tasks.properties.PropertyValue
import org.gradle.api.internal.tasks.properties.PropertyVisitor
import org.gradle.api.tasks.FileNormalizer
import org.gradle.execution.plan.LocalTaskNode
import org.gradle.execution.plan.TaskNodeFactory
import org.gradle.instantexecution.extensions.uncheckedCast
import org.gradle.instantexecution.runToCompletion
import org.gradle.instantexecution.serialization.Codec
import org.gradle.instantexecution.serialization.IsolateContext
import org.gradle.instantexecution.serialization.IsolateOwner
import org.gradle.instantexecution.serialization.MutableIsolateContext
import org.gradle.instantexecution.serialization.PropertyKind
import org.gradle.instantexecution.serialization.PropertyTrace
import org.gradle.instantexecution.serialization.ReadContext
import org.gradle.instantexecution.serialization.WriteContext
import org.gradle.instantexecution.serialization.beans.BeanPropertyWriter
import org.gradle.instantexecution.serialization.beans.readPropertyValue
import org.gradle.instantexecution.serialization.beans.writeNextProperty
import org.gradle.instantexecution.serialization.readCollection
import org.gradle.instantexecution.serialization.readEnum
import org.gradle.instantexecution.serialization.withIsolate
import org.gradle.instantexecution.serialization.withPropertyTrace
import org.gradle.instantexecution.serialization.writeCollection
import org.gradle.instantexecution.serialization.writeEnum
import org.gradle.util.DeferredUtil
class TaskNodeCodec(
private val projectStateRegistry: ProjectStateRegistry,
private val userTypesCodec: Codec<Any?>,
private val taskNodeFactory: TaskNodeFactory
) : Codec<LocalTaskNode> {
override suspend fun WriteContext.encode(value: LocalTaskNode) {
val task = value.task
try {
runToCompletionWithMutableStateOf(task.project) {
writeTask(task)
}
} catch (e: Exception) {
throw GradleException("Could not save state of $task.", e)
}
}
override suspend fun ReadContext.decode(): LocalTaskNode? {
val task = readTask()
return taskNodeFactory.getOrCreateNode(task) as LocalTaskNode
}
private
suspend fun WriteContext.writeTask(task: Task) {
val taskType = GeneratedSubclasses.unpack(task.javaClass)
writeClass(taskType)
writeString(task.project.path)
writeString(task.name)
withTaskOf(taskType, task, userTypesCodec) {
beanStateWriterFor(task.javaClass).run {
writeStateOf(task)
writeRegisteredPropertiesOf(task, this as BeanPropertyWriter)
}
}
}
private
suspend fun ReadContext.readTask(): Task {
val taskType = readClass().asSubclass(Task::class.java)
val projectPath = readString()
val taskName = readString()
val task = createTask(projectPath, taskName, taskType)
withTaskOf(taskType, task, userTypesCodec) {
beanStateReaderFor(task.javaClass).run {
readStateOf(task)
readRegisteredPropertiesOf(task)
}
}
return task
}
/**
* Runs the suspending [block] to completion against the [public mutable state][ProjectState.withMutableState] of [project].
*/
private
fun runToCompletionWithMutableStateOf(project: Project, block: suspend () -> Unit) {
projectStateRegistry.stateFor(project).withMutableState {
runToCompletion(block)
}
}
}
private
inline fun <T> T.withTaskOf(
taskType: Class<*>,
task: Task,
codec: Codec<Any?>,
action: () -> Unit
) where T : IsolateContext, T : MutableIsolateContext {
withIsolate(IsolateOwner.OwnerTask(task), codec) {
withPropertyTrace(PropertyTrace.Task(taskType, task.path)) {
action()
}
}
}
private
sealed class RegisteredProperty {
data class Input(
val propertyName: String,
val propertyValue: PropertyValue,
val optional: Boolean
) : RegisteredProperty()
data class InputFile(
val propertyName: String,
val propertyValue: PropertyValue,
val optional: Boolean,
val filePropertyType: InputFilePropertyType,
val skipWhenEmpty: Boolean,
val incremental: Boolean,
val fileNormalizer: Class<out FileNormalizer>?
) : RegisteredProperty()
data class OutputFile(
val propertyName: String,
val propertyValue: PropertyValue,
val optional: Boolean,
val filePropertyType: OutputFilePropertyType
) : RegisteredProperty()
}
private
suspend fun WriteContext.writeRegisteredPropertiesOf(
task: Task,
propertyWriter: BeanPropertyWriter
) = propertyWriter.run {
suspend fun writeProperty(propertyName: String, propertyValue: Any?, kind: PropertyKind): Boolean {
writeString(propertyName)
return writeNextProperty(propertyName, propertyValue, kind)
}
suspend fun writeInputProperty(propertyName: String, propertyValue: Any?): Boolean =
writeProperty(propertyName, propertyValue, PropertyKind.InputProperty)
suspend fun writeOutputProperty(propertyName: String, propertyValue: Any?): Boolean =
writeProperty(propertyName, propertyValue, PropertyKind.OutputProperty)
val inputProperties = collectRegisteredInputsOf(task)
writeCollection(inputProperties) { property ->
property.run {
when (this) {
is RegisteredProperty.InputFile -> {
val finalValue = DeferredUtil.unpack(propertyValue)
if (writeInputProperty(propertyName, finalValue)) {
writeBoolean(optional)
writeBoolean(true)
writeEnum(filePropertyType)
writeBoolean(skipWhenEmpty)
writeClass(fileNormalizer!!)
}
}
is RegisteredProperty.Input -> {
val finalValue = InputParameterUtils.prepareInputParameterValue(propertyValue)
if (writeInputProperty(propertyName, finalValue)) {
writeBoolean(optional)
writeBoolean(false)
}
}
}
}
}
val outputProperties = collectRegisteredOutputsOf(task)
writeCollection(outputProperties) { property ->
property.run {
val finalValue = DeferredUtil.unpack(propertyValue)
if (writeOutputProperty(propertyName, finalValue)) {
writeBoolean(optional)
writeEnum(filePropertyType)
}
}
}
}
private
fun collectRegisteredOutputsOf(task: Task): List<RegisteredProperty.OutputFile> {
val properties = mutableListOf<RegisteredProperty.OutputFile>()
(task.outputs as TaskOutputsInternal).visitRegisteredProperties(object : PropertyVisitor.Adapter() {
override fun visitOutputFileProperty(
propertyName: String,
optional: Boolean,
value: PropertyValue,
filePropertyType: OutputFilePropertyType
) {
properties.add(
RegisteredProperty.OutputFile(
propertyName,
value,
optional,
filePropertyType
)
)
}
})
return properties
}
private
fun collectRegisteredInputsOf(task: Task): List<RegisteredProperty> {
val properties = mutableListOf<RegisteredProperty>()
(task.inputs as TaskInputsInternal).visitRegisteredProperties(object : PropertyVisitor.Adapter() {
override fun visitInputFileProperty(
propertyName: String,
optional: Boolean,
skipWhenEmpty: Boolean,
incremental: Boolean,
fileNormalizer: Class<out FileNormalizer>?,
propertyValue: PropertyValue,
filePropertyType: InputFilePropertyType
) {
properties.add(
RegisteredProperty.InputFile(
propertyName,
propertyValue,
optional,
filePropertyType,
skipWhenEmpty,
incremental,
fileNormalizer
)
)
}
override fun visitInputProperty(
propertyName: String,
propertyValue: PropertyValue,
optional: Boolean
) {
properties.add(
RegisteredProperty.Input(
propertyName,
propertyValue,
optional
)
)
}
})
return properties
}
private
suspend fun ReadContext.readRegisteredPropertiesOf(task: Task) {
readInputPropertiesOf(task)
readOutputPropertiesOf(task)
}
private
suspend fun ReadContext.readInputPropertiesOf(task: Task) =
readCollection {
val propertyName = readString()
readPropertyValue(PropertyKind.InputProperty, propertyName) { propertyValue ->
val optional = readBoolean()
val isFileInputProperty = readBoolean()
when {
isFileInputProperty -> {
val filePropertyType = readEnum<InputFilePropertyType>()
val skipWhenEmpty = readBoolean()
val normalizer = readClass()
task.inputs.run {
when (filePropertyType) {
InputFilePropertyType.FILE -> file(pack(propertyValue))
InputFilePropertyType.DIRECTORY -> dir(pack(propertyValue))
InputFilePropertyType.FILES -> files(pack(propertyValue))
}
}.run {
withPropertyName(propertyName)
optional(optional)
skipWhenEmpty(skipWhenEmpty)
withNormalizer(normalizer.uncheckedCast())
}
}
else -> {
task.inputs
.property(propertyName, propertyValue)
.optional(optional)
}
}
}
}
private
fun pack(value: Any?) = value ?: Providers.notDefined<Any>()
private
suspend fun ReadContext.readOutputPropertiesOf(task: Task) =
readCollection {
val propertyName = readString()
readPropertyValue(PropertyKind.OutputProperty, propertyName) { propertyValue ->
val optional = readBoolean()
val filePropertyType = readEnum<OutputFilePropertyType>()
task.outputs.run {
when (filePropertyType) {
OutputFilePropertyType.DIRECTORY -> dir(pack(propertyValue))
OutputFilePropertyType.DIRECTORIES -> dirs(pack(propertyValue))
OutputFilePropertyType.FILE -> file(pack(propertyValue))
OutputFilePropertyType.FILES -> files(pack(propertyValue))
}
}.run {
withPropertyName(propertyName)
optional(optional)
}
}
}
private
fun ReadContext.createTask(projectPath: String, taskName: String, taskClass: Class<out Task>) =
getProject(projectPath).tasks.createWithoutConstructor(taskName, taskClass)
| apache-2.0 | 347c7dc80ff0d7b26989a008bd76a76b | 34.059946 | 128 | 0.648092 | 5.3702 | false | false | false | false |
Jonatino/Xena | src/main/java/org/xena/cs/Weapon.kt | 1 | 820 | /*
* Copyright 2016 Jonathan Beaudoin
*
* 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.xena.cs
class Weapon : GameObject() {
var clip1: Long = 0
var clip2: Long = 0
var canReload: Boolean = false
var ammoType: Long = 0
var weaponID: Long = 0
}
| apache-2.0 | 0d6c4e7458bd6af9ff436d3754f1deaa | 24.625 | 78 | 0.687805 | 3.796296 | false | false | false | false |
Deletescape-Media/Lawnchair | SystemUIShared/src/com/android/systemui/flags/Flag.kt | 1 | 5246 | /*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.systemui.flags
import android.os.Parcel
import android.os.Parcelable
interface Flag<T> : Parcelable {
val id: Int
val default: T
val resourceOverride: Int
override fun describeContents() = 0
fun hasResourceOverride(): Boolean {
return resourceOverride != -1
}
}
// Consider using the "parcelize" kotlin library.
data class BooleanFlag @JvmOverloads constructor(
override val id: Int,
override val default: Boolean = false,
override val resourceOverride: Int = -1
) : Flag<Boolean> {
companion object {
@JvmField
val CREATOR = object : Parcelable.Creator<BooleanFlag> {
override fun createFromParcel(parcel: Parcel) = BooleanFlag(parcel)
override fun newArray(size: Int) = arrayOfNulls<BooleanFlag>(size)
}
}
private constructor(parcel: Parcel) : this(
id = parcel.readInt(),
default = parcel.readBoolean()
)
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeInt(id)
parcel.writeBoolean(default)
}
}
data class StringFlag @JvmOverloads constructor(
override val id: Int,
override val default: String = "",
override val resourceOverride: Int = -1
) : Flag<String> {
companion object {
@JvmField
val CREATOR = object : Parcelable.Creator<StringFlag> {
override fun createFromParcel(parcel: Parcel) = StringFlag(parcel)
override fun newArray(size: Int) = arrayOfNulls<StringFlag>(size)
}
}
private constructor(parcel: Parcel) : this(
id = parcel.readInt(),
default = parcel.readString() ?: ""
)
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeInt(id)
parcel.writeString(default)
}
}
data class IntFlag @JvmOverloads constructor(
override val id: Int,
override val default: Int = 0,
override val resourceOverride: Int = -1
) : Flag<Int> {
companion object {
@JvmField
val CREATOR = object : Parcelable.Creator<IntFlag> {
override fun createFromParcel(parcel: Parcel) = IntFlag(parcel)
override fun newArray(size: Int) = arrayOfNulls<IntFlag>(size)
}
}
private constructor(parcel: Parcel) : this(
id = parcel.readInt(),
default = parcel.readInt()
)
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeInt(id)
parcel.writeInt(default)
}
}
data class LongFlag @JvmOverloads constructor(
override val id: Int,
override val default: Long = 0,
override val resourceOverride: Int = -1
) : Flag<Long> {
companion object {
@JvmField
val CREATOR = object : Parcelable.Creator<LongFlag> {
override fun createFromParcel(parcel: Parcel) = LongFlag(parcel)
override fun newArray(size: Int) = arrayOfNulls<LongFlag>(size)
}
}
private constructor(parcel: Parcel) : this(
id = parcel.readInt(),
default = parcel.readLong()
)
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeInt(id)
parcel.writeLong(default)
}
}
data class FloatFlag @JvmOverloads constructor(
override val id: Int,
override val default: Float = 0f,
override val resourceOverride: Int = -1
) : Flag<Float> {
companion object {
@JvmField
val CREATOR = object : Parcelable.Creator<FloatFlag> {
override fun createFromParcel(parcel: Parcel) = FloatFlag(parcel)
override fun newArray(size: Int) = arrayOfNulls<FloatFlag>(size)
}
}
private constructor(parcel: Parcel) : this(
id = parcel.readInt(),
default = parcel.readFloat()
)
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeInt(id)
parcel.writeFloat(default)
}
}
data class DoubleFlag @JvmOverloads constructor(
override val id: Int,
override val default: Double = 0.0,
override val resourceOverride: Int = -1
) : Flag<Double> {
companion object {
@JvmField
val CREATOR = object : Parcelable.Creator<DoubleFlag> {
override fun createFromParcel(parcel: Parcel) = DoubleFlag(parcel)
override fun newArray(size: Int) = arrayOfNulls<DoubleFlag>(size)
}
}
private constructor(parcel: Parcel) : this(
id = parcel.readInt(),
default = parcel.readDouble()
)
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeInt(id)
parcel.writeDouble(default)
}
} | gpl-3.0 | d08bb2ab96b47b47e031b5aecf9dc000 | 27.672131 | 79 | 0.647922 | 4.371667 | false | false | false | false |
tmarsteel/compiler-fiddle | src/compiler/matching/AbstractMatchingResult.kt | 1 | 3141 | /*
* Copyright 2018 Tobias Marstaller
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package compiler.matching
/**
* When a [Matcher] is matched against an input it returns an [AbstractMatchingResult] that describes
* the outcome of the matching process.
*
* If there was no doubt about the input is of the structure the matcher expects the [certainty] must be
* [ResultCertainty.DEFINITIVE]; if the given input is ambigous (e.g. does not have properties unique to the
* [Matcher]), the [certainty] should be [ResultCertainty.NOT_RECOGNIZED].
*
* Along with the [item] of the match, an [AbstractMatchingResult] can provide the caller with additional reportings
* about the matched input. If the input did not match the expectations of the [Matcher] that could be details on what
* expectations were not met.
*
* The [item] may only be null if the given input did not contain enough information to construct a meaningful item.
*/
interface AbstractMatchingResult<out ItemType,ReportingType> {
val certainty: ResultCertainty
val item: ItemType?
val reportings: Collection<ReportingType>
companion object {
fun <ItemType, ReportingType> ofResult(result: ItemType, certainty: ResultCertainty = ResultCertainty.DEFINITIVE): AbstractMatchingResult<ItemType, ReportingType> {
return object : AbstractMatchingResult<ItemType, ReportingType> {
override val certainty = certainty
override val item = result
override val reportings = emptySet<ReportingType>()
}
}
fun <ItemType, ReportingType> ofError(error: ReportingType, certainty: ResultCertainty = ResultCertainty.DEFINITIVE): AbstractMatchingResult<ItemType, ReportingType> {
return object : AbstractMatchingResult<ItemType, ReportingType> {
override val certainty = certainty
override val item = null
override val reportings = setOf(error)
}
}
inline fun <T, reified ItemType, reified ReportingType> of(thing: T, certainty: ResultCertainty = ResultCertainty.DEFINITIVE): AbstractMatchingResult<ItemType, ReportingType> {
if (thing is ItemType) return ofResult(thing, certainty)
if (thing is ReportingType) return ofError(thing, certainty)
throw IllegalArgumentException("Given object is neither of item type nor of error type")
}
}
} | lgpl-3.0 | e4b7a3c023383040b226bf92a50435ef | 48.09375 | 184 | 0.718561 | 4.802752 | false | false | false | false |
eugeis/ee-schkola | ee-schkola/src-gen/main/kotlin/ee/schkola/student/StudentApiBase.kt | 1 | 5158 | package ee.schkola.student
import ee.schkola.SchkolaBase
import ee.schkola.Trace
import ee.schkola.person.Contact
import ee.schkola.person.PersonName
import ee.schkola.person.Profile
import java.util.*
enum class AttendanceState {
REGISTERED, CONFIRMED, CANCELED, PRESENT;
fun isRegistered(): Boolean = this == REGISTERED
fun isConfirmed(): Boolean = this == CONFIRMED
fun isCanceled(): Boolean = this == CANCELED
fun isPresent(): Boolean = this == PRESENT
}
fun String?.toAttendanceState(): AttendanceState {
return if (this != null) AttendanceState.valueOf(this) else AttendanceState.REGISTERED
}
enum class GroupCategory {
COURSE_GROUP, YEAR_GROUP;
fun isCourseGroup(): Boolean = this == COURSE_GROUP
fun isYearGroup(): Boolean = this == YEAR_GROUP
}
fun String?.toGroupCategory(): GroupCategory {
return if (this != null) GroupCategory.valueOf(this) else GroupCategory.COURSE_GROUP
}
open class Attendance : SchkolaBase {
val student: Profile
val date: Date
val course: Course
val hours: Int
val state: AttendanceState
val stateTrace: Trace
val token: String
val tokenTrace: Trace
constructor(id: String = "", student: Profile = Profile(), date: Date = Date(), course: Course = Course(),
hours: Int = 0, state: AttendanceState = AttendanceState.REGISTERED, stateTrace: Trace = Trace(),
token: String = "", tokenTrace: Trace = Trace()) : super(id) {
this.student = student
this.date = date
this.course = course
this.hours = hours
this.state = state
this.stateTrace = stateTrace
this.token = token
this.tokenTrace = tokenTrace
}
companion object {
val EMPTY = Attendance()
}
}
open class Course : SchkolaBase {
val name: String
val begin: Date
val end: Date
val teacher: PersonName
val schoolYear: SchoolYear
val fee: Float
val description: String
constructor(id: String = "", name: String = "", begin: Date = Date(), end: Date = Date(),
teacher: PersonName = PersonName(), schoolYear: SchoolYear = SchoolYear(), fee: Float = 0f,
description: String = "") : super(id) {
this.name = name
this.begin = begin
this.end = end
this.teacher = teacher
this.schoolYear = schoolYear
this.fee = fee
this.description = description
}
companion object {
val EMPTY = Course()
}
}
open class Grade : SchkolaBase {
val student: Profile
val course: Course
val grade: Float
val gradeTrace: Trace
val comment: String
constructor(id: String = "", student: Profile = Profile(), course: Course = Course(), grade: Float = 0f,
gradeTrace: Trace = Trace(), comment: String = "") : super(id) {
this.student = student
this.course = course
this.grade = grade
this.gradeTrace = gradeTrace
this.comment = comment
}
companion object {
val EMPTY = Grade()
}
}
open class Group : SchkolaBase {
val name: String
val category: GroupCategory
val schoolYear: SchoolYear
val representative: Profile
val students: MutableList<Course>
val courses: MutableList<Course>
constructor(id: String = "", name: String = "", category: GroupCategory = GroupCategory.COURSE_GROUP,
schoolYear: SchoolYear = SchoolYear(), representative: Profile = Profile(),
students: MutableList<Course> = arrayListOf(), courses: MutableList<Course> = arrayListOf()) : super(id) {
this.name = name
this.category = category
this.schoolYear = schoolYear
this.representative = representative
this.students = students
this.courses = courses
}
companion object {
val EMPTY = Group()
}
}
open class SchoolApplication : SchkolaBase {
val profile: Profile
val recommendationOf: PersonName
val churchContactPerson: PersonName
val churchContact: Contact
val schoolYear: SchoolYear
val group: String
constructor(id: String = "", profile: Profile = Profile(), recommendationOf: PersonName = PersonName(),
churchContactPerson: PersonName = PersonName(), churchContact: Contact = Contact(),
schoolYear: SchoolYear = SchoolYear(), group: String = "") : super(id) {
this.profile = profile
this.recommendationOf = recommendationOf
this.churchContactPerson = churchContactPerson
this.churchContact = churchContact
this.schoolYear = schoolYear
this.group = group
}
companion object {
val EMPTY = SchoolApplication()
}
}
open class SchoolYear : SchkolaBase {
val name: String
val start: Date
val end: Date
val dates: MutableList<Course>
constructor(id: String = "", name: String = "", start: Date = Date(), end: Date = Date(),
dates: MutableList<Course> = arrayListOf()) : super(id) {
this.name = name
this.start = start
this.end = end
this.dates = dates
}
companion object {
val EMPTY = SchoolYear()
}
}
| apache-2.0 | bdb02a5d5dd3cc17e85eee7a4f5ba22f | 25.725389 | 114 | 0.642885 | 4.252267 | false | false | false | false |
FF14org/ChouseiFF14 | src/main/kotlin/com/ff14/chousei/domain/model/Character.kt | 1 | 1261 | package com.ff14.chousei.domain.model
import javax.persistence.Column
import javax.persistence.Entity
import javax.persistence.Id
import javax.persistence.GeneratedValue
import javax.persistence.ManyToOne
import javax.persistence.Table
/*
* UserテーブルのEntity.
* @param id 主キー
* @param title 書籍名
* @param subTitle 書籍の副題 ない場合はnull
* @param leadingSentence リード文
* @param url リンク先URLパス
*/
@Entity
@Table(name = "character")
data class Character(
@Id @GeneratedValue var id: Long? = null,
@Column(nullable = false) var name: String = "",
@Column var sex: String? = null,
@Column var clan: String? = null,
@Column var firstjob: String? = null,
@Column var secondJob: String? = null,
@Column var thirdJob: String? = null,
@Column var thisWeekToken: Int? = 0,
@Column var spendToken: Int? = 0,
@Column var allToken: Int = 0,
@Column var getTokenItems: String? = null,
@Column var getRaidItems: String? = null,
@Column(nullable = false) var imagePath: String = "",
@Column(nullable = false) var url: String = "",
@ManyToOne @Column var user: User? = null,
@ManyToOne @Column var team: Team? = null,
@Column var isLeader: Boolean) {
} | apache-2.0 | d10aaea2d7debd27ce4125a8dd15a4e2 | 30.578947 | 57 | 0.689741 | 3.387006 | false | false | false | false |
Commit451/LabCoat | app/src/main/java/com/commit451/gitlab/fragment/TodoFragment.kt | 2 | 3383 | package com.commit451.gitlab.fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.commit451.addendum.design.snackbar
import com.commit451.gitlab.App
import com.commit451.gitlab.R
import com.commit451.gitlab.adapter.BaseAdapter
import com.commit451.gitlab.model.api.Todo
import com.commit451.gitlab.navigation.Navigator
import com.commit451.gitlab.util.LoadHelper
import com.commit451.gitlab.viewHolder.TodoViewHolder
import com.google.android.material.snackbar.Snackbar
import kotlinx.android.synthetic.main.fragment_todo.*
class TodoFragment : BaseFragment() {
companion object {
private const val EXTRA_MODE = "extra_mode"
const val MODE_TODO = 0
const val MODE_DONE = 1
fun newInstance(mode: Int): TodoFragment {
val args = Bundle()
args.putInt(EXTRA_MODE, mode)
val fragment = TodoFragment()
fragment.arguments = args
return fragment
}
}
private lateinit var adapter: BaseAdapter<Todo, TodoViewHolder>
private lateinit var loadHelper: LoadHelper<Todo>
private var mode: Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mode = arguments?.getInt(EXTRA_MODE)!!
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_todo, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
adapter = BaseAdapter(
onCreateViewHolder = { parent, _ ->
val viewHolder = TodoViewHolder.inflate(parent)
viewHolder.itemView.setOnClickListener {
val todo = adapter.items[viewHolder.adapterPosition]
val targetUrl = todo.targetUrl
if (targetUrl != null) {
Navigator.navigateToUrl(baseActivty, targetUrl, App.get().getAccount())
} else {
root.snackbar(R.string.not_a_valid_url, Snackbar.LENGTH_SHORT)
}
}
viewHolder
},
onBindViewHolder = { viewHolder, _, item -> viewHolder.bind(item) }
)
loadHelper = LoadHelper(
lifecycleOwner = this,
recyclerView = listTodos,
baseAdapter = adapter,
swipeRefreshLayout = swipeRefreshLayout,
errorOrEmptyTextView = textMessage,
loadInitial = {
when (mode) {
MODE_TODO -> {
gitLab.getTodos(Todo.STATE_PENDING)
}
MODE_DONE -> {
gitLab.getTodos(Todo.STATE_DONE)
}
else -> throw IllegalStateException("$mode is not defined")
}
},
loadMore = {
gitLab.loadAnyList(it)
}
)
loadData()
}
override fun loadData() {
loadHelper.load()
}
}
| apache-2.0 | afa0526105decf2f79769cc72a1154d4 | 33.520408 | 116 | 0.57316 | 5.236842 | false | false | false | false |
toastkidjp/Yobidashi_kt | app/src/main/java/jp/toastkid/yobidashi/browser/bookmark/view/BookmarkListUi.kt | 1 | 21010 | /*
* Copyright (c) 2022 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.yobidashi.browser.bookmark.view
import android.Manifest
import android.app.Activity
import android.content.Context
import android.net.Uri
import android.os.Build
import android.text.format.DateFormat
import androidx.activity.ComponentActivity
import androidx.activity.compose.BackHandler
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.WorkerThread
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.DropdownMenu
import androidx.compose.material.DropdownMenuItem
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import coil.compose.AsyncImage
import jp.toastkid.lib.BrowserViewModel
import jp.toastkid.lib.ContentViewModel
import jp.toastkid.lib.intent.CreateDocumentIntentFactory
import jp.toastkid.lib.intent.GetContentIntentFactory
import jp.toastkid.lib.intent.ShareIntentFactory
import jp.toastkid.lib.model.OptionMenu
import jp.toastkid.lib.view.scroll.usecase.ScrollerUseCase
import jp.toastkid.ui.dialog.DestructiveChangeConfirmDialog
import jp.toastkid.ui.dialog.InputFileNameDialogUi
import jp.toastkid.ui.list.SwipeToDismissItem
import jp.toastkid.yobidashi.R
import jp.toastkid.yobidashi.browser.FaviconApplier
import jp.toastkid.yobidashi.browser.bookmark.BookmarkInitializer
import jp.toastkid.yobidashi.browser.bookmark.BookmarkInsertion
import jp.toastkid.yobidashi.browser.bookmark.ExportedFileParser
import jp.toastkid.yobidashi.browser.bookmark.Exporter
import jp.toastkid.yobidashi.browser.bookmark.model.Bookmark
import jp.toastkid.yobidashi.browser.bookmark.model.BookmarkRepository
import jp.toastkid.yobidashi.browser.bookmark.viewmodel.BookmarkListViewModel
import jp.toastkid.yobidashi.libs.db.DatabaseFinder
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okio.buffer
import okio.sink
import timber.log.Timber
import java.io.IOException
import java.util.Stack
private const val EXPORT_FILE_NAME = "bookmark.html"
@Composable
fun BookmarkListUi() {
val activityContext = LocalContext.current as? ComponentActivity ?: return
val bookmarkRepository = DatabaseFinder().invoke(activityContext).bookmarkRepository()
val browserViewModel = viewModel(BrowserViewModel::class.java, activityContext)
val viewModel = viewModel(BookmarkListViewModel::class.java)
val folderHistory: Stack<String> = Stack()
val onClick: (Bookmark, Boolean) -> Unit = { bookmark, isLongClick ->
when {
isLongClick -> {
browserViewModel
.openBackground(
bookmark.title,
Uri.parse(bookmark.url)
)
}
bookmark.folder -> {
folderHistory.push(bookmark.parent)
viewModel.query(bookmarkRepository, bookmark.title)
}
else -> {
browserViewModel.open(Uri.parse(bookmark.url))
}
}
}
val contentViewModel = viewModel(ContentViewModel::class.java, activityContext)
val listState = rememberLazyListState()
BookmarkList(listState, onClick) {
try {
CoroutineScope(Dispatchers.IO).launch {
viewModel.deleteItem(bookmarkRepository, it)
}
} catch (e: IOException) {
Timber.e(e)
}
}
ScrollerUseCase(contentViewModel, listState).invoke(LocalLifecycleOwner.current)
val openClearDialogState = remember { mutableStateOf(false) }
val openAddFolderDialogState = remember { mutableStateOf(false) }
val getContentLauncher =
rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (it.data == null || it.resultCode != Activity.RESULT_OK) {
return@rememberLauncherForActivityResult
}
val uri = it.data?.data ?: return@rememberLauncherForActivityResult
importBookmark(activityContext, bookmarkRepository, uri) {
viewModel.query(bookmarkRepository)
}
}
val importRequestPermissionLauncher =
rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) {
if (!it && Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
contentViewModel.snackShort(R.string.message_requires_permission_storage)
return@rememberLauncherForActivityResult
}
getContentLauncher.launch(GetContentIntentFactory()("text/html"))
}
val exportLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.StartActivityForResult()
) {
if (it.data == null || it.resultCode != Activity.RESULT_OK) {
return@rememberLauncherForActivityResult
}
val uri = it.data?.data ?: return@rememberLauncherForActivityResult
CoroutineScope(Dispatchers.IO).launch {
exportBookmark(activityContext, bookmarkRepository, uri)
}
}
val exportRequestPermissionLauncher =
rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) {
if (!it && Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
contentViewModel.snackShort(R.string.message_requires_permission_storage)
return@rememberLauncherForActivityResult
}
exportLauncher.launch(
CreateDocumentIntentFactory()("text/html", EXPORT_FILE_NAME)
)
}
InputFileNameDialogUi(openAddFolderDialogState, onCommit = { title ->
CoroutineScope(Dispatchers.Main).launch {
val currentFolderName =
if (viewModel.bookmarks().isEmpty() && folderHistory.isNotEmpty()) folderHistory.peek()
else if (viewModel.bookmarks().isEmpty()) Bookmark.getRootFolderName()
else viewModel.bookmarks()[0].parent
BookmarkInsertion(
activityContext,
title,
parent = currentFolderName,
folder = true
).insert()
viewModel.query(bookmarkRepository)
}
})
DestructiveChangeConfirmDialog(
openClearDialogState,
R.string.title_clear_bookmark
) {
CoroutineScope(Dispatchers.Main).launch {
withContext(Dispatchers.IO) { bookmarkRepository.clear() }
contentViewModel.snackShort(R.string.done_clear)
viewModel.clearItems()
}
}
BackHandler(viewModel.currentFolder() != Bookmark.getRootFolderName()) {
viewModel.query(bookmarkRepository)
}
val lifecycleOwner = LocalLifecycleOwner.current
LaunchedEffect(key1 = "first_launch", block = {
viewModel.query(bookmarkRepository)
contentViewModel.optionMenus(
OptionMenu(titleId = R.string.title_add_folder, action = {
openAddFolderDialogState.value = true
}),
OptionMenu(titleId = R.string.title_import_bookmark, action = {
importRequestPermissionLauncher.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE)
}),
OptionMenu(titleId = R.string.title_export_bookmark, action = {
exportRequestPermissionLauncher.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE)
}),
OptionMenu(titleId = R.string.title_add_default_bookmark, action = {
BookmarkInitializer.from(activityContext)() { viewModel.query(bookmarkRepository) }
contentViewModel.snackShort(R.string.done_addition)
}),
OptionMenu(titleId = R.string.title_clear_bookmark, action = {
openClearDialogState.value = true
})
)
contentViewModel.share.observe(lifecycleOwner) {
it.getContentIfNotHandled() ?: return@observe
contentViewModel.viewModelScope.launch {
val items = withContext(Dispatchers.IO) {
bookmarkRepository.all()
}
val html = withContext(Dispatchers.IO) {
Exporter(items).invoke()
}
activityContext.startActivity(
ShareIntentFactory()(html, EXPORT_FILE_NAME)
)
}
}
})
DisposableEffect(key1 = lifecycleOwner, effect = {
onDispose {
contentViewModel.share.removeObservers(lifecycleOwner)
}
})
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun BookmarkList(
listState: LazyListState,
onClick: (Bookmark, Boolean) -> Unit,
onDelete: (Bookmark) -> Unit
) {
val viewModel = viewModel(BookmarkListViewModel::class.java)
LazyColumn(
contentPadding = PaddingValues(bottom = 4.dp),
verticalArrangement = Arrangement.spacedBy(4.dp),
state = listState,
modifier = Modifier.padding(start = 8.dp, end = 8.dp)
) {
items(viewModel.bookmarks(), { it._id }) { bookmark ->
val openEditor = remember { mutableStateOf(false) }
SwipeToDismissItem(
onClickDelete = {
onDelete(bookmark)
},
dismissContent = {
Row(verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.combinedClickable(
true,
onClick = {
onClick(bookmark, false)
},
onLongClick = {
onClick(bookmark, true)
}
)
.fillMaxWidth()
.wrapContentHeight()
.animateItemPlacement()
) {
AsyncImage(
bookmark.favicon,
bookmark.title,
contentScale = ContentScale.Fit,
alignment = Alignment.Center,
placeholder = painterResource(id = if (bookmark.folder) R.drawable.ic_folder_black else R.drawable.ic_bookmark),
error = painterResource(id = if (bookmark.folder) R.drawable.ic_folder_black else R.drawable.ic_bookmark),
modifier = Modifier
.width(44.dp)
.padding(8.dp)
)
Column(modifier = Modifier.weight(1f)) {
Text(
text = bookmark.title,
fontSize = 18.sp,
maxLines = 2,
overflow = TextOverflow.Ellipsis
)
if (bookmark.url.isNotBlank()) {
Text(
text = bookmark.url,
color = colorResource(id = R.color.link_blue),
fontSize = 12.sp,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
if (bookmark.lastViewed != 0L) {
Text(
text = DateFormat.format(
stringResource(R.string.date_format),
bookmark.lastViewed
).toString(),
color = colorResource(id = R.color.gray_500_dd),
fontSize = 12.sp,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
}
if (bookmark.folder.not()) {
Icon(
painter = painterResource(id = R.drawable.ic_option_menu),
contentDescription = stringResource(id = R.string.title_option_menu),
tint = MaterialTheme.colors.secondary,
modifier = Modifier.clickable {
openEditor.value = true
}
)
}
}
},
modifier = Modifier.animateItemPlacement()
)
if (openEditor.value) {
EditorDialog(openEditor, bookmark)
}
}
}
}
@Composable
private fun EditorDialog(
openEditor: MutableState<Boolean>,
currentItem: Bookmark
) {
val viewModel = viewModel(BookmarkListViewModel::class.java)
val bookmarkRepository = DatabaseFinder().invoke(LocalContext.current).bookmarkRepository()
val folders = remember { mutableStateListOf<String>() }
val moveTo = remember { mutableStateOf(currentItem.parent) }
LaunchedEffect("load_folders") {
folders.clear()
folders.add(Bookmark.getRootFolderName())
CoroutineScope(Dispatchers.IO).launch {
folders.addAll(bookmarkRepository.folders())
}
}
Dialog(onDismissRequest = { openEditor.value = false }) {
Surface(elevation = 4.dp) {
Box {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.End,
modifier = Modifier.align(Alignment.BottomEnd)
) {
Text(
text = stringResource(id = R.string.cancel),
color = MaterialTheme.colors.onSurface,
modifier = Modifier
.clickable {
openEditor.value = false
}
.padding(16.dp)
)
Text(
text = stringResource(id = R.string.ok),
color = MaterialTheme.colors.onSurface,
modifier = Modifier
.clickable {
openEditor.value = false
if (currentItem.parent != moveTo.value) {
moveFolder(
currentItem,
moveTo.value,
bookmarkRepository,
viewModel
)
}
}
.padding(16.dp)
)
}
val openChooser = remember { mutableStateOf(false) }
Column {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
painterResource(id = R.drawable.ic_folder_black),
stringResource(id = R.string.title_add_folder)
)
Text(
"Move to other folder",
fontSize = 20.sp
)
}
Box(
Modifier
.padding(bottom = 60.dp)
.defaultMinSize(200.dp)
.background(Color(0xDDFFFFFF))
.clickable { openChooser.value = true }
) {
Text(
moveTo.value,
fontSize = 20.sp
)
DropdownMenu(
openChooser.value,
onDismissRequest = { openChooser.value = false }
) {
folders.forEach {
DropdownMenuItem(
onClick = {
openChooser.value = false
moveTo.value = it
}
) {
Text(
it,
fontSize = 20.sp
)
}
}
}
}
}
}
}
}
}
private fun moveFolder(
currentItem: Bookmark,
newFolder: String,
bookmarkRepository: BookmarkRepository,
viewModel: BookmarkListViewModel
) {
val folder = currentItem.parent
CoroutineScope(Dispatchers.IO).launch {
currentItem.parent = newFolder
bookmarkRepository.add(currentItem)
viewModel.query(bookmarkRepository, folder)
}
}
/**
* Import bookmark from selected HTML file.
*
* @param uri Bookmark exported html's Uri.
*/
private fun importBookmark(
context: Context,
bookmarkRepository: BookmarkRepository,
uri: Uri,
showRoot: () -> Unit
) {
val inputStream = context.contentResolver?.openInputStream(uri) ?: return
CoroutineScope(Dispatchers.Main).launch {
val faviconApplier = FaviconApplier(context)
withContext(Dispatchers.IO) {
ExportedFileParser()(inputStream)
.map {
it.favicon = faviconApplier.makePath(it.url)
it
}
.forEach { bookmarkRepository.add(it) }
}
showRoot()
}
}
/**
* Export bookmark.
*
* @param uri
*/
@WorkerThread
private fun exportBookmark(
context: Context,
bookmarkRepository: BookmarkRepository,
uri: Uri
) {
val items = bookmarkRepository.all()
context.contentResolver?.openOutputStream(uri)?.use { stream ->
stream.sink().buffer().use {
it.writeUtf8(Exporter(items).invoke())
}
}
} | epl-1.0 | c8114661f6b9d0783d3223a0851a7bed | 37.552294 | 140 | 0.564969 | 5.791069 | false | false | false | false |
devunt/ika | app/src/main/kotlin/org/ozinger/ika/serialization/encoding/SpacedEncoder.kt | 1 | 1602 | package org.ozinger.ika.serialization.encoding
import kotlinx.serialization.SerializationException
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.AbstractEncoder
import kotlinx.serialization.encoding.CompositeEncoder
import org.ozinger.ika.serialization.ModeStringDescriptor
import org.ozinger.ika.serialization.context
open class SpacedEncoder : AbstractEncoder() {
override val serializersModule
get() = context
protected val list = mutableListOf<String>()
private var trailing = false
val encodedValue
get() = list.joinToString(" ")
override fun encodeValue(value: Any) {
val v = value.toString()
list.add(
when {
trailing -> throw SerializationException("Parameter contains the whitespace character should be used once at the last position")
v.contains(' ') -> {
trailing = true; ":$v"
}
else -> v
}
)
}
override fun beginStructure(descriptor: SerialDescriptor): CompositeEncoder {
if (descriptor.annotations.contains(ModeStringDescriptor.annotation)) {
return WhitespaceEncoder()
}
return this
}
override fun encodeNull() {}
inner class WhitespaceEncoder : SpacedEncoder() {
override fun encodeValue(value: Any) {
list.add(value.toString())
}
override fun endStructure(descriptor: SerialDescriptor) {
[email protected](this.encodedValue)
}
}
}
| agpl-3.0 | 4acc4a1cb200b1c971f33ebedf7223b6 | 29.807692 | 144 | 0.656679 | 5.287129 | false | false | false | false |
dya-tel/TSU-Schedule | src/main/kotlin/ru/dyatel/tsuschedule/parsing/ExamScheduleParser.kt | 1 | 4066 | package ru.dyatel.tsuschedule.parsing
import hirondelle.date4j.DateTime
import org.jsoup.nodes.Element
import ru.dyatel.tsuschedule.EmptyResultException
import ru.dyatel.tsuschedule.ParsingException
import ru.dyatel.tsuschedule.model.Exam
private data class Token(
val type: TokenType?,
val discipline: String,
val datetime: DateTime,
val auditory: String,
val teacher: String
)
private enum class TokenType {
CONSULTATION, EXAM
}
object ExamScheduleParser : ParserBase() {
private val DATETIME_PATTERN = Regex("^(\\d+)\\.(\\d+)\\.(\\d+) (\\d+):(\\d+)$") // 11.06.18 09:00
private val TYPE_MAPPING = mapOf(
"конс" to TokenType.CONSULTATION,
"э" to TokenType.EXAM
)
private val TYPE_MARKER_PATTERN = Regex("\\(\\s*([А-Яа-я]+)\\.?\\s*\\)")
fun parse(element: Element): Set<Exam> {
if (element.childNodeSize() < 1) {
throw EmptyResultException()
}
return element.children()
.filter { it.tagName() == "div" }
.map { parseSingle(it) }
.distinct()
.groupBy { it.discipline }
.flatMap { merge(it.value) }
.toSet()
}
private fun parseSingle(e: Element): Token {
var discipline = parseDiscipline(e)
val type = TYPE_MARKER_PATTERN.findAll(discipline)
.map { it to it.groupValues[1].toLowerCase() }
.singleOrNull { TYPE_MAPPING.containsKey(it.second) }
?.let {
discipline = discipline.removeRange(it.first.range).trim()
TYPE_MAPPING[it.second]!!
}
val datetime = parseDatetime(e)
val auditory = parseAuditory(e)
val teacher = parseTeacher(e)
return Token(type, discipline, datetime, auditory, teacher)
}
private fun parseDatetime(e: Element): DateTime {
val text = e.getElementsByClass("time").requireSingle().text().trim()
val groups = DATETIME_PATTERN.matchEntire(text)
?.groupValues
?: throw ParsingException("Can't parse datetime from $text")
return DateTime(
groups[3].toInt(), // Year
groups[2].toInt(), // Month
groups[1].toInt(), // Day
groups[4].toInt(), // Hour
groups[5].toInt(), // Minute
0, 0)
}
private fun parseDiscipline(e: Element) =
e.getElementsByClass("disc").requireSingle().text().trim().removeSuffix(",")
private fun parseAuditory(e: Element) =
e.getElementsByClass("aud").requireSingle().text().trim()
private fun parseTeacher(e: Element) =
e.getElementsByClass("teac").requireSingle().text().trim()
private fun merge(tokens: Collection<Token>): Collection<Exam> {
val result = mutableListOf<Exam>()
val source = tokens.toMutableList()
val consultationToken = source.singleOrNull { it.type == TokenType.CONSULTATION }
val examToken = source.singleOrNull { it.type == TokenType.EXAM }
if (consultationToken != null && examToken != null) {
var teacher = examToken.teacher
if (consultationToken.teacher != examToken.teacher) {
teacher = "${consultationToken.teacher}, $teacher"
}
result += Exam(
examToken.discipline,
consultationToken.datetime,
examToken.datetime,
consultationToken.auditory,
examToken.auditory,
teacher)
source -= consultationToken
source -= examToken
}
for (token in source) {
result += Exam(
token.discipline,
null,
token.datetime,
null,
token.auditory,
token.teacher)
}
return result
}
}
| mit | 0b62561e0bee393c61083d9850090fc5 | 31.456 | 102 | 0.550407 | 4.594564 | false | false | false | false |
chrisbanes/tivi | data-android/src/main/java/app/tivi/data/repositories/relatedshows/RelatedShowsModule.kt | 1 | 3101 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.tivi.data.repositories.relatedshows
import app.tivi.data.daos.RelatedShowsDao
import app.tivi.data.daos.TiviShowDao
import app.tivi.data.entities.RelatedShowEntry
import com.dropbox.android.external.store4.Fetcher
import com.dropbox.android.external.store4.SourceOfTruth
import com.dropbox.android.external.store4.Store
import com.dropbox.android.external.store4.StoreBuilder
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.flow.map
import org.threeten.bp.Duration
import javax.inject.Singleton
typealias RelatedShowsStore = Store<Long, List<RelatedShowEntry>>
@InstallIn(SingletonComponent::class)
@Module
internal object RelatedShowsModule {
@Provides
@Singleton
fun provideRelatedShowsStore(
tmdbRelatedShows: TmdbRelatedShowsDataSource,
relatedShowsDao: RelatedShowsDao,
showDao: TiviShowDao,
lastRequestStore: RelatedShowsLastRequestStore
): RelatedShowsStore = StoreBuilder.from(
fetcher = Fetcher.of { showId: Long ->
tmdbRelatedShows(showId)
.also { lastRequestStore.updateLastRequest(showId) }
},
sourceOfTruth = SourceOfTruth.of(
reader = { showId ->
relatedShowsDao.entriesObservable(showId).map { entries ->
when {
// Store only treats null as 'no value', so convert to null
entries.isEmpty() -> null
// If the request is expired, our data is stale
lastRequestStore.isRequestExpired(showId, Duration.ofDays(28)) -> null
// Otherwise, our data is fresh and valid
else -> entries
}
}
},
writer = { showId, response ->
relatedShowsDao.withTransaction {
val entries = response.map { (show, entry) ->
entry.copy(
showId = showId,
otherShowId = showDao.getIdOrSavePlaceholder(show)
)
}
relatedShowsDao.deleteWithShowId(showId)
relatedShowsDao.insertOrUpdate(entries)
}
},
delete = relatedShowsDao::deleteWithShowId,
deleteAll = relatedShowsDao::deleteAll
)
).build()
}
| apache-2.0 | 29464e89baf36be1d3322cd64622c033 | 37.7625 | 94 | 0.635924 | 4.883465 | false | false | false | false |
vsch/idea-multimarkdown | src/main/java/com/vladsch/md/nav/flex/psi/FlexmarkExampleOptionDefinition.kt | 1 | 2139 | // Copyright (c) 2017-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.flex.psi
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiLiteralExpression
import com.vladsch.md.nav.flex.language.PsiReferenceOptionDefinitionLiteral
/**
* Definition of a flexmark spec example option
*
* @param element string literal expression defining the option
* @param textRange text range in element containing the string, is is usually [1, text.length()-1)
* @param psiClass psiClass in which it is defined
*/
class FlexmarkExampleOptionDefinition constructor(val psiClass: PsiClass, val element: PsiElement, val textRange: TextRange, val originalPsiClass: PsiClass) {
val optionName: String get() = element.text.substring(textRange.startOffset, textRange.endOffset)
val rangeInElement: TextRange get() = textRange
fun isDefinitionFor(option: FlexmarkExampleOption): Boolean = optionName == option.optionName
fun isDefinitionFor(optionName: String): Boolean = isValid && this.optionName == optionName
val literalExpressionElement: PsiLiteralExpression get() = element as PsiLiteralExpression
val isInherited: Boolean get() = originalPsiClass != psiClass
val isValid: Boolean get() = this.optionName.isNotBlank()
fun getPsiReference(): PsiReferenceOptionDefinitionLiteral {
return PsiReferenceOptionDefinitionLiteral(element as PsiLiteralExpression, textRange)
}
val isDataValid: Boolean get() = psiClass.isValid && element.isValid && originalPsiClass.isValid
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as FlexmarkExampleOptionDefinition
if (element != other.element) return false
return true
}
override fun hashCode(): Int {
var result = 0;
result = 31 * result + element.hashCode()
return result
}
}
| apache-2.0 | 49e138db227265b731339c0387dc83d2 | 40.134615 | 177 | 0.746611 | 4.817568 | false | false | false | false |
alygin/intellij-rust | src/test/kotlin/org/rust/ide/intentions/FillMatchArmsIntentionTest.kt | 1 | 3029 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.intentions
class FillMatchArmsIntentionTest : RsIntentionTestBase(FillMatchArmsIntention()) {
fun `test simple enum variants`() = doAvailableTest("""
enum FooBar {
Foo,
Bar
}
fn foo(x: FooBar) {
match x/*caret*/ {}
}
""", """
enum FooBar {
Foo,
Bar
}
fn foo(x: FooBar) {
match x {
FooBar::Foo => {/*caret*/},
FooBar::Bar => {},
}
}
""")
fun `test tuple enum variants`() = doAvailableTest("""
enum FooBar {
Foo(i32),
Bar(bool, f64)
}
fn foo(x: FooBar) {
match x/*caret*/ {}
}
""", """
enum FooBar {
Foo(i32),
Bar(bool, f64)
}
fn foo(x: FooBar) {
match x {
FooBar::Foo(_) => {/*caret*/},
FooBar::Bar(_, _) => {},
}
}
""")
fun `test struct enum variants`() = doAvailableTest("""
enum FooBar {
Foo { foo: i32 },
Bar { bar1: bool, bar2: f64 }
}
fn foo(x: FooBar) {
match x/*caret*/ {}
}
""", """
enum FooBar {
Foo { foo: i32 },
Bar { bar1: bool, bar2: f64 }
}
fn foo(x: FooBar) {
match x {
FooBar::Foo { .. } => {/*caret*/},
FooBar::Bar { .. } => {},
}
}
""")
fun `test different enum variants`() = doAvailableTest("""
enum Foo {
X,
Y(i32),
Z { foo: bool }
}
fn foo(x: Foo) {
match x/*caret*/ {}
}
""", """
enum Foo {
X,
Y(i32),
Z { foo: bool }
}
fn foo(x: Foo) {
match x {
Foo::X => {/*caret*/},
Foo::Y(_) => {},
Foo::Z { .. } => {},
}
}
""")
fun `test incomplete match expr`() = doAvailableTest("""
enum FooBar {
Foo,
Bar
}
fn foo(x: FooBar) {
match x/*caret*/
}
""", """
enum FooBar {
Foo,
Bar
}
fn foo(x: FooBar) {
match x {
FooBar::Foo => {/*caret*/},
FooBar::Bar => {},
}
}
""")
fun `test not empty match expr body`() = doUnavailableTest("""
enum FooBar {
Foo,
Bar
}
fn foo(x: FooBar) {
match x/*caret*/ {
FooBar::Foo => {},
}
}
""")
fun `test not enum in match expr`() = doUnavailableTest("""
fn foo(x: i32) {
match x/*caret*/ {}
}
""")
}
| mit | ebc7e46f6814aa173a7d49124d129f33 | 19.746575 | 82 | 0.352922 | 4.494065 | false | true | false | false |
iluu/algs-progfun | src/main/kotlin/com/hackerrank/AppendAndDelete.kt | 1 | 484 | package com.hackerrank
import java.util.*
fun main(args: Array<String>) {
val scan = Scanner(System.`in`)
val s = scan.next()
val t = scan.next()
val k = scan.nextInt()
println(if (canTransform(s, t, k)) "Yes" else "No")
}
fun canTransform(s: String, t: String, k: Int): Boolean {
val commonPrefix = t.commonPrefixWith(s)
val diff = t.length + s.length - commonPrefix.length * 2
return k >= diff && (diff % 2 == k % 2) || s.length + t.length < k
}
| mit | db84014e85cc76ca6a9f4465cd7afbc0 | 25.888889 | 70 | 0.61157 | 3.063291 | false | false | false | false |
rei-m/android_hyakuninisshu | feature/question/src/main/java/me/rei_m/hyakuninisshu/feature/question/ui/widget/YomiFudaWordView.kt | 1 | 1850 | /*
* Copyright (c) 2020. Rei Matsushita
*
* 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 me.rei_m.hyakuninisshu.feature.question.ui.widget
import android.content.Context
import android.util.AttributeSet
import android.util.TypedValue
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.content.res.ResourcesCompat
import androidx.core.content.withStyledAttributes
import me.rei_m.hyakuninisshu.feature.question.R
class YomiFudaWordView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : AppCompatTextView(context, attrs, defStyleAttr) {
private var position: Int? = null
init {
typeface = ResourcesCompat.getFont(context, R.font.hannari)
context.withStyledAttributes(attrs, R.styleable.YomiFudaWordView) {
position = getInt(R.styleable.YomiFudaWordView_position, 0)
}
}
var textSizeByPx: Int? = null
set(value) {
field = value
value ?: return
setTextSize(TypedValue.COMPLEX_UNIT_PX, value.toFloat())
}
fun setText(text: String?) {
text ?: return
val textPosition = position ?: return
if (text.length < textPosition) {
return
}
this.text = text.substring(textPosition - 1, textPosition)
}
}
| apache-2.0 | ae7fe07909445104f360df12f644835d | 33.90566 | 112 | 0.704324 | 4.262673 | false | false | false | false |
vitoling/HiWeather | src/main/kotlin/com/vito/work/weather/admin/tasks/ForecastWeatherTask.kt | 1 | 1997 | package com.vito.work.weather.admin.tasks
import com.vito.work.weather.config.SpiderStatus
import com.vito.work.weather.service.ForecastWeatherService
import com.vito.work.weather.service.LocationService
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.scheduling.annotation.EnableScheduling
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
import us.codecraft.webmagic.scheduler.QueueScheduler
/**
* Created by lingzhiyuan.
* Date : 2016/11/22.
* Time : 12:44.
* Description:
*
*/
@Component
@EnableScheduling
class ForecastWeatherTask @Autowired constructor(val locationService: LocationService, val forecastWeatherService: ForecastWeatherService) {
companion object {
val logger = LoggerFactory.getLogger(ForecastWeatherTask::class.java) !!
}
@Scheduled(cron = "0 0 7 * * ?") // 每天早上七点更新
fun scheduledForecastWeatherUpdate() {
// 如果正在更新,则跳过
if (SpiderStatus.FORECAST_UPDATE_STATUS) {
logger.info("Skip Scheduled Task : Forecast Weather Is Updating")
return
}
logger.info("Start : Executing Scheduled Task Update Forecast Weather")
// 重置 Scheduler (清空Scheduler内已爬取的 url)
ForecastWeatherService.spider.scheduler = QueueScheduler()
val districts = locationService.findDistricts()
val cities = locationService.findCities() ?: listOf()
cities.forEach {
city ->
districts.filter { it.city == city.id }.forEach { district ->
try {
forecastWeatherService.execute(city, district)
} catch(ex: Exception) {
ex.printStackTrace()
// 忽略更新时的异常
}
}
}
logger.info("Success : Task Update Forecast Weather")
}
} | gpl-3.0 | fc0d33766481ec241bad61120f08a96a | 31.1 | 140 | 0.674805 | 4.550827 | false | false | false | false |
suncycheng/intellij-community | java/java-tests/testSrc/com/intellij/java/propertyBased/PsiIndexConsistencyTest.kt | 1 | 8586 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.java.propertyBased
import com.intellij.java.propertyBased.PsiIndexConsistencyTest.Action.*
import com.intellij.lang.java.lexer.JavaLexer
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.pom.java.LanguageLevel
import com.intellij.psi.*
import com.intellij.psi.codeStyle.CodeStyleManager
import com.intellij.psi.impl.source.PostprocessReformattingAspect
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.testFramework.IdeaTestUtil
import com.intellij.testFramework.PlatformTestUtil
import com.intellij.testFramework.SkipSlowTestLocally
import com.intellij.testFramework.fixtures.CodeInsightTestFixture
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase
import com.intellij.util.FileContentUtilCore
import slowCheck.Generator
import slowCheck.PropertyChecker
/**
* @author peter
*/
@SkipSlowTestLocally
class PsiIndexConsistencyTest: LightCodeInsightFixtureTestCase() {
fun testFuzzActions() {
val genAction: Generator<Action> = Generator.frequency(mapOf(
1 to Generator.constant(Gc),
50 to Generator.sampledFrom(Commit,
AddImport,
AddEnum,
ForceReloadPsi,
Reformat,
InvisiblePsiChange,
PostponedFormatting,
RenamePsiFile,
RenameVirtualFile,
Save),
10 to Generator.sampledFrom(*RefKind.values()).map { LoadRef(it) },
10 to Generator.sampledFrom(*RefKind.values()).map { ClearRef(it) },
5 to Generator.booleans().map { ChangeLanguageLevel(if (it) LanguageLevel.HIGHEST else LanguageLevel.JDK_1_3) },
5 to Generator.from { data -> TextChange(Generator.asciiIdentifiers().suchThat { !JavaLexer.isKeyword(it, LanguageLevel.HIGHEST) }.generateValue(data),
Generator.booleans().generateValue(data),
Generator.booleans().generateValue(data)) }
))
PropertyChecker.forAll(Generator.listsOf(genAction)).withIterationCount(20).shouldHold { actions ->
runActions(*actions.toTypedArray())
true
}
}
private fun runActions(vararg actions: Action) {
val vFile = myFixture.addFileToProject("Foo.java", "class Foo {} ").virtualFile
val model = Model(vFile, myFixture)
WriteCommandAction.runWriteCommandAction(project) {
try {
actions.forEach { it.performAction(model) }
} finally {
try {
Save.performAction(model)
vFile.delete(this)
}
catch(e: Throwable) {
e.printStackTrace()
}
}
}
}
internal class Model(val vFile: VirtualFile, val fixture: CodeInsightTestFixture) {
val refs = hashMapOf<RefKind, Any?>()
val project = fixture.project!!
var docClassName = "Foo"
var psiClassName = "Foo"
fun findPsiFile() = PsiManager.getInstance(project).findFile(vFile) as PsiJavaFile
fun findPsiClass() = JavaPsiFacade.getInstance(project).findClass(psiClassName, GlobalSearchScope.allScope(project))!!
fun getDocument() = FileDocumentManager.getInstance().getDocument(vFile)!!
}
internal interface Action {
fun performAction(model: Model)
abstract class SimpleAction: Action {
override fun toString(): String = javaClass.simpleName
}
object Gc: SimpleAction() {
override fun performAction(model: Model) = PlatformTestUtil.tryGcSoftlyReachableObjects()
}
object Commit: SimpleAction() {
override fun performAction(model: Model) {
PsiDocumentManager.getInstance(model.project).commitAllDocuments()
model.psiClassName = model.docClassName
}
}
object Save: SimpleAction() {
override fun performAction(model: Model) {
PostponedFormatting.performAction(model)
FileDocumentManager.getInstance().saveAllDocuments()
}
}
object PostponedFormatting: SimpleAction() {
override fun performAction(model: Model) =
PostprocessReformattingAspect.getInstance(model.project).doPostponedFormatting()
}
object ForceReloadPsi: SimpleAction() {
override fun performAction(model: Model) {
PostponedFormatting.performAction(model)
FileContentUtilCore.reparseFiles(model.vFile)
}
}
object AddImport: SimpleAction() {
override fun performAction(model: Model) {
Commit.performAction(model)
model.findPsiFile().importList!!.add(JavaPsiFacade.getElementFactory(model.project).createImportStatementOnDemand("java.io"))
}
}
object InvisiblePsiChange: SimpleAction() {
override fun performAction(model: Model) {
Commit.performAction(model)
val ref = model.refs[RefKind.ClassRef] as PsiClass?
val cls = if (ref != null && ref.isValid) ref else model.findPsiClass()
cls.replace(cls.copy())
}
}
object RenameVirtualFile: SimpleAction() {
override fun performAction(model: Model) {
model.vFile.rename(this, model.vFile.nameWithoutExtension + "1.java")
}
}
object RenamePsiFile: SimpleAction() {
override fun performAction(model: Model) {
val newName = model.vFile.nameWithoutExtension + "1.java"
model.findPsiFile().name = newName
assert(model.findPsiFile().name == newName)
assert(model.vFile.name == newName)
}
}
object AddEnum: SimpleAction() {
override fun performAction(model: Model) {
Commit.performAction(model)
model.findPsiFile().add(JavaPsiFacade.getElementFactory(model.project).createEnum("SomeEnum"))
}
}
object Reformat: SimpleAction() {
override fun performAction(model: Model) {
Commit.performAction(model)
CodeStyleManager.getInstance(model.project).reformat(model.findPsiFile())
}
}
data class ChangeLanguageLevel(val level: LanguageLevel): Action {
override fun performAction(model: Model) {
PostponedFormatting.performAction(model)
IdeaTestUtil.setModuleLanguageLevel(model.fixture.module, level)
}
}
data class LoadRef(val kind: RefKind): Action {
override fun performAction(model: Model) {
model.refs[kind] = kind.loadRef(model)
}
}
data class ClearRef(val kind: RefKind): Action {
override fun performAction(model: Model) {
model.refs.remove(kind)
}
}
data class TextChange(val newClassName: String, val viaDocument: Boolean, val withImport: Boolean): Action {
override fun performAction(model: Model) {
PostponedFormatting.performAction(model)
val counterBefore = PsiManager.getInstance(model.project).modificationTracker.javaStructureModificationCount
model.docClassName = newClassName
val newText = (if (withImport) "import zoo.Zoo; " else "") + "class ${model.docClassName} { }"
if (viaDocument) {
model.getDocument().setText(newText)
} else {
Save.performAction(model)
VfsUtil.saveText(model.vFile, newText)
}
if (PsiDocumentManager.getInstance(model.project).uncommittedDocuments.isEmpty()) {
model.psiClassName = model.docClassName
assert(counterBefore != PsiManager.getInstance(model.project).modificationTracker.javaStructureModificationCount)
}
}
}
}
internal enum class RefKind(val loadRef: (Model) -> Any) {
ClassRef({ it.findPsiClass() }),
PsiFileRef({ it.findPsiFile()}),
AstRef({ it.findPsiClass().node }),
DocumentRef({ it.getDocument() }),
DirRef({ it.findPsiFile().containingDirectory })
}
} | apache-2.0 | 4f0cac1edeb58c5e07cb26bf04287872 | 38.571429 | 157 | 0.677032 | 4.837183 | false | true | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/libanki/Models.kt | 1 | 40453 | /****************************************************************************************
* Copyright (c) 2009 Daniel Svärd <[email protected]> *
* Copyright (c) 2010 Rick Gruber-Riemer <[email protected]> *
* Copyright (c) 2011 Norbert Nagold <[email protected]> *
* Copyright (c) 2011 Kostas Spyropoulos <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.libanki
import android.content.ContentValues
import androidx.annotation.VisibleForTesting
import com.ichi2.anki.exception.ConfirmModSchemaException
import com.ichi2.libanki.template.ParsedNode
import com.ichi2.libanki.template.TemplateError
import com.ichi2.libanki.utils.TimeManager.time
import com.ichi2.utils.*
import com.ichi2.utils.HashUtil.HashMapInit
import com.ichi2.utils.KotlinCleanup
import com.ichi2.utils.jsonObjectIterable
import com.ichi2.utils.stringIterable
import org.json.JSONArray
import org.json.JSONObject
import timber.log.Timber
import java.util.*
import java.util.regex.Pattern
@KotlinCleanup("IDE Lint")
@KotlinCleanup("Lots to do")
class Models(col: Collection) : ModelManager(col) {
/**
* Saving/loading registry
* ***********************************************************************************************
*/
private var mChanged = false
@KotlinCleanup("lateinit")
private var mModels: HashMap<Long, Model>? = null
/**
* @return the ID
*/
// BEGIN SQL table entries
val id = 0
/** {@inheritDoc} */
override fun load(json: String) {
mChanged = false
mModels = HashMap()
val modelarray = JSONObject(json)
@KotlinCleanup("simplify with ?.forEach{}")
val ids = modelarray.names()
if (ids != null) {
for (id in ids.stringIterable()) {
val o = Model(modelarray.getJSONObject(id))
mModels!![o.getLong("id")] = o
}
}
}
/** {@inheritDoc} */
override fun save(m: Model?, templates: Boolean) {
if (m != null && m.has("id")) {
m.put("mod", time.intTime())
m.put("usn", col.usn())
// TODO: fix empty id problem on _updaterequired (needed for model adding)
if (!isModelNew(m)) {
// this fills in the `req` chunk of the model. Not used on AnkiDroid 2.15+ or AnkiDesktop 2.1.x
// Included only for backwards compatibility (to AnkiDroid <2.14 etc)
// https://forums.ankiweb.net/t/is-req-still-used-or-present/9977
// https://github.com/ankidroid/Anki-Android/issues/8945
_updateRequired(m)
}
if (templates) {
_syncTemplates(m)
}
}
mChanged = true
// The following hook rebuilds the tree in the Anki Desktop browser -- we don't need it
// runHook("newModel")
}
/** {@inheritDoc} */
@KotlinCleanup("fix 'val'")
override fun flush() {
if (mChanged) {
ensureNotEmpty()
val array = JSONObject()
for ((key, value) in mModels!!) {
array.put(java.lang.Long.toString(key), value)
}
val `val` = ContentValues()
`val`.put("models", Utils.jsonToString(array))
col.db.update("col", `val`)
mChanged = false
}
}
/** {@inheritDoc} */
override fun ensureNotEmpty(): Boolean {
return if (mModels!!.isEmpty()) {
// TODO: Maybe we want to restore all models if we don't have any
StdModels.BASIC_MODEL.add(col)
true
} else {
false
}
}
/*
Retrieving and creating models
***********************************************************************************************
*/
/** {@inheritDoc} */
@KotlinCleanup("remove var and simplify fun with direct return")
override fun current(forDeck: Boolean): Model? {
var m: Model? = null
if (forDeck) {
m = get(col.decks.current().optLong("mid", -1))
}
if (m == null) {
m = get(col.get_config("curModel", -1L)!!)
}
if (m == null) {
if (!mModels!!.isEmpty()) {
m = mModels!!.values.iterator().next()
}
}
return m
}
override fun setCurrent(m: Model) {
col.set_config("curModel", m.getLong("id"))
}
/** {@inheritDoc} */
@KotlinCleanup("replace with mModels!![id] if this matches 'libanki'")
override operator fun get(id: Long): Model? {
return if (mModels!!.containsKey(id)) {
mModels!![id]
} else {
null
}
}
/** {@inheritDoc} */
override fun all(): ArrayList<Model> {
return ArrayList(mModels!!.values)
}
/** {@inheritDoc} */
@KotlinCleanup("replace with map")
override fun allNames(): ArrayList<String> {
val nameList = ArrayList<String>()
for (m in mModels!!.values) {
nameList.add(m.getString("name"))
}
return nameList
}
/** {@inheritDoc} */
@KotlinCleanup("replace with .find { }")
override fun byName(name: String): Model? {
for (m in mModels!!.values) {
if (m.getString("name") == name) {
return m
}
}
return null
}
/** {@inheritDoc} */
override fun newModel(name: String): Model {
// caller should call save() after modifying
return Model(DEFAULT_MODEL).apply {
put("name", name)
put("mod", time.intTime())
put("flds", JSONArray())
put("tmpls", JSONArray())
put("id", 0)
}
}
/** {@inheritDoc} */
@Throws(ConfirmModSchemaException::class)
override operator fun rem(m: Model) {
col.modSchema()
val id = m.getLong("id")
val current = current()!!.getLong("id") == id
// delete notes/cards
col.remCards(
col.db.queryLongList(
"SELECT id FROM cards WHERE nid IN (SELECT id FROM notes WHERE mid = ?)",
id
)
)
// then the model
mModels!!.remove(id)
save()
// GUI should ensure last model is not deleted
if (current) {
setCurrent(mModels!!.values.iterator().next())
}
}
override fun add(m: Model) {
_setID(m)
update(m)
setCurrent(m)
save(m)
}
override fun update(m: Model, preserve_usn_and_mtime: Boolean) {
if (!preserve_usn_and_mtime) {
Timber.w("preserve_usn_and_mtime is not supported in legacy java class")
}
mModels!![m.getLong("id")] = m
// mark registry changed, but don't bump mod time
save()
}
private fun _setID(m: Model) {
var id = time.intTimeMS()
while (mModels!!.containsKey(id)) {
id = time.intTimeMS()
}
m.put("id", id)
}
override fun have(id: Long): Boolean {
return mModels!!.containsKey(id)
}
override fun ids(): Set<Long> {
return mModels!!.keys
}
/*
Tools ***********************************************************************************************
*/
/** {@inheritDoc} */
override fun nids(m: Model): List<Long> {
return col.db.queryLongList("SELECT id FROM notes WHERE mid = ?", m.getLong("id"))
}
/** {@inheritDoc} */
override fun useCount(m: Model): Int {
return col.db.queryScalar("select count() from notes where mid = ?", m.getLong("id"))
}
/** {@inheritDoc} */
override fun tmplUseCount(m: Model, ord: Int): Int {
return col.db.queryScalar(
"select count() from cards, notes where cards.nid = notes.id and notes.mid = ? and cards.ord = ?",
m.getLong("id"),
ord
)
}
/*
Copying ***********************************************************************************************
*/
/** {@inheritDoc} */
override fun copy(m: Model): Model {
val m2 = m.deepClone()
m2.put("name", m2.getString("name") + " copy")
add(m2)
return m2
}
/*
* Fields ***********************************************************************************************
*/
override fun newField(name: String): JSONObject {
return JSONObject(defaultField).apply {
put("name", name)
}
}
override fun sortIdx(m: Model): Int {
return m.getInt("sortf")
}
@Throws(ConfirmModSchemaException::class)
override fun setSortIdx(m: Model, idx: Int) {
col.modSchema()
m.put("sortf", idx)
col.updateFieldCache(nids(m))
save(m)
}
override fun _addField(m: Model, field: JSONObject) {
// do the actual work of addField. Do not check whether model
// is not new.
val flds = m.getJSONArray("flds")
flds.put(field)
m.put("flds", flds)
_updateFieldOrds(m)
save(m)
_transformFields(m, TransformFieldAdd())
}
@Throws(ConfirmModSchemaException::class)
override fun addField(m: Model, field: JSONObject) {
// only mod schema if model isn't new
// this is Anki's addField.
if (!isModelNew(m)) {
col.modSchema()
}
_addField(m, field)
}
internal class TransformFieldAdd : TransformFieldVisitor {
@KotlinCleanup("remove arrayOfNulls")
override fun transform(fields: Array<String>): Array<String> {
val f = arrayOfNulls<String>(fields.size + 1)
System.arraycopy(fields, 0, f, 0, fields.size)
f[fields.size] = ""
return f.requireNoNulls()
}
}
@Throws(ConfirmModSchemaException::class)
override fun remField(m: Model, field: JSONObject) {
col.modSchema()
val flds = m.getJSONArray("flds")
val flds2 = JSONArray()
var idx = -1
for (i in 0 until flds.length()) {
if (field == flds.getJSONObject(i)) {
idx = i
continue
}
flds2.put(flds.getJSONObject(i))
}
m.put("flds", flds2)
val sortf = m.getInt("sortf")
if (sortf >= m.getJSONArray("flds").length()) {
m.put("sortf", sortf - 1)
}
_updateFieldOrds(m)
_transformFields(m, TransformFieldDelete(idx))
if (idx == sortIdx(m)) {
// need to rebuild
col.updateFieldCache(nids(m))
}
renameFieldInternal(m, field, null)
}
internal class TransformFieldDelete(private val idx: Int) : TransformFieldVisitor {
@KotlinCleanup("simplify fun with array.toMutableList().filterIndexed")
override fun transform(fields: Array<String>): Array<String> {
val fl = ArrayList(listOf(*fields))
fl.removeAt(idx)
return fl.toTypedArray()
}
}
@Throws(ConfirmModSchemaException::class)
override fun moveField(m: Model, field: JSONObject, idx: Int) {
col.modSchema()
var flds = m.getJSONArray("flds")
val l = ArrayList<JSONObject?>(flds.length())
var oldidx = -1
for (i in 0 until flds.length()) {
l.add(flds.getJSONObject(i))
if (field == flds.getJSONObject(i)) {
oldidx = i
if (idx == oldidx) {
return
}
}
}
// remember old sort field
val sortf = Utils.jsonToString(m.getJSONArray("flds").getJSONObject(m.getInt("sortf")))
// move
l.removeAt(oldidx)
l.add(idx, field)
m.put("flds", JSONArray(l))
// restore sort field
flds = m.getJSONArray("flds")
for (i in 0 until flds.length()) {
if (Utils.jsonToString(flds.getJSONObject(i)) == sortf) {
m.put("sortf", i)
break
}
}
_updateFieldOrds(m)
save(m)
_transformFields(m, TransformFieldMove(idx, oldidx))
}
internal class TransformFieldMove(private val idx: Int, private val oldidx: Int) :
TransformFieldVisitor {
@KotlinCleanup("simplify with array.toMutableList and maybe scope function")
override fun transform(fields: Array<String>): Array<String> {
val `val` = fields[oldidx]
val fl = ArrayList(listOf(*fields))
fl.removeAt(oldidx)
fl.add(idx, `val`)
return fl.toTypedArray()
}
}
@KotlinCleanup("remove this, make newName non-null and use empty string instead of null")
@KotlinCleanup("turn 'pat' into pat.toRegex()")
private fun renameFieldInternal(m: Model, field: JSONObject, newName: String?) {
@Suppress("NAME_SHADOWING")
var newName: String? = newName
col.modSchema()
val pat = String.format(
"\\{\\{([^{}]*)([:#^/]|[^:#/^}][^:}]*?:|)%s\\}\\}",
Pattern.quote(field.getString("name"))
)
if (newName == null) {
newName = ""
}
val repl = "{{$1$2$newName}}"
val tmpls = m.getJSONArray("tmpls")
for (t in tmpls.jsonObjectIterable()) {
for (fmt in arrayOf("qfmt", "afmt")) {
if ("" != newName) {
t.put(fmt, t.getString(fmt).replace(pat.toRegex(), repl))
} else {
t.put(fmt, t.getString(fmt).replace(pat.toRegex(), ""))
}
}
}
field.put("name", newName)
save(m)
}
@Throws(ConfirmModSchemaException::class)
override fun renameField(m: Model, field: JSONObject, newName: String) =
renameFieldInternal(m, field, newName)
fun _updateFieldOrds(m: JSONObject) {
val flds = m.getJSONArray("flds")
for (i in 0 until flds.length()) {
val f = flds.getJSONObject(i)
f.put("ord", i)
}
}
interface TransformFieldVisitor {
fun transform(fields: Array<String>): Array<String>
}
fun _transformFields(m: Model, fn: TransformFieldVisitor) {
// model hasn't been added yet?
if (isModelNew(m)) {
return
}
val r = ArrayList<Array<Any>>()
col.db
.query("select id, flds from notes where mid = ?", m.getLong("id")).use { cur ->
while (cur.moveToNext()) {
r.add(
arrayOf(
Utils.joinFields(fn.transform(Utils.splitFields(cur.getString(1)))),
time.intTime(), col.usn(), cur.getLong(0)
)
)
}
}
col.db.executeMany("update notes set flds=?,mod=?,usn=? where id = ?", r)
}
/** Note: should col.genCards() afterwards. */
override fun _addTemplate(m: Model, template: JSONObject) {
// do the actual work of addTemplate. Do not consider whether
// model is new or not.
val tmpls = m.getJSONArray("tmpls")
tmpls.put(template)
m.put("tmpls", tmpls)
_updateTemplOrds(m)
save(m)
}
@Throws(ConfirmModSchemaException::class)
override fun addTemplate(m: Model, template: JSONObject) {
// That is Anki's addTemplate method
if (!isModelNew(m)) {
col.modSchema()
}
_addTemplate(m, template)
}
/** {@inheritDoc} */
@Throws(ConfirmModSchemaException::class)
override fun remTemplate(m: Model, template: JSONObject) {
if (m.getJSONArray("tmpls").length() <= 1) {
return
}
// find cards using this template
var tmpls = m.getJSONArray("tmpls")
var ord = -1
for (i in 0 until tmpls.length()) {
if (tmpls.getJSONObject(i) == template) {
ord = i
break
}
}
require(ord != -1) { "Invalid template proposed for delete" }
// the code in "isRemTemplateSafe" was in place here in libanki. It is extracted to a method for reuse
val cids = getCardIdsForModel(m.getLong("id"), intArrayOf(ord))
if (cids == null) {
Timber.d("remTemplate getCardIdsForModel determined it was unsafe to delete the template")
return
}
// ok to proceed; remove cards
Timber.d("remTemplate proceeding to delete the template and %d cards", cids.size)
col.modSchema()
col.remCards(cids)
// shift ordinals
col.db
.execute(
"update cards set ord = ord - 1, usn = ?, mod = ? where nid in (select id from notes where mid = ?) and ord > ?",
col.usn(), time.intTime(), m.getLong("id"), ord
)
tmpls = m.getJSONArray("tmpls")
val tmpls2 = JSONArray()
for (i in 0 until tmpls.length()) {
if (template == tmpls.getJSONObject(i)) {
continue
}
tmpls2.put(tmpls.getJSONObject(i))
}
m.put("tmpls", tmpls2)
_updateTemplOrds(m)
save(m)
Timber.d("remTemplate done working")
}
override fun moveTemplate(m: Model, template: JSONObject, idx: Int) {
var tmpls = m.getJSONArray("tmpls")
var oldidx = -1
val l = ArrayList<JSONObject?>()
val oldidxs = HashMap<Int, Int>()
for (i in 0 until tmpls.length()) {
if (tmpls.getJSONObject(i) == template) {
oldidx = i
if (idx == oldidx) {
return
}
}
val t = tmpls.getJSONObject(i)
oldidxs[t.hashCode()] = t.getInt("ord")
l.add(t)
}
l.removeAt(oldidx)
l.add(idx, template)
m.put("tmpls", JSONArray(l))
_updateTemplOrds(m)
// generate change map - We use StringBuilder
val sb = StringBuilder()
tmpls = m.getJSONArray("tmpls")
for (i in 0 until tmpls.length()) {
val t = tmpls.getJSONObject(i)
sb.append("when ord = ").append(oldidxs[t.hashCode()]).append(" then ")
.append(t.getInt("ord"))
if (i != tmpls.length() - 1) {
sb.append(" ")
}
}
// apply
save(m)
col.db.execute(
"update cards set ord = (case " + sb +
" end),usn=?,mod=? where nid in (select id from notes where mid = ?)",
col.usn(), time.intTime(), m.getLong("id")
)
}
private fun _syncTemplates(m: Model) {
@Suppress("UNUSED_VARIABLE") // unused upstream as well
val rem = col.genCards(nids(m), m)!!
}
/*
Model changing ***********************************************************************************************
*/
/** {@inheritDoc} */
@Throws(ConfirmModSchemaException::class)
@KotlinCleanup("rename null param from genCards")
override fun change(
m: Model,
nid: NoteId,
newModel: Model,
fmap: Map<Int, Int?>,
cmap: Map<Int, Int?>
) {
col.modSchema()
_changeNote(nid, newModel, fmap)
_changeCards(nid, m, newModel, cmap)
col.genCards(nid, newModel, null)
}
private fun _changeNote(nid: Long, newModel: Model, map: Map<Int, Int?>) {
val nfields = newModel.getJSONArray("flds").length()
val mid = newModel.getLong("id")
val sflds = col.db.queryString("select flds from notes where id = ?", nid)
val flds = Utils.splitFields(sflds)
val newflds: MutableMap<Int?, String> = HashMapInit(map.size)
for ((key, value) in map) {
newflds[value] = flds[key]
}
val flds2: MutableList<String> = ArrayList(nfields)
for (c in 0 until nfields) {
@KotlinCleanup("getKeyOrDefault")
if (newflds.containsKey(c)) {
flds2.add(newflds[c]!!)
} else {
flds2.add("")
}
}
val joinedFlds = Utils.joinFields(flds2.toTypedArray())
col.db.execute(
"update notes set flds=?,mid=?,mod=?,usn=? where id = ?",
joinedFlds,
mid,
time.intTime(),
col.usn(),
nid
)
col.updateFieldCache(longArrayOf(nid))
}
private fun _changeCards(nid: Long, oldModel: Model, newModel: Model, map: Map<Int, Int?>) {
val d: MutableList<Array<Any>> = ArrayList()
val deleted: MutableList<Long> = ArrayList()
val omType = oldModel.getInt("type")
val nmType = newModel.getInt("type")
val nflds = newModel.getJSONArray("tmpls").length()
col.db.query(
"select id, ord from cards where nid = ?", nid
).use { cur ->
while (cur.moveToNext()) {
// if the src model is a cloze, we ignore the map, as the gui doesn't currently
// support mapping them
var newOrd: Int?
val cid = cur.getLong(0)
val ord = cur.getInt(1)
if (omType == Consts.MODEL_CLOZE) {
newOrd = cur.getInt(1)
if (nmType != Consts.MODEL_CLOZE) {
// if we're mapping to a regular note, we need to check if
// the destination ord is valid
if (nflds <= ord) {
newOrd = null
}
}
} else {
// mapping from a regular note, so the map should be valid
newOrd = map[ord]
}
if (newOrd != null) {
d.add(arrayOf(newOrd, col.usn(), time.intTime(), cid))
} else {
deleted.add(cid)
}
}
}
col.db.executeMany("update cards set ord=?,usn=?,mod=? where id=?", d)
col.remCards(deleted)
}
/*
Schema hash ***********************************************************************************************
*/
override fun scmhash(m: Model): String {
val s = StringBuilder()
val flds = m.getJSONArray("flds")
for (fld in flds.jsonObjectIterable()) {
s.append(fld.getString("name"))
}
val tmpls = m.getJSONArray("tmpls")
for (t in tmpls.jsonObjectIterable()) {
s.append(t.getString("name"))
}
return Utils.checksum(s.toString())
}
/**
* Required field/text cache
* ***********************************************************************************************
*/
private fun _updateRequired(m: Model) {
if (m.isCloze) {
// nothing to do
return
}
val req = JSONArray()
val flds = m.fieldsNames
val templates = m.getJSONArray("tmpls")
for (t in templates.jsonObjectIterable()) {
val ret = _reqForTemplate(m, flds, t)
val r = JSONArray()
r.put(t.getInt("ord"))
r.put(ret[0])
r.put(ret[1])
req.put(r)
}
m.put("req", req)
}
private fun _reqForTemplate(m: Model, flds: List<String>, t: JSONObject): Array<Any> {
val nbFields = flds.size
val a = Array(nbFields) { "ankiflag" }
val b = Array(nbFields) { "" }
val ord = t.getInt("ord")
val full = col._renderQA(1L, m, 1L, ord, "", a, 0)["q"]
val empty = col._renderQA(1L, m, 1L, ord, "", b, 0)["q"]
// if full and empty are the same, the template is invalid and there is no way to satisfy it
if (full == empty) {
return arrayOf(REQ_NONE, JSONArray(), JSONArray())
}
var type = REQ_ALL
var req = JSONArray()
for (i in flds.indices) {
a[i] = ""
// if no field content appeared, field is required
if (!col._renderQA(1L, m, 1L, ord, "", a, 0)["q"]!!.contains("ankiflag")) {
req.put(i)
}
a[i] = "ankiflag"
}
if (req.length() > 0) {
return arrayOf(type, req)
}
// if there are no required fields, switch to any mode
type = REQ_ANY
req = JSONArray()
for (i in flds.indices) {
b[i] = "1"
// if not the same as empty, this field can make the card non-blank
if (col._renderQA(1L, m, 1L, ord, "", b, 0)["q"] != empty) {
req.put(i)
}
b[i] = ""
}
return arrayOf(type, req)
}
/**
* Whether to allow empty note to generate a card. When importing a deck, this is useful to be able to correct it. When doing "check card" it avoids to delete empty note.
* By default, it is allowed for cloze type but not for standard type.
*/
enum class AllowEmpty {
TRUE, FALSE, ONLY_CLOZE;
companion object {
/**
* @param allowEmpty a Boolean representing whether empty note should be allowed. Null is understood as default
* @return AllowEmpty similar to the boolean
*/
fun fromBoolean(allowEmpty: Boolean?): AllowEmpty {
return if (allowEmpty == null) {
ONLY_CLOZE
} else if (allowEmpty == true) {
TRUE
} else {
FALSE
}
}
}
}
/*
* Sync handling ***********************************************************************************************
*/
override fun beforeUpload() {
val changed = Utils.markAsUploaded(all())
if (changed) {
save()
}
}
/*
* Other stuff NOT IN LIBANKI
* ***********************************************************************************************
*/
override fun setChanged() {
mChanged = true
}
val templateNames: HashMap<Long, HashMap<Int, String>>
get() {
val result = HashMapInit<Long, HashMap<Int, String>>(
mModels!!.size
)
for (m in mModels!!.values) {
val templates = m.getJSONArray("tmpls")
val names = HashMapInit<Int, String>(templates.length())
for (t in templates.jsonObjectIterable()) {
names[t.getInt("ord")] = t.getString("name")
}
result[m.getLong("id")] = names
}
return result
}
override fun getModels(): HashMap<Long, Model> {
return mModels!!
}
/** {@inheritDoc} */
override fun count(): Int {
return mModels!!.size
}
companion object {
const val NOT_FOUND_NOTE_TYPE = -1L
@VisibleForTesting
val REQ_NONE = "none"
@VisibleForTesting
val REQ_ANY = "any"
@VisibleForTesting
val REQ_ALL = "all"
// In Android, } should be escaped
private val fClozePattern1 = Pattern.compile("\\{\\{[^}]*?cloze:(?:[^}]?:)*(.+?)\\}\\}")
private val fClozePattern2 = Pattern.compile("<%cloze:(.+?)%>")
private val fClozeOrdPattern = Pattern.compile("(?si)\\{\\{c(\\d+)::.*?\\}\\}")
@KotlinCleanup("Use triple quotes for this properties and maybe `@language('json'')`")
const val DEFAULT_MODEL = (
"{\"sortf\": 0, " +
"\"did\": 1, " +
"\"latexPre\": \"" +
"\\\\documentclass[12pt]{article}\\n" +
"\\\\special{papersize=3in,5in}\\n" +
"\\\\usepackage[utf8]{inputenc}\\n" +
"\\\\usepackage{amssymb,amsmath}\\n" +
"\\\\pagestyle{empty}\\n" +
"\\\\setlength{\\\\parindent}{0in}\\n" +
"\\\\begin{document}\\n" +
"\", " +
"\"latexPost\": \"\\\\end{document}\", " +
"\"latexsvg\": false," +
"\"mod\": 0, " +
"\"usn\": 0, " +
"\"type\": " +
Consts.MODEL_STD +
", " +
"\"css\": \".card {\\n" +
" font-family: arial;\\n" +
" font-size: 20px;\\n" +
" text-align: center;\\n" +
" color: black;\\n" +
" background-color: white;\\n" +
"}\n\"" +
"}"
)
private const val defaultField =
"{\"name\": \"\", " + "\"ord\": null, " + "\"sticky\": false, " + // the following alter editing, and are used as defaults for the template wizard
"\"rtl\": false, " + "\"font\": \"Arial\", " + "\"size\": 20 }"
private const val defaultTemplate =
(
"{\"name\": \"\", " + "\"ord\": null, " + "\"qfmt\": \"\", " +
"\"afmt\": \"\", " + "\"did\": null, " + "\"bqfmt\": \"\"," + "\"bafmt\": \"\"," + "\"bfont\": \"\"," +
"\"bsize\": 0 }"
)
// /** Regex pattern used in removing tags from text before diff */
// private static final Pattern sFactPattern = Pattern.compile("%\\([tT]ags\\)s");
// private static final Pattern sModelPattern = Pattern.compile("%\\(modelTags\\)s");
// private static final Pattern sTemplPattern = Pattern.compile("%\\(cardModel\\)s");
// not in anki
fun isModelNew(m: Model): Boolean {
return m.getLong("id") == 0L
}
/** "Mapping of field name -> (ord, field). */
fun fieldMap(m: Model): Map<String, Pair<Int, JSONObject>> {
val flds = m.getJSONArray("flds")
// TreeMap<Integer, String> map = new TreeMap<Integer, String>();
val result: MutableMap<String, Pair<Int, JSONObject>> = HashMapInit(flds.length())
for (f in flds.jsonObjectIterable()) {
result[f.getString("name")] = Pair(f.getInt("ord"), f)
}
return result
}
/*
* Templates ***********************************************************************************************
*/
@KotlinCleanup("direct return and use scope function")
fun newTemplate(name: String?): JSONObject {
val t = JSONObject(defaultTemplate)
t.put("name", name)
return t
}
fun _updateTemplOrds(m: Model) {
val tmpls = m.getJSONArray("tmpls")
for (i in 0 until tmpls.length()) {
val f = tmpls.getJSONObject(i)
f.put("ord", i)
}
}
/**
* @param m A note type
* @param ord a card type number of this model
* @param sfld Fields of a note of this model. (Not trimmed)
* @return Whether this card is empty
*/
@Throws(TemplateError::class)
fun emptyCard(m: Model, ord: Int, sfld: Array<String>): Boolean {
return if (m.isCloze) {
// For cloze, getting the list of cloze numbes is linear in the size of the template
// So computing the full list is almost as efficient as checking for a particular number
!_availClozeOrds(m, sfld, false).contains(ord)
} else emptyStandardCard(
m.getJSONArray("tmpls").getJSONObject(ord), m.nonEmptyFields(sfld)
)
}
/**
* @return Whether the standard card is empty
*/
@Throws(TemplateError::class)
fun emptyStandardCard(tmpl: JSONObject, nonEmptyFields: Set<String>): Boolean {
return ParsedNode.parse_inner(tmpl.getString("qfmt")).template_is_empty(nonEmptyFields)
}
/**
* @param m A model
* @param sfld Fields of a note
* @param nodes Nodes used for parsing the variaous templates. Null for cloze
* @param allowEmpty whether to always return an ord, even if all cards are actually empty
* @return The index of the cards that are generated. For cloze cards, if no card is generated, then {0}
*/
@KotlinCleanup("nodes is only non-null on one path")
fun availOrds(
m: Model,
sfld: Array<String>,
nodes: List<ParsedNode?>?,
allowEmpty: AllowEmpty
): ArrayList<Int> {
return if (m.getInt("type") == Consts.MODEL_CLOZE) {
_availClozeOrds(
m,
sfld,
allowEmpty == AllowEmpty.TRUE || allowEmpty == AllowEmpty.ONLY_CLOZE
)
} else _availStandardOrds(
m,
sfld,
nodes!!,
allowEmpty == AllowEmpty.TRUE
)
}
fun availOrds(
m: Model,
sfld: Array<String>,
allowEmpty: AllowEmpty = AllowEmpty.ONLY_CLOZE
): ArrayList<Int> {
return if (m.isCloze) {
_availClozeOrds(
m,
sfld,
allowEmpty == AllowEmpty.TRUE || allowEmpty == AllowEmpty.ONLY_CLOZE
)
} else _availStandardOrds(m, sfld, allowEmpty == AllowEmpty.TRUE)
}
fun _availStandardOrds(
m: Model,
sfld: Array<String>,
allowEmpty: Boolean = false
): ArrayList<Int> {
return _availStandardOrds(m, sfld, m.parsedNodes(), allowEmpty)
}
/** Given a joined field string and a standard note type, return available template ordinals */
fun _availStandardOrds(
m: Model,
sfld: Array<String>,
nodes: List<ParsedNode?>,
allowEmpty: Boolean
): ArrayList<Int> {
val nonEmptyFields = m.nonEmptyFields(sfld)
val avail = ArrayList<Int>(nodes.size)
for (i in nodes.indices) {
val node = nodes[i]
if (node != null && !node.template_is_empty(nonEmptyFields)) {
avail.add(i)
}
}
if (allowEmpty && avail.isEmpty()) {
/* According to anki documentation:
When adding/importing, if a normal note doesn’t generate any cards, Anki will now add a blank card 1 instead of refusing to add the note. */
avail.add(0)
}
return avail
}
/**
* Cache of getNamesOfFieldsContainingCloze
* Computing hash of string is costly. However, hash is cashed in the string object, so this virtually ensure that
* given a card type, we don't need to recompute the hash.
*/
private val namesOfFieldsContainingClozeCache = WeakHashMap<String, List<String>>()
/** The name of all fields that are used as cloze in the question.
* It is not guaranteed that the field found are actually the name of any field of the note type. */
@VisibleForTesting
internal fun getNamesOfFieldsContainingCloze(question: String): List<String> {
if (!namesOfFieldsContainingClozeCache.containsKey(question)) {
val matches: MutableList<String> = ArrayList()
for (pattern in arrayOf(fClozePattern1, fClozePattern2)) {
val mm = pattern.matcher(question)
while (mm.find()) {
matches.add(mm.group(1)!!)
}
}
namesOfFieldsContainingClozeCache[question] = matches
}
return namesOfFieldsContainingClozeCache[question]!!
}
/**
* @param m A note type with cloze
* @param sflds The fields of a note of type m. (Assume the size of the array is the number of fields)
* @param allowEmpty Whether we allow to generate at least one card even if they are all empty
* @return The indexes (in increasing order) of cards that should be generated according to req rules.
* If empty is not allowed, it will contains ord 1.
*/
/**
* @param m A note type with cloze
* @param sflds The fields of a note of type m. (Assume the size of the array is the number of fields)
* @return The indexes (in increasing order) of cards that should be generated according to req rules.
*/
@KotlinCleanup("sflds: String? to string")
@KotlinCleanup("return arrayListOf(0)")
fun _availClozeOrds(
m: Model,
sflds: Array<String>,
allowEmpty: Boolean = true
): ArrayList<Int> {
val map = fieldMap(m)
val question = m.getJSONArray("tmpls").getJSONObject(0).getString("qfmt")
val ords: MutableSet<Int> = HashSet()
val matches = getNamesOfFieldsContainingCloze(question)
for (fname in matches) {
if (!map.containsKey(fname)) {
continue
}
val ord = map[fname]!!.first
val mm = fClozeOrdPattern.matcher(sflds[ord])
while (mm.find()) {
ords.add(mm.group(1)!!.toInt() - 1)
}
}
ords.remove(-1)
return if (ords.isEmpty() && allowEmpty) {
// empty clozes use first ord
ArrayList(listOf(0))
} else ArrayList(ords)
}
}
// private long mCrt = mCol.getTime().intTime();
// private long mMod = mCol.getTime().intTime();
// private JSONObject mConf;
// private String mCss = "";
// private JSONArray mFields;
// private JSONArray mTemplates;
// BEGIN SQL table entries
// private Decks mDeck;
// private DB mDb;
//
// ** Map for compiled Mustache Templates */
// private Map<String, Template> mCmpldTemplateMap = new HashMap<>();
//
// /** Map for convenience and speed which contains FieldNames from current model */
// private TreeMap<String, Integer> mFieldMap = new TreeMap<String, Integer>();
//
// /** Map for convenience and speed which contains Templates from current model */
// private TreeMap<Integer, JSONObject> mTemplateMap = new TreeMap<Integer, JSONObject>();
//
// /** Map for convenience and speed which contains the CSS code related to a Template */
// private HashMap<Integer, String> mCssTemplateMap = new HashMap<Integer, String>();
//
// /**
// * The percentage chosen in preferences for font sizing at the time when the css for the CardModels related to
// this
// * Model was calculated in prepareCSSForCardModels.
// */
// private transient int mDisplayPercentage = 0;
// private boolean mNightMode = false;
}
| gpl-3.0 | 29d54ee5c599e71d5ab9d1e8f229f6ff | 35.672711 | 174 | 0.502423 | 4.402002 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/cardviewer/PreviewLayout.kt | 1 | 3880 | /*
* Copyright (c) 2021 David Allison <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.anki.cardviewer
import android.content.Context
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.StringRes
import androidx.annotation.VisibleForTesting
import com.ichi2.anki.AnkiActivity
import com.ichi2.anki.R
import com.ichi2.themes.Themes
/** The "preview" controls at the bottom of the screen for [com.ichi2.anki.Previewer] and [com.ichi2.anki.CardTemplatePreviewer] */
class PreviewLayout(
private val buttonsLayout: FrameLayout,
@VisibleForTesting val prevCard: ImageView,
@VisibleForTesting val nextCard: ImageView,
private val toggleAnswerText: TextView
) {
fun displayAndInit(toggleAnswerHandler: View.OnClickListener) {
buttonsLayout.visibility = View.VISIBLE
buttonsLayout.setOnClickListener(toggleAnswerHandler)
}
/** Sets the answer text to "show answer" or "hide answer" */
fun setShowingAnswer(showingAnswer: Boolean) =
setToggleAnswerText(if (showingAnswer) R.string.hide_answer else R.string.show_answer)
fun setToggleAnswerText(@StringRes res: Int) = toggleAnswerText.setText(res)
fun setOnPreviousCard(listener: View.OnClickListener) = prevCard.setOnClickListener(listener)
fun setOnNextCard(listener: View.OnClickListener) = nextCard.setOnClickListener(listener)
fun setNextButtonEnabled(enabled: Boolean) = setEnabled(nextCard, enabled)
fun setPrevButtonEnabled(enabled: Boolean) = setEnabled(prevCard, enabled)
private fun setEnabled(button: ImageView, enabled: Boolean) {
button.isEnabled = enabled
button.alpha = if (enabled) 1f else 0.38f
}
fun enableAnimation(context: Context) {
val resId = Themes.getResFromAttr(context, R.attr.hardButtonRippleRef)
buttonsLayout.setBackgroundResource(resId)
prevCard.setBackgroundResource(R.drawable.item_background_light_selectable_borderless)
nextCard.setBackgroundResource(R.drawable.item_background_light_selectable_borderless)
}
fun hideNavigationButtons() {
prevCard.visibility = View.GONE
nextCard.visibility = View.GONE
}
fun showNavigationButtons() {
prevCard.visibility = View.VISIBLE
nextCard.visibility = View.VISIBLE
}
companion object {
fun createAndDisplay(activity: AnkiActivity, toggleAnswerHandler: View.OnClickListener): PreviewLayout {
val buttonsLayout = activity.findViewById<FrameLayout>(R.id.preview_buttons_layout)
val prevCard = activity.findViewById<ImageView>(R.id.preview_previous_flashcard)
val nextCard = activity.findViewById<ImageView>(R.id.preview_next_flashcard)
val toggleAnswerText = activity.findViewById<TextView>(R.id.preview_flip_flashcard)
val previewLayout = PreviewLayout(buttonsLayout, prevCard, nextCard, toggleAnswerText)
previewLayout.displayAndInit(toggleAnswerHandler)
if (activity.animationEnabled()) {
previewLayout.enableAnimation(activity)
}
return previewLayout
}
}
}
| gpl-3.0 | c7a32af9bd564315129ab9f743feb7d3 | 41.637363 | 131 | 0.738144 | 4.374295 | false | false | false | false |
tokenbrowser/token-android-client | app/src/main/java/com/toshi/view/custom/passphrase/keyboard/PassphraseKeyboardKeyBuilder.kt | 1 | 6606 | /*
* 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.view.custom.passphrase.keyboard
import android.content.Context
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.google.android.flexbox.FlexboxLayout
import com.toshi.R
import com.toshi.extensions.getColorById
import com.toshi.extensions.getDrawableById
import com.toshi.extensions.getPxSize
import com.toshi.extensions.getString
import com.toshi.view.custom.ForegroundImageView
import com.toshi.view.custom.passphrase.keyboard.keyboardLayouts.KeyboardLayout
class PassphraseKeyboardKeyBuilder {
fun createBackSpaceView(context: Context): ForegroundImageView {
return ForegroundImageView(context).apply {
background = getDrawableById(R.drawable.keyboard_action_key_background)
setForegroundResource(R.drawable.ic_backspace)
elevation = getPxSize(R.dimen.elevation_default).toFloat()
}
}
fun createShiftView(context: Context): ForegroundImageView {
return ForegroundImageView(context).apply {
setForegroundResource(R.drawable.ic_shift)
background = getDrawableById(R.drawable.keyboard_action_key_background)
elevation = getPxSize(R.dimen.elevation_default).toFloat()
}
}
fun createLanguageView(context: Context): ForegroundImageView {
return ForegroundImageView(context).apply {
setForegroundResource(R.drawable.ic_language)
background = getDrawableById(R.drawable.keyboard_action_key_background)
elevation = getPxSize(R.dimen.elevation_default).toFloat()
}
}
fun createSpaceBarView(context: Context): TextView {
return TextView(context).apply {
background = getDrawableById(R.drawable.keyboard_char_key_background)
gravity = Gravity.CENTER
text = getString(R.string.next).toLowerCase()
elevation = getPxSize(R.dimen.elevation_default).toFloat()
setTextSize(TypedValue.COMPLEX_UNIT_PX, getPxSize(R.dimen.text_size_subtitle).toFloat())
setTextColor(getColorById(R.color.textColorPrimary))
}
}
fun createReturnView(context: Context): TextView {
return TextView(context).apply {
background = getDrawableById(R.drawable.keyboard_action_key_background)
gravity = Gravity.CENTER
text = getString(R.string.return_key).toLowerCase()
elevation = getPxSize(R.dimen.elevation_default).toFloat()
setTextSize(TypedValue.COMPLEX_UNIT_PX, getPxSize(R.dimen.text_size_subtitle).toFloat())
setTextColor(getColorById(R.color.keyboard_tex_color_disabled))
}
}
fun createTextView(context: Context, value: String): TextView {
return TextView(context).apply {
background = getDrawableById(R.drawable.keyboard_char_key_background)
gravity = Gravity.CENTER
text = value
elevation = getPxSize(R.dimen.elevation_default).toFloat()
setTextColor(getColorById(R.color.textColorPrimary))
setTextSize(TypedValue.COMPLEX_UNIT_PX, getPxSize(R.dimen.text_size_keyboard).toFloat())
}
}
fun setLayoutParams(isLastItemOnRow: Boolean, view: View, key: Any) {
when {
key == KeyboardLayout.Action.BACKSPACE -> setSmallActionViewLayoutParams(view, isLastItemOnRow)
key == KeyboardLayout.Action.SHIFT -> setSmallActionViewLayoutParams(view, isLastItemOnRow)
key == KeyboardLayout.Action.LANGUAGE -> setLargeActionViewLayoutParams(view, isLastItemOnRow)
key == KeyboardLayout.Action.SPACEBAR -> setSpacebarLayoutParams(view, isLastItemOnRow)
key == KeyboardLayout.Action.RETURN -> setLargeActionViewLayoutParams(view, isLastItemOnRow)
view is TextView -> setTextViewLayoutParams(view, isLastItemOnRow)
}
}
private fun setSmallActionViewLayoutParams(view: View, isLastItemOnRow: Boolean) {
val layoutParams = view.layoutParams as FlexboxLayout.LayoutParams
layoutParams.apply {
width = view.getPxSize(R.dimen.keyboard_backspace_width)
height = view.getPxSize(R.dimen.keyboard_key_height)
flexGrow = 1f
setMargin(view, layoutParams, isLastItemOnRow)
}
}
private fun setLargeActionViewLayoutParams(view: View, isLastItemOnRow: Boolean) {
val layoutParams = view.layoutParams as FlexboxLayout.LayoutParams
layoutParams.apply {
width = ViewGroup.LayoutParams.WRAP_CONTENT
height = view.getPxSize(R.dimen.keyboard_key_height)
flexGrow = 1f
flexBasisPercent = 0.25f
setMargin(view, layoutParams, isLastItemOnRow)
}
}
private fun setSpacebarLayoutParams(view: View, isLastItemOnRow: Boolean) {
val layoutParams = view.layoutParams as FlexboxLayout.LayoutParams
layoutParams.apply {
width = ViewGroup.LayoutParams.WRAP_CONTENT
height = view.getPxSize(R.dimen.keyboard_key_height)
flexBasisPercent = 0.5f
setMargin(view, layoutParams, isLastItemOnRow)
}
}
private fun setTextViewLayoutParams(textView: TextView, isLastItemOnRow: Boolean) {
val layoutParams = textView.layoutParams as FlexboxLayout.LayoutParams
layoutParams.apply {
width = textView.getPxSize(R.dimen.keyboard_key_width)
height = textView.getPxSize(R.dimen.keyboard_key_height)
flexGrow = 1f
setMargin(textView, layoutParams, isLastItemOnRow)
}
}
private fun setMargin(view: View, lp: FlexboxLayout.LayoutParams, isLastItemOnRow: Boolean) {
if (!isLastItemOnRow) lp.marginEnd = view.getPxSize(R.dimen.margin_half)
}
} | gpl-3.0 | 4c461faf3db928c0cfc0eed1869216a3 | 43.342282 | 107 | 0.693612 | 4.512295 | false | false | false | false |
IntershopCommunicationsAG/scmversion-gradle-plugin | src/main/kotlin/com/intershop/gradle/scm/utils/Utils.kt | 1 | 2064 | /*
* Copyright 2020 Intershop Communications AG.
*
* 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.intershop.gradle.scm.utils
import org.gradle.api.model.ObjectFactory
import org.gradle.api.provider.ListProperty
import org.gradle.api.provider.Property
import org.gradle.api.provider.SetProperty
import kotlin.reflect.KProperty
/**
* Provides 'set' functional extension for the Property object.
*/
operator fun <T> Property<T>.setValue(receiver: Any?, property: KProperty<*>, value: T) = set(value)
/**
* Provides 'get' functional extension for the Property object.
*/
operator fun <T> Property<T>.getValue(receiver: Any?, property: KProperty<*>): T = get()
/**
* Provides 'set' functional extension for the SetProperty object.
*/
operator fun <T> SetProperty<T>.setValue(receiver: Any?, property: KProperty<*>, value: Set<T>) = set(value)
/**
* Provides 'get' functional extension for the SetProperty object.
*/
operator fun <T> SetProperty<T>.getValue(receiver: Any?, property: KProperty<*>): Set<T> = get()
/**
* Provides 'set' functional extension for the ListProperty object.
*/
operator fun <T> ListProperty<T>.setValue(receiver: Any?, property: KProperty<*>, value: List<T>) = set(value)
/**
* Provides 'get' functional extension for the ListProperty object.
*/
operator fun <T> ListProperty<T>.getValue(receiver: Any?, property: KProperty<*>): List<T> = get()
/**
* Provides functional extension for primitive objects.
*/
inline fun <reified T> ObjectFactory.property(): Property<T> = property(T::class.java)
| apache-2.0 | 70aa23a05fcd87eba20440f6c4cab561 | 35.857143 | 110 | 0.731105 | 3.954023 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/traffic_signals_sound/AddTrafficSignalsSound.kt | 1 | 2615 | package de.westnordost.streetcomplete.quests.traffic_signals_sound
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.elementfilter.toElementFilterExpression
import de.westnordost.streetcomplete.data.meta.updateWithCheckDate
import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.osm.mapdata.Element
import de.westnordost.streetcomplete.data.osm.mapdata.MapDataWithGeometry
import de.westnordost.streetcomplete.data.osm.osmquests.OsmElementQuestType
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.BLIND
import de.westnordost.streetcomplete.ktx.toYesNo
import de.westnordost.streetcomplete.quests.YesNoQuestAnswerFragment
class AddTrafficSignalsSound : OsmElementQuestType<Boolean> {
private val crossingFilter by lazy { """
nodes with crossing = traffic_signals and highway ~ crossing|traffic_signals and foot != no
and (
!$SOUND_SIGNALS
or $SOUND_SIGNALS = no and $SOUND_SIGNALS older today -4 years
or $SOUND_SIGNALS older today -8 years
)
""".toElementFilterExpression() }
private val excludedWaysFilter by lazy { """
ways with
highway = cycleway and foot !~ yes|designated
""".toElementFilterExpression() }
override val commitMessage = "Add whether traffic signals have sound signals"
override val wikiLink = "Key:$SOUND_SIGNALS"
override val icon = R.drawable.ic_quest_blind_traffic_lights_sound
override val questTypeAchievements = listOf(BLIND)
override fun getTitle(tags: Map<String, String>) = R.string.quest_traffic_signals_sound_title
override fun getApplicableElements(mapData: MapDataWithGeometry): Iterable<Element> {
val excludedWayNodeIds = mutableSetOf<Long>()
mapData.ways
.filter { excludedWaysFilter.matches(it) }
.flatMapTo(excludedWayNodeIds) { it.nodeIds }
return mapData.nodes
.filter { crossingFilter.matches(it) && it.id !in excludedWayNodeIds }
}
override fun isApplicableTo(element: Element): Boolean? =
if (!crossingFilter.matches(element))
false
else
null
override fun createForm() = YesNoQuestAnswerFragment()
override fun applyAnswerTo(answer: Boolean, changes: StringMapChangesBuilder) {
changes.updateWithCheckDate(SOUND_SIGNALS, answer.toYesNo())
}
override val defaultDisabledMessage = R.string.default_disabled_msg_boring
}
private const val SOUND_SIGNALS = "traffic_signals:sound"
| gpl-3.0 | a0fcfffe7797704ced41a8edd756faab | 41.177419 | 99 | 0.743403 | 4.798165 | false | false | false | false |
pdvrieze/ProcessManager | PE-diagram/src/commonMain/kotlin/nl.adaptivity.process/diagram/DrawableProcessNode.kt | 1 | 2634 | /*
* Copyright (c) 2017.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.process.diagram
import nl.adaptivity.diagram.Drawable
import nl.adaptivity.process.processModel.ProcessNode
typealias DrawableState = Int
interface DrawableProcessNode : ProcessNode {
open class Delegate(builder: ProcessNode.Builder) {
var state: Int = (builder as? DrawableProcessNode.Builder<*>)?.state ?: Drawable.STATE_DEFAULT
var isCompat: Boolean = (builder as? DrawableProcessNode.Builder<*>)?.isCompat ?: false
}
interface Builder<out R : DrawableProcessNode> : ProcessNode.Builder, IDrawableProcessNode {
class Delegate(var state: Int, var isCompat: Boolean) {
constructor(node: ProcessNode) :
this((node as? Drawable)?.state ?: Drawable.STATE_DEFAULT,
(node as? DrawableProcessNode)?.isCompat ?: false
)
}
val _delegate: Delegate
var isCompat: Boolean
get() = _delegate.isCompat
set(value) {
_delegate.isCompat = value
}
override var state: DrawableState
get() = _delegate.state
set(value) {
_delegate.state = value
}
override fun copy(): Builder<R>
override fun translate(dX: Double, dY: Double) {
x += dX
y += dY
}
}
// void setLabel(@Nullable String label);
val _delegate: Delegate
val isCompat: Boolean get() = _delegate.isCompat
override val maxSuccessorCount: Int
override val maxPredecessorCount: Int
/*
override fun <S : DrawingStrategy<S, PEN_T, PATH_T>,
PEN_T : Pen<PEN_T>,
PATH_T : DiagramPath<PATH_T>> drawLabel(canvas: Canvas<S, PEN_T, PATH_T>, clipBounds: Rectangle?, left: Double, top: Double) {
// TODO implement a proper drawLabel system. Perhaps that needs more knowledge of node bounds
}
*/
override fun builder(): Builder<DrawableProcessNode>
}
| lgpl-3.0 | b4c5a814d03edc0ec10c158dd0ceb48e | 30.357143 | 130 | 0.654897 | 4.549223 | false | false | false | false |
Cypher121/CSCodeExamples | src/coffee/cypher/kotlinexamples/KtFuncProg.kt | 1 | 383 | package coffee.cypher.kotlinexamples
fun main(args: Array<String>) {
val a = (1..50).multiplyEnd(2)
println(a)
println(
a.map { it * 4 }
.filter { it % 21 == 0 }
.joinToString(prefix = "[", postfix = "]", transform = { "\"" + it + "\"" })
);
}
fun IntRange.multiplyEnd(factor: Int): IntRange = (start..(endInclusive * factor)) | mit | 351e277ca1ed5d810adc0b6227a45900 | 26.428571 | 89 | 0.535248 | 3.682692 | false | false | false | false |
mopsalarm/Pr0 | app/src/main/java/com/pr0gramm/app/ui/fragments/conversation/ConversationViewModel.kt | 1 | 3576 | package com.pr0gramm.app.ui.fragments.conversation
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.*
import com.pr0gramm.app.Instant
import com.pr0gramm.app.R
import com.pr0gramm.app.api.pr0gramm.Api
import com.pr0gramm.app.services.InboxService
import com.pr0gramm.app.util.StringException
import com.pr0gramm.app.util.lazyStateFlow
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.withContext
import java.io.IOException
class ConversationViewModel(private val inboxService: InboxService, private val recipient: String) : ViewModel() {
private var currentPagingSource = lazyStateFlow<ConversationSource>()
private var firstPageConversationMessages: Api.ConversationMessages? = null
private val pager = Pager(PagingConfig(pageSize = 75, enablePlaceholders = false)) {
ConversationSource(inboxService, recipient, firstPageConversationMessages).also { source ->
currentPagingSource.send(source)
firstPageConversationMessages = null
}
}
val partner = currentPagingSource.flatMapLatest { source -> source.partner }
val paging by lazy { pager.flow.cachedIn(viewModelScope) }
var pendingMessages = MutableStateFlow(listOf<String>())
suspend fun send(messageText: String) {
// publish message as "pending"
pendingMessages.value = pendingMessages.value + messageText
try {
val response = withContext(NonCancellable) {
inboxService.send(recipient, messageText)
}
firstPageConversationMessages = response
} finally {
// invalidate even in case of errors
currentPagingSource.valueOrNull?.invalidate()
// remove the pending message "by instance"
pendingMessages.value = pendingMessages.value.filterNot { it === messageText }
}
}
suspend fun delete(name: String) {
inboxService.deleteConversation(name)
}
}
class ConversationSource(
private val inboxService: InboxService, private val name: String,
private var pending: Api.ConversationMessages?) : PagingSource<Instant, Api.ConversationMessage>() {
val partner = lazyStateFlow<Api.ConversationMessages.ConversationMessagePartner>()
override suspend fun load(params: LoadParams<Instant>): LoadResult<Instant, Api.ConversationMessage> {
val olderThan = params.key
try {
val response = pending ?: try {
inboxService.messagesInConversation(name, olderThan)
} catch (err: Exception) {
return LoadResult.Error(err)
}
if (response.error != null) {
return LoadResult.Error(StringException("load", R.string.conversation_load_error))
}
// It should never be the case that 'response.with' is null as we are only fetching
// messages
response.with?.let {
partner.send(it)
}
pending = null
val nextKey = if (response.atEnd) null else response.messages.lastOrNull()?.creationTime
return LoadResult.Page(response.messages.reversed(), nextKey = null, prevKey = nextKey)
} catch (err: IOException) {
return LoadResult.Error(err)
}
}
override fun getRefreshKey(state: PagingState<Instant, Api.ConversationMessage>): Instant? {
return null
}
}
| mit | d02e3138877cb4622c287558498b8923 | 35.121212 | 114 | 0.684004 | 4.891929 | false | false | false | false |
jonnyzzz/spring_io_2017 | src/v4/src/main/java/loader_plugins.kt | 1 | 1213 | package plugin.extensions.core
import org.springframework.context.annotation.AnnotationConfigApplicationContext
import org.springframework.context.event.ContextStartedEvent
import org.springframework.context.event.EventListener
import org.springframework.stereotype.Component
import plugin.extensions.Extension
import plugin.extensions.ExtensionRegistry
@Component
class PluginLoader(
val detector: PluginDetector,
val registry: ExtensionRegistry
) {
init {
println("I'm plugin loader")
}
@EventListener
fun onContextStarted(e: ContextStartedEvent) {
println("PluginLoader: loading plugins...")
val packages = detector.detectPlugins().map { "plugin.extensions.$it" }
val parentContext = e.applicationContext
packages.forEach {
val context = AnnotationConfigApplicationContext()
context.parent = parentContext
context.displayName = "plugin: $it"
context.scan(it)
context.refresh()
context.getBeansOfType(Extension::class.java)
.values
.forEach {
registry.register(it)
}
}
}
}
@Component
class PluginDetector {
fun detectPlugins() = listOf("plugin_1", "plugin_2")
}
| apache-2.0 | b75c541c3731fb48edee7f16101bf277 | 25.955556 | 80 | 0.715581 | 4.756863 | false | false | false | false |
ntlv/BasicLauncher2 | app/src/main/java/se/ntlv/basiclauncher/dagger/ApplicationModule.kt | 1 | 1243 | package se.ntlv.basiclauncher.dagger
import android.app.Application
import android.content.Context
import android.content.pm.PackageManager
import com.google.android.gms.gcm.GcmNetworkManager
import dagger.Module
import dagger.Provides
import org.jetbrains.anko.defaultSharedPreferences
import se.ntlv.basiclauncher.database.AppDetailDB
import se.ntlv.basiclauncher.database.GlobalConfig
import java.io.File
import javax.inject.Named
import javax.inject.Singleton
@Module
class ApplicationModule(private val app: Application) {
@Provides
fun provideApplication(): Application = app
@Provides
fun provideContext(): Context = app
@Provides
fun providePackageManager(): PackageManager = app.packageManager
@Singleton
@Provides
fun provideDatabase(): AppDetailDB = AppDetailDB(app)
@Provides
@Named("cache")
fun providesCacheDir(): File = app.cacheDir
@Provides
@Named("version")
fun providesAppVersion(): Int = app.packageManager.getPackageInfo(app.packageName, 0).versionCode
@Provides
fun provideGcmManager() : GcmNetworkManager = GcmNetworkManager.getInstance(app)
@Provides
fun provideConfig() : GlobalConfig = GlobalConfig(app.defaultSharedPreferences)
}
| mit | e54cf5f6cba3532dc98e9374ae9c85ac | 26.622222 | 101 | 0.77313 | 4.620818 | false | true | false | false |
arturbosch/detekt | detekt-cli/src/main/kotlin/io/gitlab/arturbosch/detekt/cli/ArgumentConverters.kt | 1 | 2366 | package io.gitlab.arturbosch.detekt.cli
import com.beust.jcommander.IStringConverter
import com.beust.jcommander.ParameterException
import org.jetbrains.kotlin.config.JvmTarget
import org.jetbrains.kotlin.config.LanguageVersion
import java.io.File
import java.net.URL
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
class ExistingPathConverter : IStringConverter<Path> {
override fun convert(value: String): Path {
require(value.isNotBlank()) { "Provided path '$value' is empty." }
val config = File(value).toPath()
if (Files.notExists(config)) {
throw ParameterException("Provided path '$value' does not exist!")
}
return config
}
}
class PathConverter : IStringConverter<Path> {
override fun convert(value: String): Path {
return Paths.get(value)
}
}
interface DetektInputPathConverter<T> : IStringConverter<List<T>> {
val converter: IStringConverter<T>
override fun convert(value: String): List<T> =
value.splitToSequence(SEPARATOR_COMMA, SEPARATOR_SEMICOLON)
.map { it.trim() }
.map { converter.convert(it) }
.toList()
.takeIf { it.isNotEmpty() }
?: error("Given input '$value' was impossible to parse!")
}
class MultipleClasspathResourceConverter : DetektInputPathConverter<URL> {
override val converter = ClasspathResourceConverter()
}
class MultipleExistingPathConverter : DetektInputPathConverter<Path> {
override val converter = ExistingPathConverter()
}
class LanguageVersionConverter : IStringConverter<LanguageVersion> {
override fun convert(value: String): LanguageVersion =
checkNotNull(LanguageVersion.fromFullVersionString(value)) { "Invalid value passed to --language-version" }
}
class JvmTargetConverter : IStringConverter<JvmTarget> {
override fun convert(value: String): JvmTarget =
checkNotNull(JvmTarget.fromString(value)) { "Invalid value passed to --jvm-target" }
}
class ClasspathResourceConverter : IStringConverter<URL> {
override fun convert(resource: String): URL {
val relativeResource = if (resource.startsWith("/")) resource else "/$resource"
return javaClass.getResource(relativeResource)
?: throw ParameterException("Classpath resource '$resource' does not exist!")
}
}
| apache-2.0 | bbbc6471c24e76b1d756463810959220 | 35.4 | 115 | 0.714286 | 4.506667 | false | true | false | false |
nemerosa/ontrack | ontrack-extension-auto-versioning/src/test/java/net/nemerosa/ontrack/extension/av/audit/AutoVersioningAuditQueryServiceIT.kt | 1 | 14862 | package net.nemerosa.ontrack.extension.av.audit
import net.nemerosa.ontrack.extension.av.AbstractAutoVersioningTestSupport
import net.nemerosa.ontrack.extension.av.AutoVersioningTestFixtures.createOrder
import net.nemerosa.ontrack.extension.av.dispatcher.AutoVersioningOrder
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import kotlin.test.assertEquals
class AutoVersioningAuditQueryServiceIT : AbstractAutoVersioningTestSupport() {
@Autowired
private lateinit var autoVersioningAuditService: AutoVersioningAuditService
@Autowired
private lateinit var autoVersioningAuditQueryService: AutoVersioningAuditQueryService
@Autowired
private lateinit var autoVersioningAuditCleanupService: AutoVersioningAuditCleanupService
@Test
fun `Last orders for a branch`() {
val source = project()
project {
branch {
val orders = (1..20).map {
createOrder(sourceProject = source.name, targetVersion = "2.0.$it").apply {
autoVersioningAuditService.onQueuing(this, "routing", cancelling = false)
autoVersioningAuditService.onReceived(this, "queue")
}
}
val entries = autoVersioningAuditQueryService.findByFilter(
AutoVersioningAuditQueryFilter(
project = project.name, branch = name
)
)
val actualVersions = entries.map { it.order.targetVersion }
val expectedVersions = orders.takeLast(10).reversed().map { it.targetVersion }
assertEquals(expectedVersions, actualVersions, "Returned the last 10 orders for this branch")
}
}
}
@Test
fun `Last five orders for a branch`() {
val source = project()
project {
branch {
val orders = (1..20).map {
createOrder(sourceProject = source.name, targetVersion = "2.0.$it").apply {
autoVersioningAuditService.onQueuing(this, "routing", cancelling = false)
autoVersioningAuditService.onReceived(this, "queue")
}
}
val entries = autoVersioningAuditQueryService.findByFilter(
AutoVersioningAuditQueryFilter(
project = project.name, branch = name,
count = 5
)
)
val actualVersions = entries.map { it.order.targetVersion }
val expectedVersions = orders.takeLast(5).reversed().map { it.targetVersion }
assertEquals(expectedVersions, actualVersions, "Returned the last 10 orders for this branch")
}
}
}
@Test
fun `Offset orders for a branch`() {
val source = project()
project {
branch {
val orders = (1..20).map {
createOrder(sourceProject = source.name, targetVersion = "2.0.$it").apply {
autoVersioningAuditService.onQueuing(this, "routing", cancelling = false)
autoVersioningAuditService.onReceived(this, "queue")
}
}
val entries = autoVersioningAuditQueryService.findByFilter(
AutoVersioningAuditQueryFilter(
project = project.name, branch = name,
offset = 10,
count = 5
)
)
val actualVersions = entries.map { it.order.targetVersion }
val expectedVersions = orders.dropLast(10).takeLast(5).reversed().map { it.targetVersion }
assertEquals(
expectedVersions,
actualVersions,
"Returned the last 5 orders after the last 10 for this branch"
)
}
}
}
@Test
fun `Filter order on UUID for a branch`() {
val source = project()
project {
branch {
val orders = (1..20).map {
createOrder(sourceProject = source.name, targetVersion = "2.0.$it").apply {
autoVersioningAuditService.onQueuing(this, "routing", cancelling = false)
autoVersioningAuditService.onReceived(this, "queue")
}
}
val entries = autoVersioningAuditQueryService.findByFilter(
AutoVersioningAuditQueryFilter(
project = project.name, branch = name,
uuid = orders[10].uuid
)
)
val actualVersions = entries.map { it.order.targetVersion }
val expectedVersions = listOf(orders[10].targetVersion)
assertEquals(expectedVersions, actualVersions)
}
}
}
@Test
fun `Filter order on version for a branch`() {
val source = project()
project {
branch {
val orders = (1..20).map {
createOrder(sourceProject = source.name, targetVersion = "2.0.$it").apply {
autoVersioningAuditService.onQueuing(this, "routing", cancelling = false)
autoVersioningAuditService.onReceived(this, "queue")
}
}
val entries = autoVersioningAuditQueryService.findByFilter(
AutoVersioningAuditQueryFilter(
project = project.name, branch = name,
version = orders[10].targetVersion
)
)
val actualVersions = entries.map { it.order.targetVersion }
val expectedVersions = listOf(orders[10].targetVersion)
assertEquals(expectedVersions, actualVersions)
}
}
}
@Test
fun `Filter orders on states for a branch`() {
val source = project()
project {
branch {
val orders = (1..20).map {
createOrder(sourceProject = source.name, targetVersion = "2.0.$it").apply {
autoVersioningAuditService.onQueuing(this, "routing", cancelling = false)
if (it % 2 == 0) {
autoVersioningAuditService.onReceived(this, "queue")
}
}
}
val entries = autoVersioningAuditQueryService.findByFilter(
AutoVersioningAuditQueryFilter(
project = project.name, branch = name,
state = AutoVersioningAuditState.CREATED
)
)
val actualVersions = entries.map { it.order.targetVersion }
val expectedVersions =
orders.filterIndexed { index, _ -> (index + 1) % 2 != 0 }.reversed().map { it.targetVersion }
assertEquals(expectedVersions, actualVersions)
}
}
}
@Test
fun `Filter orders on state and version for a branch`() {
val source = project()
project {
branch {
val orders = (1..20).map {
createOrder(sourceProject = source.name, targetVersion = "2.0.$it").apply {
autoVersioningAuditService.onQueuing(this, "routing", cancelling = false)
if (it % 2 == 0) {
autoVersioningAuditService.onReceived(this, "queue")
}
}
}
val entries = autoVersioningAuditQueryService.findByFilter(
AutoVersioningAuditQueryFilter(
project = project.name, branch = name,
state = AutoVersioningAuditState.CREATED,
version = orders[8].targetVersion
)
)
val actualVersions = entries.map { it.order.targetVersion }
val expectedVersions = listOf(orders[8].targetVersion)
assertEquals(expectedVersions, actualVersions)
}
}
}
@Test
fun `Filter orders on source project for a branch`() {
val sourceA = project()
val sourceB = project()
project {
branch {
(1..5).forEach {
createOrder(sourceProject = sourceA.name, targetVersion = "2.0.$it").apply {
autoVersioningAuditService.onQueuing(this, "routing", cancelling = false)
}
}
val ordersB = (1..5).map {
createOrder(sourceProject = sourceB.name, targetVersion = "3.0.$it").apply {
autoVersioningAuditService.onQueuing(this, "routing", cancelling = false)
}
}
val entries = autoVersioningAuditQueryService.findByFilter(
AutoVersioningAuditQueryFilter(
project = project.name, branch = name,
source = sourceB.name
)
)
val actualVersions = entries.map { it.order.targetVersion }
val expectedVersions = ordersB.reversed().map { it.targetVersion }
assertEquals(expectedVersions, actualVersions)
}
}
}
@Test
fun `Filter orders for a project`() {
val source = project()
project {
val orders = mutableListOf<AutoVersioningOrder>()
branch {
orders += (1..5).map {
createOrder(sourceProject = source.name, targetVersion = "2.0.$it").apply {
autoVersioningAuditService.onQueuing(this, "routing", cancelling = false)
}
}
}
branch {
orders += (1..5).map {
createOrder(sourceProject = source.name, targetVersion = "3.0.$it").apply {
autoVersioningAuditService.onQueuing(this, "routing", cancelling = false)
}
}
}
autoVersioningAuditQueryService.findByFilter(
AutoVersioningAuditQueryFilter(
project = name, branch = null
)
).let { entries ->
val actualVersions = entries.map { it.order.targetVersion }
val expectedVersions = orders.reversed().map { it.targetVersion }
assertEquals(expectedVersions, actualVersions)
}
autoVersioningAuditQueryService.findByFilter(
AutoVersioningAuditQueryFilter(
project = name, branch = null,
count = 7
)
).let { entries ->
val actualVersions = entries.map { it.order.targetVersion }
val expectedVersions = orders.reversed().take(7).map { it.targetVersion }
assertEquals(expectedVersions, actualVersions)
}
autoVersioningAuditQueryService.findByFilter(
AutoVersioningAuditQueryFilter(
project = name, branch = null,
version = orders[2].targetVersion
)
).let { entries ->
val actualVersions = entries.map { it.order.targetVersion }
val expectedVersions = listOf(orders[2].targetVersion)
assertEquals(expectedVersions, actualVersions)
}
}
}
@Test
fun `Last orders on a project on several branches`() {
val source = project()
project {
val branch1 = branch()
val branch2 = branch()
val orders = mutableListOf<AutoVersioningOrder>()
(1..20).forEach {
orders += if (it % 2 == 0) {
branch1.createOrder(sourceProject = source.name, targetVersion = "1.0.$it").apply {
autoVersioningAuditService.onQueuing(this, "routing", cancelling = false)
autoVersioningAuditService.onReceived(this, "queue")
}
} else {
branch2.createOrder(sourceProject = source.name, targetVersion = "2.0.$it").apply {
autoVersioningAuditService.onQueuing(this, "routing", cancelling = false)
autoVersioningAuditService.onReceived(this, "queue")
}
}
}
val entries = autoVersioningAuditQueryService.findByFilter(
AutoVersioningAuditQueryFilter(
project = name
)
)
val actualVersions = entries.map { it.order.targetVersion }
val expectedVersions = orders.takeLast(10).reversed().map { it.targetVersion }
assertEquals(expectedVersions, actualVersions, "Returned the last 10 orders for this project")
}
}
@Test
fun `Last orders on a all projects on several branches`() {
val source = project()
// Clears all audit entries
autoVersioningAuditCleanupService.purge()
val project1 = project()
val project2 = project()
val branch1 = project1.branch()
val branch2 = project2.branch()
val orders = mutableListOf<AutoVersioningOrder>()
(1..20).forEach {
orders += if (it % 2 == 0) {
branch1.createOrder(sourceProject = source.name, targetVersion = "1.0.$it").apply {
autoVersioningAuditService.onQueuing(this, "routing", cancelling = false)
autoVersioningAuditService.onReceived(this, "queue")
}
} else {
branch2.createOrder(sourceProject = source.name, targetVersion = "2.0.$it").apply {
autoVersioningAuditService.onQueuing(this, "routing", cancelling = false)
autoVersioningAuditService.onReceived(this, "queue")
}
}
}
val entries = withGrantViewToAll {
asUser {
autoVersioningAuditQueryService.findByFilter(AutoVersioningAuditQueryFilter())
}
}
val actualVersions = entries.map { it.order.targetVersion }
val expectedVersions = orders.takeLast(10).reversed().map { it.targetVersion }
assertEquals(expectedVersions, actualVersions, "Returned the last 10 orders for all projects")
}
} | mit | 2d3e3f3d29a3a34294cba6f672471e61 | 41.465714 | 113 | 0.532163 | 5.516704 | false | false | false | false |
nextcloud/android | app/src/main/java/com/owncloud/android/ui/fragment/util/GalleryFastScrollViewHelper.kt | 1 | 10193 | /*
* Nextcloud Android Library is available under MIT license
*
* @author Álvaro Brey Vilas
* Copyright (C) 2022 Álvaro Brey Vilas
* Copyright (C) 2022 Nextcloud GmbH
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.owncloud.android.ui.fragment.util
import android.graphics.Canvas
import android.graphics.Rect
import android.view.MotionEvent
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ItemDecoration
import androidx.recyclerview.widget.RecyclerView.SimpleOnItemTouchListener
import com.afollestad.sectionedrecyclerview.ItemCoord
import com.owncloud.android.datamodel.GalleryItems
import com.owncloud.android.ui.adapter.GalleryAdapter
import me.zhanghai.android.fastscroll.FastScroller
import me.zhanghai.android.fastscroll.PopupTextProvider
import me.zhanghai.android.fastscroll.Predicate
import kotlin.math.ceil
import kotlin.math.min
/**
* Custom ViewHelper to get fast scroll working on gallery, which has a gridview and variable height (due to headers)
*
* Copied from me.zhanghai.android.fastscroll.RecyclerViewHelper and heavily modified for gallery structure
*/
class GalleryFastScrollViewHelper(
private val mView: RecyclerView,
private val mPopupTextProvider: PopupTextProvider?
) : FastScroller.ViewHelper {
// used to calculate paddings
private val mTempRect = Rect()
private val layoutManager by lazy { mView.layoutManager as GridLayoutManager }
// header is always 1st in the adapter
private val headerHeight by lazy { getItemHeight(0) }
// the 2nd element is always an item
private val rowHeight by lazy { getItemHeight(1) }
private val columnCount by lazy { layoutManager.spanCount }
private fun getItemHeight(position: Int): Int {
if (mView.childCount <= position) {
return 0
}
val itemView = mView.getChildAt(position)
mView.getDecoratedBoundsWithMargins(itemView, mTempRect)
return mTempRect.height()
}
override fun addOnPreDrawListener(onPreDraw: Runnable) {
mView.addItemDecoration(object : ItemDecoration() {
override fun onDraw(canvas: Canvas, parent: RecyclerView, state: RecyclerView.State) {
onPreDraw.run()
}
})
}
override fun addOnScrollChangedListener(onScrollChanged: Runnable) {
mView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
onScrollChanged.run()
}
})
}
override fun addOnTouchEventListener(onTouchEvent: Predicate<MotionEvent?>) {
mView.addOnItemTouchListener(object : SimpleOnItemTouchListener() {
override fun onInterceptTouchEvent(recyclerView: RecyclerView, event: MotionEvent): Boolean {
return onTouchEvent.test(event)
}
override fun onTouchEvent(recyclerView: RecyclerView, event: MotionEvent) {
onTouchEvent.test(event)
}
})
}
override fun getScrollRange(): Int {
val headerCount = getHeaderCount()
val rowCount = getRowCount()
if (headerCount == 0 || rowCount == 0) {
return 0
}
val totalHeaderHeight = headerCount * headerHeight
val totalRowHeight = rowCount * rowHeight
return mView.paddingTop + totalHeaderHeight + totalRowHeight + mView.paddingBottom
}
private fun getHeaderCount(): Int {
val adapter = mView.adapter as GalleryAdapter
return adapter.sectionCount
}
private fun getRowCount(): Int {
val adapter = mView.adapter as GalleryAdapter
if (adapter.sectionCount == 0) return 0
// in each section, the final row may contain less than the max of items
return adapter.files.sumOf { itemCountToRowCount(it.rows.size) }
}
/**
* Calculates current absolute offset depending on view state (first visible element)
*/
override fun getScrollOffset(): Int {
val firstItemPosition = getFirstItemAdapterPosition()
if (firstItemPosition == RecyclerView.NO_POSITION) {
return 0
}
val adapter = mView.adapter as GalleryAdapter
val itemCoord: ItemCoord = adapter.getRelativePosition(firstItemPosition)
val isHeader = itemCoord.relativePos() == -1
val seenRowsInPreviousSections = adapter.files
.subList(0, min(itemCoord.section(), adapter.files.size))
.sumOf { itemCountToRowCount(it.rows.size) }
val seenRowsInThisSection = if (isHeader) 0 else itemCountToRowCount(itemCoord.relativePos())
val totalSeenRows = seenRowsInPreviousSections + seenRowsInThisSection
val seenHeaders = when {
isHeader -> itemCoord.section() // don't count the current section header
else -> itemCoord.section() + 1
}
val firstItemTop = getFirstItemOffset()
val totalRowOffset = totalSeenRows * rowHeight
val totalHeaderOffset = seenHeaders * headerHeight
return mView.paddingTop + totalHeaderOffset + totalRowOffset - firstItemTop
}
/**
* Scrolls to an absolute offset
*/
override fun scrollTo(offset: Int) {
mView.stopScroll()
val offsetTmp = offset - mView.paddingTop
val (position, remainingOffset) = findPositionForOffset(offsetTmp)
scrollToPositionWithOffset(position, -remainingOffset)
}
/**
* Given an absolute offset, returns the closest position to that offset (without going over it),
* and the remaining offset
*/
private fun findPositionForOffset(offset: Int): Pair<Int, Int> {
val adapter = mView.adapter as GalleryAdapter
// find section
val sectionStartOffsets = getSectionStartOffsets(adapter.files)
val previousSections = sectionStartOffsets.filter { it <= offset }
val section = previousSections.size - 1
val sectionStartOffset = previousSections.last()
// now calculate where to scroll within the section
var remainingOffset = offset - sectionStartOffset
val positionWithinSection: Int
if (remainingOffset <= headerHeight) {
// header position
positionWithinSection = -1
} else {
// row position
remainingOffset -= headerHeight
val rowCount = remainingOffset / rowHeight
if (rowCount > 0) {
val rowStartIndex = rowCount * columnCount
positionWithinSection = rowStartIndex
remainingOffset -= rowCount * rowHeight
} else {
positionWithinSection = 0 // first item
}
}
val absolutePosition = adapter.getAbsolutePosition(section, positionWithinSection)
return Pair(absolutePosition, remainingOffset)
}
/**
* Returns a list of the offset heights at which the section corresponding to that index starts
*/
private fun getSectionStartOffsets(files: List<GalleryItems>): List<Int> {
val sectionHeights =
files.map { headerHeight + itemCountToRowCount(it.rows.size) * rowHeight }
val sectionStartOffsets = sectionHeights.indices.map { i ->
when (i) {
0 -> 0
else -> sectionHeights.subList(0, i).sum()
}
}
return sectionStartOffsets
}
private fun itemCountToRowCount(itemsCount: Int): Int {
return ceil(itemsCount.toDouble() / columnCount).toInt()
}
override fun getPopupText(): String? {
var popupTextProvider: PopupTextProvider? = mPopupTextProvider
if (popupTextProvider == null) {
val adapter = mView.adapter
if (adapter is PopupTextProvider) {
popupTextProvider = adapter
}
}
if (popupTextProvider == null) {
return null
}
val position = getFirstItemAdapterPosition()
return if (position == RecyclerView.NO_POSITION) {
null
} else {
popupTextProvider.getPopupText(position)
}
}
private fun getFirstItemAdapterPosition(): Int {
if (mView.childCount == 0) {
return RecyclerView.NO_POSITION
}
val itemView = mView.getChildAt(0)
return layoutManager.getPosition(itemView)
}
private fun getFirstItemOffset(): Int {
if (mView.childCount == 0) {
return RecyclerView.NO_POSITION
}
val itemView = mView.getChildAt(0)
mView.getDecoratedBoundsWithMargins(itemView, mTempRect)
return mTempRect.top
}
private fun scrollToPositionWithOffset(position: Int, offset: Int) {
var offsetTmp = offset
// LinearLayoutManager actually takes offset from paddingTop instead of top of RecyclerView.
offsetTmp -= mView.paddingTop
layoutManager.scrollToPositionWithOffset(position, offsetTmp)
}
}
| gpl-2.0 | 90e5e5c297f10666ffb398b9368ccc63 | 37.026119 | 117 | 0.673928 | 4.983374 | false | false | false | false |
BOINC/boinc | android/BOINC/app/src/main/java/edu/berkeley/boinc/rpc/CcStateParser.kt | 2 | 11959 | /*
* This file is part of BOINC.
* http://boinc.berkeley.edu
* Copyright (C) 2021 University of California
*
* BOINC is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* BOINC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with BOINC. If not, see <http://www.gnu.org/licenses/>.
*/
package edu.berkeley.boinc.rpc
import android.util.Xml
import edu.berkeley.boinc.utils.Logging
import org.xml.sax.Attributes
import org.xml.sax.SAXException
class CcStateParser : BaseParser() {
val ccState = CcState()
private var myProject = Project()
private val mVersionInfo = VersionInfo()
private val mAppsParser = AppsParser()
private val mAppVersionsParser = AppVersionsParser()
private val mHostInfoParser = HostInfoParser()
private val mProjectsParser = ProjectsParser()
private val mResultsParser = ResultsParser()
private val mWorkUnitsParser = WorkUnitsParser()
private var mInApp = false
private var mInAppVersion = false
private var mInHostInfo = false
private var mInProject = false
private var mInResult = false
private var mInWorkUnit = false
@Throws(SAXException::class)
override fun startElement(uri: String?, localName: String, qName: String?, attributes: Attributes?) {
super.startElement(uri, localName, qName, attributes)
if (localName.equals(CLIENT_STATE_TAG, ignoreCase = true)) {
//Starting the query, clear mCcState
ccState.clearArrays()
}
if (localName.equals(HostInfoParser.HOST_INFO_TAG, ignoreCase = true)) {
// Just stepped inside <host_info>
mInHostInfo = true
}
if (mInHostInfo) {
mHostInfoParser.startElement(uri, localName, qName, attributes)
}
if (localName.equals(PROJECT, ignoreCase = true)) {
// Just stepped inside <project>
mInProject = true
}
if (mInProject) {
mProjectsParser.startElement(uri, localName, qName, attributes)
}
if (localName.equals(AppsParser.APP_TAG, ignoreCase = true)) {
// Just stepped inside <app>
mInApp = true
}
if (mInApp) {
mAppsParser.startElement(uri, localName, qName, attributes)
}
if (localName.equals(AppVersionsParser.APP_VERSION_TAG, ignoreCase = true)) {
// Just stepped inside <app_version>
mInAppVersion = true
}
if (mInAppVersion) {
mAppVersionsParser.startElement(uri, localName, qName, attributes)
}
if (localName.equals(WorkUnitsParser.WORKUNIT_TAG, ignoreCase = true)) {
// Just stepped inside <workunit>
mInWorkUnit = true
}
if (mInWorkUnit) {
mWorkUnitsParser.startElement(uri, localName, qName, attributes)
}
if (localName.equals(ResultsParser.RESULT_TAG, ignoreCase = true)) {
// Just stepped inside <result>
mInResult = true
}
if (mInResult) {
mResultsParser.startElement(uri, localName, qName, attributes)
}
if (localName.equalsAny(CORE_CLIENT_MAJOR_VERSION_TAG, CORE_CLIENT_MINOR_VERSION_TAG,
CORE_CLIENT_RELEASE_TAG, CcState.Fields.HAVE_ATI,
CcState.Fields.HAVE_CUDA, ignoreCase = true)) {
// VersionInfo elements
mElementStarted = true
mCurrentElement.setLength(0)
}
}
@Throws(SAXException::class)
override fun characters(ch: CharArray, start: Int, length: Int) {
super.characters(ch, start, length)
if (mInHostInfo) { // We are inside <host_info>
mHostInfoParser.characters(ch, start, length)
}
if (mInProject) { // We are inside <project>
mProjectsParser.characters(ch, start, length)
}
if (mInApp) { // We are inside <project>
mAppsParser.characters(ch, start, length)
}
if (mInAppVersion) { // We are inside <project>
mAppVersionsParser.characters(ch, start, length)
}
if (mInWorkUnit) { // We are inside <workunit>
mWorkUnitsParser.characters(ch, start, length)
}
if (mInResult) { // We are inside <result>
mResultsParser.characters(ch, start, length)
}
// VersionInfo elements are handled in super.characters()
}
@Throws(SAXException::class)
override fun endElement(uri: String?, localName: String, qName: String?) {
super.endElement(uri, localName, qName)
try {
if (mInHostInfo) { // We are inside <host_info>
// parse it by sub-parser in any case (to parse also closing element)
mHostInfoParser.endElement(uri, localName, qName)
ccState.hostInfo = mHostInfoParser.hostInfo
if (localName.equals(HostInfoParser.HOST_INFO_TAG, ignoreCase = true)) {
mInHostInfo = false
}
}
if (mInProject) { // We are inside <project>
// parse it by sub-parser in any case (must parse also closing element!)
mProjectsParser.endElement(uri, localName, qName)
if (localName.equals(PROJECT, ignoreCase = true)) {
// Closing tag of <project>
mInProject = false
val projects = mProjectsParser.projects
if (projects.isNotEmpty()) {
myProject = projects.last()
ccState.projects.add(myProject)
}
}
}
if (mInApp) { // We are inside <app>
// parse it by sub-parser in any case (must parse also closing element!)
mAppsParser.endElement(uri, localName, qName)
if (localName.equals(AppsParser.APP_TAG, ignoreCase = true)) {
// Closing tag of <app>
mInApp = false
val apps: List<App> = mAppsParser.apps
if (apps.isNotEmpty()) {
val myApp = apps.last()
myApp.project = myProject
ccState.apps.add(myApp)
}
}
}
if (mInAppVersion) { // We are inside <app_version>
// parse it by sub-parser in any case (must also parse closing element!)
mAppVersionsParser.endElement(uri, localName, qName)
if (localName.equals(AppVersionsParser.APP_VERSION_TAG, ignoreCase = true)) {
// Closing tag of <app_version>
mInAppVersion = false
val appVersions: List<AppVersion> = mAppVersionsParser.appVersions
if (appVersions.isNotEmpty()) {
val myAppVersion = appVersions.last()
myAppVersion.project = myProject
myAppVersion.app = ccState.lookupApp(myProject, myAppVersion.appName)
ccState.appVersions.add(myAppVersion)
}
}
}
if (mInWorkUnit) { // We are inside <workunit>
// parse it by sub-parser in any case (must parse also closing element!)
mWorkUnitsParser.endElement(uri, localName, qName)
if (localName.equals(WorkUnitsParser.WORKUNIT_TAG, ignoreCase = true)) {
// Closing tag of <workunit>
mInWorkUnit = false
val workUnits = mWorkUnitsParser.workUnits
if (workUnits.isNotEmpty()) {
val myWorkUnit = workUnits.last()
myWorkUnit.project = myProject
myWorkUnit.app = ccState.lookupApp(myProject, myWorkUnit.appName)
ccState.workUnits.add(myWorkUnit)
}
}
}
if (mInResult) {
// We are inside <result>
// parse it by sub-parser in any case (must parse also closing element!)
mResultsParser.endElement(uri, localName, qName)
if (localName.equals(ResultsParser.RESULT_TAG, ignoreCase = true)) {
// Closing tag of <result>
mInResult = false
val results = mResultsParser.results
if (results.isNotEmpty()) {
val myResult = results.last()
myResult.project = myProject
myResult.workUnit = ccState.lookupWorkUnit(myProject, myResult.workUnitName)
if (myResult.workUnit != null) {
myResult.app = myResult.workUnit!!.app
myResult.appVersion = ccState.lookupAppVersion(myProject, myResult.app,
myResult.versionNum, myResult.planClass)
}
ccState.results.add(myResult)
}
}
}
if (mElementStarted) {
trimEnd()
// VersionInfo?
when {
localName.equals(CORE_CLIENT_MAJOR_VERSION_TAG, ignoreCase = true) -> {
mVersionInfo.major = mCurrentElement.toInt()
}
localName.equals(CORE_CLIENT_MINOR_VERSION_TAG, ignoreCase = true) -> {
mVersionInfo.minor = mCurrentElement.toInt()
}
localName.equals(CORE_CLIENT_RELEASE_TAG, ignoreCase = true) -> {
mVersionInfo.release = mCurrentElement.toInt()
}
localName.equals(CcState.Fields.HAVE_ATI, ignoreCase = true) -> {
ccState.haveAti = mCurrentElement.toString() != "0"
}
localName.equals(CcState.Fields.HAVE_CUDA, ignoreCase = true) -> {
ccState.haveCuda = mCurrentElement.toString() != "0"
}
}
mElementStarted = false
ccState.versionInfo = mVersionInfo
}
} catch (e: Exception) {
Logging.logException(Logging.Category.XML, "CcStateParser.endElement error: ", e)
}
}
companion object {
const val CLIENT_STATE_TAG = "client_state"
const val CORE_CLIENT_MAJOR_VERSION_TAG = "core_client_major_version"
const val CORE_CLIENT_MINOR_VERSION_TAG = "core_client_minor_version"
const val CORE_CLIENT_RELEASE_TAG = "core_client_release"
/**
* Parse the RPC result (state) and generate vector of projects info
*
* @param rpcResult String returned by RPC call of core client
* @return connected client state
*/
@JvmStatic
fun parse(rpcResult: String?): CcState? {
return try {
val parser = CcStateParser()
Xml.parse(rpcResult, parser)
parser.ccState
} catch (e: SAXException) {
Logging.logException(Logging.Category.RPC, "CcStateParser: malformed XML ", e)
Logging.logDebug(Logging.Category.XML, "CcStateParser: $rpcResult")
null
}
}
}
}
| lgpl-3.0 | 3e5eaf1d668c0736d823330627725394 | 43.623134 | 105 | 0.557823 | 4.72501 | false | false | false | false |
openHPI/android-app | app/src/main/java/de/xikolo/controllers/course/AnnouncementListFragment.kt | 1 | 2788 | package de.xikolo.controllers.course
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import butterknife.BindView
import com.yatatsu.autobundle.AutoBundleField
import de.xikolo.R
import de.xikolo.controllers.announcement.AnnouncementActivityAutoBundle
import de.xikolo.controllers.base.ViewModelFragment
import de.xikolo.controllers.main.AnnouncementListAdapter
import de.xikolo.extensions.observe
import de.xikolo.models.Announcement
import de.xikolo.utils.LanalyticsUtil
import de.xikolo.viewmodels.main.AnnouncementListViewModel
class AnnouncementListFragment : ViewModelFragment<AnnouncementListViewModel>() {
companion object {
val TAG: String = AnnouncementListFragment::class.java.simpleName
}
@AutoBundleField
internal lateinit var courseId: String
@BindView(R.id.content_view)
internal lateinit var recyclerView: RecyclerView
private lateinit var announcementListAdapter: AnnouncementListAdapter
override val layoutResource = R.layout.fragment_announcement_list
override fun createViewModel(): AnnouncementListViewModel {
return AnnouncementListViewModel(courseId)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
announcementListAdapter = AnnouncementListAdapter({ announcementId -> openAnnouncement(announcementId) }, false)
val layoutManager = LinearLayoutManager(activity)
recyclerView.layoutManager = layoutManager
val dividerItemDecoration = DividerItemDecoration(recyclerView.context, layoutManager.orientation)
recyclerView.addItemDecoration(dividerItemDecoration)
recyclerView.setHasFixedSize(true)
recyclerView.adapter = announcementListAdapter
viewModel.announcements
.observe(viewLifecycleOwner) {
showAnnouncementList(it)
}
}
private fun showAnnouncementList(announcements: List<Announcement>) {
if (announcements.isEmpty()) {
showEmptyMessage(R.string.empty_message_course_announcements_title)
} else {
showContent()
announcementListAdapter.update(announcements)
}
}
private fun openAnnouncement(announcementId: String) {
val intent = AnnouncementActivityAutoBundle.builder(announcementId, false).build(activity!!)
startActivity(intent)
LanalyticsUtil.trackVisitedAnnouncementDetail(announcementId)
}
}
| bsd-3-clause | 3f91d76a0747d0c0bf4d73e5a4441fe1 | 35.684211 | 120 | 0.762554 | 5.56487 | false | false | false | false |
mockk/mockk | modules/mockk/src/commonMain/kotlin/io/mockk/impl/instantiation/AbstractMockFactory.kt | 2 | 4259 | package io.mockk.impl.instantiation
import io.mockk.InternalPlatformDsl
import io.mockk.InternalPlatformDsl.toStr
import io.mockk.MockKException
import io.mockk.MockKGateway
import io.mockk.MockKSettings
import io.mockk.impl.InternalPlatform
import io.mockk.impl.log.Logger
import io.mockk.impl.stub.*
import kotlin.reflect.KClass
abstract class AbstractMockFactory(
val stubRepository: StubRepository,
val instantiator: AbstractInstantiator,
gatewayAccessIn: StubGatewayAccess
) : MockKGateway.MockFactory {
val safeToString = gatewayAccessIn.safeToString
val log = safeToString(Logger<AbstractMockFactory>())
val gatewayAccess = gatewayAccessIn.copy(mockFactory = this)
abstract fun <T : Any> newProxy(
cls: KClass<out T>,
moreInterfaces: Array<out KClass<*>>,
stub: Stub,
useDefaultConstructor: Boolean = false,
instantiate: Boolean = false
): T
override fun <T : Any> mockk(
mockType: KClass<T>,
name: String?,
relaxed: Boolean,
moreInterfaces: Array<out KClass<*>>,
relaxUnitFun: Boolean
): T {
val id = newId()
val newName = (name ?: "") + "#$id"
val stub = MockKStub(
mockType,
newName,
relaxed || MockKSettings.relaxed,
relaxUnitFun || MockKSettings.relaxUnitFun,
gatewayAccess,
true,
MockType.REGULAR
)
if (moreInterfaces.isEmpty()) {
log.debug { "Creating mockk for ${mockType.toStr()} name=$newName" }
} else {
log.debug { "Creating mockk for ${mockType.toStr()} name=$newName, moreInterfaces=${moreInterfaces.contentToString()}" }
}
log.trace { "Building proxy for ${mockType.toStr()} hashcode=${InternalPlatform.hkd(mockType)}" }
val proxy = newProxy(mockType, moreInterfaces, stub)
stub.hashCodeStr = InternalPlatform.hkd(proxy)
stubRepository.add(proxy, stub)
return proxy
}
override fun <T : Any> spyk(
mockType: KClass<T>?,
objToCopy: T?,
name: String?,
moreInterfaces: Array<out KClass<*>>,
recordPrivateCalls: Boolean
): T {
val id = newId()
val newName = (name ?: "") + "#$id"
val actualCls = when {
objToCopy != null -> objToCopy::class
mockType != null -> mockType
else -> throw MockKException("Either mockType or objToCopy should not be null")
}
if (moreInterfaces.isEmpty()) {
log.debug { "Creating spyk for ${actualCls.toStr()} name=$newName" }
} else {
log.debug { "Creating spyk for ${actualCls.toStr()} name=$newName, moreInterfaces=${moreInterfaces.contentToString()}" }
}
val stub = SpyKStub(
actualCls,
newName,
gatewayAccess,
recordPrivateCalls || MockKSettings.recordPrivateCalls,
MockType.SPY
)
val useDefaultConstructor = objToCopy == null
log.trace { "Building proxy for ${actualCls.toStr()} hashcode=${InternalPlatform.hkd(actualCls)}" }
val proxy = newProxy(actualCls, moreInterfaces, stub, useDefaultConstructor)
stub.hashCodeStr = InternalPlatform.hkd(proxy)
if (objToCopy != null) {
InternalPlatform.copyFields(proxy, objToCopy)
}
stubRepository.add(proxy, stub)
return proxy
}
override fun temporaryMock(mockType: KClass<*>): Any {
val stub = MockKStub(
mockType,
"temporary mock",
gatewayAccess = gatewayAccess,
recordPrivateCalls = true,
mockType = MockType.TEMPORARY
)
log.trace { "Building proxy for ${mockType.toStr()} hashcode=${InternalPlatform.hkd(mockType)}" }
val proxy = newProxy(mockType, arrayOf(), stub, instantiate = true)
stub.hashCodeStr = InternalPlatform.hkd(proxy)
return proxy
}
override fun isMock(value: Any) = gatewayAccess.stubRepository[value] != null
companion object {
val idCounter = InternalPlatformDsl.counter()
fun newId(): Long = idCounter.increment() + 1
}
}
| apache-2.0 | 87e47e4d19d297a416623623a12e8f6a | 29.205674 | 132 | 0.615168 | 4.58944 | false | false | false | false |
ohmae/mmupnp | mmupnp/src/main/java/net/mm2d/upnp/internal/parser/DeviceParser.kt | 1 | 6389 | /*
* Copyright (c) 2019 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.upnp.internal.parser
import net.mm2d.upnp.Http
import net.mm2d.upnp.HttpClient
import net.mm2d.upnp.Icon
import net.mm2d.upnp.internal.impl.DeviceImpl
import net.mm2d.upnp.internal.impl.IconImpl
import net.mm2d.upnp.internal.impl.ServiceImpl
import net.mm2d.xml.node.XmlElement
import net.mm2d.xml.parser.XmlParser
import java.io.IOException
/**
* Parser for Device.
*
* Download Description XML, parse it, set value to builder.
*
* @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected])
*/
internal object DeviceParser {
/**
* load DeviceDescription.
*
* Parse the Description and register it with the Builder.
* In addition, download Icon / description of Service described internally, parses it,
* and creates each Builder.
*
* @param client HttpClient
* @param builder DeviceのBuilder
* @throws IOException if an I/O error occurs.
*/
@Throws(IOException::class)
fun loadDescription(client: HttpClient, builder: DeviceImpl.Builder) {
val url = Http.makeUrlWithScopeId(builder.getLocation(), builder.getSsdpMessage().scopeId)
// DIAL Application-URL
// val response = client.download(url)
// Logger.d { response.getHeader("Application-URL") }
val description = client.downloadString(url)
if (description.isEmpty()) {
throw IOException("download error: $url")
}
builder.setDownloadInfo(client)
parseDescription(builder, description)
loadServices(client, builder)
}
@Throws(IOException::class)
private fun loadServices(client: HttpClient, builder: DeviceImpl.Builder) {
builder.getServiceBuilderList().forEach {
ServiceParser.loadDescription(client, builder, it)
}
builder.getEmbeddedDeviceBuilderList().forEach {
loadServices(client, it)
}
}
@Throws(IOException::class)
internal fun parseDescription(builder: DeviceImpl.Builder, description: String) {
builder.setDescription(description)
val rootNode = XmlParser.parse(description) ?: throw IOException()
val deviceNode = rootNode.childElements
.find { it.localName == "device" } ?: throw IOException()
parseDevice(builder, deviceNode)
}
private fun parseDevice(builder: DeviceImpl.Builder, deviceNode: XmlElement) {
deviceNode.childElements.forEach {
when (val tag = it.localName) {
"iconList" ->
parseIconList(builder, it)
"serviceList" ->
parseServiceList(builder, it)
"deviceList" ->
parseDeviceList(builder, it)
else -> {
val namespace = it.uri
val value = it.value
builder.putTag(namespace, tag, value)
builder.setField(tag, value)
}
}
}
}
private fun DeviceImpl.Builder.setField(tag: String, value: String) {
when (tag) {
"UDN" ->
setUdn(value)
"UPC" ->
setUpc(value)
"deviceType" ->
setDeviceType(value)
"friendlyName" ->
setFriendlyName(value)
"manufacturer" ->
setManufacture(value)
"manufacturerURL" ->
setManufactureUrl(value)
"modelName" ->
setModelName(value)
"modelURL" ->
setModelUrl(value)
"modelDescription" ->
setModelDescription(value)
"modelNumber" ->
setModelNumber(value)
"serialNumber" ->
setSerialNumber(value)
"presentationURL" ->
setPresentationUrl(value)
"URLBase" ->
setUrlBase(value)
}
}
private fun parseIconList(builder: DeviceImpl.Builder, listNode: XmlElement) {
listNode.childElements
.filter { it.localName == "icon" }
.forEach { builder.addIcon(parseIcon(it)) }
}
private fun parseIcon(iconNode: XmlElement): Icon {
val builder = IconImpl.Builder()
iconNode.childElements
.forEach { builder.setField(it.localName, it.value) }
return builder.build()
}
private fun IconImpl.Builder.setField(tag: String, value: String) {
when (tag) {
"mimetype" ->
setMimeType(value)
"height" ->
setHeight(value)
"width" ->
setWidth(value)
"depth" ->
setDepth(value)
"url" ->
setUrl(value)
}
}
private fun parseServiceList(builder: DeviceImpl.Builder, listNode: XmlElement) {
listNode.childElements
.filter { it.localName == "service" }
.forEach { builder.addServiceBuilder(parseService(it)) }
}
private fun parseService(serviceNode: XmlElement): ServiceImpl.Builder {
val serviceBuilder = ServiceImpl.Builder()
serviceNode.childElements
.forEach { serviceBuilder.setField(it.localName, it.value) }
return serviceBuilder
}
private fun ServiceImpl.Builder.setField(tag: String, value: String) {
when (tag) {
"serviceType" ->
setServiceType(value)
"serviceId" ->
setServiceId(value)
"SCPDURL" ->
setScpdUrl(value)
"eventSubURL" ->
setEventSubUrl(value)
"controlURL" ->
setControlUrl(value)
}
}
private fun parseDeviceList(builder: DeviceImpl.Builder, listNode: XmlElement) {
val builderList = ArrayList<DeviceImpl.Builder>()
listNode.childElements
.filter { it.localName == "device" }
.forEach {
val embeddedBuilder = builder.createEmbeddedDeviceBuilder()
parseDevice(embeddedBuilder, it)
builderList.add(embeddedBuilder)
}
builder.setEmbeddedDeviceBuilderList(builderList)
}
}
| mit | 2f2c5c5f85e4b36a862b041e93b702c6 | 32.531579 | 98 | 0.581227 | 4.560487 | false | false | false | false |
DemonWav/IntelliJBukkitSupport | src/main/kotlin/creator/buildsystem/BuildSystem.kt | 1 | 4460 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.creator.buildsystem
import com.demonwav.mcdev.creator.CreatorStep
import com.demonwav.mcdev.creator.ProjectCreator
import com.demonwav.mcdev.creator.buildsystem.gradle.GradleBuildSystem
import com.demonwav.mcdev.creator.buildsystem.gradle.GradleCreator
import com.demonwav.mcdev.creator.buildsystem.maven.MavenBuildSystem
import com.demonwav.mcdev.creator.buildsystem.maven.MavenCreator
import com.demonwav.mcdev.platform.PlatformType
import com.intellij.openapi.module.Module
import java.nio.file.Path
import java.util.EnumSet
import kotlin.reflect.KClass
/**
* Base class for build system project creation.
*/
abstract class BuildSystem(
val groupId: String,
val artifactId: String,
val version: String
) {
open val parent: BuildSystem? = null
val parentOrError: BuildSystem
get() = parent ?: throw IllegalStateException("Sub-module build system does not have a parent")
abstract val type: BuildSystemType
abstract fun buildCreator(obj: Any, rootDirectory: Path, module: Module): ProjectCreator
open fun configure(list: Collection<Any>, rootDirectory: Path) {}
var repositories: MutableList<BuildRepository> = mutableListOf()
var dependencies: MutableList<BuildDependency> = mutableListOf()
var directories: DirectorySet? = null
val dirsOrError: DirectorySet
get() = directories ?: throw IllegalStateException("Project structure is not yet created")
val commonModuleName: String
get() = parentOrError.artifactId + "-common"
/**
* Initial [CreatorStep]s to execute when creating the base of a multi-module project for this build system type.
* These steps run before the platform-specific submodule steps run.
*
* @see com.demonwav.mcdev.creator.MinecraftProjectCreator.CreateTask.run
*/
abstract fun multiModuleBaseSteps(
module: Module,
types: List<PlatformType>,
rootDirectory: Path
): Iterable<CreatorStep>
/**
* Finalizer [CreatorStep]s to execute when finishing a multi-module project for this build system type. These steps
* are run after the platform-specific submodule steps are run, as well as after [multiModuleCommonSteps].
*
* @see com.demonwav.mcdev.creator.MinecraftProjectCreator.CreateTask.run
*/
abstract fun multiModuleBaseFinalizer(
module: Module,
rootDirectory: Path
): Iterable<CreatorStep>
/**
* [CreatorStep]s for creating the shared common module for a multi-module project for this build system type. These
* steps run after the platform-specific submodule steps are run, and before [multiModuleBaseFinalizer].
*
* @see com.demonwav.mcdev.creator.MinecraftProjectCreator.CreateTask.run
*/
abstract fun multiModuleCommonSteps(
module: Module,
rootDirectory: Path
): Iterable<CreatorStep>
/**
* Using the given [artifactId] create a new child [BuildSystem] instance which shares all of the other properties
* as this instance, except for the `artifactId`.
*/
abstract fun createSub(artifactId: String): BuildSystem
}
enum class BuildSystemType(private val readableName: String, val creatorType: KClass<*>) {
MAVEN("Maven", MavenCreator::class) {
override fun create(groupId: String, artifactId: String, version: String): BuildSystem {
return MavenBuildSystem(groupId, artifactId, version)
}
},
GRADLE("Gradle", GradleCreator::class) {
override fun create(groupId: String, artifactId: String, version: String): BuildSystem {
return GradleBuildSystem(groupId, artifactId, version)
}
};
/**
* Create a new [BuildSystem] instance using the provided artifact definition.
*/
abstract fun create(groupId: String, artifactId: String, version: String): BuildSystem
override fun toString(): String {
return readableName
}
}
data class BuildDependency(
val groupId: String = "",
val artifactId: String = "",
val version: String = "",
val mavenScope: String? = null,
val gradleConfiguration: String? = null
)
data class BuildRepository(
var id: String = "",
var url: String = "",
val buildSystems: EnumSet<BuildSystemType> = EnumSet.allOf(BuildSystemType::class.java)
)
| mit | e3eb2da1856716bc55d982954da23bba | 34.11811 | 120 | 0.714574 | 4.621762 | false | false | false | false |
REBOOTERS/AndroidAnimationExercise | app/src/main/java/home/smart/fly/animations/ui/activity/PullToScaleActivity.kt | 1 | 2319 | package home.smart.fly.animations.ui.activity
import android.os.Bundle
import com.google.android.material.snackbar.Snackbar
import androidx.appcompat.app.AppCompatActivity
import android.util.Log
import android.view.View
import home.smart.fly.animations.R
import home.smart.fly.animations.widget.NestedScrollView
import kotlinx.android.synthetic.main.activity_pull_to_scale.*
import kotlinx.android.synthetic.main.content_pull_to_scale.*
class PullToScaleActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_pull_to_scale)
setSupportActionBar(toolbar)
nested_scrollview.setOnScrollChangeListener(object : NestedScrollView.OnScrollChangeListener {
/**
* Called when the scroll position of a view changes.
*
* @param v The view whose scroll position has changed.
* @param scrollX Current horizontal scroll origin.
* @param scrollY Current vertical scroll origin.
* @param oldScrollX Previous horizontal scroll origin.
* @param oldScrollY Previous vertical scroll origin.
*/
override fun onScrollChange(v: NestedScrollView?, scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int) {
Log.e("TAG", "scrolly===$scrollY")
if (scrollY >= 0) {
val height = image.measuredHeight
if (height != content.paddingTop) {
var params = image.layoutParams
params.height = content.paddingTop
image.layoutParams = params
}
val isOver = scrollY >= height
if (isOver) {
image.visibility = View.GONE
} else {
image.visibility = View.VISIBLE
}
image.scrollTo(0, scrollY/3)
} else {
image.scrollTo(0, 0)
val params = image.layoutParams
params.height = content.paddingTop - scrollY
image.layoutParams = params
}
}
})
}
}
| apache-2.0 | 4080343750dfa3c4fb9f32f1db5aa261 | 39.684211 | 125 | 0.581285 | 5.368056 | false | false | false | false |
martin-nordberg/KatyDOM | Katydid-VDOM-JVM/src/test/kotlin/jvm/katydid/vdom/builders/forms/MeterTests.kt | 1 | 3709 | //
// (C) Copyright 2018-2019 Martin E. Nordberg III
// Apache 2.0 License
//
package jvm.katydid.vdom.builders.forms
import jvm.katydid.vdom.api.checkBuild
import o.katydid.vdom.application.katydid
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
@Suppress("RemoveRedundantBackticks")
class MeterTests {
@Test
fun `A meter element with floating point attributes produces correct HTML`() {
val vdomNode = katydid<Unit> {
form {
meter(
high = 90.0,
low = 10.0,
max = 100.0,
min = 0.0,
optimum = 50.0,
value = 40.0
) {}
}
}
val html = """<form>
| <meter high="90.0" low="10.0" max="100.0" min="0.0" optimum="50.0" value="40.0"></meter>
|</form>""".trimMargin()
checkBuild(html, vdomNode)
}
@Test
fun `A meter element with integer attributes produces correct HTML`() {
val vdomNode = katydid<Unit> {
form {
meter(
high = 90,
low = 10,
max = 100,
min = 0,
optimum = 50,
value = 40
) {}
}
}
val html = """<form>
| <meter high="90" low="10" max="100" min="0" optimum="50" value="40"></meter>
|</form>""".trimMargin()
checkBuild(html, vdomNode)
}
@Test
fun `A meter may not be nested`() {
assertThrows<IllegalStateException> {
katydid<Unit> {
meter(value = 0.5) {
meter(value = 0.2) {}
}
}
}
}
@Test
fun `A meter's range must be well-defined`() {
assertThrows<IllegalArgumentException> {
katydid<Unit> {
meter(value = 5, min = 10, max = 0) {}
}
}
assertThrows<IllegalArgumentException> {
katydid<Unit> {
meter(value = 0.5, min = 1.0, max = 0.0) {}
}
}
}
@Test
fun `A meter's attributes must be in its default range`() {
assertThrows<IllegalArgumentException> {
katydid<Unit> {
meter(value = 1.1) {}
}
}
assertThrows<IllegalArgumentException> {
katydid<Unit> {
meter(high = 1.1, value = 0.5) {}
}
}
assertThrows<IllegalArgumentException> {
katydid<Unit> {
meter(low = -0.1, value = 0.5) {}
}
}
assertThrows<IllegalArgumentException> {
katydid<Unit> {
meter(optimum = 1.1, value = 0.5) {}
}
}
}
@Test
fun `A meter's attributes must be in range`() {
assertThrows<IllegalArgumentException> {
katydid<Unit> {
meter(min = 0, max = 100, value = 110) {}
}
}
assertThrows<IllegalArgumentException> {
katydid<Unit> {
meter(min = 0, max = 100, high = 110, value = 50) {}
}
}
assertThrows<IllegalArgumentException> {
katydid<Unit> {
meter(min = 0, max = 100, low = -10, value = 50) {}
}
}
assertThrows<IllegalArgumentException> {
katydid<Unit> {
meter(min = 0, max = 100, optimum = 110, value = 50) {}
}
}
}
}
| apache-2.0 | 402d758919534eee3dceadb89b2c0b59 | 19.157609 | 112 | 0.44028 | 4.55092 | false | false | false | false |
JimSeker/drawing | AnimatedGifDemo_kt/app/src/main/java/edu/cs4730/animatedgifdemo_kt/MainActivity.kt | 1 | 3013 | package edu.cs4730.animatedgifdemo_kt
import android.graphics.Color
import android.graphics.ColorFilter
import android.graphics.ImageDecoder
import android.graphics.LightingColorFilter
import android.graphics.PorterDuff
import android.graphics.PorterDuffColorFilter
import android.graphics.drawable.AnimatedImageDrawable
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import java.io.IOException
/**
* Simple demo to load and display animated gifs.
* The second gifs has it color altered using color filter, (which works on any drawable image, not just animated)
*
*
* Note, this works on API 28+, since no androidx libraries were used.
*/
class MainActivity : AppCompatActivity() {
lateinit var decodedAnimation: Drawable
lateinit var decodedAnimation2: Drawable
lateinit var iva: ImageView
lateinit var iva2: ImageView
lateinit var colorFilter: ColorFilter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
iva = findViewById(R.id.imageView)
iva2 = findViewById(R.id.imageView2)
//get the animated gif, but can't be on the main thread, so
Thread {
try {
decodedAnimation =
ImageDecoder.decodeDrawable( // create ImageDecoder.Source object
ImageDecoder.createSource(resources, R.drawable.what)
)
decodedAnimation2 =
ImageDecoder.decodeDrawable( // create ImageDecoder.Source object
ImageDecoder.createSource(resources, R.drawable.rainbowkitty)
)
// change color of gif, Multiplies the RGB channels by one color, and then adds a second color.
// change color of gif, Multiplies the RGB channels by one color, and then adds a second color.
// colorFilter = LightingColorFilter(Color.RED, Color.BLUE)
// decodedAnimation.colorFilter = colorFilter
//Change Color with PorterDuffColorFilter
decodedAnimation2.colorFilter =
PorterDuffColorFilter(Color.RED, PorterDuff.Mode.DARKEN)
} catch (e: IOException) {
e.printStackTrace()
}
//can't change the imageview from a thread, so add to the main thread via a post.
runOnUiThread { // set the drawable as image source of ImageView
iva.setImageDrawable(decodedAnimation)
//start it animated, not animatedImageDrawable is a child of Drawable, so casting.
(decodedAnimation as AnimatedImageDrawable).start()
//now the second image.
iva2.setImageDrawable(decodedAnimation2)
(decodedAnimation2 as AnimatedImageDrawable).start()
}
}.start()
}
}
| apache-2.0 | 9cd379cf1ed88fce0ff4872d336a40c1 | 41.43662 | 114 | 0.664122 | 5.212803 | false | false | false | false |
Ztiany/Repository | Kotlin/Kotlin-Basic/src/main/kotlin/me/ztiany/advance/KotlinCollections.kt | 2 | 3055 | package me.ztiany.advance
/**
* Kotlin中集合:
*
* 1,Kotlin 区分可变集合和不可变集合(lists、sets、maps 等)。精确控制什么时候集合可编辑有助于消除 bug 和设计良好的 API。
* 2,Kotlin 没有专门的语法结构创建 list 或 set。 要用标准库的方法,如 listOf()、 mutableListOf()、 setOf()、 mutableSetOf()
* 3,在非性能关键代码中创建 map 可以用一个简单的惯用法来完成:mapOf(a to b, c to d)
*/
private open class Shape
private class Square : Shape()
private fun useCollections() {
//可变集合
val mutableList = mutableListOf(1, 2, 3, 4, 5, 6, 7, 8, 9)
mutableList.clear()
//listOf创建的是只读集合
val readOnlyList = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9)
//创建set
val strSet = hashSetOf("a", "b", "c", "c")
//在非性能关键代码中创建 map 可以用一个简单的惯用法来完成
val map = mapOf("A" to 1, "B" to 2)
//协变性,不可变集合具有协变性
var listShape: List<Shape> = listOf()
val listSquare: List<Square> = listOf()
listShape = listSquare
//对于可变集合,使用toList()可以返回一个快照
val intList = mutableListOf(1, 2, 3, 4, 5, 6, 7, 8, 9)
val readOnlyIntList = intList.toList()
}
/*
Kotlin为操作集合容器添加了许多的函数式API,操作即可变得更加方便简洁。
下标操作类
contains —— 判断是否有指定元素
elementAt —— 返回对应的元素,越界会抛IndexOutOfBoundsException
firstOrNull —— 返回符合条件的第一个元素,没有 返回null
lastOrNull —— 返回符合条件的最后一个元素,没有 返回null
indexOf —— 返回指定元素的下标,没有 返回-1
singleOrNull —— 返回符合条件的单个元素,如有没有符合或超过一个,返回null
判断类
any —— 判断集合中 是否有满足条件 的元素
all —— 判断集合中的元素 是否都满足条件
none —— 判断集合中是否 都不满足条件,是则返回true
count —— 查询集合中 满足条件 的 元素个数
reduce —— 从 第一项到最后一项进行累计
过滤类
filter —— 过滤 掉所有 满足条件 的元素
filterNot —— 过滤所有不满足条件的元素
filterNotNull —— 过滤NULL
take —— 返回前 n 个元素
转换类
map —— 转换成另一个集合(与上面我们实现的 convert 方法作用一样);
mapIndexed —— 除了转换成另一个集合,还可以拿到Index(下标);
mapNotNull —— 执行转换前过滤掉 为 NULL 的元素
flatMap —— 自定义逻辑合并两个集合;
groupBy —— 按照某个条件分组,返回Map;
排序类
reversed —— 反序
sorted —— 升序
sortedBy —— 自定义排序
sortedDescending —— 降序
*/
private fun functionalApi() {
}
fun main(args: Array<String>) {
useCollections()
}
| apache-2.0 | 950a613671c778586725b8d1841a8c2d | 20.285714 | 102 | 0.653072 | 2.496134 | false | false | false | false |
edvin/tornadofx | src/main/java/tornadofx/Forms.kt | 1 | 13451 | package tornadofx
import javafx.beans.DefaultProperty
import javafx.beans.binding.Bindings.createObjectBinding
import javafx.beans.property.SimpleObjectProperty
import javafx.beans.property.SimpleStringProperty
import javafx.collections.ListChangeListener
import javafx.collections.ObservableList
import javafx.css.PseudoClass
import javafx.event.EventTarget
import javafx.geometry.Orientation
import javafx.geometry.Orientation.HORIZONTAL
import javafx.geometry.Orientation.VERTICAL
import javafx.scene.Node
import javafx.scene.control.ButtonBar
import javafx.scene.control.Label
import javafx.scene.layout.*
import javafx.scene.layout.Priority.SOMETIMES
import javafx.stage.Stage
import java.util.*
import java.util.concurrent.Callable
fun EventTarget.form(op: Form.() -> Unit = {}) = opcr(this, Form(), op)
fun EventTarget.fieldset(text: String? = null, icon: Node? = null, labelPosition: Orientation? = null, wrapWidth: Double? = null, op: Fieldset.() -> Unit = {}): Fieldset {
val fieldset = Fieldset(text ?: "")
if (wrapWidth != null) fieldset.wrapWidth = wrapWidth
if (labelPosition != null) fieldset.labelPosition = labelPosition
if (icon != null) fieldset.icon = icon
opcr(this, fieldset, op)
return fieldset
}
/**
* Creates a ButtonBarFiled with the given button order (refer to [javafx.scene.control.ButtonBar#buttonOrderProperty()] for more information about buttonOrder).
*/
fun EventTarget.buttonbar(buttonOrder: String? = null, forceLabelIndent: Boolean = true, op: ButtonBar.() -> Unit = {}): ButtonBarField {
val field = ButtonBarField(buttonOrder, forceLabelIndent)
opcr(this, field){}
op(field.inputContainer)
return field
}
/**
* Create a field with the given text and operate on it.
* @param text The label of the field
* @param forceLabelIndent Indent the label even if it's empty, good for aligning buttons etc
* @orientation Whether to create an HBox (HORIZONTAL) or a VBox (VERTICAL) container for the field content
* @op Code that will run in the context of the content container (Either HBox or VBox per the orientation)
*
* @see buttonbar
*/
fun EventTarget.field(text: String? = null, orientation: Orientation = HORIZONTAL, forceLabelIndent: Boolean = false, op: Field.() -> Unit = {}): Field {
val field = Field(text ?: "", orientation, forceLabelIndent)
opcr(this, field){}
op(field)
return field
}
open class Form : VBox() {
init {
addClass(Stylesheet.form)
}
internal fun labelContainerWidth(height: Double): Double
= fieldsets.flatMap { it.fields }.map { it.labelContainer }.map { f -> f.prefWidth(-height) }.max() ?: 0.0
internal val fieldsets = HashSet<Fieldset>()
override fun getUserAgentStylesheet(): String =
Form::class.java.getResource("form.css").toExternalForm()
}
@DefaultProperty("children")
open class Fieldset(text: String? = null, labelPosition: Orientation = HORIZONTAL) : VBox() {
@Deprecated("Please use the new more concise syntax.", ReplaceWith("textProperty"))
fun textProperty() = textProperty
val textProperty = SimpleStringProperty()
var text by textProperty
val inputGrowProperty = SimpleObjectProperty<Priority>(SOMETIMES)
var inputGrow by inputGrowProperty
@Deprecated("Please use the new more concise syntax.", ReplaceWith("inputGrowProperty"), DeprecationLevel.WARNING)
fun inputGrowProperty() = inputGrowProperty
var labelPositionProperty = SimpleObjectProperty<Orientation>()
var labelPosition by labelPositionProperty
@Deprecated("Please use the new more concise syntax.", ReplaceWith("labelPositionProperty"), DeprecationLevel.WARNING)
fun labelPositionProperty() = labelPositionProperty
val wrapWidthProperty = SimpleObjectProperty<Number>()
var wrapWidth by wrapWidthProperty
@Deprecated("Please use the new more concise syntax.", ReplaceWith("wrapWidthProperty"), DeprecationLevel.WARNING)
fun wrapWidthProperty() = wrapWidthProperty
val iconProperty = SimpleObjectProperty<Node>()
var icon by iconProperty
@Deprecated("Please use the new more concise syntax.", ReplaceWith("iconProperty"), DeprecationLevel.WARNING)
fun iconProperty() = iconProperty
val legendProperty = SimpleObjectProperty<Label>()
var legend by legendProperty
@Deprecated("Please use the new more concise syntax.", ReplaceWith("legendProperty"), DeprecationLevel.WARNING)
fun legendProperty() = legendProperty
init {
addClass(Stylesheet.fieldset)
// Apply pseudo classes when orientation changes
syncOrientationState()
// Add legend label when text is populated
textProperty.onChange { newValue -> if (!newValue.isNullOrBlank()) addLegend() }
// Add legend when icon is populated
iconProperty.onChange { newValue -> if (newValue != null) addLegend() }
// Make sure input children gets the configured HBox.hgrow property
syncHgrow()
// Initial values
[email protected] = labelPosition
if (text != null) [email protected] = text
// Register/deregister with parent Form
parentProperty().addListener { _, oldParent, newParent ->
((oldParent as? Form) ?: oldParent?.findParent<Form>())?.fieldsets?.remove(this)
((newParent as? Form) ?: newParent?.findParent<Form>())?.fieldsets?.add(this)
}
}
private fun syncHgrow() {
children.addListener(ListChangeListener { c ->
while (c.next()) {
if (c.wasAdded()) {
c.addedSubList.asSequence().filterIsInstance<Field>().forEach { added ->
// Configure hgrow for current children
added.inputContainer.children.forEach { configureHgrow(it) }
// Add listener to support inputs added later
added.inputContainer.children.addListener(ListChangeListener { while (it.next()) if (it.wasAdded()) it.addedSubList.forEach { configureHgrow(it) } })
}
}
}
})
// Change HGrow for unconfigured children when inputGrow changes
inputGrowProperty.onChange {
children.asSequence().filterIsInstance<Field>().forEach { field ->
field.inputContainer.children.forEach { configureHgrow(it) }
}
}
}
private fun syncOrientationState() {
labelPositionProperty.onChange { newValue ->
if (newValue == HORIZONTAL) {
pseudoClassStateChanged(VERTICAL_PSEUDOCLASS_STATE, false)
pseudoClassStateChanged(HORIZONTAL_PSEUDOCLASS_STATE, true)
} else {
pseudoClassStateChanged(HORIZONTAL_PSEUDOCLASS_STATE, false)
pseudoClassStateChanged(VERTICAL_PSEUDOCLASS_STATE, true)
}
}
// Setup listeneres for wrapping
wrapWidthProperty.onChange { newValue ->
val responsiveOrientation = createObjectBinding<Orientation>(Callable {
if (width < newValue?.toDouble() ?: 0.0) VERTICAL else HORIZONTAL
}, widthProperty())
labelPositionProperty.cleanBind(responsiveOrientation)
}
}
private fun addLegend() {
if (legend == null) {
legend = Label()
legend.textProperty().bind(textProperty)
legend.addClass(Stylesheet.legend)
children.add(0, legend)
}
legend.graphic = icon
}
private fun configureHgrow(input: Node) {
HBox.setHgrow(input, inputGrow)
}
val form: Form get() = findParent() ?: kotlin.error("FieldSet should be a child of Form node")
internal val fields = HashSet<Field>()
companion object {
private val HORIZONTAL_PSEUDOCLASS_STATE = PseudoClass.getPseudoClass("horizontal")
private val VERTICAL_PSEUDOCLASS_STATE = PseudoClass.getPseudoClass("vertical")
}
}
class StageAwareFieldset(text: String? = null, labelPosition: Orientation = HORIZONTAL) : Fieldset(text, labelPosition) {
lateinit var stage: Stage
fun close() = stage.close()
}
/**
* Make this Node (presumably an input element) the mnemonicTarget for the field label. When the label
* of the field is activated, this input element will receive focus.
*/
fun Node.mnemonicTarget() {
findParent<Field>()?.apply {
label.isMnemonicParsing = true
label.labelFor = this@mnemonicTarget
}
}
@DefaultProperty("inputs")
class ButtonBarField(buttonOrder: String? = null, forceLabelIndent: Boolean = true) : AbstractField("", forceLabelIndent) {
override val inputContainer = ButtonBar(buttonOrder)
override val inputs: ObservableList<Node> = inputContainer.buttons
init {
inputContainer.addClass(Stylesheet.inputContainer)
children.add(inputContainer)
}
}
@DefaultProperty("inputs")
class Field(text: String? = null, orientation: Orientation = HORIZONTAL, forceLabelIndent: Boolean = false) : AbstractField(text, forceLabelIndent) {
override val inputContainer = if (orientation == HORIZONTAL) HBox() else VBox()
override val inputs: ObservableList<Node> = inputContainer.children
init {
inputContainer.addClass(Stylesheet.inputContainer)
inputContainer.addPseudoClass(orientation.name.toLowerCase())
children.add(inputContainer)
// Register/deregister with parent Fieldset
parentProperty().addListener { _, oldParent, newParent ->
((oldParent as? Fieldset) ?: oldParent?.findParent<Fieldset>())?.fields?.remove(this)
((newParent as? Fieldset) ?: newParent?.findParent<Fieldset>())?.fields?.add(this)
}
}
}
@DefaultProperty("inputs")
abstract class AbstractField(text: String? = null, val forceLabelIndent: Boolean = false) : Pane() {
val textProperty = SimpleStringProperty(text)
@Deprecated("Please use the new more concise syntax.", ReplaceWith("textProperty"), DeprecationLevel.WARNING)
fun textProperty() = textProperty
var text by textProperty
val label = Label()
val labelContainer = HBox(label).apply { addClass(Stylesheet.labelContainer) }
abstract val inputContainer: Region
@Suppress("unused") // FXML Default Target
abstract val inputs: ObservableList<Node>
init {
isFocusTraversable = false
addClass(Stylesheet.field)
label.textProperty().bind(textProperty)
children.add(labelContainer)
}
val fieldset: Fieldset get() = findParent() ?: kotlin.error("Field should be a child of FieldSet node")
override fun computePrefHeight(width: Double): Double {
val labelHasContent = forceLabelIndent || !textProperty.value.isNullOrBlank()
val labelHeight = if (labelHasContent) labelContainer.prefHeight(width) else 0.0
val inputHeight = inputContainer.prefHeight(width)
val insets = insets
if (fieldset.labelPosition == HORIZONTAL)
return Math.max(labelHeight, inputHeight) + insets.top + insets.bottom
return labelHeight + inputHeight + insets.top + insets.bottom
}
override fun computePrefWidth(height: Double): Double {
val fieldset = fieldset
val labelHasContent = forceLabelIndent || !textProperty.value.isNullOrBlank()
val labelWidth = if (labelHasContent) fieldset.form.labelContainerWidth(height) else 0.0
val inputWidth = inputContainer.prefWidth(height)
val insets = insets
if (fieldset.labelPosition == VERTICAL)
return Math.max(labelWidth, inputWidth) + insets.left + insets.right
return labelWidth + inputWidth + insets.left + insets.right
}
override fun computeMinHeight(width: Double) = computePrefHeight(width)
override fun layoutChildren() {
val fieldset = fieldset
val labelHasContent = forceLabelIndent || !textProperty.value.isNullOrBlank()
val insets = insets
val contentX = insets.left
val contentY = insets.top
val contentWidth = width - insets.left - insets.right
val contentHeight = height - insets.top - insets.bottom
val labelWidth = Math.min(contentWidth, fieldset.form.labelContainerWidth(height))
if (fieldset.labelPosition == HORIZONTAL) {
if (labelHasContent) {
labelContainer.resizeRelocate(contentX, contentY, labelWidth, contentHeight)
val inputX = contentX + labelWidth
val inputWidth = contentWidth - labelWidth
inputContainer.resizeRelocate(inputX, contentY, inputWidth, contentHeight)
} else {
inputContainer.resizeRelocate(contentX, contentY, contentWidth, contentHeight)
}
} else {
if (labelHasContent) {
val labelPrefHeight = labelContainer.prefHeight(width)
val labelHeight = Math.min(labelPrefHeight, contentHeight)
labelContainer.resizeRelocate(contentX, contentY, Math.min(labelWidth, contentWidth), labelHeight)
val restHeight = contentHeight - labelHeight
inputContainer.resizeRelocate(contentX, contentY + labelHeight, contentWidth, restHeight)
} else {
inputContainer.resizeRelocate(contentX, contentY, contentWidth, contentHeight)
}
}
}
} | apache-2.0 | 8a811276bb1f9fd57abe1d7e6dc58c87 | 38.681416 | 173 | 0.683369 | 4.776634 | false | false | false | false |
cashapp/sqldelight | sqldelight-gradle-plugin/src/test/integration-mysql-async/src/test/kotlin/app/cash/sqldelight/mysql/integration/async/MySqlTest.kt | 1 | 1882 | package app.cash.sqldelight.mysql.integration.async
import app.cash.sqldelight.async.coroutines.awaitAsList
import app.cash.sqldelight.async.coroutines.awaitAsOne
import app.cash.sqldelight.async.coroutines.awaitCreate
import app.cash.sqldelight.driver.r2dbc.R2dbcDriver
import com.google.common.truth.Truth.assertThat
import io.r2dbc.spi.ConnectionFactories
import kotlinx.coroutines.reactive.awaitSingle
import org.junit.Test
class MySqlTest {
private val factory = ConnectionFactories.get("r2dbc:tc:mysql:///myDb?TC_IMAGE_TAG=8.0")
private fun runTest(block: suspend (MyDatabase) -> Unit) = kotlinx.coroutines.test.runTest {
val connection = factory.create().awaitSingle()
val driver = R2dbcDriver(connection)
val db = MyDatabase(driver).also { MyDatabase.Schema.awaitCreate(driver) }
block(db)
}
@Test fun simpleSelect() = runTest { database ->
database.dogQueries.insertDog("Tilda", "Pomeranian")
assertThat(database.dogQueries.selectDogs().awaitAsOne())
.isEqualTo(
Dog(
name = "Tilda",
breed = "Pomeranian",
is_good = true,
),
)
}
@Test
fun simpleSelectWithIn() = runTest { database ->
with(database) {
dogQueries.insertDog("Tilda", "Pomeranian")
dogQueries.insertDog("Tucker", "Portuguese Water Dog")
dogQueries.insertDog("Cujo", "Pomeranian")
dogQueries.insertDog("Buddy", "Pomeranian")
assertThat(
dogQueries.selectDogsByBreedAndNames(
breed = "Pomeranian",
name = listOf("Tilda", "Buddy"),
).awaitAsList(),
)
.containsExactly(
Dog(
name = "Tilda",
breed = "Pomeranian",
is_good = true,
),
Dog(
name = "Buddy",
breed = "Pomeranian",
is_good = true,
),
)
}
}
}
| apache-2.0 | 3009b9782df698e501b4061c2996f68c | 29.354839 | 94 | 0.638682 | 3.794355 | false | true | false | false |
niranjan94/show-java | app/src/main/kotlin/com/njlabs/showjava/workers/DecompilerWorker.kt | 1 | 6924 | /*
* Show Java - A java/apk decompiler for android
* Copyright (c) 2018 Niranjan Rajendran
*
* 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.njlabs.showjava.workers
import android.content.Context
import androidx.work.Data
import androidx.work.WorkManager
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.crashlytics.android.Crashlytics
import com.njlabs.showjava.decompilers.BaseDecompiler
import com.njlabs.showjava.decompilers.JarExtractionWorker
import com.njlabs.showjava.decompilers.JavaExtractionWorker
import com.njlabs.showjava.decompilers.ResourcesExtractionWorker
import com.njlabs.showjava.utils.ProcessNotifier
import com.njlabs.showjava.utils.UserPreferences
import timber.log.Timber
import java.io.File
import java.util.concurrent.CountDownLatch
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
/**
* A wrapper for each of the 3 extractors to be able to use with Android WorkManager
*/
class DecompilerWorker(val context: Context, params: WorkerParameters) : Worker(context, params) {
private var worker: BaseDecompiler? = null
private lateinit var step: String
private val maxAttempts = params.inputData.getInt("maxAttempts", UserPreferences.DEFAULTS.MAX_ATTEMPTS)
private val id: String = params.inputData.getString("id").toString()
private val packageName: String = params.inputData.getString("name").toString()
private val packageLabel: String = params.inputData.getString("label").toString()
private val decompiler: String = params.inputData.getString("decompiler").toString()
private val chunkSize: Int = params.inputData.getInt("chunkSize", UserPreferences.DEFAULTS.CHUNK_SIZE)
private val memoryThreshold: Int = params.inputData.getInt("memoryThreshold", UserPreferences.DEFAULTS.MEMORY_THRESHOLD)
private val inputPackageFile: File = File(params.inputData.getString("inputPackageFile"))
private val decompilerExecutor: ExecutorService = Executors.newSingleThreadExecutor()
/**
* Initialize the appropriate extractor based on the current step of the job
*/
init {
if (tags.contains("jar-extraction")) {
step = "jar-extraction"
worker = JarExtractionWorker(context, params.inputData)
}
if (tags.contains("java-extraction")) {
step = "java-extraction"
worker = JavaExtractionWorker(context, params.inputData)
}
if (tags.contains("resources-extraction")) {
step = "resources-extraction"
worker = ResourcesExtractionWorker(context, params.inputData)
}
}
/**
* Execute the extractor. Also handles
*
* - Retries based on the set max attempts and failure status.
* - Stopping of the job when memory usage reaches the given threshold
*
* Every extractor is run within an executor thread. This allows us to force kill the thread
* via [ExecutorService.shutdownNow] method when memory usage exceeds set threshold.
*
*/
override fun doWork(): Result {
var result = if (runAttemptCount >= (maxAttempts - 1)) Result.failure() else Result.retry()
var ranOutOfMemory = false
val notifier = ProcessNotifier(context, id)
.withPackageInfo(packageName, packageLabel, inputPackageFile)
Crashlytics.setString("decompilation_step", step)
Crashlytics.setString("decompilation_decompiler", decompiler)
Crashlytics.setString("decompilation_package_name", packageName)
Crashlytics.setString("decompilation_package_label", packageLabel)
Crashlytics.setInt("decompilation_chunk_size", chunkSize)
Crashlytics.setInt("decompilation_memory_threshold", memoryThreshold)
var outputData = Data.Builder().build()
worker ?.let {
try {
val latch = CountDownLatch(1)
decompilerExecutor.execute {
result = it.withNotifier(notifier)
.withLowMemoryCallback { isLowMemory ->
ranOutOfMemory = isLowMemory
outputData = Data.Builder()
.putBoolean("ranOutOfMemory", isLowMemory)
.build()
if (isLowMemory) {
latch.countDown()
decompilerExecutor.shutdownNow()
}
}
.withAttempt(runAttemptCount)
latch.countDown()
}
latch.await()
decompilerExecutor.shutdownNow()
decompilerExecutor.awaitTermination(2, TimeUnit.SECONDS)
} catch (e: Exception) {
Timber.e(e)
}
it.onStopped()
}
if (ranOutOfMemory) {
result = Result.failure(outputData)
}
if (result == Result.failure()) {
try {
if (ranOutOfMemory) {
notifier.lowMemory(decompiler)
} else {
notifier.error()
}
} catch (e: Exception) {
Timber.e(e)
}
}
Crashlytics.setString("decompilation_step", "")
Crashlytics.setString("decompilation_decompiler", "")
Crashlytics.setString("decompilation_package_name", "")
Crashlytics.setString("decompilation_package_label", "")
Crashlytics.setInt("decompilation_chunk_size", -1)
Crashlytics.setInt("decompilation_memory_threshold", -1)
return result
}
/**
* Called when the job is stopped. (Either by user-initiated cancel or when complete)
* We clean up the notifications and caches if any on shutdown.
*
*/
override fun onStopped() {
super.onStopped()
worker?.onStopped()
}
companion object {
/**
* A helper method to cancel a decompilation job by packageName ([id])
*/
fun cancel(context: Context, id: String) {
ProcessNotifier(context, id).cancel()
WorkManager.getInstance().cancelUniqueWork(id)
}
}
}
| gpl-3.0 | 81f2e9fa7159dcf6a926e7e9aa1bacae | 38.565714 | 124 | 0.645436 | 4.924609 | false | false | false | false |
matejdro/WearMusicCenter | wear/src/main/java/com/matejdro/wearmusiccenter/watch/communication/PhoneConnection.kt | 1 | 13502 | package com.matejdro.wearmusiccenter.watch.communication
import android.content.Context
import android.graphics.Bitmap
import android.net.Uri
import android.os.Handler
import android.os.Looper
import androidx.lifecycle.MutableLiveData
import com.google.android.gms.wearable.CapabilityClient
import com.google.android.gms.wearable.CapabilityInfo
import com.google.android.gms.wearable.DataClient
import com.google.android.gms.wearable.DataEvent
import com.google.android.gms.wearable.DataEventBuffer
import com.google.android.gms.wearable.DataItem
import com.google.android.gms.wearable.Wearable
import com.matejdro.wearmusiccenter.R
import com.matejdro.wearmusiccenter.common.CommPaths
import com.matejdro.wearmusiccenter.common.buttonconfig.ButtonInfo
import com.matejdro.wearmusiccenter.common.util.FloatPacker
import com.matejdro.wearmusiccenter.proto.CustomList
import com.matejdro.wearmusiccenter.proto.CustomListItemAction
import com.matejdro.wearmusiccenter.proto.MusicState
import com.matejdro.wearmusiccenter.proto.Notification
import com.matejdro.wearmusiccenter.watch.util.launchWithErrorHandling
import com.matejdro.wearutils.coroutines.await
import com.matejdro.wearutils.lifecycle.ListenableLiveData
import com.matejdro.wearutils.lifecycle.LiveDataLifecycleCombiner
import com.matejdro.wearutils.lifecycle.LiveDataLifecycleListener
import com.matejdro.wearutils.lifecycle.Resource
import com.matejdro.wearutils.lifecycle.SingleLiveEvent
import com.matejdro.wearutils.messages.getByteArrayAsset
import com.matejdro.wearutils.messages.getNearestNodeId
import com.matejdro.wearutils.messages.sendMessageToNearestClient
import com.matejdro.wearutils.miscutils.BitmapUtils
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.cancel
import kotlinx.coroutines.withContext
import java.lang.ref.WeakReference
import java.nio.ByteBuffer
import java.util.concurrent.atomic.AtomicBoolean
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class PhoneConnection @Inject constructor(@ApplicationContext private val context: Context) : DataClient.OnDataChangedListener,
CapabilityClient.OnCapabilityChangedListener,
LiveDataLifecycleListener {
private var scope: CoroutineScope? = null
companion object {
const val MESSAGE_CLOSE_CONNECTION = 0
const val CONNECTION_CLOSE_DELAY_MS = 15_000L
}
val musicState = ListenableLiveData<Resource<MusicState>>()
val albumArt = ListenableLiveData<Bitmap?>()
val customList = ListenableLiveData<CustomListWithBitmaps>()
val notification = SingleLiveEvent<com.matejdro.wearmusiccenter.watch.model.Notification>()
val rawPlaybackConfig = MutableLiveData<DataItem>()
val rawStoppedConfig = MutableLiveData<DataItem>()
val rawActionMenuConfig = MutableLiveData<DataItem>()
private val lifecycleObserver = LiveDataLifecycleCombiner(this)
private val messageClient = Wearable.getMessageClient(context)
private val dataClient = Wearable.getDataClient(context)
private val capabilityClient = Wearable.getCapabilityClient(context)
private val nodeClient = Wearable.getNodeClient(context)
private val closeHandler = ConnectionCloseHandler(WeakReference(this))
private var sendingVolume = false
private var nextVolume = -1f
private var running = AtomicBoolean(false)
init {
lifecycleObserver.addLiveData(musicState)
lifecycleObserver.addLiveData(albumArt)
}
private fun start() {
if (!running.compareAndSet(false, true)) {
return
}
scope = CoroutineScope(Job() + Dispatchers.Main)
scope?.launchWithErrorHandling(context, musicState) {
val capabilities = capabilityClient.getCapability(
CommPaths.PHONE_APP_CAPABILITY,
CapabilityClient.FILTER_REACHABLE
).await()
onWatchConnectionUpdated(capabilities)
dataClient.addListener(this)
capabilityClient.addListener(this, CommPaths.PHONE_APP_CAPABILITY)
loadCurrentActionConfig(CommPaths.DATA_PLAYING_ACTION_CONFIG, rawPlaybackConfig)
loadCurrentActionConfig(CommPaths.DATA_STOPPING_ACTION_CONFIG, rawStoppedConfig)
loadCurrentActionConfig(CommPaths.DATA_LIST_ITEMS, rawActionMenuConfig)
musicState.postValue(Resource.loading(null))
}
}
private fun stop() {
if (!running.compareAndSet(true, false)) {
return
}
scope?.launchWithErrorHandling(context, musicState) {
try {
dataClient.removeListener(this)
val phoneNode = nodeClient.getNearestNodeId()
if (phoneNode != null) {
messageClient.sendMessage(phoneNode, CommPaths.MESSAGE_WATCH_CLOSED, null).await()
}
} finally {
scope?.cancel()
}
}
}
private fun onWatchConnectionUpdated(capabilityInfo: CapabilityInfo) {
val firstNode = capabilityInfo.nodes.firstOrNull { it.isNearby }
if (firstNode != null) {
scope?.launchWithErrorHandling(context, musicState) {
messageClient.sendMessage(capabilityInfo.nodes.first().id, CommPaths.MESSAGE_WATCH_OPENED, null).await()
}
} else {
musicState.postValue(Resource.error(context.getString(R.string.no_phone), null))
}
}
suspend fun sendManualCloseMessage() {
if (!running.get()) {
return
}
// Activity closes when manual close happens, so we must ignore cancel signal here
withContext(NonCancellable) {
val phoneNode = nodeClient.getNearestNodeId()
if (phoneNode != null) {
messageClient.sendMessage(phoneNode, CommPaths.MESSAGE_WATCH_CLOSED_MANUALLY, null).await()
}
}
}
fun sendVolume(newVolume: Float) {
scope?.launchWithErrorHandling(context, musicState) {
nextVolume = -1f
if (sendingVolume) {
nextVolume = newVolume
return@launchWithErrorHandling
}
try {
sendingVolume = true
messageClient.sendMessageToNearestClient(
nodeClient,
CommPaths.MESSAGE_CHANGE_VOLUME,
FloatPacker.packFloat(newVolume)
)
} finally {
sendingVolume = false
if (nextVolume >= 0) {
sendVolume(nextVolume)
}
}
}
}
suspend fun executeButtonAction(buttonInfo: ButtonInfo) {
messageClient.sendMessageToNearestClient(
nodeClient,
CommPaths.MESSAGE_EXECUTE_ACTION,
buttonInfo.buildProtoVersion().build().toByteArray()
)
}
suspend fun executeMenuAction(index: Int) {
messageClient.sendMessageToNearestClient(
nodeClient,
CommPaths.MESSAGE_EXECUTE_MENU_ACTION,
ByteBuffer.allocate(4).putInt(index).array()
)
}
suspend fun executeCustomMenuAction(listId: String, entryId: String) {
messageClient.sendMessageToNearestClient(
nodeClient,
CommPaths.MESSAGE_CUSTOM_LIST_ITEM_SELECTED,
CustomListItemAction.newBuilder()
.setListId(listId)
.setEntryId(entryId)
.build()
.toByteArray()
)
}
private suspend fun sendAck() {
messageClient.sendMessageToNearestClient(nodeClient, CommPaths.MESSAGE_ACK)
}
override fun onDataChanged(data: DataEventBuffer?) {
if (data == null) {
return
}
val frozenData = data.use { _ ->
data.map { it.freeze() }
}
scope?.launchWithErrorHandling(context, musicState) {
frozenData.filter { it.type == DataEvent.TYPE_CHANGED }
.map { it.dataItem }
.forEach {
when (it.uri.path) {
CommPaths.DATA_MUSIC_STATE -> {
val dataItem = it.freeze()
val receivedMusicState = MusicState.parseFrom(dataItem.data)
if (receivedMusicState.error) {
musicState.postValue(Resource.error(receivedMusicState.title, null))
} else {
musicState.postValue(Resource.success(receivedMusicState))
sendAck()
val albumArtData = dataItem.assets[CommPaths.ASSET_ALBUM_ART]
?.let { asset -> dataClient.getByteArrayAsset(asset) }
albumArt.postValue(BitmapUtils.deserialize(albumArtData))
}
}
CommPaths.DATA_NOTIFICATION -> {
val dataItem = it.freeze()
val receivedNotification = Notification.parseFrom(dataItem.data)
sendAck()
val pictureData = dataItem.assets[CommPaths.ASSET_NOTIFICATION_BACKGROUND]
?.let { asset -> dataClient.getByteArrayAsset(asset) }
val picture = BitmapUtils.deserialize(pictureData)
val mergedNotification = com.matejdro.wearmusiccenter.watch.model.Notification(
receivedNotification.title,
receivedNotification.description,
picture
)
notification.postValue(mergedNotification)
}
CommPaths.DATA_PLAYING_ACTION_CONFIG -> rawPlaybackConfig.postValue(it.freeze())
CommPaths.DATA_STOPPING_ACTION_CONFIG -> rawStoppedConfig.postValue(it.freeze())
CommPaths.DATA_LIST_ITEMS -> rawActionMenuConfig.postValue(it.freeze())
CommPaths.DATA_CUSTOM_LIST -> {
val dataItem = it.freeze()
val receivedCustomList = CustomList.parseFrom(dataItem.data)
val listItems = receivedCustomList.actionsList
.mapIndexed { index, rawListEntry ->
val pictureData = dataItem.assets[index.toString()]
?.let { asset -> dataClient.getByteArrayAsset(asset) }
val picture = BitmapUtils.deserialize(pictureData)
CustomListItemWithIcon(
rawListEntry,
picture
)
}
customList.postValue(
CustomListWithBitmaps(
receivedCustomList.listTimestamp,
receivedCustomList.listId,
listItems
)
)
}
}
}
}
}
override fun onCapabilityChanged(capability: CapabilityInfo) {
onWatchConnectionUpdated(capability)
}
private suspend fun loadCurrentActionConfig(configPath: String, targetLiveData: MutableLiveData<DataItem>) {
val dataItems = dataClient.getDataItems(
Uri.parse("wear://*$configPath"),
DataClient.FILTER_LITERAL)
.await()
val dataItem = dataItems.firstOrNull() ?: return
targetLiveData.postValue(dataItem.freeze())
dataItems.release()
}
override fun onInactive() {
// Delay connection closing for a bit to make sure it is not just brief configuration change
closeHandler.removeMessages(MESSAGE_CLOSE_CONNECTION)
closeHandler.sendEmptyMessageDelayed(MESSAGE_CLOSE_CONNECTION, CONNECTION_CLOSE_DELAY_MS)
}
override fun onActive() {
closeHandler.removeMessages(MESSAGE_CLOSE_CONNECTION)
start()
}
suspend fun openPlaybackQueue() {
messageClient.sendMessageToNearestClient(nodeClient, CommPaths.MESSAGE_OPEN_PLAYBACK_QUEUE)
}
private class ConnectionCloseHandler(val phoneConnection: WeakReference<PhoneConnection>) : Handler(Looper.getMainLooper()) {
override fun dispatchMessage(msg: android.os.Message) {
if (msg.what == MESSAGE_CLOSE_CONNECTION) {
phoneConnection.get()?.stop()
}
}
}
}
| gpl-3.0 | efa4d76ef3d4d6eeb5be323544eba19c | 38.479532 | 129 | 0.597171 | 5.51102 | false | true | false | false |
syrop/Victor-Events | events/src/main/kotlin/pl/org/seva/events/message/MessagesAdapter.kt | 1 | 1914 | /*
* Copyright (C) 2019 Wiktor Nizio
*
* 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/>.
*
* If you like this program, consider donating bitcoin: bc1qncxh5xs6erq6w4qz3a7xl7f50agrgn3w58dsfp
*/
package pl.org.seva.events.message
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.row_message.view.*
import pl.org.seva.events.R
import pl.org.seva.events.main.init.instance
class MessagesAdapter : RecyclerView.Adapter<MessagesAdapter.ViewHolder>() {
private val messages by instance<Messages>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
ViewHolder(parent.inflate())
private fun ViewGroup.inflate() =
LayoutInflater.from(context).inflate(R.layout.row_message, this, false)
override fun getItemCount() = messages.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
with(messages[position]) {
holder.time.text = time.toString()
holder.content.text = content
}
}
class ViewHolder internal constructor(view: View) : RecyclerView.ViewHolder(view) {
val time = checkNotNull(view.time)
val content = checkNotNull(view.content)
}
}
| gpl-3.0 | db7b846499ed64d94ce6cce99cc87ed1 | 35.113208 | 98 | 0.732497 | 4.197368 | false | false | false | false |
Mashape/httpsnippet | test/fixtures/output/kotlin/okhttp/application-form-encoded.kt | 1 | 368 | val client = OkHttpClient()
val mediaType = MediaType.parse("application/x-www-form-urlencoded")
val body = RequestBody.create(mediaType, "foo=bar&hello=world")
val request = Request.Builder()
.url("http://mockbin.com/har")
.post(body)
.addHeader("content-type", "application/x-www-form-urlencoded")
.build()
val response = client.newCall(request).execute()
| mit | 2718463ce230dc4842ec02c68388a6ba | 32.454545 | 68 | 0.730978 | 3.439252 | false | false | false | false |
hannesa2/owncloud-android | owncloudData/src/main/java/com/owncloud/android/data/authentication/repository/OCAuthenticationRepository.kt | 2 | 3741 | /**
* ownCloud Android client application
*
* @author Abel García de Prada
* @author David González Verdugo
* Copyright (C) 2020 ownCloud GmbH.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.owncloud.android.data.authentication.repository
import com.owncloud.android.data.authentication.datasources.LocalAuthenticationDataSource
import com.owncloud.android.data.authentication.datasources.RemoteAuthenticationDataSource
import com.owncloud.android.domain.authentication.AuthenticationRepository
import com.owncloud.android.domain.authentication.oauth.model.ClientRegistrationInfo
import com.owncloud.android.domain.server.model.ServerInfo
import com.owncloud.android.domain.user.model.UserInfo
class OCAuthenticationRepository(
private val localAuthenticationDataSource: LocalAuthenticationDataSource,
private val remoteAuthenticationDataSource: RemoteAuthenticationDataSource
) : AuthenticationRepository {
override fun loginBasic(
serverInfo: ServerInfo,
username: String,
password: String,
updateAccountWithUsername: String?
): String {
val userInfoAndRedirectionPath: Pair<UserInfo, String?> =
remoteAuthenticationDataSource.loginBasic(
serverPath = serverInfo.baseUrl,
username = username,
password = password
)
return localAuthenticationDataSource.addBasicAccount(
userName = username,
lastPermanentLocation = userInfoAndRedirectionPath.second,
password = password,
serverInfo = serverInfo,
userInfo = userInfoAndRedirectionPath.first,
updateAccountWithUsername = updateAccountWithUsername
)
}
override fun loginOAuth(
serverInfo: ServerInfo,
username: String,
authTokenType: String,
accessToken: String,
refreshToken: String,
scope: String?,
updateAccountWithUsername: String?,
clientRegistrationInfo: ClientRegistrationInfo?
): String {
val userInfoAndRedirectionPath: Pair<UserInfo, String?> =
remoteAuthenticationDataSource.loginOAuth(
serverPath = serverInfo.baseUrl,
username = username,
accessToken = accessToken
)
return localAuthenticationDataSource.addOAuthAccount(
userName = if (username.isNotBlank()) username else userInfoAndRedirectionPath.first.id,
lastPermanentLocation = userInfoAndRedirectionPath.second,
authTokenType = authTokenType,
accessToken = accessToken,
serverInfo = serverInfo,
userInfo = userInfoAndRedirectionPath.first,
refreshToken = refreshToken,
scope = scope,
updateAccountWithUsername = updateAccountWithUsername,
clientRegistrationInfo = clientRegistrationInfo
)
}
override fun supportsOAuth2UseCase(accountName: String): Boolean =
localAuthenticationDataSource.supportsOAuth2(accountName)
override fun getBaseUrl(accountName: String): String = localAuthenticationDataSource.getBaseUrl(accountName)
}
| gpl-2.0 | 633ff50a3dba0fa38c60f0c167ce0cea | 40.087912 | 112 | 0.712223 | 5.34907 | false | false | false | false |
pyamsoft/padlock | padlock-list/src/main/java/com/pyamsoft/padlock/list/info/LockInfoEvent.kt | 1 | 1417 | /*
* 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.list.info
import androidx.annotation.CheckResult
import com.pyamsoft.padlock.model.list.ActivityEntry
import com.pyamsoft.padlock.model.LockState
data class LockInfoEvent internal constructor(
val id: String,
val name: String,
val packageName: String,
val oldState: LockState,
val newState: LockState,
val code: String?,
val system: Boolean
) {
companion object {
@JvmStatic
@CheckResult
fun from(
entry: ActivityEntry.Item,
newState: LockState,
code: String?,
system: Boolean
): LockInfoEvent {
return LockInfoEvent(
id = entry.id, name = entry.name, packageName = entry.packageName,
oldState = entry.lockState, newState = newState, code = code,
system = system
)
}
}
}
| apache-2.0 | e7602b4bec1d94a67a1f1a9abea0df2d | 26.25 | 76 | 0.702893 | 4.217262 | false | false | false | false |
nonylene/PhotoLinkViewer | app/src/main/java/net/nonylene/photolinkviewer/view/UserTweetView.kt | 1 | 6746 | package net.nonylene.photolinkviewer.view
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.support.v4.content.ContextCompat
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import butterknife.bindView
import com.bumptech.glide.Glide
import net.nonylene.photolinkviewer.R
import net.nonylene.photolinkviewer.core.event.DownloadButtonEvent
import net.nonylene.photolinkviewer.core.tool.PLVUrl
import net.nonylene.photolinkviewer.core.tool.PLVUrlService
import net.nonylene.photolinkviewer.core.tool.createTwitterPLVUrls
import net.nonylene.photolinkviewer.core.view.TilePhotoView
import org.greenrobot.eventbus.EventBus
import twitter4j.Status
import java.text.SimpleDateFormat
import java.util.*
class UserTweetView(context: Context, attrs: AttributeSet?) : LinearLayout(context, attrs) {
private val baseView: LinearLayout by bindView(R.id.twBase)
private val textView: TextView by bindView(R.id.twTxt)
private val snView: TextView by bindView(R.id.twSN)
private val dayView: TextView by bindView(R.id.twDay)
private val likeView: TextView by bindView(R.id.likeCount)
private val rtView: TextView by bindView(R.id.rtCount)
private val iconView: ImageView by bindView(R.id.twImageView)
private val urlBaseLayout: LinearLayout by bindView(R.id.url_base)
private val urlLayout: LinearLayout by bindView(R.id.url_linear)
private val urlPhotoLayout: TilePhotoView by bindView(R.id.url_photos)
private val photoBaseLayout: LinearLayout by bindView(R.id.photo_base)
private val photoLayout: TilePhotoView by bindView(R.id.photos)
var tilePhotoViewListener: TilePhotoView.TilePhotoViewListener? = null
var sendDownloadEvent = false
var status : Status? = null
private set
private val DP = context.resources.displayMetrics.density
fun setEntry(status: Status) {
this.status = status
//retweet check
val finStatus = if (status.isRetweet) status.retweetedStatus else status
// long tap to copy text
baseView.setOnLongClickListener {
(context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager).primaryClip =
ClipData.newPlainText("tweet text", textView.text)
Toast.makeText(context.applicationContext, "Tweet copied!", Toast.LENGTH_LONG).show()
true
}
// put status on text
textView.text = finStatus.text
dayView.text = SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.getDefault()).format(finStatus.createdAt)
likeView.text = "Like: " + finStatus.favoriteCount
rtView.text = "RT: " + finStatus.retweetCount
finStatus.user.let { user ->
snView.text = user.name + " @" + user.screenName
if (user.isProtected) {
// add key icon
val iconSize = (17 * DP).toInt()
// resize app icon (bitmap_factory makes low-quality images)
val protect = ContextCompat.getDrawable(context, R.drawable.lock)
protect.setBounds(0, 0, iconSize, iconSize)
// set app-icon and bounds
snView.setCompoundDrawables(protect, null, null, null)
} else {
// initialize
snView.setCompoundDrawables(null, null, null, null)
}
// set icon
Glide.with(context.applicationContext).load(user.biggerProfileImageURL).into(iconView)
iconView.setBackgroundResource(R.drawable.twitter_image_design)
//show user when tapped
iconView.setOnClickListener {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://twitter.com/" + user.screenName))
context.startActivity(intent)
}
}
finStatus.urlEntities.let { urlEntities ->
// initialize
urlLayout.removeAllViews()
urlPhotoLayout.initialize()
if (!urlEntities.isEmpty()) {
urlBaseLayout.visibility = View.VISIBLE
urlPhotoLayout.tilePhotoViewListener = tilePhotoViewListener
for (urlEntity in urlEntities) {
val url = urlEntity.expandedURL
addUrl(url)
val service = PLVUrlService(context).apply {
plvUrlListener = getPLVUrlListener(urlPhotoLayout)
}
service.requestGetPLVUrl(url)
}
} else {
urlBaseLayout.visibility = View.GONE
}
}
finStatus.mediaEntities.let { mediaEntities ->
// initialize
photoLayout.initialize()
if (!mediaEntities.isEmpty()) {
photoBaseLayout.visibility = View.VISIBLE
photoLayout.tilePhotoViewListener = tilePhotoViewListener
val plvUrls = createTwitterPLVUrls(finStatus, context)
if (sendDownloadEvent) EventBus.getDefault().postSticky(DownloadButtonEvent(plvUrls, true))
photoLayout.setPLVUrls(photoLayout.addImageView(), plvUrls.toTypedArray())
photoLayout.notifyChanged()
} else {
photoBaseLayout.visibility = View.GONE
}
}
}
private fun getPLVUrlListener(tileView: TilePhotoView): PLVUrlService.PLVUrlListener {
return (object : PLVUrlService.PLVUrlListener {
var position: Int? = null
override fun onGetPLVUrlFinished(plvUrls: Array<PLVUrl>) {
tileView.setPLVUrls(position!!, plvUrls)
tileView.notifyChanged()
}
override fun onGetPLVUrlFailed(text: String) {
position?.let {
tileView.removeImageView(it)
tileView.notifyChanged()
}
}
override fun onURLAccepted() {
position = tileView.addImageView()
tileView.notifyChanged()
}
})
}
private fun addUrl(url: String) {
val textView = LayoutInflater.from(urlLayout.context).inflate(R.layout.twitter_url, urlLayout, false) as TextView
textView.text = url
textView.paint.isUnderlineText = true
textView.setOnClickListener {
context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
}
urlLayout.addView(textView)
}
}
| gpl-2.0 | d5d7d009d9acd23d2c3d2d6bedd28af3 | 37.770115 | 121 | 0.647347 | 4.811698 | false | false | false | false |
Undin/intellij-rust | src/test/kotlin/org/rust/lang/core/completion/RsVisibilityCompletionTest.kt | 2 | 4125 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.completion
class RsVisibilityCompletionTest : RsCompletionTestBase() {
fun `test named field decl`() = checkCompletion("pub", """
struct S {
/*caret*/a: u32
}
""", """
struct S {
pub /*caret*/a: u32
}
""")
fun `test inside struct block fields`() = checkContainsCompletion("pub", """
struct S {
/*caret*/
}
""")
fun `test move caret after completing pub()`() = checkCompletion("pub()", """
struct S {
/*caret*/a: u32
}
""", """
struct S {
pub(/*caret*/) a: u32
}
""")
fun `test no completion in named field decl of enum variant`() = checkNoCompletion("""
enum E {
S {
/*caret*/a: u32
}
}
""")
fun `test no completion in named field decl with visibility`() = checkNotContainsCompletion("pub", """
struct S {
pub /*caret*/ a: u32
}
""")
fun `test tuple field decl`() = checkCompletion("pub", """
struct S(/*caret*/u32);
""", """
struct S(pub /*caret*/u32);
""")
fun `test inside struct tuple fields`() = checkContainsCompletion("pub", """
struct S(/*caret*/);
""")
fun `test inside inherent impl`() = checkCompletion("pub", """
struct S;
impl S {
/*caret*/
}
""", """
struct S;
impl S {
pub /*caret*/
}
""")
fun `test no completion in tuple field decl of enum variant`() = checkNotContainsCompletion("pub", """
enum E {
S(/*caret*/u32)
}
""")
fun `test no completion in tuple field decl with visibility`() = checkNotContainsCompletion("pub", """
struct S(pub /*caret*/u32);
""")
fun `test no completion before enum variant`() = checkNotContainsCompletion("pub", """
enum E {
/*caret*/ V1
}
""")
fun `test no completion inside trait`() = checkNotContainsCompletion("pub", """
trait Trait {
/*caret*/ fn foo();
}
""")
fun `test no completion inside trait impl`() = checkNotContainsCompletion("pub", """
trait Trait {
fn foo();
}
impl Trait for () {
/*caret*/ fn foo() {}
}
""")
fun `test no completion for function after unsafe`() = checkNotContainsCompletion("pub", """
unsafe /*caret*/fn foo() {}
""")
fun `test no completion for function after extern`() = checkNotContainsCompletion("pub", """
extern "C" /*caret*/fn foo() {}
""")
fun `test no completion for function after const`() = checkNotContainsCompletion("pub", """
const /*caret*/fn foo() {}
""")
fun `test no completion for function after async`() = checkNotContainsCompletion("pub", """
async /*caret*/fn foo() {}
""")
fun `test fn`() = checkContainsCompletion(DEFAULT_VISIBILITIES, """
/*caret*/fn foo() {}
""")
fun `test const`() = checkContainsCompletion(DEFAULT_VISIBILITIES, """
/*caret*/const FOO: u32 = 0;
""")
fun `test static`() = checkContainsCompletion(DEFAULT_VISIBILITIES, """
/*caret*/static FOO: u32 = 0;
""")
fun `test struct`() = checkContainsCompletion(DEFAULT_VISIBILITIES, """
/*caret*/struct S;
""")
fun `test enum`() = checkContainsCompletion(DEFAULT_VISIBILITIES, """
/*caret*/enum E { V1 }
""")
fun `test use`() = checkContainsCompletion(DEFAULT_VISIBILITIES, """
/*caret*/use foo;
""")
fun `test extern crate`() = checkContainsCompletion(DEFAULT_VISIBILITIES, """
/*caret*/extern crate foo;
""")
fun `test mod`() = checkContainsCompletion(DEFAULT_VISIBILITIES, """
/*caret*/mod foo;
""")
companion object {
private val DEFAULT_VISIBILITIES = listOf("pub", "pub(crate)", "pub()")
}
}
| mit | 5efb1cde6547b02ea93ac86a682b25a7 | 25.612903 | 106 | 0.526788 | 4.573171 | false | true | false | false |
androidx/androidx | compose/ui/ui/src/androidAndroidTest/kotlin/androidx/compose/ui/window/PopupAlignmentTest.kt | 3 | 14667 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.window
import android.view.View
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.unit.IntRect
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.height
import androidx.compose.ui.unit.width
import androidx.test.espresso.matcher.BoundedMatcher
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import org.hamcrest.Description
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
@MediumTest
@RunWith(AndroidJUnit4::class)
class PopupAlignmentTest {
@get:Rule
val rule = createComposeRule()
private val testTag = "testedPopup"
private val offset = IntOffset(10, 10)
private val popupSize = IntSize(40, 20)
private val parentBounds = IntRect(50, 50, 150, 150)
private val parentSize = IntSize(parentBounds.width, parentBounds.height)
private var composeViewAbsolutePos = IntOffset(0, 0)
@Test
fun popup_correctPosition_alignmentTopStart() {
/* Expected TopStart Position
x = offset.x
y = offset.y
*/
val expectedPosition = IntOffset(10, 10)
createPopupWithAlignmentRule(alignment = Alignment.TopStart)
rule.popupMatches(testTag, matchesPosition(composeViewAbsolutePos + expectedPosition))
}
@Test
fun popup_correctPosition_alignmentTopStart_rtl() {
/* Expected TopStart Position
x = -offset.x + parentSize.x - popupSize.x
y = offset.y
*/
val expectedPosition = IntOffset(50, 10)
createPopupWithAlignmentRule(alignment = Alignment.TopStart, isRtl = true)
rule.popupMatches(testTag, matchesPosition(composeViewAbsolutePos + expectedPosition))
}
@Test
fun popup_correctPosition_alignmentTopCenter() {
/* Expected TopCenter Position
x = offset.x + parentSize.x / 2 - popupSize.x / 2
y = offset.y
*/
val expectedPosition = IntOffset(40, 10)
createPopupWithAlignmentRule(alignment = Alignment.TopCenter)
rule.popupMatches(testTag, matchesPosition(composeViewAbsolutePos + expectedPosition))
}
@Test
fun popup_correctPosition_alignmentTopCenter_rtl() {
/* Expected TopCenter Position
x = -offset.x + parentSize.x / 2 - popupSize.x / 2
y = offset.y
*/
val expectedPosition = IntOffset(20, 10)
createPopupWithAlignmentRule(alignment = Alignment.TopCenter, isRtl = true)
rule.popupMatches(testTag, matchesPosition(composeViewAbsolutePos + expectedPosition))
}
@Test
fun popup_correctPosition_alignmentTopEnd() {
/* Expected TopEnd Position
x = offset.x + parentSize.x - popupSize.x
y = offset.y
*/
val expectedPosition = IntOffset(70, 10)
createPopupWithAlignmentRule(alignment = Alignment.TopEnd)
rule.popupMatches(testTag, matchesPosition(composeViewAbsolutePos + expectedPosition))
}
@Test
fun popup_correctPosition_alignmentTopEnd_rtl() {
/* Expected TopEnd Position
x = -offset.x falls back to zero if outside the screen
y = offset.y
*/
val expectedPosition = IntOffset(0, 10)
createPopupWithAlignmentRule(alignment = Alignment.TopEnd, isRtl = true)
rule.popupMatches(testTag, matchesPosition(composeViewAbsolutePos + expectedPosition))
}
@Test
fun popup_correctPosition_alignmentCenterEnd() {
/* Expected CenterEnd Position
x = offset.x + parentSize.x - popupSize.x
y = offset.y + parentSize.y / 2 - popupSize.y / 2
*/
val expectedPosition = IntOffset(70, 50)
createPopupWithAlignmentRule(alignment = Alignment.CenterEnd)
rule.popupMatches(testTag, matchesPosition(composeViewAbsolutePos + expectedPosition))
}
@Test
fun popup_correctPosition_alignmentCenterEnd_rtl() {
/* Expected CenterEnd Position
x = -offset.x falls back to zero if outside the screen
y = offset.y + parentSize.y / 2 - popupSize.y / 2
*/
val expectedPosition = IntOffset(0, 50)
createPopupWithAlignmentRule(alignment = Alignment.CenterEnd, isRtl = true)
rule.popupMatches(testTag, matchesPosition(composeViewAbsolutePos + expectedPosition))
}
@Test
fun popup_correctPosition_alignmentBottomEnd() {
/* Expected BottomEnd Position
x = offset.x + parentSize.x - popupSize.x
y = offset.y + parentSize.y - popupSize.y
*/
val expectedPosition = IntOffset(70, 90)
createPopupWithAlignmentRule(alignment = Alignment.BottomEnd)
rule.popupMatches(testTag, matchesPosition(composeViewAbsolutePos + expectedPosition))
}
@Test
fun popup_correctPosition_alignmentBottomEnd_rtl() {
/* Expected BottomEnd Position
x = -offset.x falls back to zero if outside the screen
y = offset.y + parentSize.y - popupSize.y
*/
val expectedPosition = IntOffset(0, 90)
createPopupWithAlignmentRule(alignment = Alignment.BottomEnd, isRtl = true)
rule.popupMatches(testTag, matchesPosition(composeViewAbsolutePos + expectedPosition))
}
@Test
fun popup_correctPosition_alignmentBottomCenter() {
/* Expected BottomCenter Position
x = offset.x + parentSize.x / 2 - popupSize.x / 2
y = offset.y + parentSize.y - popupSize.y
*/
val expectedPosition = IntOffset(40, 90)
createPopupWithAlignmentRule(alignment = Alignment.BottomCenter)
rule.popupMatches(testTag, matchesPosition(composeViewAbsolutePos + expectedPosition))
}
@Test
fun popup_correctPosition_alignmentBottomCenter_rtl() {
/* Expected BottomCenter Position
x = -offset.x + parentSize.x / 2 - popupSize.x / 2
y = offset.y + parentSize.y - popupSize.y
*/
val expectedPosition = IntOffset(20, 90)
createPopupWithAlignmentRule(alignment = Alignment.BottomCenter, isRtl = true)
rule.popupMatches(testTag, matchesPosition(composeViewAbsolutePos + expectedPosition))
}
@Test
fun popup_correctPosition_alignmentBottomStart() {
/* Expected BottomStart Position
x = offset.x
y = offset.y + parentSize.y - popupSize.y
*/
val expectedPosition = IntOffset(10, 90)
createPopupWithAlignmentRule(alignment = Alignment.BottomStart)
rule.popupMatches(testTag, matchesPosition(composeViewAbsolutePos + expectedPosition))
}
@Test
fun popup_correctPosition_alignmentBottomStart_rtl() {
/* Expected BottomStart Position
x = -offset.x + parentSize.x - popupSize.x
y = offset.y + parentSize.y - popupSize.y
*/
val expectedPosition = IntOffset(50, 90)
createPopupWithAlignmentRule(alignment = Alignment.BottomStart, isRtl = true)
rule.popupMatches(testTag, matchesPosition(composeViewAbsolutePos + expectedPosition))
}
@Test
fun popup_correctPosition_alignmentCenterStart() {
/* Expected CenterStart Position
x = offset.x
y = offset.y + parentSize.y / 2 - popupSize.y / 2
*/
val expectedPosition = IntOffset(10, 50)
createPopupWithAlignmentRule(alignment = Alignment.CenterStart)
rule.popupMatches(testTag, matchesPosition(composeViewAbsolutePos + expectedPosition))
}
@Test
fun popup_correctPosition_alignmentCenterStart_rtl() {
/* Expected CenterStart Position
x = -offset.x + parentSize.x - popupSize.x
y = offset.y + parentSize.y / 2 - popupSize.y / 2
*/
val expectedPosition = IntOffset(50, 50)
createPopupWithAlignmentRule(alignment = Alignment.CenterStart, isRtl = true)
rule.popupMatches(testTag, matchesPosition(composeViewAbsolutePos + expectedPosition))
}
@Test
fun popup_correctPosition_alignmentCenter() {
/* Expected Center Position
x = offset.x + parentSize.x / 2 - popupSize.x / 2
y = offset.y + parentSize.y / 2 - popupSize.y / 2
*/
val expectedPosition = IntOffset(40, 50)
createPopupWithAlignmentRule(alignment = Alignment.Center)
rule.popupMatches(testTag, matchesPosition(composeViewAbsolutePos + expectedPosition))
}
@Test
fun popup_correctPosition_alignmentCenter_rtl() {
/* Expected Center Position
x = -offset.x + parentSize.x / 2 - popupSize.x / 2
y = offset.y + parentSize.y / 2 - popupSize.y / 2
*/
val expectedPosition = IntOffset(20, 50)
createPopupWithAlignmentRule(alignment = Alignment.Center, isRtl = true)
rule.popupMatches(testTag, matchesPosition(composeViewAbsolutePos + expectedPosition))
}
// TODO(b/140215440): Some tests are calling the OnChildPosition method inside the Popup too
// many times
private fun createPopupWithAlignmentRule(
alignment: Alignment,
isRtl: Boolean = false
) {
val measureLatch = CountDownLatch(1)
with(rule.density) {
val popupWidthDp = popupSize.width.toDp()
val popupHeightDp = popupSize.height.toDp()
val parentWidthDp = parentSize.width.toDp()
val parentHeightDp = parentSize.height.toDp()
rule.setContent {
// Get the compose view position on screen
val composeView = LocalView.current
val positionArray = IntArray(2)
composeView.getLocationOnScreen(positionArray)
composeViewAbsolutePos = IntOffset(
positionArray[0],
positionArray[1]
)
// Align the parent of the popup on the top left corner, this results in the global
// position of the parent to be (0, 0)
TestAlign {
val layoutDirection = if (isRtl) LayoutDirection.Rtl else LayoutDirection.Ltr
CompositionLocalProvider(LocalLayoutDirection provides layoutDirection) {
SimpleContainer(width = parentWidthDp, height = parentHeightDp) {
PopupTestTag(testTag) {
Popup(alignment = alignment, offset = offset) {
// This is called after the OnChildPosition method in Popup() which
// updates the popup to its final position
SimpleContainer(
width = popupWidthDp,
height = popupHeightDp,
modifier = Modifier.onGloballyPositioned {
measureLatch.countDown()
},
content = {}
)
}
}
}
}
}
}
}
measureLatch.await(1, TimeUnit.SECONDS)
}
@Composable
private fun TestAlign(content: @Composable () -> Unit) {
Layout(content) { measurables, constraints ->
val measurable = measurables.firstOrNull()
// The child cannot be larger than our max constraints, but we ignore min constraints.
val placeable = measurable?.measure(constraints.copy(minWidth = 0, minHeight = 0))
// The layout is as large as possible for bounded constraints,
// or wrap content otherwise.
val layoutWidth = if (constraints.hasBoundedWidth) {
constraints.maxWidth
} else {
placeable?.width ?: constraints.minWidth
}
val layoutHeight = if (constraints.hasBoundedHeight) {
constraints.maxHeight
} else {
placeable?.height ?: constraints.minHeight
}
layout(layoutWidth, layoutHeight) {
if (placeable != null) {
val position = Alignment.TopStart.align(
IntSize(placeable.width, placeable.height),
IntSize(layoutWidth, layoutHeight),
layoutDirection
)
placeable.placeRelative(position.x, position.y)
}
}
}
}
private fun matchesPosition(expectedPosition: IntOffset): BoundedMatcher<View, View> {
return object : BoundedMatcher<View, View>(View::class.java) {
// (-1, -1) no position found
var positionFound = IntOffset(-1, -1)
override fun matchesSafely(item: View?): Boolean {
val position = IntArray(2)
item?.getLocationOnScreen(position)
positionFound = IntOffset(position[0], position[1])
return expectedPosition == positionFound
}
override fun describeTo(description: Description?) {
description?.appendText(
"with expected position: $expectedPosition but position found: $positionFound"
)
}
}
}
} | apache-2.0 | 45a11f7eadb644a70a960a59a782969c | 35.67 | 103 | 0.628145 | 5.021226 | false | true | false | false |
androidx/androidx | privacysandbox/tools/tools-core/src/main/java/androidx/privacysandbox/tools/core/generator/AidlGenerator.kt | 3 | 10827 | /*
* 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.privacysandbox.tools.core.generator
import androidx.privacysandbox.tools.core.generator.poet.AidlFileSpec
import androidx.privacysandbox.tools.core.generator.poet.AidlInterfaceSpec
import androidx.privacysandbox.tools.core.generator.poet.AidlInterfaceSpec.Companion.aidlInterface
import androidx.privacysandbox.tools.core.generator.poet.AidlMethodSpec
import androidx.privacysandbox.tools.core.generator.poet.AidlParcelableSpec.Companion.aidlParcelable
import androidx.privacysandbox.tools.core.generator.poet.AidlTypeSpec
import androidx.privacysandbox.tools.core.model.AnnotatedInterface
import androidx.privacysandbox.tools.core.model.AnnotatedValue
import androidx.privacysandbox.tools.core.model.Method
import androidx.privacysandbox.tools.core.model.Parameter
import androidx.privacysandbox.tools.core.model.ParsedApi
import androidx.privacysandbox.tools.core.model.Type
import androidx.privacysandbox.tools.core.model.Types
import androidx.privacysandbox.tools.core.model.getOnlyService
import androidx.privacysandbox.tools.core.model.hasSuspendFunctions
import java.io.File
import java.nio.file.Path
import java.nio.file.Paths
class AidlGenerator private constructor(
private val aidlCompiler: AidlCompiler,
private val api: ParsedApi,
private val workingDir: Path,
) {
init {
check(api.services.count() <= 1) { "Multiple services are not supported." }
}
companion object {
fun generate(
aidlCompiler: AidlCompiler,
api: ParsedApi,
workingDir: Path,
): List<GeneratedSource> {
return AidlGenerator(aidlCompiler, api, workingDir).generate()
}
const val cancellationSignalName = "ICancellationSignal"
const val throwableParcelName = "PrivacySandboxThrowableParcel"
const val parcelableStackFrameName = "ParcelableStackFrame"
}
private fun generate(): List<GeneratedSource> {
if (api.services.isEmpty()) return listOf()
return compileAidlInterfaces(generateAidlInterfaces())
}
private fun generateAidlInterfaces(): List<GeneratedSource> {
workingDir.toFile().ensureDirectory()
val aidlSources = generateAidlContent().map {
val aidlFile = getAidlFile(workingDir, it)
aidlFile.parentFile.mkdirs()
aidlFile.createNewFile()
aidlFile.writeText(it.getFileContent())
GeneratedSource(it.type.packageName, it.type.simpleName, aidlFile)
}
return aidlSources
}
private fun compileAidlInterfaces(aidlSources: List<GeneratedSource>): List<GeneratedSource> {
aidlCompiler.compile(workingDir, aidlSources.map { it.file.toPath() })
val javaSources = aidlSources.map {
GeneratedSource(
packageName = it.packageName,
interfaceName = it.interfaceName,
file = getJavaFileForAidlFile(it.file)
)
}
javaSources.forEach {
check(it.file.exists()) {
"Missing AIDL compilation output ${it.file.absolutePath}"
}
}
return javaSources
}
private fun generateAidlContent(): List<AidlFileSpec> {
val values = api.values.map(::generateValue)
val service = aidlInterface(api.getOnlyService())
val customCallbacks = api.callbacks.map(::aidlInterface)
val interfaces = api.interfaces.map(::aidlInterface)
val suspendFunctionUtilities = generateSuspendFunctionUtilities()
return suspendFunctionUtilities +
service +
values +
customCallbacks +
interfaces
}
private fun aidlInterface(annotatedInterface: AnnotatedInterface) =
aidlInterface(Type(annotatedInterface.type.packageName, annotatedInterface.aidlName())) {
annotatedInterface.methods.forEach { addMethod(it) }
}
private fun AidlInterfaceSpec.Builder.addMethod(method: Method) {
addMethod(method.name) {
method.parameters.forEach { addParameter(it) }
if (method.isSuspend) {
addParameter("transactionCallback", transactionCallback(method.returnType))
}
}
}
private fun AidlMethodSpec.Builder.addParameter(parameter: Parameter) {
check(parameter.type != Types.unit) {
"Void cannot be a parameter type."
}
val aidlType = getAidlTypeDeclaration(parameter.type)
addParameter(
parameter.name,
aidlType,
isIn = api.valueMap.containsKey(parameter.type) || aidlType.isList
)
}
private fun generateSuspendFunctionUtilities(): List<AidlFileSpec> {
if (!api.hasSuspendFunctions()) return emptyList()
return generateTransactionCallbacks() +
generateParcelableFailure() +
generateParcelableStackTrace() +
generateICancellationSignal()
}
private fun generateTransactionCallbacks(): List<AidlFileSpec> {
val annotatedInterfaces = api.services + api.interfaces
return annotatedInterfaces
.flatMap(AnnotatedInterface::methods)
.filter(Method::isSuspend)
.map(Method::returnType).toSet()
.map { generateTransactionCallback(it) }
}
private fun generateTransactionCallback(type: Type): AidlFileSpec {
return aidlInterface(Type(packageName(), type.transactionCallbackName())) {
addMethod("onCancellable") {
addParameter("cancellationSignal", cancellationSignalType())
}
addMethod("onSuccess") {
if (type != Types.unit) addParameter(Parameter("result", type))
}
addMethod("onFailure") {
addParameter("throwableParcel", AidlTypeSpec(throwableParcelType()), isIn = true)
}
}
}
private fun generateICancellationSignal() = aidlInterface(cancellationSignalType().innerType) {
addMethod("cancel")
}
private fun generateParcelableFailure(): AidlFileSpec {
return aidlParcelable(throwableParcelType()) {
addProperty("exceptionClass", primitive("String"))
addProperty("errorMessage", primitive("String"))
addProperty("stackTrace", AidlTypeSpec(parcelableStackFrameType(), isList = true))
addProperty("cause", AidlTypeSpec(throwableParcelType(), isList = true))
addProperty(
"suppressedExceptions", AidlTypeSpec(throwableParcelType(), isList = true)
)
}
}
private fun generateParcelableStackTrace(): AidlFileSpec {
return aidlParcelable(parcelableStackFrameType()) {
addProperty("declaringClass", primitive("String"))
addProperty("methodName", primitive("String"))
addProperty("fileName", primitive("String"))
addProperty("lineNumber", primitive("int"))
}
}
private fun generateValue(value: AnnotatedValue): AidlFileSpec {
return aidlParcelable(value.aidlType().innerType) {
for (property in value.properties) {
addProperty(property.name, getAidlTypeDeclaration(property.type))
}
}
}
private fun getAidlFile(rootPath: Path, aidlSource: AidlFileSpec) = Paths.get(
rootPath.toString(),
*aidlSource.type.packageName.split(".").toTypedArray(),
aidlSource.type.simpleName + ".aidl"
).toFile()
private fun getJavaFileForAidlFile(aidlFile: File): File {
check(aidlFile.extension == "aidl") {
"AIDL path has the wrong extension: ${aidlFile.extension}."
}
return aidlFile.resolveSibling("${aidlFile.nameWithoutExtension}.java")
}
private fun packageName() = api.getOnlyService().type.packageName
private fun cancellationSignalType() = AidlTypeSpec(Type(packageName(), cancellationSignalName))
private fun throwableParcelType() = Type(packageName(), throwableParcelName)
private fun parcelableStackFrameType() = Type(packageName(), parcelableStackFrameName)
private fun transactionCallback(type: Type) =
AidlTypeSpec(Type(api.getOnlyService().type.packageName, type.transactionCallbackName()))
private fun getAidlTypeDeclaration(type: Type): AidlTypeSpec {
api.valueMap[type]?.let { return it.aidlType() }
api.callbackMap[type]?.let { return it.aidlType() }
api.interfaceMap[type]?.let { return it.aidlType() }
return when (type.qualifiedName) {
Boolean::class.qualifiedName -> primitive("boolean")
Int::class.qualifiedName -> primitive("int")
Long::class.qualifiedName -> primitive("long")
Float::class.qualifiedName -> primitive("float")
Double::class.qualifiedName -> primitive("double")
String::class.qualifiedName -> primitive("String")
Char::class.qualifiedName -> primitive("char")
// TODO: AIDL doesn't support short, make sure it's handled correctly.
Short::class.qualifiedName -> primitive("int")
Unit::class.qualifiedName -> primitive("void")
List::class.qualifiedName -> getAidlTypeDeclaration(type.typeParameters[0]).listSpec()
else -> throw IllegalArgumentException(
"Unsupported type conversion ${type.qualifiedName}"
)
}
}
}
data class GeneratedSource(val packageName: String, val interfaceName: String, val file: File)
internal fun File.ensureDirectory() {
check(exists()) {
"$this doesn't exist"
}
check(isDirectory) {
"$this is not a directory"
}
}
fun AnnotatedInterface.aidlName() = "I${type.simpleName}"
fun Type.transactionCallbackName() =
"I${simpleName}${typeParameters.joinToString("") { it.simpleName }}TransactionCallback"
internal fun AnnotatedValue.aidlType() =
AidlTypeSpec(Type(type.packageName, "Parcelable${type.simpleName}"))
internal fun AnnotatedInterface.aidlType() = AidlTypeSpec(Type(type.packageName, aidlName()))
internal fun primitive(name: String) = AidlTypeSpec(Type("", name), requiresImport = false)
| apache-2.0 | c00c282420dfb98a6ae78f44d53fcf5f | 40.324427 | 100 | 0.67581 | 4.788589 | false | false | false | false |
SevenLines/Celebs-Image-Viewer | src/main/kotlin/theplace/views/MainLayout.kt | 1 | 4450 | package theplace.views
import javafx.collections.FXCollections.observableList
import javafx.collections.transformation.FilteredList
import javafx.event.EventHandler
import javafx.scene.control.*
import javafx.scene.input.KeyCode
import javafx.scene.layout.VBox
import javafx.stage.DirectoryChooser
import theplace.controllers.MainLayoutController
import theplace.parsers.BaseParser
import theplace.parsers.SuperiorPicsParser
import theplace.parsers.ThePlaceParser
import theplace.parsers.elements.Gallery
import tornadofx.View
import java.io.File
import java.util.prefs.Preferences
/**
* Created by mk on 03.04.16.
*/
class MainLayout : View() {
override val root: VBox by fxml()
val galleriesList: ListView<Gallery> by fxid()
val cmbParsers: ComboBox<BaseParser> by fxid()
val btnSavePathSelector: Button by fxid()
val btnRefresh: Button by fxid()
val txtQuery: TextField by fxid()
val txtSavePath: TextField by fxid()
val tabPane: TabPane by fxid()
val controller: MainLayoutController by inject()
var galleries: FilteredList<Gallery>? = null
var tabMap: MutableMap<Gallery, Tab> = mutableMapOf()
private var parsers = observableList(listOf(
ThePlaceParser(),
SuperiorPicsParser()
))
init {
cmbParsers.selectionModel.selectedItemProperty().addListener({ obs, o, newParser ->
background {
galleries = FilteredList(observableList(newParser.galleries), {
it.title.contains(txtQuery.text, true)
})
} ui {
Preferences.userRoot().put("parser", newParser.title)
galleriesList.items = galleries
}
})
txtQuery.textProperty().addListener({
value, old, new ->
run {
galleries?.setPredicate { it.title.contains(new, true) }
Preferences.userRoot().put("query", new)
}
})
btnSavePathSelector.onAction = EventHandler {
var chooser = DirectoryChooser()
chooser.initialDirectory = File(if (!txtSavePath.text.isNullOrEmpty()) txtSavePath.text else ".")
var file = chooser.showDialog(primaryStage)
if (file != null) {
txtSavePath.text = file.absolutePath
Preferences.userRoot().put("savepath", file.absolutePath)
}
}
root.onKeyPressed = EventHandler {
if (it.isControlDown && it.code == KeyCode.W) {
if (tabPane.selectionModel.selectedItem != null) {
tabMap.remove(tabPane.selectionModel.selectedItem.userData)
tabPane.tabs.remove(tabPane.selectionModel.selectedItem)
}
}
}
// btnRefresh.onAction = EventHandler {
// background {
// galleries = FilteredList(observableList(controller.refreshGalleries()), {
// it.title.contains(txtQuery.text, true)
// })
// } ui {
// galleriesList.items = galleries
// }
// }
galleriesList.selectionModel.selectedItemProperty().addListener({
observableValue, old, newGallery ->
if (newGallery != null) {
if (tabMap.containsKey(newGallery)) {
var tab = tabMap.get(newGallery)
tabPane.selectionModel.select(tab)
} else {
var tab = Tab()
tab.text = newGallery.title
tab.content = GalleryLayout(newGallery).root
tabPane.tabs.add(0, tab)
tabPane.selectionModel.select(0)
tab.onClosed = EventHandler {
tabMap.remove(newGallery)
}
tab.userData = newGallery
tabMap.set(newGallery, tab)
}
}
})
txtSavePath.text = Preferences.userRoot().get("savepath", ".")
txtQuery.text = Preferences.userRoot().get("query", "")
cmbParsers.items = parsers
var galleryItem = cmbParsers.items.find { it.title == Preferences.userRoot().get("parser", "") }
if (galleryItem != null)
cmbParsers.selectionModel.select(galleryItem)
else
cmbParsers.selectionModel.select(cmbParsers.items[0])
}
}
| mit | 5ed144a350e048dfe764ac7ca53e6e9d | 34.03937 | 109 | 0.590337 | 4.64025 | false | false | false | false |
mvosske/comlink | app/src/main/java/org/tnsfit/dragon/comlink/matrix/SocketPool.kt | 1 | 1012 | package org.tnsfit.dragon.comlink.matrix
import java.io.Closeable
import java.util.*
/**
* Created by dragon on 18.10.16.
* verwaltet die Sockets, um sie bei Bedarf alle schließen zu können
*/
class SocketPool {
val lock = Object()
private val mSockets: MutableList<Closeable> = ArrayList()
var isRunning = true
private set
fun registerSocket(socket: Closeable): Boolean {
synchronized(lock) {
if (isRunning) {
mSockets.add(socket)
return true
} else {
socket.close()
return false
}
}
}
fun unregisterSocket(socket: Closeable) {
synchronized(lock) {
if (isRunning) mSockets.remove(socket)
}
}
fun stop() {isRunning = false}
fun closeAllSockets() {
synchronized(lock) {
isRunning = false
for (socket in mSockets) {
socket.close()
}
}
}
}
| gpl-3.0 | 75263c5020be7484a33e78db4ad766cf | 20.041667 | 68 | 0.541584 | 4.190871 | false | false | false | false |
andstatus/andstatus | app/src/main/kotlin/org/andstatus/app/util/InstanceId.kt | 1 | 2036 | /**
* Copyright (C) 2014 yvolk (Yuri Volkov), http://yurivolkov.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.andstatus.app.util
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicLong
object InstanceId {
/**
* IDs used for testing purposes to identify instances of reference types.
*/
private val PREV_INSTANCE_ID: AtomicLong = AtomicLong(0)
/**
* @return Unique for this process integer, numbers are given in the order starting from 1
*/
operator fun next(): Long {
return PREV_INSTANCE_ID.incrementAndGet()
}
// TODO: To be replaced with View.generateViewId() for API >= 17
private val sNextViewId: AtomicInteger = AtomicInteger(1)
/**
* http://stackoverflow.com/questions/1714297/android-view-setidint-id-programmatically-how-to-avoid-id-conflicts
* Generate a value suitable for use in [android.view.View.setId].
* This value will not collide with ID values generated at build time by aapt for R.id.
*
* @return a generated ID value
*/
fun generateViewId(): Int {
while (true) {
val result = sNextViewId.get()
// aapt-generated IDs have the high byte nonzero; clamp to the range under that.
var newValue = result + 1
if (newValue > 0x00FFFFFF) newValue = 1 // Roll over to 1, not 0.
if (sNextViewId.compareAndSet(result, newValue)) {
return result
}
}
}
}
| apache-2.0 | 5e576ab68fa8c7ccb77131d71d5edb4b | 36.018182 | 117 | 0.674361 | 4.250522 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/platform/mixin/insight/MixinLineMarkerProvider.kt | 1 | 2296 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.insight
import com.demonwav.mcdev.asset.MixinAssets
import com.demonwav.mcdev.platform.mixin.util.findSourceClass
import com.demonwav.mcdev.platform.mixin.util.isMixin
import com.demonwav.mcdev.platform.mixin.util.mixinTargets
import com.intellij.codeInsight.daemon.GutterIconNavigationHandler
import com.intellij.codeInsight.daemon.LineMarkerInfo
import com.intellij.codeInsight.daemon.LineMarkerProviderDescriptor
import com.intellij.codeInsight.daemon.impl.PsiElementListNavigator
import com.intellij.ide.util.PsiClassListCellRenderer
import com.intellij.openapi.editor.markup.GutterIconRenderer
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiIdentifier
import java.awt.event.MouseEvent
class MixinLineMarkerProvider : LineMarkerProviderDescriptor(), GutterIconNavigationHandler<PsiIdentifier> {
override fun getName() = "Mixin line marker"
override fun getIcon() = MixinAssets.MIXIN_CLASS_ICON
override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<PsiIdentifier>? {
if (element !is PsiClass) {
return null
}
val identifier = element.nameIdentifier ?: return null
if (!element.isMixin) {
return null
}
return LineMarkerInfo(
identifier,
identifier.textRange,
icon,
{ "Go to target class" },
this,
GutterIconRenderer.Alignment.LEFT,
{ "mixin target class indicator" }
)
}
override fun navigate(e: MouseEvent, elt: PsiIdentifier) {
val psiClass = elt.parent as? PsiClass ?: return
val name = psiClass.name ?: return
val targets = psiClass.mixinTargets
.mapNotNull { it.findSourceClass(psiClass.project, psiClass.resolveScope, canDecompile = true) }
if (targets.isNotEmpty()) {
PsiElementListNavigator.openTargets(
e,
targets.toTypedArray(),
"Choose target class of $name",
null,
PsiClassListCellRenderer()
)
}
}
}
| mit | df71edded8757c0541c72b6d0b18401c | 32.275362 | 108 | 0.68554 | 4.905983 | false | false | false | false |
inorichi/tachiyomi-extensions | src/es/tumangaonline/src/eu/kanade/tachiyomi/extension/es/tumangaonline/TuMangaOnlineUrlActivity.kt | 1 | 1352 | package eu.kanade.tachiyomi.extension.es.tumangaonline
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.os.Bundle
import android.util.Log
import kotlin.system.exitProcess
/**
* Springboard that accepts https://lectortmo.com/library/:type/:id/:slug intents and redirects them to
* the main Tachiyomi process.
*/
class TuMangaOnlineUrlActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val pathSegments = intent?.data?.pathSegments
if (pathSegments != null && pathSegments.size > 3) {
val type = pathSegments[1]
val id = pathSegments[2]
val slug = pathSegments[3]
val mainIntent = Intent().apply {
action = "eu.kanade.tachiyomi.SEARCH"
putExtra("query", "${TuMangaOnline.PREFIX_ID_SEARCH}$type/$id/$slug")
putExtra("filter", packageName)
}
try {
startActivity(mainIntent)
} catch (e: ActivityNotFoundException) {
Log.e("TMOUrlActivity", e.toString())
}
} else {
Log.e("TMOUrlActivity", "could not parse uri from intent $intent")
}
finish()
exitProcess(0)
}
}
| apache-2.0 | cfea09404a16f3da54585905885bfdf6 | 31.190476 | 103 | 0.622781 | 4.646048 | false | false | false | false |
inorichi/tachiyomi-extensions | multisrc/src/main/java/eu/kanade/tachiyomi/multisrc/genkan/GenkanOriginal.kt | 1 | 2731 | package eu.kanade.tachiyomi.multisrc.genkan
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.util.asJsoup
import okhttp3.Request
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import org.jsoup.select.Elements
/**
* For sites using the older Genkan CMS that didn't have a search function
*/
open class GenkanOriginal(
override val name: String,
override val baseUrl: String,
override val lang: String
) : Genkan(name, baseUrl, lang) {
private var searchQuery = ""
private var searchPage = 1
private var nextPageSelectorElement = Elements()
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
if (page == 1) searchPage = 1
searchQuery = query
return popularMangaRequest(page)
}
override fun searchMangaParse(response: Response): MangasPage {
val searchMatches = mutableListOf<SManga>()
val document = response.asJsoup()
searchMatches.addAll(getMatchesFrom(document))
/* call another function if there's more pages to search
not doing it this way can lead to a false "no results found"
if no matches are found on the first page but there are matches
on subsequent pages */
nextPageSelectorElement = document.select(searchMangaNextPageSelector())
while (nextPageSelectorElement.hasText()) {
searchMatches.addAll(searchMorePages())
}
return MangasPage(searchMatches, false)
}
// search the given document for matches
private fun getMatchesFrom(document: Document): MutableList<SManga> {
val searchMatches = mutableListOf<SManga>()
document.select(searchMangaSelector())
.filter { it.text().contains(searchQuery, ignoreCase = true) }
.map { searchMatches.add(searchMangaFromElement(it)) }
return searchMatches
}
// search additional pages if called
private fun searchMorePages(): MutableList<SManga> {
searchPage++
val nextPage = client.newCall(popularMangaRequest(searchPage)).execute().asJsoup()
val searchMatches = mutableListOf<SManga>()
searchMatches.addAll(getMatchesFrom(nextPage))
nextPageSelectorElement = nextPage.select(searchMangaNextPageSelector())
return searchMatches
}
override fun searchMangaSelector() = popularMangaSelector()
override fun searchMangaFromElement(element: Element) = popularMangaFromElement(element)
override fun searchMangaNextPageSelector() = popularMangaNextPageSelector()
}
| apache-2.0 | 075be436ef2bda628ec49440742ed0fc | 35.413333 | 93 | 0.71439 | 5.001832 | false | false | false | false |
ligee/kotlin-jupyter | src/main/kotlin/org/jetbrains/kotlinx/jupyter/libraries/libraryResolvers.kt | 1 | 5460 | package org.jetbrains.kotlinx.jupyter.libraries
import org.jetbrains.kotlinx.jupyter.api.libraries.LibraryDefinition
import org.jetbrains.kotlinx.jupyter.api.libraries.LibraryReference
import org.jetbrains.kotlinx.jupyter.api.libraries.LibraryResolutionInfo
import org.jetbrains.kotlinx.jupyter.api.libraries.Variable
import org.jetbrains.kotlinx.jupyter.common.getHttp
import org.jetbrains.kotlinx.jupyter.common.text
import org.jetbrains.kotlinx.jupyter.config.getLogger
import org.jetbrains.kotlinx.jupyter.exceptions.ReplLibraryLoadingException
import java.io.File
import kotlin.reflect.KClass
import kotlin.reflect.cast
class DefaultInfoLibraryResolver(
private val parent: LibraryResolver,
private val infoProvider: ResolutionInfoProvider,
paths: List<File> = emptyList(),
) : LibraryResolver {
private val resolutionInfos = paths.map { AbstractLibraryResolutionInfo.ByDir(it) }
override fun resolve(reference: LibraryReference, arguments: List<Variable>): LibraryDefinition? {
val referenceInfo = reference.info
if (referenceInfo !is AbstractLibraryResolutionInfo.Default) return parent.resolve(reference, arguments)
val definitionText = resolutionInfos.asSequence().mapNotNull { byDirResolver.resolveRaw(it, reference.name) }.firstOrNull()
if (definitionText != null) return parseLibraryDescriptor(definitionText).convertToDefinition(arguments)
val newReference = transformReference(referenceInfo, reference.name)
return parent.resolve(newReference, arguments)
}
private fun transformReference(referenceInfo: AbstractLibraryResolutionInfo.Default, referenceName: String?): LibraryReference {
val transformedInfo = infoProvider.get(referenceInfo.string)
return LibraryReference(transformedInfo, referenceName)
}
}
class LocalLibraryResolver(
parent: LibraryResolver?,
mainLibrariesDir: File?
) : ChainedLibraryResolver(parent) {
private val logger = getLogger()
private val pathsToCheck: List<File>
init {
val paths = mutableListOf(
KERNEL_LIBRARIES.userCacheDir,
KERNEL_LIBRARIES.userLibrariesDir,
)
mainLibrariesDir?.let { paths.add(it) }
pathsToCheck = paths
}
override fun shouldResolve(reference: LibraryReference): Boolean {
return reference.shouldBeCachedLocally
}
override fun tryResolve(reference: LibraryReference, arguments: List<Variable>): LibraryDefinition? {
val files = pathsToCheck.mapNotNull { dir ->
val file = reference.getFile(dir)
if (file.exists()) file else null
}
if (files.size > 1) {
logger.warn("More than one file for library $reference found in local cache directories")
}
val jsonFile = files.firstOrNull() ?: return null
return parseLibraryDescriptor(jsonFile.readText()).convertToDefinition(arguments)
}
override fun save(reference: LibraryReference, definition: LibraryDefinition) {
val text = definition.originalDescriptorText ?: return
val dir = pathsToCheck.first()
val file = reference.getFile(dir)
file.parentFile.mkdirs()
file.writeText(text)
}
private fun LibraryReference.getFile(dir: File) = dir.resolve(KERNEL_LIBRARIES.descriptorFileName(key))
}
object FallbackLibraryResolver : ChainedLibraryResolver() {
private val standardResolvers = listOf(
byDirResolver,
resolver<AbstractLibraryResolutionInfo.ByGitRef> { name ->
if (name == null) throw ReplLibraryLoadingException(message = "Reference library resolver needs name to be specified")
KERNEL_LIBRARIES.downloadLibraryDescriptor(sha, name)
},
resolver<AbstractLibraryResolutionInfo.ByFile> {
file.readText()
},
resolver<AbstractLibraryResolutionInfo.ByURL> {
val response = getHttp(url.toString())
response.text
},
resolver<ByNothingLibraryResolutionInfo> { "{}" },
resolver<AbstractLibraryResolutionInfo.Default> { null }
)
override fun tryResolve(reference: LibraryReference, arguments: List<Variable>): LibraryDefinition? {
return standardResolvers.firstOrNull { it.accepts(reference) }?.resolve(reference, arguments)
}
}
class SpecificLibraryResolver<T : LibraryResolutionInfo>(private val kClass: KClass<T>, val resolveRaw: (T, String?) -> String?) : LibraryResolver {
fun accepts(reference: LibraryReference): Boolean {
return kClass.isInstance(reference.info)
}
override fun resolve(reference: LibraryReference, arguments: List<Variable>): LibraryDefinition? {
if (!accepts(reference)) return null
val text = resolveRaw(kClass.cast(reference.info), reference.name) ?: return null
return parseLibraryDescriptor(text).convertToDefinition(arguments)
}
}
private inline fun <reified T : LibraryResolutionInfo> resolver(noinline resolverFun: T.(String?) -> String?) = SpecificLibraryResolver(T::class, resolverFun)
private val byDirResolver = resolver<AbstractLibraryResolutionInfo.ByDir> { name ->
if (name == null) throw ReplLibraryLoadingException(name, "Directory library resolver needs library name to be specified")
val jsonFile = librariesDir.resolve(KERNEL_LIBRARIES.descriptorFileName(name))
if (jsonFile.exists() && jsonFile.isFile) jsonFile.readText()
else null
}
| apache-2.0 | d6a5ea9c4033e3627fc67e0923b211f8 | 41.65625 | 158 | 0.73022 | 4.751958 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/osmnotes/notequests/OsmNoteQuestsChangesUploader.kt | 1 | 3002 | package de.westnordost.streetcomplete.data.osmnotes.notequests
import android.util.Log
import javax.inject.Inject
import de.westnordost.streetcomplete.data.osm.upload.ConflictException
import de.westnordost.streetcomplete.data.osmnotes.ImageUploadException
import de.westnordost.streetcomplete.data.osmnotes.OsmNoteWithPhotosUploader
import de.westnordost.streetcomplete.data.osmnotes.deleteImages
import de.westnordost.streetcomplete.data.upload.OnUploadedChangeListener
import de.westnordost.streetcomplete.data.upload.Uploader
import java.util.concurrent.atomic.AtomicBoolean
/** Gets all note quests from local DB and uploads them via the OSM API */
class OsmNoteQuestsChangesUploader @Inject constructor(
private val osmNoteQuestController: OsmNoteQuestController,
private val singleNoteUploader: OsmNoteWithPhotosUploader
): Uploader {
override var uploadedChangeListener: OnUploadedChangeListener? = null
/** Uploads all note quests from local DB and closes them on successful upload.
*
* Drops any notes where the upload failed because of a conflict but keeps any notes where
* the upload failed because attached photos could not be uploaded (so it can try again
* later). */
@Synchronized override fun upload(cancelled: AtomicBoolean) {
var created = 0
var obsolete = 0
if (cancelled.get()) return
for (quest in osmNoteQuestController.getAllAnswered()) {
if (cancelled.get()) break
try {
val newNote = singleNoteUploader.comment(quest.note.id, quest.comment ?: "", quest.imagePaths)
quest.note.comments = newNote.comments
quest.note.dateClosed = newNote.dateClosed
quest.note.status = newNote.status
osmNoteQuestController.success(quest)
Log.d(TAG, "Uploaded note comment ${quest.logString}")
uploadedChangeListener?.onUploaded(NOTE, quest.center)
created++
deleteImages(quest.imagePaths)
} catch (e: ConflictException) {
osmNoteQuestController.fail(quest)
Log.d(TAG, "Dropped note comment ${quest.logString}: ${e.message}")
uploadedChangeListener?.onDiscarded(NOTE, quest.center)
obsolete++
deleteImages(quest.imagePaths)
} catch (e: ImageUploadException) {
Log.e(TAG, "Error uploading image attached to note comment ${quest.logString}", e)
}
}
var logMsg = "Commented on $created notes"
if (obsolete > 0) {
logMsg += " but dropped $obsolete comments because the notes have already been closed"
}
Log.i(TAG, logMsg)
}
companion object {
private const val TAG = "CommentNoteUpload"
private const val NOTE = "NOTE"
}
}
private val OsmNoteQuest.logString get() = "\"$comment\" at ${center.latitude}, ${center.longitude}"
| gpl-3.0 | 97d13102716eb48250fdffd0ead05401 | 41.885714 | 110 | 0.676216 | 4.905229 | false | false | false | false |
kesmarag/megaptera | src/main/org/kesmarag/megaptera/utils/Functions.kt | 1 | 1942 | package org.kesmarag.megaptera.utils
import org.kesmarag.megaptera.linear.ColumnVector
import org.kesmarag.megaptera.linear.RowVector
fun sigmoid(a: Double): Double = 1.0 / (1.0 + Math.exp(-a))
fun tanhBased(a: Double): Double = 1.7159 * Math.tanh(2.0 * a / 3.0)
fun sigmoid(vector: ColumnVector): ColumnVector {
val sigmoidVector = ColumnVector(vector.dimension)
for (i in 0..vector.dimension - 1) {
sigmoidVector[i] = sigmoid(vector[i])
}
return sigmoidVector
}
fun tanhBased(vector: ColumnVector): ColumnVector {
val tanhBasedVector = ColumnVector(vector.dimension)
for (i in 0..vector.dimension - 1) {
tanhBasedVector[i] = tanhBased(vector[i])
}
return tanhBasedVector
}
fun tanhBased(vector: RowVector): RowVector {
return tanhBased(vector.t()).t()
}
fun sigmoid(vector: RowVector): RowVector {
return sigmoid(vector.t()).t()
}
fun softmax(vector: ColumnVector): ColumnVector {
var softmaxVector = ColumnVector(vector.dimension)
var sumOfExp = 0.0
for (i in 0..vector.dimension - 1) {
val exp = Math.exp(vector[i])
sumOfExp += exp
softmaxVector[i] = exp
}
softmaxVector = softmaxVector * (1.0 / sumOfExp)
return softmaxVector
}
fun softmax2(vector: ColumnVector): ColumnVector {
var softmaxVector = ColumnVector(vector.dimension)
var sumOfExp = 0.0
for (i in 0..vector.dimension - 1) {
val exp = Math.exp(vector[i]*0.01)
sumOfExp += exp
softmaxVector[i] = exp
}
softmaxVector = softmaxVector * (1.0 / sumOfExp)
//println("softmax <-$softmaxVector")
return softmaxVector
}
fun softmax(vector: RowVector): RowVector {
return softmax(vector.t()).t()
}
fun exp(a: Double, vector: RowVector): RowVector {
val expVector = RowVector(vector.dimension)
for (i in 0..vector.dimension - 1) {
expVector[i] = Math.exp(vector[i] * a)
}
return expVector
} | apache-2.0 | 70663d4aacffb5b5741ed50096064480 | 26.366197 | 68 | 0.664779 | 3.1072 | false | false | false | false |
mattvchandler/ProgressBars | app/src/main/java/settings/Datepicker_frag.kt | 1 | 3478 | /*
Copyright (C) 2020 Matthew Chandler
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.mattvchandler.progressbars.settings
import android.app.DatePickerDialog
import android.app.Dialog
import android.os.Build
import android.os.Bundle
import android.widget.Toast
import androidx.fragment.app.DialogFragment
import androidx.preference.PreferenceManager
import org.mattvchandler.progressbars.R
import org.mattvchandler.progressbars.settings.Settings.Companion.get_date_format
import java.security.InvalidParameterException
import java.text.ParsePosition
import java.util.*
// date picker dialog
class Datepicker_frag: DialogFragment()
{
override fun onCreateDialog(saved_instance_state: Bundle?): Dialog
{
// parse from current widget text
val year: Int
val month: Int
val day: Int
val cal = Calendar.getInstance()
val preferenceManager = PreferenceManager.getDefaultSharedPreferences(activity)
val date_format = preferenceManager.getString(resources.getString(R.string.pref_date_format_key), resources.getString(R.string.pref_date_format_default))
val date = arguments!!.getString(DATE) ?: throw InvalidParameterException("No date argument given")
val df = get_date_format(activity!!)
val date_obj = df.parse(date, ParsePosition(0))
if(date_obj == null)
{
// couldn't parse
Toast.makeText(activity, resources.getString(R.string.invalid_date, date, if(date_format != "locale") date_format else df.toLocalizedPattern()), Toast.LENGTH_LONG).show()
// set to stored date
cal.timeInMillis = arguments!!.getLong(STORE_DATE, 0) * 1000
}
else
{
cal.time = date_obj
}
year = cal.get(Calendar.YEAR)
month = cal.get(Calendar.MONTH)
day = cal.get(Calendar.DAY_OF_MONTH)
val date_picker = DatePickerDialog(activity!!, activity as Settings?, year, month, day)
if(Build.VERSION.SDK_INT >= 21)
{
val first_day_of_wk = preferenceManager.getString(resources.getString(R.string.pref_first_day_of_wk_key), resources.getString(R.string.pref_first_day_of_wk_default))!!.toInt()
if(first_day_of_wk != 0)
date_picker.datePicker.firstDayOfWeek = first_day_of_wk
}
return date_picker
}
companion object
{
const val STORE_DATE = "STORE_DATE"
const val DATE = "DATE"
}
}
| mit | 24ad20777a5ce2928587c4118d7c19c0 | 37.21978 | 187 | 0.713053 | 4.369347 | false | false | false | false |
apollostack/apollo-android | apollo-graphql-ast/src/main/kotlin/com/apollographql/apollo3/graphql/ast/add_typename.kt | 1 | 1599 | package com.apollographql.apollo3.graphql.ast
fun GQLOperationDefinition.withTypenameWhenNeeded(schema: Schema): GQLOperationDefinition {
return copy(
selectionSet = selectionSet.withTypenameWhenNeeded(schema)
)
}
fun GQLFragmentDefinition.withTypenameWhenNeeded(schema: Schema): GQLFragmentDefinition {
return copy(
// Force the typename on all Fragments
selectionSet = selectionSet.withTypenameWhenNeeded(schema, true)
)
}
private val typeNameField = GQLField(
name = "__typename",
arguments = null,
selectionSet = null,
sourceLocation = SourceLocation.UNKNOWN,
directives = emptyList(),
alias = null
)
private fun GQLSelectionSet.withTypenameWhenNeeded(schema: Schema, force: Boolean = false): GQLSelectionSet {
var newSelections = selections.map {
when (it) {
is GQLInlineFragment -> {
it.copy(
selectionSet = it.selectionSet.withTypenameWhenNeeded(schema)
)
}
is GQLFragmentSpread -> it
is GQLField -> it.copy(
selectionSet = it.selectionSet?.withTypenameWhenNeeded(schema)
)
}
}
val hasFragment = selections.filter { it is GQLFragmentSpread || it is GQLInlineFragment }.isNotEmpty()
newSelections = if (force || hasFragment) {
// remove the __typename if it exists
// and add it again at the top so we're guaranteed to have it at the beginning of json parsing
listOf(typeNameField) + newSelections.filterNot { (it as? GQLField)?.name == "__typename" }
} else {
newSelections
}
return copy(
selections = newSelections
)
}
| mit | 955cec7fe56e4ed3111d6d1d1050857c | 28.611111 | 109 | 0.697936 | 4.25266 | false | false | false | false |
apollostack/apollo-android | apollo-api/src/commonMain/kotlin/com/apollographql/apollo3/api/Error.kt | 1 | 1070 | package com.apollographql.apollo3.api
/**
* Represents an error response returned from the GraphQL server
*/
class Error(
/**
* Server error message
*/
val message: String,
/**
* Locations of the errors in the GraphQL operation
*/
val locations: List<Location> = emptyList(),
/**
* Custom attributes associated with this error
*/
val customAttributes: Map<String, Any?> = emptyMap(),
) {
override fun toString(): String {
return "Error(message = $message, locations = $locations, customAttributes = $customAttributes)"
}
/**
* Represents the location of the error in the GraphQL operation sent to the server. This location is represented in
* terms of the line and column number.
*/
class Location(
/**
* Line number of the error location
*/
val line: Long,
/**
* Column number of the error location.
*/
val column: Long,
) {
override fun toString(): String {
return "Location(line = $line, column = $column)"
}
}
}
| mit | 99575d1b6e07d304b46fb97d55b80c1b | 21.765957 | 118 | 0.615888 | 4.533898 | false | false | false | false |
google/filament | android/filament-utils-android/src/main/java/com/google/android/filament/utils/GestureDetector.kt | 1 | 5452 | /*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.filament.utils
import android.view.MotionEvent
import android.view.View
import java.util.*
/**
* Responds to Android touch events and manages a camera manipulator.
* Supports one-touch orbit, two-touch pan, and pinch-to-zoom.
*/
class GestureDetector(private val view: View, private val manipulator: Manipulator) {
private enum class Gesture { NONE, ORBIT, PAN, ZOOM }
// Simplified memento of MotionEvent, minimal but sufficient for our purposes.
private data class TouchPair(var pt0: Float2, var pt1: Float2, var count: Int) {
constructor() : this(Float2(0f), Float2(0f), 0)
constructor(me: MotionEvent, height: Int) : this() {
if (me.pointerCount >= 1) {
this.pt0 = Float2(me.getX(0), height - me.getY(0))
this.pt1 = this.pt0
this.count++
}
if (me.pointerCount >= 2) {
this.pt1 = Float2(me.getX(1), height - me.getY(1))
this.count++
}
}
val separation get() = distance(pt0, pt1)
val midpoint get() = mix(pt0, pt1, 0.5f)
val x: Int get() = midpoint.x.toInt()
val y: Int get() = midpoint.y.toInt()
}
private var currentGesture = Gesture.NONE
private var previousTouch = TouchPair()
private val tentativePanEvents = ArrayList<TouchPair>()
private val tentativeOrbitEvents = ArrayList<TouchPair>()
private val tentativeZoomEvents = ArrayList<TouchPair>()
private val kGestureConfidenceCount = 2
private val kPanConfidenceDistance = 4
private val kZoomConfidenceDistance = 10
private val kZoomSpeed = 1f / 10f
fun onTouchEvent(event: MotionEvent) {
val touch = TouchPair(event, view.height)
when (event.actionMasked) {
MotionEvent.ACTION_MOVE -> {
// CANCEL GESTURE DUE TO UNEXPECTED POINTER COUNT
if ((event.pointerCount != 1 && currentGesture == Gesture.ORBIT) ||
(event.pointerCount != 2 && currentGesture == Gesture.PAN) ||
(event.pointerCount != 2 && currentGesture == Gesture.ZOOM)) {
endGesture()
return
}
// UPDATE EXISTING GESTURE
if (currentGesture == Gesture.ZOOM) {
val d0 = previousTouch.separation
val d1 = touch.separation
manipulator.scroll(touch.x, touch.y, (d0 - d1) * kZoomSpeed)
previousTouch = touch
return
}
if (currentGesture != Gesture.NONE) {
manipulator.grabUpdate(touch.x, touch.y)
return
}
// DETECT NEW GESTURE
if (event.pointerCount == 1) {
tentativeOrbitEvents.add(touch)
}
if (event.pointerCount == 2) {
tentativePanEvents.add(touch)
tentativeZoomEvents.add(touch)
}
if (isOrbitGesture()) {
manipulator.grabBegin(touch.x, touch.y, false)
currentGesture = Gesture.ORBIT
return
}
if (isZoomGesture()) {
currentGesture = Gesture.ZOOM
previousTouch = touch
return
}
if (isPanGesture()) {
manipulator.grabBegin(touch.x, touch.y, true)
currentGesture = Gesture.PAN
return
}
}
MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_UP -> {
endGesture()
}
}
}
private fun endGesture() {
tentativePanEvents.clear()
tentativeOrbitEvents.clear()
tentativeZoomEvents.clear()
currentGesture = Gesture.NONE
manipulator.grabEnd()
}
private fun isOrbitGesture(): Boolean {
return tentativeOrbitEvents.size > kGestureConfidenceCount
}
private fun isPanGesture(): Boolean {
if (tentativePanEvents.size <= kGestureConfidenceCount) {
return false
}
val oldest = tentativePanEvents.first().midpoint
val newest = tentativePanEvents.last().midpoint
return distance(oldest, newest) > kPanConfidenceDistance
}
private fun isZoomGesture(): Boolean {
if (tentativeZoomEvents.size <= kGestureConfidenceCount) {
return false
}
val oldest = tentativeZoomEvents.first().separation
val newest = tentativeZoomEvents.last().separation
return kotlin.math.abs(newest - oldest) > kZoomConfidenceDistance
}
}
| apache-2.0 | 600a807a01cec00a962523ffafea9f36 | 34.402597 | 86 | 0.574285 | 4.600844 | false | false | false | false |
Heiner1/AndroidAPS | insight/src/main/java/info/nightscout/androidaps/insight/database/InsightBolusID.kt | 1 | 534 | package info.nightscout.androidaps.insight.database
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
@Entity(tableName = DATABASE_INSIGHT_BOLUS_IDS,
indices = [
Index("bolusID"),
Index("pumpSerial"),
Index("timestamp")
])
data class InsightBolusID(
var timestamp: Long,
val pumpSerial: String? = null,
val bolusID: Int? = null,
var startID: Long? = null,
var endID: Long? = null
) {
@PrimaryKey(autoGenerate = true)
var id: Long = 0
} | agpl-3.0 | bc8e4420c6ce510e4c185d92258cc618 | 23.318182 | 51 | 0.666667 | 3.787234 | false | false | false | false |
DevJake/SaltBot-2.0 | src/main/kotlin/me/salt/entities/cmd/CommandListener.kt | 1 | 4040 | /*
* Copyright 2017 DevJake
*
* 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 me.salt.entities.cmd
import me.salt.utilities.logging.logDebug
import me.salt.utilities.logging.logInfo
import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent
import net.dv8tion.jda.core.hooks.ListenerAdapter
/**
* This command listens for a range of events in relation to the Command System, and handles them accordingly.
*
* Namely, this class identifies [Commands][Command] from a [GuildMessageReceivedEvent], and fires any respective handlers.
*/
class CommandListener : ListenerAdapter() {
/**
* This method receives information about any messages sent to a guild.
* As a result, this method handles the analyses of the incoming message's prefix
* (performed through [CommandParser.isPotentialCommand]), and identifies any applicable commands.
* If any commands are identified, their respective [preExecute][Command.preExecute],
* [execute][Command.execute] and [postExecute][Command.postExecute] methods are invoked.
*
* @see Command
*/
override fun onGuildMessageReceived(event: GuildMessageReceivedEvent?) {
if (CommandParser.isPotentialCommand(event?.message?.rawContent ?: return)) {
logInfo("Received a potential command from user ${event.author} (ID: ${event.author.id})", "COMMAND")
val cc = CommandParser.parse(event.message.rawContent, event.guild.id, event.channel.id, event.author.id) ?: return
val filteredCommands = CommandRegistry.getCommands().filterByCommandPrefix(cc.beheadedLiteralLower)
filteredCommands.forEach {
if (it.preExecute == null) {
logDebug("Didn't call null-value preExecute method of $it", "COMMAND")
} else {
it.preExecute.invoke(cc, event, CmdInstanceHandle(it))
logDebug("Called preExecute method of $it", "COMMAND")
}
}
filteredCommands.forEach {
if (it.execute == null) {
logDebug("Didn't call null-value execute method of $it", "COMMAND")
} else {
it.execute.invoke(cc, event, CmdInstanceHandle(it))
logDebug("Called execute method of $it", "COMMAND")
}
}
filteredCommands.forEach {
if (it.postExecute == null) {
logDebug("Didn't call null-value postExecute method of $it", "COMMAND")
} else {
it.postExecute.invoke(cc, event)
logDebug("Called postExecute method of $it", "COMMAND")
}
}
}
}
}
/**
* This method filters a [List] of [Commands][Command] by the given prefix.
*
* @param prefix - The prefix to be used for filtering
* @param checkAliases - If the filter should also check the current command's aliases
*
* @return A list of [Commands][Command] filtered by the given [prefix] and the optional [alias check][checkAliases]
*
* @see Command
*/
fun List<Command>.filterByCommandPrefix(prefix: String, checkAliases: Boolean = false): List<Command> =
this.filter {
if (!it.cmdPrefix.isBlank())
if (it.cmdPrefix == prefix.toLowerCase())
return@filter true
if (checkAliases)
it.aliases.any { it == prefix.toLowerCase() }
else
false
} | apache-2.0 | d542acfd2ca981a9b03870e4261dbb0d | 41.989362 | 127 | 0.639109 | 4.534231 | false | false | false | false |
kronenpj/iqtimesheet | IQTimeSheet/src/main/com/github/kronenpj/iqtimesheet/IQTimeSheet/MySqlHelper.kt | 1 | 9780 | package com.github.kronenpj.iqtimesheet.IQTimeSheet
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.util.Log
import org.jetbrains.anko.db.*
/**
* Created by kronenpj on 6/21/17.
*/
class MySqlHelper(ctx: Context) : ManagedSQLiteOpenHelper(ctx, DATABASE_NAME, version = DATABASE_VERSION) {
companion object {
private var instance: MySqlHelper? = null
private const val DATABASE_VERSION = 3
private const val TAG = "MySqlHelper"
const val DATABASE_NAME = "TimeSheetDB.db"
@Synchronized
fun getInstance(ctx: Context): MySqlHelper {
if (instance == null) {
instance = MySqlHelper(ctx.applicationContext)
}
return instance!!
}
}
override fun onCreate(db: SQLiteDatabase) {
db.createTable("Tasks", true,
//"_id" to INTEGER + PRIMARY_KEY + AUTOINCREMENT,
"_id" to SqlType.create("INTEGER PRIMARY KEY AUTOINCREMENT"),
"task" to TEXT + NOT_NULL,
// Active should be a BOOLEAN, default to TRUE
//"active" to INTEGER + NOT_NULL + DEFAULT("1"),
"active" to SqlType.create("INTEGER NOT_NULL DEFAULT '1'"),
//"usage" to INTEGER + NOT_NULL + DEFAULT("0"),
"usage" to SqlType.create("INTEGER NOT_NULL DEFAULT '0'"),
//"oldusage" to INTEGER + NOT_NULL + DEFAULT("0"),
"oldusage" to SqlType.create("INTEGER NOT_NULL DEFAULT '0'"),
//"lastused" to INTEGER + NOT_NULL + DEFAULT("0"),
"lastused" to SqlType.create("INTEGER NOT_NULL DEFAULT '0'"),
"split" to INTEGER + DEFAULT("0")
)
db.createTable("TimeSheet", true,
//"_id" to INTEGER + PRIMARY_KEY + AUTOINCREMENT,
"_id" to SqlType.create("INTEGER PRIMARY KEY AUTOINCREMENT"),
"chargeno" to INTEGER + NOT_NULL,
//"timein" to INTEGER + NOT_NULL + DEFAULT("0"),
"timein" to SqlType.create("INTEGER NOT_NULL DEFAULT '0'"),
//"timeout" to INTEGER + NOT_NULL + DEFAULT("0"),
"timeout" to SqlType.create("INTEGER NOT_NULL DEFAULT '0'"),
FOREIGN_KEY("chargeno", "Tasks", "_id")
)
db.createTable("TaskSplit", true,
//"_id" to INTEGER + PRIMARY_KEY + AUTOINCREMENT,
"_id" to SqlType.create("INTEGER PRIMARY KEY AUTOINCREMENT"),
"chargeno" to INTEGER + NOT_NULL,
"task" to INTEGER + NOT_NULL,
//"percentage" to REAL + NOT_NULL + DEFAULT("100"),
"percentage" to SqlType.create("REAL NOT_NULL DEFAULT '100' CHECK ('percentage' >=0 AND 'percentage' <= 100)"),
FOREIGN_KEY("chargeno", "Tasks", "_id"),
FOREIGN_KEY("task", "Tasks", "_id")
// Need bounds check here, preferably.
//"percentage" to REAL + NOT_NULL + DEFAULT("100") +
// CHECK ("percentage" >=0 AND "percentage" <= 100
)
/*
db.execSQL("""ALTER TABLE TaskSplit
ADD 'percent' REAL NOT NULL DEFAULT 100 CONSTRAINT CHECK
("percentage" >= 0 AND 'percentage' <= 100)"""
)
*/
db.execSQL("""CREATE VIEW EntryItems AS
SELECT TimeSheet._id AS _id,
Tasks.task AS task,
TimeSheet.timein AS timein,
TimeSheet.timeout AS timeout
FROM TimeSheet, Tasks WHERE TimeSheet.chargeno = Tasks._id"""
)
db.execSQL("""CREATE VIEW TaskSplitReport AS
SELECT Tasks._id AS _id,
TaskSplit.chargeno AS parenttask,
Tasks.task AS taskdesc,
TaskSplit.percentage AS percentage
FROM Tasks, TaskSplit WHERE Tasks._id = TaskSplit.task"""
)
db.execSQL("""CREATE VIEW EntryReport AS SELECT
TimeSheet._id AS _id,
Tasks.task AS task,
TimeSheet.timein AS timein,
TimeSheet.timeout AS timeout,
strftime("%H:%M", timein/1000,"unixepoch","localtime")
|| ' to ' || CASE WHEN timeout = 0 THEN 'now' ELSE
strftime("%H:%M", timeout/1000,"unixepoch","localtime") END as range
FROM TimeSheet, Tasks WHERE
TimeSheet.chargeno = Tasks._id"""
)
db.execSQL("""CREATE UNIQUE INDEX Tasks_index ON "Tasks" ("task")""")
db.execSQL("""CREATE INDEX TimeSheet_chargeno_index ON "TimeSheet" ("chargeno")""")
db.execSQL("""CREATE UNIQUE INDEX TaskSplit_chargeno_index ON "TaskSplit" ("task")""")
db.execSQL("""CREATE INDEX TimeSheet_timein_index ON "TimeSheet" ("timein")""")
db.execSQL("""CREATE INDEX TimeSheet_timeout_index ON "TimeSheet" ("timeout")""")
db.createTable("TimeSheetMeta", true, "version" to INTEGER + PRIMARY_KEY)
db.insert("TimeSheetMeta", "version" to DATABASE_VERSION)
db.insert("Tasks",
"task" to "Example task entry",
"lastused" to System.currentTimeMillis()
)
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ".")
// db.execSQL("ALTER TABLE TimeSheet ADD...");
// db.execSQL("UPDATE TimeSheet SET ");
when (oldVersion) {
1 -> {
Log.d(TAG, "Old DB version <= 1")
Log.d(TAG, "Running: CHARGENO_INDEX")
db.execSQL("""CREATE UNIQUE INDEX TimeSheet_chargeno_index ON "TimeSheet" ("chargeno")""")
db.execSQL("""CREATE UNIQUE INDEX Tasks_index ON "Tasks" ("task")""")
Log.d(TAG, "Running: TIMEIN_INDEX")
db.execSQL("""CREATE UNIQUE INDEX TimeSheet_timein_index ON "TimeSheet" ("timein")""")
Log.d(TAG, "Running: TIMEOUT_INDEX")
db.execSQL("""CREATE UNIQUE INDEX TimeSheet_timeout_index ON "TimeSheet" ("timeout")""")
Log.d(TAG, "Old DB version <= 2")
Log.d(TAG, "Running: TASK_TABLE_ALTER3")
db.execSQL("""ALTER TABLE "Tasks" ADD COLUMN "split" INTEGER DEFAULT 0""")
Log.d(TAG, "Running: TASKSPLIT_TABLE_CREATE")
db.createTable("TaskSplit", true,
"_id" to INTEGER + PRIMARY_KEY + AUTOINCREMENT,
"chargeno" to INTEGER + NOT_NULL,
"task" to INTEGER + NOT_NULL,
"percentage" to REAL + NOT_NULL + DEFAULT("100"),
FOREIGN_KEY("chargeno", "Tasks", "_id"),
FOREIGN_KEY("task", "Tasks", "_id")
// Need bounds check here, preferably.
//"percentage" to REAL + NOT_NULL + DEFAULT("100") +
// CHECK ("percentage" >=0 AND "percentage" <= 100
)
Log.d(TAG, "Running: TASKSPLITREPORT_VIEW_CREATE")
db.execSQL("""CREATE VIEW TaskSplitReport AS
SELECT Tasks._id AS _id,
TaskSplit.chargeno AS parenttask,
Tasks.task AS taskdesc,
TaskSplit.percentage AS percentage
FROM Tasks, TaskSplit WHERE Tasks._id = TaskSplit.task"""
)
Log.d(TAG, "Running: SPLIT_INDEX")
db.execSQL("""CREATE UNIQUE INDEX TaskSplit_chargeno_index ON "TaskSplit" ("chargeno")""")
if (newVersion != oldVersion)
db.update("TimeSheetMetadata", "version" to newVersion)
}
2 -> {
Log.d(TAG, "Old DB version <= 2")
Log.d(TAG, "Running: TASK_TABLE_ALTER3")
db.execSQL("""ALTER TABLE "Tasks" ADD COLUMN "split" INTEGER DEFAULT 0""")
Log.d(TAG, "Running: TASKSPLIT_TABLE_CREATE")
db.createTable("TaskSplit", true,
"_id" to INTEGER + PRIMARY_KEY + AUTOINCREMENT,
"chargeno" to INTEGER + NOT_NULL,
"task" to INTEGER + NOT_NULL,
"percentage" to REAL + NOT_NULL + DEFAULT("100"),
FOREIGN_KEY("chargeno", "Tasks", "_id"),
FOREIGN_KEY("task", "Tasks", "_id")
// Need bounds check here, preferably.
//"percentage" to REAL + NOT_NULL + DEFAULT("100") +
// CHECK ("percentage" >=0 AND "percentage" <= 100
)
Log.d(TAG, "Running: TASKSPLITREPORT_VIEW_CREATE")
db.execSQL("""CREATE VIEW TaskSplitReport AS
SELECT Tasks._id AS _id,
TaskSplit.chargeno AS parenttask,
Tasks.task AS taskdesc,
TaskSplit.percentage AS percentage
FROM Tasks, TaskSplit WHERE Tasks._id = TaskSplit.task"""
)
Log.d(TAG, "Running: SPLIT_INDEX")
db.execSQL("""CREATE UNIQUE INDEX TaskSplit_chargeno_index ON "TaskSplit" ("task")""")
if (newVersion != oldVersion)
db.update("TimeSheetMetadata", "version" to newVersion)
}
else -> if (newVersion != oldVersion)
db.update("TimeSheetMetadata", "version" to newVersion)
}
}
}
// Access property for Context
val Context.database: MySqlHelper
get() = MySqlHelper.getInstance(applicationContext)
| apache-2.0 | c553c7172bdb3fb1346225dadef1dcd5 | 47.9 | 127 | 0.529243 | 4.561567 | false | false | false | false |
Saketme/JRAW | lib/src/main/kotlin/net/dean/jraw/references/WikiReference.kt | 2 | 3008 | package net.dean.jraw.references
import com.squareup.moshi.Types
import net.dean.jraw.*
import net.dean.jraw.models.Submission
import net.dean.jraw.models.WikiPage
import net.dean.jraw.models.WikiRevision
import net.dean.jraw.models.internal.RedditModelEnvelope
import net.dean.jraw.pagination.BarebonesPaginator
/**
* A WikiReference is a reference to a specific subreddit's wiki.
*
* @property subreddit The name of the subreddit without the "/r/" prefix.
*/
class WikiReference internal constructor(reddit: RedditClient, val subreddit: String) : AbstractReference(reddit) {
/** Fetches the names of all accessible wiki pages. */
@EndpointImplementation(Endpoint.GET_WIKI_PAGES)
fun pages(): List<String> {
val res = reddit.request { it.endpoint(Endpoint.GET_WIKI_PAGES, subreddit) }
val adapter = JrawUtils.moshi.adapter<RedditModelEnvelope<List<String>>>(pagesType)
return res.deserializeWith(adapter).data
}
/** Fetches information about a given wiki page */
@EndpointImplementation(Endpoint.GET_WIKI_PAGE)
fun page(name: String): WikiPage {
return reddit.request {
it.endpoint(Endpoint.GET_WIKI_PAGE, subreddit, name)
}.deserializeEnveloped()
}
/** Updates a given wiki page */
@EndpointImplementation(Endpoint.POST_WIKI_EDIT)
fun update(page: String, content: String, reason: String) {
reddit.request {
it.endpoint(Endpoint.POST_WIKI_EDIT, subreddit)
.post(mapOf(
"content" to content,
"page" to page,
"reason" to reason
))
}
}
/** Returns a Paginator.Builder that iterates through all revisions of all wiki pages */
@EndpointImplementation(Endpoint.GET_WIKI_REVISIONS, type = MethodType.NON_BLOCKING_CALL)
fun revisions(): BarebonesPaginator.Builder<WikiRevision> =
BarebonesPaginator.Builder.create(reddit, "/r/$subreddit/wiki/revisions")
/** Returns a Paginator.Builder that iterates through all revisions of a specific wiki page */
@EndpointImplementation(Endpoint.GET_WIKI_REVISIONS_PAGE, type = MethodType.NON_BLOCKING_CALL)
fun revisionsFor(page: String): BarebonesPaginator.Builder<WikiRevision> =
BarebonesPaginator.Builder.create(reddit, "/r/$subreddit/wiki/revisions/$page")
/** Returns a Paginator.Builder that iterates through all Submissions that link to this specific wiki page */
@EndpointImplementation(Endpoint.GET_WIKI_DISCUSSIONS_PAGE, type = MethodType.NON_BLOCKING_CALL)
fun discussionsAbout(page: String): BarebonesPaginator.Builder<Submission> =
BarebonesPaginator.Builder.create(reddit, "/r/$subreddit/wiki/discussions/$page")
/** */
companion object {
// RedditModelEnvelope<List<String>>
private val pagesType = Types.newParameterizedType(RedditModelEnvelope::class.java,
Types.newParameterizedType(List::class.java, String::class.java))
}
}
| mit | 7599151333540ba8323ce668e8e88934 | 43.895522 | 115 | 0.704787 | 4.378457 | false | false | false | false |
ligi/PassAndroid | android/src/androidTest/java/org/ligi/passandroid/TestApp.kt | 1 | 1833 | package org.ligi.passandroid
import org.koin.core.module.Module
import org.koin.dsl.module
import org.ligi.passandroid.injections.FixedPassListPassStore
import org.ligi.passandroid.model.PassStore
import org.ligi.passandroid.model.Settings
import org.ligi.passandroid.model.comparator.PassSortOrder
import org.ligi.passandroid.model.pass.BarCode
import org.ligi.passandroid.model.pass.Pass
import org.ligi.passandroid.model.pass.PassBarCodeFormat
import org.ligi.passandroid.model.pass.PassImpl
import org.mockito.Mockito.`when`
import org.mockito.Mockito.mock
import java.io.File
import java.util.*
class TestApp : App() {
override fun createKoin(): Module {
return module {
single { passStore as PassStore }
single { settings }
single { tracker }
}
}
companion object {
val tracker = mock(Tracker::class.java)
val passStore = FixedPassListPassStore(emptyList())
val settings = mock(Settings::class.java).apply {
`when`(getSortOrder()).thenReturn(PassSortOrder.DATE_ASC)
`when`(getPassesDir()).thenReturn(File(""))
`when`(doTraceDroidEmailSend()).thenReturn(false)
}
fun populatePassStoreWithSinglePass() {
val passList = ArrayList<Pass>()
val pass = PassImpl(UUID.randomUUID().toString())
pass.description = "description"
pass.barCode = BarCode(PassBarCodeFormat.AZTEC, "messageprobe")
passList.add(pass)
fixedPassListPassStore().setList(passList)
passStore.classifier.moveToTopic(pass, "test")
}
fun emptyPassStore() {
fixedPassListPassStore().setList(emptyList())
}
private fun fixedPassListPassStore() = passStore as FixedPassListPassStore
}
}
| gpl-3.0 | 972f0fc016424460735fc3c553fb7731 | 30.603448 | 82 | 0.677578 | 4.243056 | false | false | false | false |
blindpirate/gradle | subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/provider/KotlinScriptClassPathProvider.kt | 1 | 8601 | /*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.kotlin.dsl.provider
import org.gradle.api.Project
import org.gradle.api.artifacts.Dependency
import org.gradle.api.artifacts.SelfResolvingDependency
import org.gradle.api.file.FileCollection
import org.gradle.api.internal.ClassPathRegistry
import org.gradle.api.internal.artifacts.dsl.dependencies.DependencyFactory
import org.gradle.api.internal.classpath.ModuleRegistry
import org.gradle.api.internal.file.FileCollectionFactory
import org.gradle.api.internal.initialization.ClassLoaderScope
import org.gradle.internal.classloader.ClassLoaderVisitor
import org.gradle.internal.classpath.ClassPath
import org.gradle.internal.classpath.DefaultClassPath
import org.gradle.kotlin.dsl.codegen.generateApiExtensionsJar
import org.gradle.kotlin.dsl.support.gradleApiMetadataModuleName
import org.gradle.kotlin.dsl.support.isGradleKotlinDslJar
import org.gradle.kotlin.dsl.support.isGradleKotlinDslJarName
import org.gradle.kotlin.dsl.support.ProgressMonitor
import org.gradle.kotlin.dsl.support.serviceOf
import org.gradle.util.internal.GFileUtils.moveFile
import com.google.common.annotations.VisibleForTesting
import org.gradle.api.internal.file.temp.TemporaryFileProvider
import java.io.File
import java.net.URI
import java.net.URISyntaxException
import java.net.URL
import java.util.concurrent.ConcurrentHashMap
fun gradleKotlinDslOf(project: Project): List<File> =
kotlinScriptClassPathProviderOf(project).run {
gradleKotlinDsl.asFiles
}
fun gradleKotlinDslJarsOf(project: Project): FileCollection =
project.fileCollectionOf(
kotlinScriptClassPathProviderOf(project).gradleKotlinDslJars.asFiles.filter(::isGradleKotlinDslJar),
"gradleKotlinDsl"
)
internal
fun Project.fileCollectionOf(files: Collection<File>, name: String): FileCollection =
serviceOf<FileCollectionFactory>().fixed(name, files)
internal
fun kotlinScriptClassPathProviderOf(project: Project) =
project.serviceOf<KotlinScriptClassPathProvider>()
internal
typealias JarCache = (String, JarGenerator) -> File
internal
typealias JarGenerator = (File) -> Unit
private
typealias JarGeneratorWithProgress = (File, () -> Unit) -> Unit
internal
typealias JarsProvider = () -> Collection<File>
class KotlinScriptClassPathProvider(
val moduleRegistry: ModuleRegistry,
val classPathRegistry: ClassPathRegistry,
val coreAndPluginsScope: ClassLoaderScope,
val gradleApiJarsProvider: JarsProvider,
val jarCache: JarCache,
val temporaryFileProvider: TemporaryFileProvider,
val progressMonitorProvider: JarGenerationProgressMonitorProvider
) {
/**
* Generated Gradle API jar plus supporting libraries such as groovy-all.jar and generated API extensions.
*/
@VisibleForTesting
val gradleKotlinDsl: ClassPath by lazy {
gradleApi + gradleApiExtensions + gradleKotlinDslJars
}
private
val gradleApi: ClassPath by lazy {
DefaultClassPath.of(gradleApiJarsProvider())
}
/**
* Generated extensions to the Gradle API.
*/
private
val gradleApiExtensions: ClassPath by lazy {
DefaultClassPath.of(gradleKotlinDslExtensions())
}
/**
* gradle-kotlin-dsl.jar plus kotlin libraries.
*/
internal
val gradleKotlinDslJars: ClassPath by lazy {
DefaultClassPath.of(gradleKotlinDslJars())
}
/**
* The Gradle implementation classpath which should **NOT** be visible
* in the compilation classpath of any script.
*/
private
val gradleImplementationClassPath: Set<File> by lazy {
cachedClassLoaderClassPath.of(coreAndPluginsScope.exportClassLoader)
}
fun compilationClassPathOf(scope: ClassLoaderScope): ClassPath =
cachedScopeCompilationClassPath.computeIfAbsent(scope, ::computeCompilationClassPath)
private
fun computeCompilationClassPath(scope: ClassLoaderScope): ClassPath {
return gradleKotlinDsl + exportClassPathFromHierarchyOf(scope)
}
fun exportClassPathFromHierarchyOf(scope: ClassLoaderScope): ClassPath {
require(scope.isLocked) {
"$scope must be locked before it can be used to compute a classpath!"
}
val exportedClassPath = cachedClassLoaderClassPath.of(scope.exportClassLoader)
return DefaultClassPath.of(exportedClassPath - gradleImplementationClassPath)
}
private
fun gradleKotlinDslExtensions(): File =
produceFrom("kotlin-dsl-extensions") { outputFile, onProgress ->
generateApiExtensionsJar(temporaryFileProvider, outputFile, gradleJars, gradleApiMetadataJar, onProgress)
}
private
fun produceFrom(id: String, generate: JarGeneratorWithProgress): File =
jarCache(id) { outputFile ->
progressMonitorFor(outputFile, 3).use { progressMonitor ->
generateAtomically(outputFile) { generate(it, progressMonitor::onProgress) }
}
}
private
fun generateAtomically(outputFile: File, generate: JarGenerator) {
val tempFile = tempFileFor(outputFile)
generate(tempFile)
moveFile(tempFile, outputFile)
}
private
fun progressMonitorFor(outputFile: File, totalWork: Int): ProgressMonitor =
progressMonitorProvider.progressMonitorFor(outputFile, totalWork)
private
fun tempFileFor(outputFile: File): File =
temporaryFileProvider.createTemporaryFile(outputFile.nameWithoutExtension, outputFile.extension).apply {
// This is here as a safety measure in case the process stops before moving this file to it's destination.
deleteOnExit()
}
private
fun gradleKotlinDslJars(): List<File> =
gradleJars.filter { file ->
file.name.let { isKotlinJar(it) || isGradleKotlinDslJarName(it) }
}
private
val gradleJars by lazy {
classPathRegistry.getClassPath(gradleApiNotation.name).asFiles
}
private
val gradleApiMetadataJar by lazy {
moduleRegistry.getExternalModule(gradleApiMetadataModuleName).classpath.asFiles.single()
}
private
val cachedScopeCompilationClassPath = ConcurrentHashMap<ClassLoaderScope, ClassPath>()
private
val cachedClassLoaderClassPath = ClassLoaderClassPathCache()
}
internal
fun gradleApiJarsProviderFor(dependencyFactory: DependencyFactory): JarsProvider =
{ (dependencyFactory.gradleApi() as SelfResolvingDependency).resolve() }
private
fun DependencyFactory.gradleApi(): Dependency =
createDependency(gradleApiNotation)
private
val gradleApiNotation = DependencyFactory.ClassPathNotation.GRADLE_API
private
fun isKotlinJar(name: String): Boolean =
name.startsWith("kotlin-stdlib-")
|| name.startsWith("kotlin-reflect-")
private
class ClassLoaderClassPathCache {
private
val cachedClassPaths = hashMapOf<ClassLoader, Set<File>>()
fun of(classLoader: ClassLoader): Set<File> =
cachedClassPaths.getOrPut(classLoader) {
classPathOf(classLoader)
}
private
fun classPathOf(classLoader: ClassLoader): Set<File> {
val classPathFiles = mutableSetOf<File>()
object : ClassLoaderVisitor() {
override fun visitClassPath(classPath: Array<URL>) {
classPath.forEach { url ->
if (url.protocol == "file") {
classPathFiles.add(fileFrom(url))
}
}
}
override fun visitParent(classLoader: ClassLoader) {
classPathFiles.addAll(of(classLoader))
}
}.visit(classLoader)
return classPathFiles
}
private
fun fileFrom(url: URL) = File(toURI(url))
}
private
fun toURI(url: URL): URI =
try {
url.toURI()
} catch (e: URISyntaxException) {
URL(
url.protocol,
url.host,
url.port,
url.file.replace(" ", "%20")
).toURI()
}
| apache-2.0 | 965b6afdf9b90e55bc2b0966e3b8ca45 | 29.392226 | 118 | 0.719916 | 4.765097 | false | false | false | false |
blindpirate/gradle | subprojects/configuration-cache/src/main/kotlin/org/gradle/configurationcache/serialization/Combinators.kt | 1 | 11048 | /*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.configurationcache.serialization
import org.gradle.configurationcache.extensions.uncheckedCast
import org.gradle.configurationcache.extensions.useToRun
import org.gradle.configurationcache.problems.DocumentationSection
import org.gradle.configurationcache.problems.StructuredMessageBuilder
import org.gradle.internal.classpath.ClassPath
import org.gradle.internal.classpath.DefaultClassPath
import org.gradle.internal.serialize.BaseSerializerFactory
import org.gradle.internal.serialize.Decoder
import org.gradle.internal.serialize.Encoder
import org.gradle.internal.serialize.Serializer
import java.io.File
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import kotlin.coroutines.Continuation
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.coroutineContext
import kotlin.coroutines.startCoroutine
import kotlin.coroutines.suspendCoroutine
internal
fun <T> singleton(value: T): Codec<T> =
SingletonCodec(value)
internal
inline fun <reified T : Any> unsupported(
documentationSection: DocumentationSection = DocumentationSection.RequirementsDisallowedTypes
): Codec<T> = codec(
encode = { value ->
logUnsupported("serialize", T::class, value.javaClass, documentationSection)
},
decode = {
logUnsupported("deserialize", T::class, documentationSection)
null
}
)
internal
inline fun <reified T : Any> unsupported(
description: String,
documentationSection: DocumentationSection = DocumentationSection.RequirementsDisallowedTypes
) = unsupported<T>(documentationSection) {
text(description)
}
internal
inline fun <reified T : Any> unsupported(
documentationSection: DocumentationSection = DocumentationSection.RequirementsDisallowedTypes,
noinline unsupportedMessage: StructuredMessageBuilder
): Codec<T> = codec(
encode = {
logUnsupported("serialize", documentationSection, unsupportedMessage)
},
decode = {
logUnsupported("deserialize", documentationSection, unsupportedMessage)
null
}
)
internal
fun <T> codec(
encode: suspend WriteContext.(T) -> Unit,
decode: suspend ReadContext.() -> T?
): Codec<T> = object : Codec<T> {
override suspend fun WriteContext.encode(value: T) = encode(value)
override suspend fun ReadContext.decode(): T? = decode()
}
internal
inline fun <reified T> ReadContext.ownerService() =
ownerService(T::class.java)
internal
fun <T> ReadContext.ownerService(serviceType: Class<T>) =
isolate.owner.service(serviceType)
internal
fun <T : Any> reentrant(codec: Codec<T>): Codec<T> = object : Codec<T> {
var encodeCall: EncodeFrame<T>? = null
var decodeCall: DecodeFrame<T?>? = null
override suspend fun WriteContext.encode(value: T) {
when (encodeCall) {
null -> {
encodeCall = EncodeFrame(value, null)
encodeLoop(coroutineContext)
}
else -> suspendCoroutine<Unit> { k ->
encodeCall = EncodeFrame(value, k)
}
}
}
override suspend fun ReadContext.decode(): T? =
when {
immediateMode -> {
codec.run { decode() }
}
decodeCall == null -> {
decodeCall = DecodeFrame(null)
decodeLoop(coroutineContext)
}
else -> suspendCoroutine { k ->
decodeCall = DecodeFrame(k)
}
}
private
fun WriteContext.encodeLoop(coroutineContext: CoroutineContext) {
do {
val call = encodeCall!!
suspend {
codec.run {
encode(call.value)
}
}.startCoroutine(
Continuation(coroutineContext) {
when (val k = call.k) {
null -> {
encodeCall = null
it.getOrThrow()
}
else -> k.resumeWith(it)
}
}
)
} while (encodeCall != null)
}
private
fun ReadContext.decodeLoop(coroutineContext: CoroutineContext): T? {
var result: T? = null
do {
val call = decodeCall!!
suspend {
codec.run { decode() }
}.startCoroutine(
Continuation(coroutineContext) {
when (val k = call.k) {
null -> {
decodeCall = null
result = it.getOrThrow()
}
else -> k.resumeWith(it)
}
}
)
} while (decodeCall != null)
return result
}
}
private
class DecodeFrame<T>(val k: Continuation<T>?)
private
data class EncodeFrame<T>(val value: T, val k: Continuation<Unit>?)
private
data class SingletonCodec<T>(
private val singleton: T
) : Codec<T> {
override suspend fun WriteContext.encode(value: T) = Unit
override suspend fun ReadContext.decode(): T? = singleton
}
internal
data class SerializerCodec<T>(val serializer: Serializer<T>) : Codec<T> {
override suspend fun WriteContext.encode(value: T) = serializer.write(this, value)
override suspend fun ReadContext.decode(): T = serializer.read(this)
}
internal
fun WriteContext.writeClassArray(values: Array<Class<*>>) {
writeArray(values) { writeClass(it) }
}
internal
fun ReadContext.readClassArray(): Array<Class<*>> =
readArray { readClass() }
internal
suspend fun ReadContext.readList(): List<Any?> =
readList { read() }
internal
inline fun <T : Any?> ReadContext.readList(readElement: () -> T): List<T> =
readCollectionInto({ size -> ArrayList(size) }) {
readElement()
}
internal
suspend fun WriteContext.writeCollection(value: Collection<*>) {
writeCollection(value) { write(it) }
}
internal
suspend fun <T : MutableCollection<Any?>> ReadContext.readCollectionInto(factory: (Int) -> T): T =
readCollectionInto(factory) { read() }
internal
suspend fun WriteContext.writeMap(value: Map<*, *>) {
writeSmallInt(value.size)
writeMapEntries(value)
}
internal
suspend fun WriteContext.writeMapEntries(value: Map<*, *>) {
for (entry in value.entries) {
write(entry.key)
write(entry.value)
}
}
internal
suspend fun <T : MutableMap<Any?, Any?>> ReadContext.readMapInto(factory: (Int) -> T): T {
val size = readSmallInt()
val items = factory(size)
readMapEntriesInto(items, size)
return items
}
internal
suspend fun <K, V, T : MutableMap<K, V>> ReadContext.readMapEntriesInto(items: T, size: Int) {
@Suppress("unchecked_cast")
for (i in 0 until size) {
val key = read() as K
val value = read() as V
items[key] = value
}
}
internal
fun Encoder.writeClassPath(classPath: ClassPath) {
writeCollection(classPath.asFiles) {
writeFile(it)
}
}
internal
fun Decoder.readClassPath(): ClassPath {
val size = readSmallInt()
val builder = DefaultClassPath.builderWithExactSize(size)
for (i in 0 until size) {
builder.add(readFile())
}
return builder.build()
}
internal
fun Encoder.writeFile(file: File?) {
BaseSerializerFactory.FILE_SERIALIZER.write(this, file)
}
internal
fun Decoder.readFile(): File =
BaseSerializerFactory.FILE_SERIALIZER.read(this)
internal
fun Encoder.writeStrings(strings: Collection<String>) {
writeCollection(strings) {
writeString(it)
}
}
internal
fun Decoder.readStrings(): List<String> =
readCollectionInto({ size -> ArrayList(size) }) {
readString()
}
internal
inline fun <T> Encoder.writeCollection(collection: Collection<T>, writeElement: (T) -> Unit) {
writeSmallInt(collection.size)
for (element in collection) {
writeElement(element)
}
}
internal
inline fun Decoder.readCollection(readElement: () -> Unit) {
val size = readSmallInt()
for (i in 0 until size) {
readElement()
}
}
internal
inline fun <T, C : MutableCollection<T>> Decoder.readCollectionInto(
containerForSize: (Int) -> C,
readElement: () -> T
): C {
val size = readSmallInt()
val container = containerForSize(size)
for (i in 0 until size) {
container.add(readElement())
}
return container
}
internal
inline fun <T : Any?> WriteContext.writeArray(array: Array<T>, writeElement: (T) -> Unit) {
writeClass(array.javaClass.componentType)
writeSmallInt(array.size)
for (element in array) {
writeElement(element)
}
}
internal
inline fun <T : Any?> ReadContext.readArray(readElement: () -> T): Array<T> {
val componentType = readClass()
val size = readSmallInt()
val array: Array<T> = java.lang.reflect.Array.newInstance(componentType, size).uncheckedCast()
for (i in 0 until size) {
array[i] = readElement()
}
return array
}
fun <E : Enum<E>> Encoder.writeEnum(value: E) {
writeSmallInt(value.ordinal)
}
inline fun <reified E : Enum<E>> Decoder.readEnum(): E =
readSmallInt().let { ordinal -> enumValues<E>()[ordinal] }
fun Encoder.writeShort(value: Short) {
BaseSerializerFactory.SHORT_SERIALIZER.write(this, value)
}
fun Decoder.readShort(): Short =
BaseSerializerFactory.SHORT_SERIALIZER.read(this)
fun Encoder.writeFloat(value: Float) {
BaseSerializerFactory.FLOAT_SERIALIZER.write(this, value)
}
fun Decoder.readFloat(): Float =
BaseSerializerFactory.FLOAT_SERIALIZER.read(this)
fun Encoder.writeDouble(value: Double) {
BaseSerializerFactory.DOUBLE_SERIALIZER.write(this, value)
}
fun Decoder.readDouble(): Double =
BaseSerializerFactory.DOUBLE_SERIALIZER.read(this)
inline
fun <reified T : Any> ReadContext.readClassOf(): Class<out T> =
readClass().asSubclass(T::class.java)
/**
* Workaround for serializing JDK types with complex/opaque state on Java 17+.
*
* **IMPORTANT** Should be avoided for composite/container types as all components would be serialized
* using Java serialization.
*/
internal
fun WriteContext.encodeUsingJavaSerialization(value: Any) {
ObjectOutputStream(outputStream).useToRun {
writeObject(value)
}
}
internal
fun ReadContext.decodeUsingJavaSerialization(): Any? =
ObjectInputStream(inputStream).readObject()
| apache-2.0 | 23e6527f594a59ad8dc058bde98f3481 | 24.515012 | 102 | 0.655865 | 4.278854 | false | false | false | false |
bertilxi/DC-Android | app/src/main/java/utnfrsf/dondecurso/activity/SetupActivity.kt | 1 | 2475 | package utnfrsf.dondecurso.activity
import android.os.Bundle
import android.support.design.widget.FloatingActionButton
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.widget.AdapterView
import android.widget.Spinner
import android.widget.TextView
import io.paperdb.Paper
import utnfrsf.dondecurso.R
import utnfrsf.dondecurso.common.async
import utnfrsf.dondecurso.common.findView
import utnfrsf.dondecurso.common.launchActivity
import utnfrsf.dondecurso.common.onUI
import utnfrsf.dondecurso.domain.Carrera
import utnfrsf.dondecurso.view.MyArrayAdapter
class SetupActivity : AppCompatActivity() {
private val spinner: Spinner by lazy { findView<Spinner>(R.id.spinner_carrera) }
private val textViewError: TextView by lazy { findView<TextView>(R.id.textview_error) }
private val fab: FloatingActionButton by lazy { findView<FloatingActionButton>(R.id.fab_setup) }
private var carreras: ArrayList<Carrera> = ArrayList<Carrera>()
private var carrera: Carrera? = null
private var adapter: MyArrayAdapter<Carrera>? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_setup)
async {
carreras = Paper.book().read("carreras", ArrayList<Carrera>())
onUI { setupView() }
}
}
fun setupView(){
adapter = MyArrayAdapter(this@SetupActivity, R.layout.spinner_item, carreras, false)
spinner.adapter = adapter
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {
carrera = null
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
carrera = carreras[position]
if(carrera!!.id == 0) carrera = null
}
}
fab.setOnClickListener {
if(carrera == null) {
textViewError.visibility = View.VISIBLE
textViewError.text = ""
textViewError.error = "Seleccione una carrera por favor"
return@setOnClickListener
}
async {
Paper.book().write("carrera", carrera)
onUI {
launchActivity(MainActivity())
finish()
}
}
}
}
}
| mit | b352eefaecbde1c456b1047af0c96260 | 34.869565 | 104 | 0.653333 | 4.209184 | false | false | false | false |
kelsos/mbrc | app/src/main/kotlin/com/kelsos/mbrc/ui/navigation/nowplaying/NowPlayingAdapter.kt | 1 | 5762 | package com.kelsos.mbrc.ui.navigation.nowplaying
import android.app.Activity
import android.graphics.Color
import android.view.LayoutInflater
import android.view.MotionEvent.ACTION_DOWN
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.RecyclerView
import butterknife.BindView
import butterknife.ButterKnife
import com.kelsos.mbrc.R
import com.kelsos.mbrc.data.NowPlaying
import com.kelsos.mbrc.ui.drag.ItemTouchHelperAdapter
import com.kelsos.mbrc.ui.drag.OnStartDragListener
import com.kelsos.mbrc.ui.drag.TouchHelperViewHolder
import com.raizlabs.android.dbflow.kotlinextensions.delete
import com.raizlabs.android.dbflow.kotlinextensions.save
import com.raizlabs.android.dbflow.list.FlowCursorList
import com.raizlabs.android.dbflow.list.FlowCursorList.OnCursorRefreshListener
import timber.log.Timber
import javax.inject.Inject
class NowPlayingAdapter
@Inject constructor(context: Activity) : RecyclerView.Adapter<NowPlayingAdapter.TrackHolder>(),
ItemTouchHelperAdapter,
OnCursorRefreshListener<NowPlaying> {
private val dragStartListener: OnStartDragListener = context as OnStartDragListener
private var data: FlowCursorList<NowPlaying>? = null
private var playingTrackIndex: Int = 0
private var currentTrack: String = ""
private val inflater: LayoutInflater = LayoutInflater.from(context)
private var listener: NowPlayingListener? = null
private fun setPlayingTrack(index: Int) {
notifyItemChanged(playingTrackIndex)
this.playingTrackIndex = index
notifyItemChanged(index)
}
fun getPlayingTrackIndex(): Int {
return this.playingTrackIndex
}
fun setPlayingTrack(path: String) {
val data = this.data ?: return
this.currentTrack = path
data.forEachIndexed { index, (_, _, itemPath) ->
if (itemPath.equals(path)) {
setPlayingTrack(index)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TrackHolder {
val inflatedView = inflater.inflate(R.layout.ui_list_track_item, parent, false)
val holder = TrackHolder(inflatedView)
holder.itemView.setOnClickListener { onClick(holder) }
holder.container.setOnClickListener { onClick(holder) }
holder.dragHandle.setOnTouchListener { view, motionEvent ->
view.performClick()
if (motionEvent.action == ACTION_DOWN) {
dragStartListener.onStartDrag(holder)
}
return@setOnTouchListener false
}
return holder
}
private fun onClick(holder: TrackHolder) {
val listener = this.listener ?: return
val position = holder.adapterPosition
setPlayingTrack(position)
listener.onPress(position)
}
override fun onBindViewHolder(holder: TrackHolder, position: Int) {
val (title, artist) = data?.getItem(position.toLong()) ?: return
holder.title.text = title
holder.artist.text = artist
if (position == playingTrackIndex) {
holder.trackPlaying.setImageResource(R.drawable.ic_media_now_playing)
} else {
holder.trackPlaying.setImageResource(android.R.color.transparent)
}
}
override fun getItemCount(): Int {
return data?.count?.toInt() ?: 0
}
override fun onItemMove(from: Int, to: Int): Boolean {
swapPositions(from, to)
listener?.onMove(from, to)
notifyItemMoved(from, to)
if (currentTrack.isNotBlank()) {
setPlayingTrack(currentTrack)
}
return true
}
private fun swapPositions(from: Int, to: Int) {
val data = this.data ?: return
Timber.v("Swapping %d => %d", from, to)
val fromTrack = data.getItem(from.toLong()) ?: return
val toTrack = data.getItem(to.toLong()) ?: return
Timber.v("from => %s to => %s", fromTrack, toTrack)
val position = toTrack.position
toTrack.position = fromTrack.position
fromTrack.position = position
toTrack.save()
fromTrack.save()
// Before saving remove the listener to avoid interrupting the swapping functionality
data.removeOnCursorRefreshListener(this)
data.refresh()
data.addOnCursorRefreshListener(this)
Timber.v("after swap => from => %s to => %s", fromTrack, toTrack)
}
override fun onItemDismiss(position: Int) {
val nowPlaying = data?.getItem(position.toLong())
nowPlaying?.let {
it.delete()
refresh()
notifyItemRemoved(position)
listener?.onDismiss(position)
}
}
fun refresh() {
data?.refresh()
}
fun update(cursor: FlowCursorList<NowPlaying>) {
this.data = cursor
notifyDataSetChanged()
}
fun setListener(listener: NowPlayingListener) {
this.listener = listener
}
/**
* Callback when data refreshes.
* @param cursorList The object that changed.
*/
override fun onCursorRefreshed(cursorList: FlowCursorList<NowPlaying>) {
notifyDataSetChanged()
}
interface NowPlayingListener {
fun onPress(position: Int)
fun onMove(from: Int, to: Int)
fun onDismiss(position: Int)
}
class TrackHolder(itemView: View) : RecyclerView.ViewHolder(itemView), TouchHelperViewHolder {
@BindView(R.id.track_title)
lateinit var title: TextView
@BindView(R.id.track_artist)
lateinit var artist: TextView
@BindView(R.id.track_indicator_view)
lateinit var trackPlaying: ImageView
@BindView(R.id.track_container)
lateinit var container: ConstraintLayout
@BindView(R.id.drag_handle)
lateinit var dragHandle: View
init {
ButterKnife.bind(this, itemView)
}
override fun onItemSelected() {
this.itemView.setBackgroundColor(Color.DKGRAY)
}
override fun onItemClear() {
this.itemView.setBackgroundColor(0)
}
}
}
| gpl-3.0 | bc8c984fd0941bd6f70129f3cbbe1e93 | 27.524752 | 96 | 0.724922 | 4.293592 | false | false | false | false |
InsideZhou/Instep | dao/src/main/kotlin/instep/dao/sql/ColumnExtensions.kt | 1 | 3930 | @file:Suppress("unused")
package instep.dao.sql
infix fun Column<*>.eq(value: Any): ColumnCondition = ColumnCondition(this, "= ${this.table.dialect.placeholderForParameter(this)}", value)
infix fun Column<*>.notEQ(value: Any): ColumnCondition = ColumnCondition(this, "<> ${this.table.dialect.placeholderForParameter(this)}", value)
infix fun Column<*>.gt(value: Any): ColumnCondition = ColumnCondition(this, "> ${this.table.dialect.placeholderForParameter(this)}", value)
infix fun Column<*>.gte(value: Any): ColumnCondition = ColumnCondition(this, ">= ${this.table.dialect.placeholderForParameter(this)}", value)
infix fun Column<*>.lt(value: Any): ColumnCondition = ColumnCondition(this, "< ${this.table.dialect.placeholderForParameter(this)}", value)
infix fun Column<*>.lte(value: Any): ColumnCondition = ColumnCondition(this, "<= ${this.table.dialect.placeholderForParameter(this)}", value)
fun Column<*>.isNull(): ColumnCondition = ColumnCondition(this, "IS NULL")
fun Column<*>.notNull(): ColumnCondition = ColumnCondition(this, "IS NOT NULL")
infix fun Column<*>.inArray(values: Array<*>): ColumnCondition {
val placeholder = this.table.dialect.placeholderForParameter(this)
val builder = StringBuilder("IN (")
values.forEach { _ ->
builder.append("$placeholder,")
}
builder.deleteCharAt(builder.length - 1)
builder.append(")")
val condition = ColumnCondition(this, builder.toString())
condition.addParameters(*values)
return condition
}
infix fun StringColumn.startsWith(value: String): ColumnCondition = ColumnCondition(this, "LIKE ${this.table.dialect.placeholderForParameter(this)}", "$value%")
infix fun StringColumn.endsWith(value: String): ColumnCondition = ColumnCondition(this, "LIKE ${this.table.dialect.placeholderForParameter(this)}", "%$value")
infix fun StringColumn.contains(value: String): ColumnCondition = ColumnCondition(this, "LIKE ${this.table.dialect.placeholderForParameter(this)}", "%$value%")
infix fun <T : Enum<*>> IntegerColumn.gt(value: T): ColumnCondition = gt(value.ordinal)
infix fun <T : Enum<*>> IntegerColumn.gte(value: T): ColumnCondition = gte(value.ordinal)
infix fun <T : Enum<*>> IntegerColumn.lt(value: T): ColumnCondition = lt(value.ordinal)
infix fun <T : Enum<*>> IntegerColumn.lte(value: T): ColumnCondition = lte(value.ordinal)
infix fun <T : Enum<*>> IntegerColumn.inArray(value: Array<T>): ColumnCondition = inArray(value.map { it.ordinal }.toTypedArray())
@JvmOverloads
fun Column<*>.alias(alias: String = "") = ColumnSelectExpression(this, alias.ifBlank { "${table.tableName}_$name" })
@JvmOverloads
fun Column<*>.count(alias: String = "") = SelectExpression("count(${qualifiedName})", alias)
@JvmOverloads
fun NumberColumn<*>.sum(alias: String = "") = SelectExpression("sum(${qualifiedName})", alias)
@JvmOverloads
fun NumberColumn<*>.avg(alias: String = "") = SelectExpression("avg(${qualifiedName})", alias)
@JvmOverloads
fun NumberColumn<*>.max(alias: String = "") = SelectExpression("max(${qualifiedName})", alias)
@JvmOverloads
fun NumberColumn<*>.min(alias: String = "") = SelectExpression("min(${qualifiedName})", alias)
@JvmOverloads
fun DateTimeColumn.max(alias: String = "") = SelectExpression("max(${qualifiedName})", alias)
@JvmOverloads
fun DateTimeColumn.min(alias: String = "") = SelectExpression("min(${qualifiedName})", alias)
@JvmOverloads
fun Column<*>.asc(nullFirst: Boolean = false): OrderBy {
val column = this
return object : OrderBy {
override val column: Column<*> = column
override val descending: Boolean = false
override val nullFirst: Boolean = nullFirst
}
}
@JvmOverloads
fun Column<*>.desc(nullFirst: Boolean = false): OrderBy {
val column = this
return object : OrderBy {
override val column: Column<*> = column
override val descending: Boolean = true
override val nullFirst: Boolean = nullFirst
}
}
| bsd-2-clause | aa5113768d1b509760d823f24564374b | 44.172414 | 160 | 0.719084 | 4.141201 | false | false | false | false |
team401/SnakeSkin | SnakeSkin-Core/src/main/kotlin/org/snakeskin/state/StateMachine.kt | 1 | 8447 | package org.snakeskin.state
import org.snakeskin.ability.IWaitable
import org.snakeskin.executor.ExceptionHandlingRunnable
import org.snakeskin.executor.IExecutorTaskHandle
import org.snakeskin.logic.NullWaitable
import org.snakeskin.logic.TickedWaitable
import org.snakeskin.logic.WaitableFuture
import org.snakeskin.measure.Seconds
import org.snakeskin.runtime.SnakeskinRuntime
import org.snakeskin.subsystem.States
import org.snakeskin.utility.value.HistoryValue
import java.util.concurrent.locks.ReentrantLock
/**
* @author Cameron Earle
* @version 8/3/17
*
* The type parameter (T) is really just a mask
* that allows your IDE to fill in state names for you
* and ensure that you don't put the wrong state name in the wrong place
*/
class StateMachine<T> {
private val executor = SnakeskinRuntime.primaryExecutor
private val states = hashMapOf<Any, State<*>>() //List of states that this state machine has
private val globalRejections = hashMapOf<List<*>, () -> Boolean>() //Map of global rejection conditions for specific states
private var registered = false //Becomes true once the parent subsystem calls "register". Prevents disabled subsystems from running.
init {
//Register default state implementations
states[States.DISABLED] = State(States.DISABLED)
}
/**
* Adds a global rejection to the state machine, which will
* reject all of the given states if the condition is met
*
* If no states are passed, the rejection condition will reject ALL states if the condition is met
* Note that this case will also prevent your state machine from disabling, so be careful when using this.
*
* Makes cleaner syntax for rejecting a bunch of states for one reason
*/
fun addGlobalRejection(states: List<T>, condition: () -> Boolean) {
globalRejections[states] = condition
}
private fun isGloballyRejected(state: Any): Boolean {
for (pair in globalRejections) {
if (pair.key.isEmpty() || pair.key.contains(state)) { //If this key-value pair contains the given state OR the list is empty (reject ALL)
if (pair.value()) { //If this pair's rejection case evaluates true
return true
}
}
}
return false //State is not rejected
}
private fun checkSwitchConditions(stateName: Any): Boolean {
if (!registered) return false //Do not allow transitions on non-registered machines
if (stateName == activeState?.name) return false //Do not allow transitions to the same state
val state = states[stateName] ?: return false //Do not allow transitions to a state which isn't defined
//Evaluate rejection conditions for the incoming state
if (isGloballyRejected(stateName)) return false
if (state.rejectionConditions()) return false
return true //Switching is permitted
}
/**
* Adds a state to this state machine
* @param state The state to add
*/
fun addState(state: State<*>) {
states[state.name as Any] = state
}
private var activeState: State<*>? = null
private var activeTimeoutHandle: IExecutorTaskHandle? = null //Represents the timeout that the state machine is currently running
private val stateHistory = HistoryValue<Any?>(null) //State logic ignores T
private fun startTransition(desiredState: Any): Boolean {
if (!checkSwitchConditions(desiredState)) {
return false //Do not transition if conditions are not met
}
activeTimeoutHandle?.stopTask(true) //Stop any potential timeouts
activeState?.actionManager?.stopAction() //Stop the currently running action loop.
return true
}
private fun finishTransition(state: Any, waitable: TickedWaitable?) {
activeState?.actionManager?.awaitDone() //Wait for the current action loop to finish (this is re-entrant safe)
activeState?.exit?.run() //Run the exit and wait
activeState = states[state] //Update the active state to the new state
stateHistory.update(activeState!!.name) //Update the state history to the new state
activeState?.entry?.run()
waitable?.tick()
if (activeState?.timeout?.value != -1.0) {
activeTimeoutHandle = executor.scheduleSingleTask(ExceptionHandlingRunnable {
activeState?.timeoutTo?.let { setStateFromAction(it, false) }
}, activeState?.timeout ?: 0.0.Seconds)
}
activeState?.actionManager?.startAction()
}
internal fun register() {
registered = true
states.forEach { (_, state) ->
state.actionManager.register()
}
}
private fun setStateAny(state: Any): IWaitable {
if (startTransition(state)) {
val waitable = TickedWaitable()
executor.scheduleSingleTaskNow(ExceptionHandlingRunnable { finishTransition(state, waitable) })
return waitable
}
return NullWaitable
}
internal fun setStateFromAction(state: Any, async: Boolean) {
if (startTransition(state)) {
if (async) {
executor.scheduleSingleTaskNow(ExceptionHandlingRunnable { finishTransition(state, null) })
} else {
finishTransition(state, null)
}
}
}
internal fun disableFromAction(async: Boolean) {
if (startTransition(States.DISABLED)) {
if (async) {
executor.scheduleSingleTaskNow(ExceptionHandlingRunnable { finishTransition(States.DISABLED, null) })
} else {
finishTransition(States.DISABLED, null)
}
}
}
internal fun backFromAction(async: Boolean) {
val lastState = getLastState()
if (startTransition(lastState)) {
if (async) {
executor.scheduleSingleTaskNow(ExceptionHandlingRunnable { finishTransition(lastState, null) })
} else {
finishTransition(lastState, null)
}
}
}
/**
* Sets the state of this machine to the given state.
* If the machine is already in the given state, no action is taken.
* @param state The state to switch to
* @return A waitable object that unblocks when the state's "entry" finishes
*/
fun setState(state: T) = setStateAny(state as Any)
/**
* Returns the state machine to the state it was in previously
*/
fun back() = setStateAny(getLastState())
/**
* Sets the state machine to the built in "disabled" state
*/
fun disable() = setStateAny(States.DISABLED)
/**
* Gets the state that the machine is currently in
* Note that this value is not updated during a state change until the "exit" method of the previous state finishes
* @return The state that the machine is currently in
*/
@Synchronized fun getState() = stateHistory.current ?: States.ELSE
/**
* Gets the state that the machine was in last
* Note that this value is not updated during a state change until the "exit" method of the previous state finishes
* @return The state that the machine was last in
*/
@Synchronized fun getLastState() = stateHistory.last ?: States.ELSE
/**
* Checks if a machine is in the given state
* @param state The state to check
* @return true if the machine is in this state, false otherwise
*/
@Synchronized fun isInState(state: T) = stateHistory.current == state
/**
* Checks if a machine was in the given state
* @param state The state to check
* @return true if the machine is in this state, false otherwise
*/
@Synchronized fun wasInState(state: T) = stateHistory.last == state
/**
* Toggles between two states.
* The logic is as follows:
* If the machine is in state1, switch to state2. Otherwise, switch to state1
* This means that if the machine is in any other state than state1, it will switch to state1.
* @param state1 State 1 to toggle
* @param state2 State 2 to toggle
* @return The waitable of whatever state was switched to
*/
@Synchronized fun toggle(state1: T, state2: T): IWaitable {
return if (getState() == state1) {
setState(state2)
} else {
setState(state1)
}
}
} | gpl-3.0 | c714a79b36902943bb3133c6b316bf3e | 36.546667 | 149 | 0.658222 | 4.610808 | false | false | false | false |
Major-/Vicis | legacy/src/main/kotlin/rs/emulate/legacy/archive/ArchiveEntry.kt | 1 | 1301 | package rs.emulate.legacy.archive
import io.netty.buffer.ByteBuf
import rs.emulate.legacy.archive.Archive.Companion.entryHash
/**
* A single entry in an [Archive].
*
* @param identifier The identifier.
* @param buffer The buffer containing this entry's data.
*/
class ArchiveEntry(val identifier: Int, buffer: ByteBuf) {
init {
require(buffer.readerIndex() == 0) { "Cannot create an ArchiveEntry with a partially-read buffer" }
}
/**
* The buffer of this entry.
*/
val buffer: ByteBuf = buffer.copy()
get() = field.copy(0, field.writerIndex())
/**
* Gets the size of this entry (i.e. the capacity of the [ByteBuf] backing it), in bytes.
*/
val size: Int
get() = buffer.writerIndex()
/**
* Creates the archive entry.
*
* @param name The name of the archive.
* @param buffer The buffer containing this entry's data.
*/
constructor(name: String, buffer: ByteBuf) : this(name.entryHash(), buffer)
override fun equals(other: Any?): Boolean {
if (other is ArchiveEntry) {
return identifier == other.identifier && buffer == other.buffer
}
return false
}
override fun hashCode(): Int {
return 31 * buffer.hashCode() + identifier
}
}
| isc | 84d96dafb0da71bb05f0d72a3757768b | 25.02 | 107 | 0.624904 | 4.104101 | false | false | false | false |
JavaEden/Orchid-Core | OrchidTest/src/main/kotlin/com/eden/orchid/strikt/html.kt | 2 | 3084 | package com.eden.orchid.strikt
import com.eden.orchid.utilities.applyIf
import kotlinx.html.DETAILS
import kotlinx.html.HTMLTag
import kotlinx.html.HtmlBlockTag
import kotlinx.html.HtmlTagMarker
import kotlinx.html.TagConsumer
import kotlinx.html.attributesMapOf
import kotlinx.html.visit
import org.jsoup.Jsoup
import org.jsoup.nodes.Comment
import org.jsoup.nodes.Document
import org.jsoup.nodes.Node
import org.jsoup.select.Elements
import org.jsoup.select.NodeFilter
import strikt.api.Assertion
/**
* Parse an input String to a DOM tree, which can be further evaluated.
*
* @see select
* @see attr
*/
fun Assertion.Builder<String>.asHtml(
removeComments: Boolean = true
): Assertion.Builder<Document> =
get("as HTML document") { normalizeDoc(removeComments) }
/**
* Apply a CSS selector to a document, and evaluate a block of assertions on the selected elements.
*
* @see asHtml
* @see attr
*/
fun Assertion.Builder<Document>.select(
cssQuery: String,
selectorAssertion: Assertion.Builder<Elements>.() -> Unit
): Assertion.Builder<Document> =
assertBlock("select '$cssQuery'") {
get { select(cssQuery) }.selectorAssertion()
}
/**
* Assert that at least one node was matches (such as by a CSS selector).
*
* @see select
*/
fun Assertion.Builder<Elements>.matches(): Assertion.Builder<Elements> =
assertThat("matches at least one node") { it.isNotEmpty() }
/**
* Assert that at least one node was matches (such as by a CSS selector).
*
* @see select
*/
fun Assertion.Builder<Elements>.matchCountIs(count: Int): Assertion.Builder<Elements> =
assertThat("matches at least one node") { it.size == count }
/**
* Get the value of an attribute on the selected elements, and evaluate a block of assertions on its value.
*
* @see asHtml
* @see select
*/
fun Assertion.Builder<Elements>.attr(
attrName: String,
attrAssertion: Assertion.Builder<String?>.() -> Unit
): Assertion.Builder<Elements> =
assertBlock("attribute '$attrName'") {
get("with value %s") { this[attrName] }.attrAssertion()
}
fun String.trimLines() = this
.lines()
.map { it.trimEnd() }
.joinToString("\n")
private operator fun Elements.get(attrName: String): String? {
return if (hasAttr(attrName))
attr(attrName)
else if (hasAttr("data-$attrName"))
attr("data-$attrName")
else
null
}
object CommentFilter : NodeFilter {
override fun tail(node: Node, depth: Int) =
if (node is Comment) NodeFilter.FilterResult.REMOVE else NodeFilter.FilterResult.CONTINUE
override fun head(node: Node, depth: Int) =
if (node is Comment) NodeFilter.FilterResult.REMOVE else NodeFilter.FilterResult.CONTINUE
}
open class SUMMARY(initialAttributes: Map<String, String>, override val consumer: TagConsumer<*>) :
HTMLTag("summary", consumer, initialAttributes, null, false, false), HtmlBlockTag {
}
@HtmlTagMarker
fun DETAILS.summary(classes: String? = null, block: SUMMARY.() -> Unit = {}): Unit =
SUMMARY(attributesMapOf("class", classes), consumer).visit(block)
| mit | 0a0ed94b63f125710e7839852076cad9 | 29.235294 | 107 | 0.712387 | 3.893939 | false | false | false | false |
JavaEden/Orchid-Core | OrchidCore/src/main/kotlin/com/eden/orchid/utilities/OrchidExtensions.kt | 2 | 9105 | package com.eden.orchid.utilities
import com.caseyjbrooks.clog.Clog
import com.eden.common.util.EdenUtils
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.options.OptionsHolder
import com.eden.orchid.api.registration.OrchidModule
import com.eden.orchid.api.resources.resource.OrchidResource
import com.eden.orchid.api.theme.pages.OrchidPage
import com.google.inject.binder.LinkedBindingBuilder
import org.apache.commons.lang3.StringUtils
import java.io.ByteArrayInputStream
import java.io.InputStream
import java.util.ArrayList
import java.util.regex.Pattern
import java.util.stream.Stream
import kotlin.reflect.KClass
fun String?.empty(): Boolean {
return EdenUtils.isEmpty(this)
}
fun String?.wrap(width: Int = 80): List<String> {
val matchList = ArrayList<String>()
if (this != null) {
if (!this.empty()) {
val regex = Pattern.compile("(.{1,$width}(?:\\s|$))|(.{0,$width})", Pattern.DOTALL)
val regexMatcher = regex.matcher(this)
while (regexMatcher.find()) {
val line = regexMatcher.group().trim { it <= ' ' }
if (!EdenUtils.isEmpty(line)) {
matchList.add(line)
}
}
}
}
return matchList
}
@Suppress(SuppressedWarnings.UNUSED_PARAMETER)
fun String.logSyntaxError(
extension: String,
lineNumberNullable: Int?,
lineColumn: Int?,
errorMessage: String? = "",
cause: Throwable? = null
) {
val lineNumber = lineNumberNullable ?: 0
val lines = this.lines()
val linesBeforeStart = Math.max(lineNumber - 3, 0)
val linesBeforeEnd = Math.max(lineNumber - 1, 0)
val linesAfterStart = lineNumber
val linesAfterEnd = Math.min(lineNumber + 5, lines.size)
val linesBefore = " |" + lines.subList(linesBeforeStart, linesBeforeEnd).joinToString("\n |")
val errorLine = "#{\$0|fg('RED')}-->|#{\$0|reset}" + lines[linesBeforeEnd]
val linesAfter = " |" + lines.subList(linesAfterStart, linesAfterEnd).joinToString("\n |")
val formattedMessage = """
|_| |.${extension} error
|_| | Reason: $errorMessage
|_| | Cause: ${cause?.toString() ?: "Unknown cause"}
|_| |
|_|$linesBefore
|_|$errorLine
|_|$linesAfter
""".trimMargin("|_|")
Clog.tag("Template error").e("\n$formattedMessage")
}
// string conversions
infix fun String.from(mapper: String.() -> Array<String>): Array<String> {
return mapper(this)
}
infix fun Array<String>.to(mapper: Array<String>.() -> String): String {
return mapper(this)
}
infix fun Array<String>.with(mapper: String.() -> String): Array<String> {
return this.map { mapper(it) }.toTypedArray()
}
// "from" mappers
fun String.camelCase(): Array<String> {
return StringUtils.splitByCharacterTypeCamelCase(this)
}
fun String.camelCase(mapper: String.() -> String): Array<String> {
return camelCase().with(mapper)
}
fun String.words(): Array<String> {
return StringUtils.splitByWholeSeparator(this, null)
}
fun String.words(mapper: String.() -> String): Array<String> {
return words().with(mapper)
}
fun String.snakeCase(): Array<String> {
return StringUtils.splitByWholeSeparator(this, "_")
}
fun String.snakeCase(mapper: String.() -> String): Array<String> {
return snakeCase().with(mapper)
}
fun String.dashCase(): Array<String> {
return StringUtils.splitByWholeSeparator(this, "-")
}
fun String.dashCase(mapper: String.() -> String): Array<String> {
return dashCase().with(mapper)
}
fun String.filename(): Array<String> {
return this
.words()
.flatMap {
it.dashCase().toList()
}
.flatMap {
it.snakeCase().toList()
}
.flatMap {
it.camelCase().toList()
}
.toTypedArray()
}
fun String.filename(mapper: String.() -> String): Array<String> {
return filename().with(mapper)
}
// "to" mappers
fun Array<String>.pascalCase(): String {
return map { it.toLowerCase().capitalize() }.joinToString(separator = "")
}
fun List<String>.pascalCase(): String {
return toTypedArray().pascalCase()
}
fun Array<String>.pascalCase(mapper: String.() -> String): String {
return map(mapper).pascalCase()
}
fun Array<String>.camelCase(): String {
return pascalCase().decapitalize()
}
fun List<String>.camelCase(): String {
return toTypedArray().camelCase()
}
fun Array<String>.camelCase(mapper: String.() -> String): String {
return map(mapper).camelCase()
}
fun Array<String>.words(): String {
return joinToString(separator = " ")
}
fun List<String>.words(): String {
return toTypedArray().words()
}
fun Array<String>.words(mapper: String.() -> String): String {
return map(mapper).words()
}
fun Array<String>.snakeCase(): String {
return map { it.toUpperCase() }.joinToString(separator = "_")
}
fun List<String>.snakeCase(): String {
return toTypedArray().snakeCase()
}
fun Array<String>.snakeCase(mapper: String.() -> String): String {
return map(mapper).snakeCase()
}
fun Array<String>.dashCase(): String {
return joinToString(separator = "-")
}
fun List<String>.dashCase(): String {
return toTypedArray().dashCase()
}
fun Array<String>.dashCase(mapper: String.() -> String): String {
return map(mapper).dashCase()
}
fun Array<String>.slug(): String {
return dashCase().toLowerCase()
}
fun List<String>.slug(): String {
return toTypedArray().slug()
}
fun Array<String>.slug(mapper: String.() -> String): String {
return map(mapper).slug()
}
fun Array<String>.titleCase(): String {
return joinToString(separator = " ", transform = { it.capitalize() })
}
fun List<String>.titleCase(): String {
return toTypedArray().titleCase()
}
fun Array<String>.titleCase(mapper: String.() -> String): String {
return map(mapper).titleCase()
}
// "with" mappers
fun String.urlSafe(): String {
return replace("\\s+".toRegex(), "-").replace("[^\\w-_]".toRegex(), "")
}
fun String.urlSafe(mapper: String.() -> String): String {
return urlSafe().mapper()
}
// Better Kotlin Module registration
//----------------------------------------------------------------------------------------------------------------------
// bind
inline fun <reified T : Any> OrchidModule.bind(): LinkedBindingBuilder<T> {
return this._bind(T::class.java)
}
// addToSet
inline fun <reified T : Any> OrchidModule.addToSet(vararg objectClasses: KClass<out T>) {
this.addToSet(T::class.java, *(objectClasses.map { it.java }.toTypedArray()))
}
inline fun <reified T : Any, reified IMPL : T> OrchidModule.addToSet() {
this.addToSet(T::class.java, IMPL::class.java)
}
inline fun <reified T : Any> OrchidModule.addToSet(vararg objects: T) {
this.addToSet(T::class.java, *objects)
}
// Better dynamic object resolution
//----------------------------------------------------------------------------------------------------------------------
inline fun <reified T : Any> OrchidContext.resolve(): T {
return this.resolve(T::class.java)
}
inline fun <reified T : Any> OrchidContext.resolve(named: String): T {
return this.resolve(T::class.java, named)
}
inline fun <reified T : Any> OrchidContext.resolveSet(): Set<T> {
return this.resolveSet(T::class.java)
}
fun Number.makeMillisReadable(): String {
val lMillis = this.toDouble()
val hours: Int
val minutes: Int
val seconds: Int
val millis: Int
val sTime: String
seconds = (lMillis / 1000).toInt() % 60
millis = (lMillis % 1000).toInt()
if (seconds > 0) {
minutes = (lMillis / 1000.0 / 60.0).toInt() % 60
if (minutes > 0) {
hours = (lMillis / 1000.0 / 60.0 / 60.0).toInt() % 24
if (hours > 0) {
sTime = hours.toString() + "h " + minutes + "m " + seconds + "s " + millis + "ms"
} else {
sTime = minutes.toString() + "m " + seconds + "s " + millis + "ms"
}
} else {
sTime = seconds.toString() + "s " + millis + "ms"
}
} else {
sTime = millis.toString() + "ms"
}
return sTime
}
fun findPageByServerPath(pages: Stream<OrchidPage>, path: String): OrchidPage? {
val requestedPath = OrchidUtils.normalizePath(path)
return pages
.filter { page -> page.reference.pathOnDisk == requestedPath }
.findFirst()
.orElse(null)
}
fun InputStream?.readToString(): String? = this?.bufferedReader()?.use { it.readText() }
fun String?.asInputStream(): InputStream = ByteArrayInputStream((this ?: "").toByteArray(Charsets.UTF_8))
fun OptionsHolder.extractOptionsFromResource(context: OrchidContext, resource: OrchidResource): Map<String, Any?> {
val data = resource.embeddedData
extractOptions(context, data)
return data
}
inline fun <reified U> Any?.takeIf(): U? {
return if (this is U) this else null
}
inline fun <T> T.applyIf(condition: Boolean, block: T.() -> Unit): T {
if (condition) block()
return this
}
fun <T> T.debugger(): T {
return this
}
| mit | 02751a20b7506a3af1dee2d73c3d34bd | 27.015385 | 120 | 0.625371 | 3.812814 | false | false | false | false |
iMeiji/Daily | app/src/main/java/com/meiji/daily/util/NetWorkUtil.kt | 1 | 1774 | package com.meiji.daily.util
import android.content.Context
import android.net.ConnectivityManager
/**
* Created by Meiji on 2017/5/2.
*/
object NetWorkUtil {
/**
* 判断是否有网络连接
*/
fun isNetworkConnected(context: Context): Boolean {
// 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)
val manager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
// 获取NetworkInfo对象
val networkInfo = manager.activeNetworkInfo
//判断NetworkInfo对象是否为空
return networkInfo?.isAvailable ?: false
}
/**
* 判断WIFI网络是否可用
*/
fun isWifiConnected(context: Context): Boolean {
// 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)
val manager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
// 获取NetworkInfo对象
val networkInfo = manager.activeNetworkInfo
//判断NetworkInfo对象是否为空 并且类型是否为WIFI
return networkInfo?.isAvailable ?: false && networkInfo?.type == ConnectivityManager.TYPE_WIFI
}
/**
* 判断MOBILE网络是否可用
*/
fun isMobileConnected(context: Context): Boolean {
//获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)
val manager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
//获取NetworkInfo对象
val networkInfo = manager.activeNetworkInfo
//判断NetworkInfo对象是否为空 并且类型是否为MOBILE
return networkInfo?.isAvailable ?: false && networkInfo?.type == ConnectivityManager.TYPE_MOBILE
}
}
| apache-2.0 | d40325a2e232be9e03021e9ffaed5876 | 30.87234 | 104 | 0.688251 | 4.354651 | false | false | false | false |
square/picasso | picasso-pollexor/src/main/java/com/squareup/picasso3/pollexor/PollexorRequestTransformer.kt | 1 | 3036 | /*
* Copyright (C) 2022 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.picasso3.pollexor
import android.net.Uri
import com.squareup.picasso3.Picasso.RequestTransformer
import com.squareup.picasso3.Request
import com.squareup.picasso3.pollexor.PollexorRequestTransformer.Callback
import com.squareup.pollexor.Thumbor
import com.squareup.pollexor.ThumborUrlBuilder
import com.squareup.pollexor.ThumborUrlBuilder.ImageFormat.WEBP
/**
* A [RequestTransformer] that changes requests to use [Thumbor] for some remote
* transformations.
* By default images are only transformed with Thumbor if they have a size set,
* unless alwaysTransform is set to true
*/
class PollexorRequestTransformer @JvmOverloads constructor(
private val thumbor: Thumbor,
private val alwaysTransform: Boolean = false,
private val callback: Callback = NONE
) : RequestTransformer {
constructor(thumbor: Thumbor, callback: Callback) : this(thumbor, false, callback)
override fun transformRequest(request: Request): Request {
if (request.resourceId != 0) {
return request // Don't transform resource requests.
}
val uri = requireNotNull(request.uri) { "Null uri passed to ${javaClass.canonicalName}" }
val scheme = uri.scheme
if ("https" != scheme && "http" != scheme) {
return request // Thumbor only supports remote images.
}
// Only transform requests that have resizes unless `alwaysTransform` is set.
if (!request.hasSize() && !alwaysTransform) {
return request
}
// Start building a new request for us to mutate.
val newRequest = request.newBuilder()
// Create the url builder to use.
val urlBuilder = thumbor.buildImage(uri.toString())
callback.configure(urlBuilder)
// Resize the image to the target size if it has a size.
if (request.hasSize()) {
urlBuilder.resize(request.targetWidth, request.targetHeight)
newRequest.clearResize()
}
// If the center inside flag is set, perform that with Thumbor as well.
if (request.centerInside) {
urlBuilder.fitIn()
newRequest.clearCenterInside()
}
// Use WebP for downloading.
urlBuilder.filter(ThumborUrlBuilder.format(WEBP))
// Update the request with the completed Thumbor URL.
newRequest.setUri(Uri.parse(urlBuilder.toUrl()))
return newRequest.build()
}
fun interface Callback {
fun configure(builder: ThumborUrlBuilder)
}
companion object {
private val NONE = Callback { }
}
}
| apache-2.0 | aeb5942d843a6aaefe35378409892095 | 33.11236 | 93 | 0.726614 | 4.176066 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/internal/FindImplicitNothingAction.kt | 5 | 7169 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.actions.internal
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileVisitor
import com.intellij.psi.PsiManager
import com.intellij.usageView.UsageInfo
import com.intellij.usages.UsageInfo2UsageAdapter
import com.intellij.usages.UsageTarget
import com.intellij.usages.UsageViewManager
import com.intellij.usages.UsageViewPresentation
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.builtins.getReturnTypeFromFunctionType
import org.jetbrains.kotlin.builtins.isFunctionType
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.util.application.isApplicationInternalMode
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.calls.util.getCalleeExpressionIfAny
import org.jetbrains.kotlin.types.KotlinType
import javax.swing.SwingUtilities
class FindImplicitNothingAction : AnAction() {
companion object {
private val LOG = Logger.getInstance("#org.jetbrains.kotlin.idea.actions.internal.FindImplicitNothingAction")
}
override fun actionPerformed(e: AnActionEvent) {
val selectedFiles = selectedKotlinFiles(e).toList()
val project = CommonDataKeys.PROJECT.getData(e.dataContext)!!
ProgressManager.getInstance().runProcessWithProgressSynchronously(
{ find(selectedFiles, project) },
KotlinBundle.message("progress.finding.implicit.nothing.s"),
true,
project
)
}
private fun find(files: Collection<KtFile>, project: Project) {
val progressIndicator = ProgressManager.getInstance().progressIndicator
val found = ArrayList<KtCallExpression>()
for ((i, file) in files.withIndex()) {
progressIndicator?.text = KotlinBundle.message("scanning.files.0.fo.1.file.2.occurrences.found", i, files.size, found.size)
progressIndicator?.text2 = file.virtualFile.path
val resolutionFacade = file.getResolutionFacade()
file.acceptChildren(object : KtVisitorVoid() {
override fun visitKtElement(element: KtElement) {
ProgressManager.checkCanceled()
element.acceptChildren(this)
}
override fun visitCallExpression(expression: KtCallExpression) {
expression.acceptChildren(this)
try {
val bindingContext = resolutionFacade.analyze(expression)
val type = bindingContext.getType(expression) ?: return
if (KotlinBuiltIns.isNothing(type) && !expression.hasExplicitNothing(bindingContext)) { //TODO: what about nullable Nothing?
found.add(expression)
}
} catch (e: ProcessCanceledException) {
throw e
} catch (t: Throwable) { // do not stop on internal error
LOG.error(t)
}
}
})
progressIndicator?.fraction = (i + 1) / files.size.toDouble()
}
SwingUtilities.invokeLater {
if (found.isNotEmpty()) {
val usages = found.map { UsageInfo2UsageAdapter(UsageInfo(it)) }.toTypedArray()
val presentation = UsageViewPresentation()
presentation.tabName = KotlinBundle.message("implicit.nothing.s")
UsageViewManager.getInstance(project).showUsages(arrayOf<UsageTarget>(), usages, presentation)
} else {
Messages.showInfoMessage(
project,
KotlinBundle.message("not.found.in.0.files", files.size),
KotlinBundle.message("titile.not.found")
)
}
}
}
private fun KtExpression.hasExplicitNothing(bindingContext: BindingContext): Boolean {
val callee = getCalleeExpressionIfAny() ?: return false
when (callee) {
is KtSimpleNameExpression -> {
val target = bindingContext[BindingContext.REFERENCE_TARGET, callee] ?: return false
val callableDescriptor = (target as? CallableDescriptor ?: return false).original
val declaration = DescriptorToSourceUtils.descriptorToDeclaration(callableDescriptor) as? KtCallableDeclaration
if (declaration != null && declaration.typeReference == null) return false // implicit type
val type = callableDescriptor.returnType ?: return false
return type.isNothingOrNothingFunctionType()
}
else -> {
return callee.hasExplicitNothing(bindingContext)
}
}
}
private fun KotlinType.isNothingOrNothingFunctionType(): Boolean {
return KotlinBuiltIns.isNothing(this) ||
(isFunctionType && this.getReturnTypeFromFunctionType().isNothingOrNothingFunctionType())
}
override fun getActionUpdateThread() = ActionUpdateThread.BGT
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = isApplicationInternalMode()
}
private fun selectedKotlinFiles(e: AnActionEvent): Sequence<KtFile> {
val virtualFiles = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY) ?: return sequenceOf()
val project = CommonDataKeys.PROJECT.getData(e.dataContext) ?: return sequenceOf()
return allKotlinFiles(virtualFiles, project)
}
private fun allKotlinFiles(filesOrDirs: Array<VirtualFile>, project: Project): Sequence<KtFile> {
val manager = PsiManager.getInstance(project)
return allFiles(filesOrDirs)
.asSequence()
.mapNotNull { manager.findFile(it) as? KtFile }
}
private fun allFiles(filesOrDirs: Array<VirtualFile>): Collection<VirtualFile> {
val result = ArrayList<VirtualFile>()
for (file in filesOrDirs) {
VfsUtilCore.visitChildrenRecursively(file, object : VirtualFileVisitor<Unit>() {
override fun visitFile(file: VirtualFile): Boolean {
result.add(file)
return true
}
})
}
return result
}
}
| apache-2.0 | cf9d57e3cef771a083f2ae4df1ca17e9 | 44.373418 | 148 | 0.674153 | 5.435178 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/emoji/EmojiJsonParser.kt | 2 | 5138 | package org.thoughtcrime.securesms.emoji
import android.net.Uri
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import org.signal.core.util.Hex
import org.thoughtcrime.securesms.components.emoji.CompositeEmojiPageModel
import org.thoughtcrime.securesms.components.emoji.Emoji
import org.thoughtcrime.securesms.components.emoji.EmojiPageModel
import org.thoughtcrime.securesms.components.emoji.StaticEmojiPageModel
import java.io.InputStream
import java.nio.charset.Charset
typealias UriFactory = (sprite: String, format: String) -> Uri
/**
* Takes an emoji_data.json file data and parses it into an EmojiSource
*/
object EmojiJsonParser {
private val OBJECT_MAPPER = ObjectMapper()
private const val ESTIMATED_EMOJI_COUNT = 3500
@JvmStatic
fun verify(body: InputStream) {
parse(body) { _, _ -> Uri.EMPTY }.getOrThrow()
}
fun parse(body: InputStream, uriFactory: UriFactory): Result<ParsedEmojiData> {
return try {
Result.success(buildEmojiSourceFromNode(OBJECT_MAPPER.readTree(body), uriFactory))
} catch (e: Exception) {
Result.failure(e)
}
}
private fun buildEmojiSourceFromNode(node: JsonNode, uriFactory: UriFactory): ParsedEmojiData {
val format: String = node["format"].textValue()
val obsolete: List<ObsoleteEmoji> = node["obsolete"].toObseleteList()
val dataPages: List<EmojiPageModel> = getDataPages(format, node["emoji"], uriFactory)
val jumboPages: Map<String, String> = getJumboPages(node["jumbomoji"])
val displayPages: List<EmojiPageModel> = mergeToDisplayPages(dataPages)
val metrics: EmojiMetrics = node["metrics"].toEmojiMetrics()
val densities: List<String> = node["densities"].toDensityList()
return ParsedEmojiData(metrics, densities, format, displayPages, dataPages, jumboPages, obsolete)
}
private fun getDataPages(format: String, emoji: JsonNode, uriFactory: UriFactory): List<EmojiPageModel> {
return emoji.fields()
.asSequence()
.sortedWith { lhs, rhs ->
val lhsCategory = EmojiCategory.forKey(lhs.key.asCategoryKey())
val rhsCategory = EmojiCategory.forKey(rhs.key.asCategoryKey())
val comp = lhsCategory.priority.compareTo(rhsCategory.priority)
if (comp == 0) {
val lhsIndex = lhs.key.getPageIndex()
val rhsIndex = rhs.key.getPageIndex()
lhsIndex.compareTo(rhsIndex)
} else {
comp
}
}
.map { createPage(it.key, format, it.value, uriFactory) }
.toList()
}
private fun getJumboPages(jumbo: JsonNode?): Map<String, String> {
if (jumbo != null) {
return jumbo.fields()
.asSequence()
.map { (page: String, node: JsonNode) ->
node.associate { it.textValue() to page }
}
.flatMap { it.entries }
.associateTo(HashMap(ESTIMATED_EMOJI_COUNT)) { it.key to it.value }
}
return emptyMap()
}
private fun createPage(pageName: String, format: String, page: JsonNode, uriFactory: UriFactory): EmojiPageModel {
val category = EmojiCategory.forKey(pageName.asCategoryKey())
val pageList = page.mapIndexed { i, data ->
if (data.size() == 0) {
throw IllegalStateException("Page index $pageName.$i had no data")
} else {
val variations: MutableList<String> = mutableListOf()
val rawVariations: MutableList<String> = mutableListOf()
data.forEach {
variations += it.textValue().encodeAsUtf16()
rawVariations += it.textValue()
}
Emoji(variations, rawVariations)
}
}
return StaticEmojiPageModel(category, pageList, uriFactory(pageName, format))
}
private fun mergeToDisplayPages(dataPages: List<EmojiPageModel>): List<EmojiPageModel> {
return dataPages.groupBy { it.iconAttr }
.map { (icon, pages) -> if (pages.size <= 1) pages.first() else CompositeEmojiPageModel(icon, pages) }
}
}
private fun JsonNode?.toObseleteList(): List<ObsoleteEmoji> {
return if (this == null) {
listOf()
} else {
map { node ->
ObsoleteEmoji(node["obsoleted"].textValue().encodeAsUtf16(), node["replace_with"].textValue().encodeAsUtf16())
}.toList()
}
}
private fun JsonNode.toEmojiMetrics(): EmojiMetrics {
return EmojiMetrics(this["raw_width"].asInt(), this["raw_height"].asInt(), this["per_row"].asInt())
}
private fun JsonNode.toDensityList(): List<String> {
return map { it.textValue() }
}
private fun String.encodeAsUtf16() = String(Hex.fromStringCondensed(this), Charset.forName("UTF-16"))
private fun String.asCategoryKey() = replace("(_\\d+)*$".toRegex(), "")
private fun String.getPageIndex() = "^.*_(\\d+)+$".toRegex().find(this)?.let { it.groupValues[1] }?.toInt() ?: throw IllegalStateException("No index.")
data class ParsedEmojiData(
override val metrics: EmojiMetrics,
override val densities: List<String>,
override val format: String,
override val displayPages: List<EmojiPageModel>,
override val dataPages: List<EmojiPageModel>,
override val jumboPages: Map<String, String>,
override val obsolete: List<ObsoleteEmoji>
) : EmojiData
| gpl-3.0 | f926fa674b397e261f53d1c898c3daff | 36.231884 | 151 | 0.695991 | 3.98913 | false | false | false | false |
jk1/intellij-community | platform/script-debugger/backend/src/debugger/values/ValueManager.kt | 3 | 1400 | /*
* 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.debugger.values
import org.jetbrains.concurrency.Obsolescent
import java.util.concurrent.atomic.AtomicInteger
/**
* The main idea of this class - don't create value for remote value handle if already exists. So,
* implementation of this class keep map of value to remote value handle.
* Also, this class maintains cache timestamp.
* Currently WIP implementation doesn't keep such map due to protocol issue. But V8 does.
*/
abstract class ValueManager() : Obsolescent {
private val cacheStamp = AtomicInteger()
@Volatile private var obsolete = false
open fun clearCaches() {
cacheStamp.incrementAndGet()
}
fun getCacheStamp(): Int = cacheStamp.get()
override final fun isObsolete(): Boolean = obsolete
fun markObsolete() {
obsolete = true
}
} | apache-2.0 | 2926cc70eaa3447603e5adeb4957acda | 31.581395 | 98 | 0.744286 | 4.307692 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/components/menu/ContextMenuList.kt | 1 | 3086 | package org.thoughtcrime.securesms.components.menu
import android.os.Build
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.util.adapter.mapping.LayoutFactory
import org.thoughtcrime.securesms.util.adapter.mapping.MappingAdapter
import org.thoughtcrime.securesms.util.adapter.mapping.MappingModel
import org.thoughtcrime.securesms.util.adapter.mapping.MappingViewHolder
/**
* Handles the setup and display of actions shown in a context menu.
*/
class ContextMenuList(recyclerView: RecyclerView, onItemClick: () -> Unit) {
private val mappingAdapter = MappingAdapter().apply {
registerFactory(DisplayItem::class.java, LayoutFactory({ ItemViewHolder(it, onItemClick) }, R.layout.signal_context_menu_item))
}
init {
recyclerView.apply {
adapter = mappingAdapter
layoutManager = LinearLayoutManager(context)
itemAnimator = null
}
}
fun setItems(items: List<ActionItem>) {
mappingAdapter.submitList(items.toAdapterItems())
}
private fun List<ActionItem>.toAdapterItems(): List<DisplayItem> {
return this.mapIndexed { index, item ->
val displayType: DisplayType = when {
this.size == 1 -> DisplayType.ONLY
index == 0 -> DisplayType.TOP
index == this.size - 1 -> DisplayType.BOTTOM
else -> DisplayType.MIDDLE
}
DisplayItem(item, displayType)
}
}
private data class DisplayItem(
val item: ActionItem,
val displayType: DisplayType
) : MappingModel<DisplayItem> {
override fun areItemsTheSame(newItem: DisplayItem): Boolean {
return this == newItem
}
override fun areContentsTheSame(newItem: DisplayItem): Boolean {
return this == newItem
}
}
private enum class DisplayType {
TOP, BOTTOM, MIDDLE, ONLY
}
private class ItemViewHolder(
itemView: View,
private val onItemClick: () -> Unit,
) : MappingViewHolder<DisplayItem>(itemView) {
val icon: ImageView = itemView.findViewById(R.id.signal_context_menu_item_icon)
val title: TextView = itemView.findViewById(R.id.signal_context_menu_item_title)
override fun bind(model: DisplayItem) {
icon.setImageResource(model.item.iconRes)
title.text = model.item.title
itemView.setOnClickListener {
model.item.action.run()
onItemClick()
}
if (Build.VERSION.SDK_INT >= 21) {
when (model.displayType) {
DisplayType.TOP -> itemView.setBackgroundResource(R.drawable.signal_context_menu_item_background_top)
DisplayType.BOTTOM -> itemView.setBackgroundResource(R.drawable.signal_context_menu_item_background_bottom)
DisplayType.MIDDLE -> itemView.setBackgroundResource(R.drawable.signal_context_menu_item_background_middle)
DisplayType.ONLY -> itemView.setBackgroundResource(R.drawable.signal_context_menu_item_background_only)
}
}
}
}
}
| gpl-3.0 | fdc264f3c5b0e380c74a049113072c11 | 32.912088 | 131 | 0.721322 | 4.371105 | false | false | false | false |
RayBa82/DVBViewerController | dvbViewerController/src/main/java/org/dvbviewer/controller/ui/adapter/MediaAdapter.kt | 1 | 3947 | package org.dvbviewer.controller.ui.adapter
import android.content.Context
import android.graphics.drawable.Drawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.content.res.AppCompatResources
import androidx.appcompat.widget.AppCompatImageButton
import androidx.appcompat.widget.AppCompatImageView
import androidx.recyclerview.widget.RecyclerView
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.list_item_video.view.*
import org.dvbviewer.controller.R
import org.dvbviewer.controller.data.media.MediaFile
import org.dvbviewer.controller.utils.ServerConsts
/**
* Created by rayba on 21.04.17.
*/
open class MediaAdapter(context: Context, private val listener: OnMediaClickListener) : RecyclerView.Adapter<MediaAdapter.MediaViewHolder>() {
private var mCursor: List<MediaFile>? = null
private val placeHolder: Drawable? = AppCompatResources.getDrawable(context, R.drawable.ic_play_white_40dp)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MediaViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.list_item_video, parent, false)
return MediaViewHolder(itemView)
}
override fun onBindViewHolder(holder: MediaViewHolder, position: Int) {
val file = mCursor!![position]
val isDir = file.isDirectory
holder.icon!!.visibility = if (isDir) View.VISIBLE else View.GONE
holder.thumbNailContainer!!.visibility = if (!isDir) View.VISIBLE else View.GONE
holder.thumbNail!!.visibility = if (!isDir) View.VISIBLE else View.GONE
holder.widgetFrame!!.visibility = if (!isDir) View.VISIBLE else View.GONE
holder.name!!.text = file.name
holder.itemView.tag = position
holder.itemView.setOnClickListener { v ->
val position = v.tag as Int
val file = mCursor!![position]
listener.onMediaClick(file)
}
holder.thumbNailContainer!!.tag = position
holder.thumbNailContainer!!.setOnClickListener { v ->
val position = v.tag as Int
val file = mCursor!![position]
listener.onMediaStreamClick(file)
}
holder.contextMenu!!.tag = position
holder.contextMenu!!.setOnClickListener { v ->
val position = v.tag as Int
val file = mCursor!![position]
listener.onMediaContextClick(file)
}
if (!isDir) {
holder.thumbNail!!.setImageDrawable(null)
Picasso.get()
.load(ServerConsts.REC_SERVICE_URL + "/" + file.thumb)
.placeholder(placeHolder!!)
.fit()
.centerCrop()
.into(holder.thumbNail)
}
}
override fun getItemViewType(position: Int): Int {
val file = mCursor!![position]
return if (file.isDirectory) VIEWTYPE_DIR else VIEWTYPE_FILE
}
override fun getItemCount(): Int {
return if (mCursor != null) mCursor!!.size else 0
}
class MediaViewHolder(v: View) : RecyclerView.ViewHolder(v) {
var name: TextView? = v.name
var icon: AppCompatImageView? = v.icon
var thumbNailContainer: View? = v.thumbNailContainer
var thumbNail: ImageView? = v.thumbNail
var contextMenu: AppCompatImageButton? = v.contextMenu
var widgetFrame: View? = v.widget_frame
}
fun setCursor(cursor: List<MediaFile>) {
mCursor = cursor
}
interface OnMediaClickListener {
fun onMediaClick(mediaFile: MediaFile)
fun onMediaStreamClick(mediaFile: MediaFile)
fun onMediaContextClick(mediaFile: MediaFile)
}
companion object {
private const val VIEWTYPE_DIR = 0
private const val VIEWTYPE_FILE = 1
}
}
| apache-2.0 | e6523d6af3ca531a5561803cd0d5a8a1 | 32.449153 | 142 | 0.672409 | 4.563006 | false | false | false | false |
contentful/contentful-management.java | src/test/kotlin/com/contentful/java/cma/RolesTests.kt | 1 | 12783 | /*
* Copyright (C) 2019 Contentful GmbH
*
* 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.contentful.java.cma
import com.contentful.java.cma.lib.TestCallback
import com.contentful.java.cma.lib.TestUtils
import com.contentful.java.cma.model.CMAConstraint
import com.contentful.java.cma.model.CMAConstraint.Equals
import com.contentful.java.cma.model.CMAConstraint.FieldKeyPath
import com.contentful.java.cma.model.CMAPermissions
import com.contentful.java.cma.model.CMAPolicy
import com.contentful.java.cma.model.CMAPolicy.ALLOW
import com.contentful.java.cma.model.CMARole
import com.google.gson.Gson
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import org.junit.After
import org.junit.Before
import java.util.logging.LogManager
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
import org.junit.Test as test
class RolesTests{
var server: MockWebServer? = null
var client: CMAClient? = null
var gson: Gson? = null
@Before
fun setUp() {
LogManager.getLogManager().reset()
// MockWebServer
server = MockWebServer()
server!!.start()
// Client
// overwrite client to not use environments
client = CMAClient.Builder()
.setAccessToken("token")
.setCoreEndpoint(server!!.url("/").toString())
.setUploadEndpoint(server!!.url("/").toString())
.setSpaceId("configuredSpaceId")
.build()
gson = CMAClient.createGson()
}
@After
fun tearDown() {
server!!.shutdown()
}
@test
fun testFetchOne() {
val responseBody = TestUtils.fileToString("roles_get_one.json")
server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody))
val result = assertTestCallback(client!!.roles().async()
.fetchOne("SPACE_ID", "ROLE_ID", TestCallback()) as TestCallback)!!
assertEquals("DELETE ME!!", result.name)
assertEquals("Test role", result.description)
assertNotNull(result.policies)
assertEquals(9, result.policies.size)
val policy = result.policies[0]
assertEquals("allow", policy.effect)
assertEquals(1, (policy.actions as List<*>).size)
assertEquals("read", (policy.actions as List<*>)[0])
assertNotNull(policy.constraint)
assertNull(policy.constraint.or)
assertNull(policy.constraint.equals)
assertNull(policy.constraint.not)
assertNotNull(policy.constraint.and)
assertEquals("sys.type", policy.constraint.and[0].equals.path.doc)
assertEquals("Entry", policy.constraint.and[0].equals.value)
assertNotNull(result.permissions)
assertNotNull(result.permissions.contentModel)
assertEquals(1, (result.permissions.contentModel as List<*>).size)
assertNotNull(result.permissions.settings)
assertEquals(0, (result.permissions.settings as List<*>).size)
assertNotNull(result.permissions.contentDelivery)
assertNotNull("all", result.permissions.contentDelivery as String?)
assertEquals("1sJzssG9PfxOKGVr2ePpXm", result.id)
assertEquals("Role", result.system.type.name)
// Request
val recordedRequest = server!!.takeRequest()
assertEquals("GET", recordedRequest.method)
assertEquals("/spaces/SPACE_ID/roles/ROLE_ID", recordedRequest.path)
}
@test
fun testFetchOneWithConfiguredSpaceAndEnvironment() {
val responseBody = TestUtils.fileToString("roles_get_one.json")
server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody))
assertTestCallback(client!!.roles().async().fetchOne("ROLE_ID", TestCallback()) as TestCallback)!!
// Request
val recordedRequest = server!!.takeRequest()
assertEquals("GET", recordedRequest.method)
assertEquals("/spaces/configuredSpaceId/roles/ROLE_ID", recordedRequest.path)
}
@test
fun testFetchAll() {
val responseBody = TestUtils.fileToString("roles_get_all.json")
server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody))
val result = assertTestCallback(client!!.roles().async()
.fetchAll("SPACE_ID", TestCallback()) as TestCallback)!!
assertEquals(7, result.total)
assertEquals(25, result.limit)
assertEquals(0, result.skip)
assertEquals(7, result.items.size)
assertEquals("Editor", result.items[0].name)
assertEquals(2, result.items[0].policies.size)
assertEquals("DELETE ME!!", result.items[1].name)
assertEquals(1, result.items[1].policies.size)
// Request
val recordedRequest = server!!.takeRequest()
assertEquals("GET", recordedRequest.method)
assertEquals("/spaces/SPACE_ID/roles", recordedRequest.path)
}
@test
fun testFetchAllWithConfiguredSpaceAndEnvironment() {
val responseBody = TestUtils.fileToString("roles_get_all.json")
server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody))
assertTestCallback(client!!.roles().async()
.fetchAll(TestCallback()) as TestCallback)!!
// Request
val recordedRequest = server!!.takeRequest()
assertEquals("GET", recordedRequest.method)
assertEquals("/spaces/configuredSpaceId/roles", recordedRequest.path)
}
@test
fun testFetchAllWithQuery() {
val responseBody = TestUtils.fileToString("roles_get_all.json")
server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody))
assertTestCallback(client!!.roles().async()
.fetchAll("SPACE_ID",
hashMapOf("skip" to "3"),
TestCallback()) as TestCallback)!!
// Request
val recordedRequest = server!!.takeRequest()
assertEquals("GET", recordedRequest.method)
assertEquals("/spaces/SPACE_ID/roles?skip=3", recordedRequest.path)
}
@test
fun testFetchAllWithQueryWithConfiguredSpaceAndEnvironment() {
val responseBody = TestUtils.fileToString("roles_get_all.json")
server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody))
assertTestCallback(client!!.roles().async().fetchAll(mapOf("skip" to "3"), TestCallback())
as TestCallback)!!
// Request
val recordedRequest = server!!.takeRequest()
assertEquals("GET", recordedRequest.method)
assertEquals("/spaces/configuredSpaceId/roles?skip=3", recordedRequest.path)
}
@test
fun testCreateNew() {
val responseBody = TestUtils.fileToString("roles_create.json")
server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody))
val role = CMARole()
.setName("Manage Settings Role is actually all")
.setDescription("Test role")
.setPermissions(
CMAPermissions().setSettings("all")
)
val result = assertTestCallback(client!!.roles().async()
.create("SPACE_ID", role, TestCallback()) as TestCallback)!!
assertEquals("Manage Settings Role is actually all", result.name)
assertEquals("Test role", result.description)
assertEquals("0g3FcTwbFicqZuoaY288Qe", result.id)
assertNotNull(result.permissions.settings)
// Request
val recordedRequest = server!!.takeRequest()
assertEquals("POST", recordedRequest.method)
assertEquals("/spaces/SPACE_ID/roles/", recordedRequest.path)
}
@test
fun testCreateNewWithConfiguredSpaceAndEnvironment() {
val responseBody = TestUtils.fileToString("roles_create.json")
server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody))
val role = CMARole()
.setName("Manage Settings Role is actually all")
.setDescription("Test role")
.setPermissions(
CMAPermissions().setSettings("all")
)
assertTestCallback(client!!.roles().async().create(role, TestCallback()) as TestCallback)!!
// Request
val recordedRequest = server!!.takeRequest()
assertEquals("POST", recordedRequest.method)
assertEquals("/spaces/configuredSpaceId/roles/", recordedRequest.path)
}
@test
fun testUpdate() {
val responseBody = TestUtils.fileToString("roles_update.json")
server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody))
// DO NOT USE IN PRODUCTION: USE A FETCH FIRST!
val role = CMARole()
.setId("sampleId")
.setSpaceId("SPACE_ID")
.setVersion(3)
.setName("DELETE ME!!")
.setDescription("Test role")
.addPolicy(
CMAPolicy()
.allow()
.read()
.create()
.update()
.delete()
.publish()
.unpublish()
.archive()
.unarchive()
.setConstraint(
CMAConstraint()
.setAnd(
CMAConstraint()
.setEquals(
Equals()
.setPath(FieldKeyPath()
.setDoc("fields.foo"))
.setValue("something")
)
)
)
)
.setPermissions(
CMAPermissions()
.setContentModel(arrayListOf("read")
)
)
val result = assertTestCallback(client!!.roles().async()
.update(role, TestCallback()) as TestCallback)!!
assertEquals("3h44ENEEpAA9XNx52dRDs0", result.id)
assertEquals("DELETE ME!!", result.name)
assertEquals("Test role", result.description)
assertEquals(1, result.policies.size)
assertEquals(ALLOW, result.policies[0].effect)
val actions = result.policies[0].actions as List<*>
assertTrue(actions.contains("read"))
assertTrue(actions.contains("create"))
assertTrue(actions.contains("update"))
assertTrue(actions.contains("delete"))
assertTrue(actions.contains("publish"))
assertTrue(actions.contains("unpublish"))
assertTrue(actions.contains("archive"))
assertTrue(actions.contains("unarchive"))
assertEquals("[read]", result.permissions.contentModel.toString())
// Request
val recordedRequest = server!!.takeRequest()
assertEquals("PUT", recordedRequest.method)
assertEquals("/spaces/SPACE_ID/roles/sampleId", recordedRequest.path)
}
@test
fun testDeleteOne() {
val responseBody = TestUtils.fileToString("roles_delete.json")
server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody))
assertTestCallback(client!!.roles().async()
.delete(
CMARole().setId("ROLE_ID").setSpaceId("SPACE_ID"),
TestCallback()
) as TestCallback)
// Request
val recordedRequest = server!!.takeRequest()
assertEquals("DELETE", recordedRequest.method)
assertEquals("/spaces/SPACE_ID/roles/ROLE_ID", recordedRequest.path)
}
} | apache-2.0 | 15462442e104b7e6d7730d5ebd50a373 | 38.45679 | 110 | 0.597825 | 5.245384 | false | true | false | false |
onnerby/musikcube | src/musikdroid/app/src/main/java/io/casey/musikcube/remote/ui/shared/model/DefaultSlidingWindow.kt | 1 | 3984 | package io.casey.musikcube.remote.ui.shared.model
import android.util.Log
import com.simplecityapps.recyclerview_fastscroll.views.FastScrollRecyclerView
import io.casey.musikcube.remote.service.websocket.model.IMetadataProxy
import io.casey.musikcube.remote.service.websocket.model.ITrack
import io.casey.musikcube.remote.service.websocket.model.ITrackListQueryFactory
import io.reactivex.rxkotlin.subscribeBy
class DefaultSlidingWindow(
private val recyclerView: FastScrollRecyclerView,
metadataProxy: IMetadataProxy,
private val queryFactory: ITrackListQueryFactory)
: BaseSlidingWindow(recyclerView, metadataProxy)
{
private var queryOffset = -1
private var queryLimit = -1
private var initialPosition = -1
private var windowSize = DEFAULT_WINDOW_SIZE
private val cache = object : LinkedHashMap<Int, CacheEntry>() {
override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Int, CacheEntry>): Boolean = size >= MAX_SIZE
}
override fun requery() {
if (queryFactory.offline() || connected) {
cancelMessages()
var queried = false
val countObservable = queryFactory.count()
if (countObservable != null) {
@Suppress countObservable.subscribeBy(
onNext = { newCount ->
count = newCount
if (initialPosition != -1) {
recyclerView.scrollToPosition(initialPosition)
initialPosition = -1
}
loadedListener?.onReloaded(count)
},
onError = { _ ->
Log.d("DefaultSlidingWindow", "message send failed, likely canceled")
})
queried = true
}
if (!queried) {
count = 0
loadedListener?.onReloaded(0)
}
}
}
override fun getTrack(index: Int): ITrack? {
val track = cache[index]
if (track == null || track.dirty) {
if (!scrolling()) {
getPageAround(index)
}
}
return track?.value
}
fun setInitialPosition(initialIndex: Int) {
initialPosition = initialIndex
}
override fun invalidate() {
cancelMessages()
for (entry in cache.values) {
entry.dirty = true
}
}
private fun cancelMessages() {
queryLimit = -1
queryOffset = queryLimit
}
override fun getPageAround(index: Int) {
if (!connected || scrolling()) {
return
}
if (index >= queryOffset && index <= queryOffset + queryLimit) {
return /* already in flight */
}
val offset = Math.max(0, index - 10) /* snag a couple before */
val limit = windowSize
val pageRequest = queryFactory.page(offset, limit)
if (pageRequest != null) {
cancelMessages()
queryOffset = offset
queryLimit = limit
@Suppress pageRequest.subscribeBy(
onNext = { response ->
queryLimit = -1
queryOffset = queryLimit
var i = 0
response.forEach { track ->
val entry = CacheEntry()
entry.dirty = false
entry.value = track
cache[offset + i++] = entry
}
notifyAdapterChanged()
notifyMetadataLoaded(offset, i)
},
onError = { _ ->
Log.d("DefaultSlidingWindow", "message send failed, likely canceled")
})
}
}
companion object {
private const val MAX_SIZE = 150
private const val DEFAULT_WINDOW_SIZE = 75
}
}
| bsd-3-clause | e88f32874c75830dc09c6d405308d200 | 29.181818 | 116 | 0.535894 | 5.312 | false | false | false | false |
DemonWav/MinecraftDev | src/main/kotlin/com/demonwav/mcdev/util/MinecraftFileTemplateGroupFactory.kt | 1 | 5373 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.util
import com.demonwav.mcdev.asset.PlatformAssets
import com.intellij.ide.fileTemplates.FileTemplateDescriptor
import com.intellij.ide.fileTemplates.FileTemplateGroupDescriptor
import com.intellij.ide.fileTemplates.FileTemplateGroupDescriptorFactory
class MinecraftFileTemplateGroupFactory : FileTemplateGroupDescriptorFactory {
override fun getFileTemplatesDescriptor(): FileTemplateGroupDescriptor {
val group = FileTemplateGroupDescriptor("Minecraft", PlatformAssets.MINECRAFT_ICON)
group.addTemplate(FileTemplateDescriptor(BUKKIT_MAIN_CLASS_TEMPLATE, PlatformAssets.BUKKIT_ICON))
group.addTemplate(FileTemplateDescriptor(BUKKIT_PLUGIN_YML_TEMPLATE, PlatformAssets.BUKKIT_ICON))
group.addTemplate(FileTemplateDescriptor(BUKKIT_POM_TEMPLATE, PlatformAssets.BUKKIT_ICON))
group.addTemplate(FileTemplateDescriptor(BUNGEECORD_MAIN_CLASS_TEMPLATE, PlatformAssets.BUNGEECORD_ICON))
group.addTemplate(FileTemplateDescriptor(BUNGEECORD_PLUGIN_YML_TEMPLATE, PlatformAssets.BUNGEECORD_ICON))
group.addTemplate(FileTemplateDescriptor(BUNGEECORD_POM_TEMPLATE, PlatformAssets.BUNGEECORD_ICON))
group.addTemplate(FileTemplateDescriptor(SPONGE_BUILD_GRADLE_TEMPLATE, PlatformAssets.SPONGE_ICON))
group.addTemplate(FileTemplateDescriptor(SPONGE_SUBMODULE_BUILD_GRADLE_TEMPLATE, PlatformAssets.SPONGE_ICON))
group.addTemplate(FileTemplateDescriptor(SPONGE_MAIN_CLASS_TEMPLATE, PlatformAssets.SPONGE_ICON))
group.addTemplate(FileTemplateDescriptor(SPONGE_POM_TEMPLATE, PlatformAssets.SPONGE_ICON))
group.addTemplate(FileTemplateDescriptor(FORGE_GRADLE_PROPERTIES_TEMPLATE, PlatformAssets.FORGE_ICON))
group.addTemplate(FileTemplateDescriptor(FORGE_BUILD_GRADLE_TEMPLATE, PlatformAssets.FORGE_ICON))
group.addTemplate(FileTemplateDescriptor(FORGE_SUBMODULE_BUILD_GRADLE_TEMPLATE, PlatformAssets.FORGE_ICON))
group.addTemplate(FileTemplateDescriptor(FORGE_MAIN_CLASS_TEMPLATE, PlatformAssets.FORGE_ICON))
group.addTemplate(FileTemplateDescriptor(MCMOD_INFO_TEMPLATE, PlatformAssets.FORGE_ICON))
group.addTemplate(FileTemplateDescriptor(GRADLE_PROPERTIES_TEMPLATE, PlatformAssets.MINECRAFT_ICON))
group.addTemplate(FileTemplateDescriptor(BUILD_GRADLE_TEMPLATE, PlatformAssets.MINECRAFT_ICON))
group.addTemplate(FileTemplateDescriptor(MULTI_MODULE_BUILD_GRADLE_TEMPLATE, PlatformAssets.MINECRAFT_ICON))
group.addTemplate(FileTemplateDescriptor(SETTINGS_GRADLE_TEMPLATE, PlatformAssets.MINECRAFT_ICON))
group.addTemplate(FileTemplateDescriptor(SUBMODULE_BUILD_GRADLE_TEMPLATE, PlatformAssets.MINECRAFT_ICON))
group.addTemplate(FileTemplateDescriptor(LITELOADER_GRADLE_PROPERTIES_TEMPLATE, PlatformAssets.LITELOADER_ICON))
group.addTemplate(FileTemplateDescriptor(LITELOADER_BUILD_GRADLE_TEMPLATE, PlatformAssets.LITELOADER_ICON))
group.addTemplate(FileTemplateDescriptor(LITELOADER_SUBMODULE_BUILD_GRADLE_TEMPLATE, PlatformAssets.LITELOADER_ICON))
group.addTemplate(FileTemplateDescriptor(LITELOADER_MAIN_CLASS_TEMPLATE, PlatformAssets.LITELOADER_ICON))
group.addTemplate(FileTemplateDescriptor(MIXIN_OVERWRITE_FALLBACK, PlatformAssets.MIXIN_ICON))
return group
}
companion object {
const val BUKKIT_MAIN_CLASS_TEMPLATE = "bukkit_main_class.java"
const val BUKKIT_PLUGIN_YML_TEMPLATE = "bukkit_plugin_description_file.yml"
const val BUKKIT_POM_TEMPLATE = "bukkit_pom_template.xml"
const val BUNGEECORD_MAIN_CLASS_TEMPLATE = "bungeecord_main_class.java"
const val BUNGEECORD_PLUGIN_YML_TEMPLATE = "bungeecord_plugin_description_file.yml"
const val BUNGEECORD_POM_TEMPLATE = "bungeecord_pom_template.xml"
const val SPONGE_BUILD_GRADLE_TEMPLATE = "sponge_build.gradle"
const val SPONGE_SUBMODULE_BUILD_GRADLE_TEMPLATE = "sponge_submodule_build.gradle"
const val SPONGE_MAIN_CLASS_TEMPLATE = "sponge_main_class.java"
const val SPONGE_POM_TEMPLATE = "sponge_pom_template.xml"
const val FORGE_GRADLE_PROPERTIES_TEMPLATE = "forge_gradle.properties"
const val FORGE_BUILD_GRADLE_TEMPLATE = "forge_build.gradle"
const val FORGE_SUBMODULE_BUILD_GRADLE_TEMPLATE = "forge_submodule_build.gradle"
const val FORGE_MAIN_CLASS_TEMPLATE = "forge_main_class.java"
const val MCMOD_INFO_TEMPLATE = "mcmod.info"
const val GRADLE_PROPERTIES_TEMPLATE = "gradle.properties"
const val MULTI_MODULE_BUILD_GRADLE_TEMPLATE = "multi_module_build.gradle"
const val BUILD_GRADLE_TEMPLATE = "build.gradle"
const val SETTINGS_GRADLE_TEMPLATE = "settings.gradle"
const val SUBMODULE_BUILD_GRADLE_TEMPLATE = "submodule_build.gradle"
const val LITELOADER_GRADLE_PROPERTIES_TEMPLATE = "liteloader_gradle.properties"
const val LITELOADER_BUILD_GRADLE_TEMPLATE = "liteloader_build.gradle"
const val LITELOADER_SUBMODULE_BUILD_GRADLE_TEMPLATE = "liteloader_submodule_build.gradle"
const val LITELOADER_MAIN_CLASS_TEMPLATE = "liteloader_main_class.java"
const val MIXIN_OVERWRITE_FALLBACK = "Mixin Overwrite Fallback.java"
}
}
| mit | 83990ed1a5fefe6cb25e945aa88edfc9 | 56.774194 | 125 | 0.772194 | 4.481234 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.