repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
openMF/android-client | mifosng-android/src/main/java/com/mifos/mifosxdroid/online/clientdetails/ClientDetailsFragment.kt | 1 | 29161 | /*
* This project is licensed under the open source MPL V2.
* See https://github.com/openMF/android-client/blob/master/LICENSE.md
*/
package com.mifos.mifosxdroid.online.clientdetails
import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.text.TextUtils
import android.util.Log
import android.view.*
import android.widget.*
import androidx.appcompat.widget.PopupMenu
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.res.ResourcesCompat
import butterknife.BindView
import butterknife.ButterKnife
import butterknife.OnClick
import com.joanzapata.iconify.fonts.MaterialIcons
import com.joanzapata.iconify.widget.IconTextView
import com.mifos.mifosxdroid.R
import com.mifos.mifosxdroid.activity.pinpointclient.PinpointClientActivity
import com.mifos.mifosxdroid.adapters.LoanAccountsListAdapter
import com.mifos.mifosxdroid.adapters.SavingsAccountsListAdapter
import com.mifos.mifosxdroid.core.MifosBaseActivity
import com.mifos.mifosxdroid.core.MifosBaseFragment
import com.mifos.mifosxdroid.core.util.Toaster
import com.mifos.mifosxdroid.online.activate.ActivateFragment
import com.mifos.mifosxdroid.online.clientcharge.ClientChargeFragment
import com.mifos.mifosxdroid.online.clientidentifiers.ClientIdentifiersFragment
import com.mifos.mifosxdroid.online.datatable.DataTableFragment
import com.mifos.mifosxdroid.online.documentlist.DocumentListFragment
import com.mifos.mifosxdroid.online.loanaccount.LoanAccountFragment
import com.mifos.mifosxdroid.online.note.NoteFragment
import com.mifos.mifosxdroid.online.savingsaccount.SavingsAccountFragment
import com.mifos.mifosxdroid.online.sign.SignatureFragment
import com.mifos.mifosxdroid.online.surveylist.SurveyListFragment
import com.mifos.mifosxdroid.views.CircularImageView
import com.mifos.objects.accounts.ClientAccounts
import com.mifos.objects.accounts.savings.DepositType
import com.mifos.objects.client.Charges
import com.mifos.objects.client.Client
import com.mifos.utils.Constants
import com.mifos.utils.FragmentConstants
import com.mifos.utils.ImageLoaderUtils
import com.mifos.utils.Utils
import okhttp3.ResponseBody
import java.io.File
import java.io.FileOutputStream
import java.util.*
import javax.inject.Inject
class ClientDetailsFragment : MifosBaseFragment(), ClientDetailsMvpView {
var imgDecodableString: String? = null
private val TAG = ClientDetailsFragment::class.java.simpleName
var clientId = 0
var chargesList: MutableList<Charges> = ArrayList()
@JvmField
@BindView(R.id.tv_fullName)
var tv_fullName: TextView? = null
@JvmField
@BindView(R.id.tv_accountNumber)
var tv_accountNumber: TextView? = null
@JvmField
@BindView(R.id.tv_externalId)
var tv_externalId: TextView? = null
@JvmField
@BindView(R.id.tv_activationDate)
var tv_activationDate: TextView? = null
@JvmField
@BindView(R.id.tv_office)
var tv_office: TextView? = null
@JvmField
@BindView(R.id.tv_mobile_no)
var tvMobileNo: TextView? = null
@JvmField
@BindView(R.id.tv_group)
var tvGroup: TextView? = null
@JvmField
@BindView(R.id.iv_clientImage)
var iv_clientImage: CircularImageView? = null
@JvmField
@BindView(R.id.pb_imageProgressBar)
var pb_imageProgressBar: ProgressBar? = null
@JvmField
@BindView(R.id.row_account)
var rowAccount: TableRow? = null
@JvmField
@BindView(R.id.row_external)
var rowExternal: TableRow? = null
@JvmField
@BindView(R.id.row_activation)
var rowActivation: TableRow? = null
@JvmField
@BindView(R.id.row_office)
var rowOffice: TableRow? = null
@JvmField
@BindView(R.id.row_group)
var rowGroup: TableRow? = null
@JvmField
@BindView(R.id.row_staff)
var rowStaff: TableRow? = null
@JvmField
@BindView(R.id.row_loan)
var rowLoan: TableRow? = null
@JvmField
@BindView(R.id.tableRow_mobile_no)
var rowMobileNo: TableRow? = null
@JvmField
@BindView(R.id.ll_bottom_panel)
var llBottomPanel: LinearLayout? = null
@JvmField
@BindView(R.id.rl_client)
var rlClient: RelativeLayout? = null
@JvmField
@Inject
var mClientDetailsPresenter: ClientDetailsPresenter? = null
private lateinit var rootView: View
private var mListener: OnFragmentInteractionListener? = null
private val clientImageFile = File(Environment.getExternalStorageDirectory().toString() +
"/client_image.png")
private var accountAccordion: AccountAccordion? = null
private var isClientActive = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
(activity as MifosBaseActivity?)!!.activityComponent.inject(this)
if (arguments != null) {
clientId = requireArguments().getInt(Constants.CLIENT_ID)
}
setHasOptionsMenu(true)
checkPermissions()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
rootView = inflater.inflate(R.layout.fragment_client_details, container, false)
ButterKnife.bind(this, rootView)
mClientDetailsPresenter!!.attachView(this)
inflateClientInformation()
return rootView
}
@OnClick(R.id.btn_activate_client)
fun onClickActivateClient() {
activateClient()
}
fun inflateClientInformation() {
mClientDetailsPresenter!!.loadClientDetailsAndClientAccounts(clientId)
}
override fun onAttach(activity: Activity) {
super.onAttach(activity)
mListener = try {
activity as OnFragmentInteractionListener
} catch (e: ClassCastException) {
throw ClassCastException(requireActivity().javaClass.simpleName + " must " +
"implement OnFragmentInteractionListener")
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
try {
// When an Image is picked
if (requestCode == UPLOAD_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == Activity.RESULT_OK && null != data && data.data != null) {
// Get the Image from data
val selectedImage = data.data!!
val filePathColumn = arrayOf(MediaStore.Images.Media.DATA)
// Get the cursor
val cursor = requireActivity().applicationContext.contentResolver.query(
selectedImage,
filePathColumn, null, null, null)!!
// Move to first row
cursor.moveToFirst()
val columnIndex = cursor.getColumnIndex(filePathColumn[0])
imgDecodableString = cursor.getString(columnIndex)
cursor.close()
val pickedImage = BitmapFactory.decodeFile(imgDecodableString)
saveBitmap(clientImageFile, pickedImage)
uploadImage(clientImageFile)
} else if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE
&& resultCode == Activity.RESULT_OK) {
uploadImage(clientImageFile)
} else {
Toaster.show(rootView, R.string.havent_picked_image,
Toast.LENGTH_LONG)
}
} catch (e: Exception) {
Toaster.show(rootView, e.toString(), Toast.LENGTH_LONG)
}
}
fun saveBitmap(file: File, mBitmap: Bitmap) {
try {
file.createNewFile()
var fOut: FileOutputStream? = null
fOut = FileOutputStream(file)
mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut)
fOut.flush()
fOut.close()
} catch (exception: Exception) {
//Empty catch block to prevent crashing
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
}
override fun onPrepareOptionsMenu(menu: Menu) {
menu.clear()
if (isClientActive) {
menu.add(Menu.NONE, MENU_ITEM_DATA_TABLES, Menu.NONE, getString(R.string.more_info))
menu.add(Menu.NONE, MENU_ITEM_PIN_POINT, Menu.NONE, getString(R.string.pinpoint))
menu.add(Menu.NONE, MENU_ITEM_CLIENT_CHARGES, Menu.NONE, getString(R.string.charges))
menu.add(Menu.NONE, MENU_ITEM_ADD_SAVINGS_ACCOUNT, Menu.NONE, getString(R.string.savings_account))
menu.add(Menu.NONE, MENU_ITEM_ADD_LOAN_ACCOUNT, Menu.NONE,
getString(R.string.add_loan))
menu.add(Menu.NONE, MENU_ITEM_DOCUMENTS, Menu.NONE, getString(R.string.documents))
menu.add(Menu.NONE, MENU_ITEM_UPLOAD_SIGN, Menu.NONE, R.string.upload_sign)
menu.add(Menu.NONE, MENU_ITEM_IDENTIFIERS, Menu.NONE, getString(R.string.identifiers))
menu.add(Menu.NONE, MENU_ITEM_SURVEYS, Menu.NONE, getString(R.string.survey))
menu.add(Menu.NONE, MENU_ITEM_NOTE, Menu.NONE, getString(R.string.note))
}
super.onPrepareOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
MENU_ITEM_DATA_TABLES -> loadClientDataTables()
MENU_ITEM_DOCUMENTS -> loadDocuments()
MENU_ITEM_UPLOAD_SIGN -> loadSignUpload()
MENU_ITEM_CLIENT_CHARGES -> loadClientCharges()
MENU_ITEM_ADD_SAVINGS_ACCOUNT -> addsavingsaccount()
MENU_ITEM_ADD_LOAN_ACCOUNT -> addloanaccount()
MENU_ITEM_IDENTIFIERS -> loadIdentifiers()
MENU_ITEM_PIN_POINT -> {
val i = Intent(activity, PinpointClientActivity::class.java)
i.putExtra(Constants.CLIENT_ID, clientId)
startActivity(i)
}
MENU_ITEM_SURVEYS -> loadSurveys()
MENU_ITEM_NOTE -> loadNotes()
}
return super.onOptionsItemSelected(item)
}
fun captureClientImage() {
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(clientImageFile))
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
}
private fun checkPermissions() {
if (ContextCompat.checkSelfPermission(requireActivity(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(requireActivity(), arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
CHECK_PERMISSIONS)
}
}
fun uploadClientImage() {
// Create intent to Open Image applications like Gallery, Google Photos
val galleryIntent = Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
// Start the Intent
galleryIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(clientImageFile))
startActivityForResult(galleryIntent, UPLOAD_IMAGE_ACTIVITY_REQUEST_CODE)
}
/**
* A service to upload the image of the client.
*
* @param pngFile - PNG images supported at the moment
*/
private fun uploadImage(pngFile: File) {
mClientDetailsPresenter!!.uploadImage(clientId, pngFile)
}
override fun onDestroyView() {
super.onDestroyView()
mClientDetailsPresenter!!.detachView()
}
fun loadDocuments() {
val documentListFragment = DocumentListFragment.newInstance(Constants.ENTITY_TYPE_CLIENTS, clientId)
val fragmentTransaction = requireActivity().supportFragmentManager
.beginTransaction()
fragmentTransaction.addToBackStack(FragmentConstants.FRAG_CLIENT_DETAILS)
fragmentTransaction.replace(R.id.container, documentListFragment)
fragmentTransaction.commit()
}
fun loadNotes() {
val noteFragment = NoteFragment.newInstance(Constants.ENTITY_TYPE_CLIENTS, clientId)
val fragmentTransaction = requireActivity().supportFragmentManager
.beginTransaction()
fragmentTransaction.addToBackStack(FragmentConstants.FRAG_CLIENT_DETAILS)
fragmentTransaction.replace(R.id.container, noteFragment)
fragmentTransaction.commit()
}
fun loadClientCharges() {
val clientChargeFragment: ClientChargeFragment = ClientChargeFragment.Companion.newInstance(clientId,
chargesList)
val fragmentTransaction = requireActivity().supportFragmentManager
.beginTransaction()
fragmentTransaction.addToBackStack(FragmentConstants.FRAG_CLIENT_DETAILS)
fragmentTransaction.replace(R.id.container, clientChargeFragment)
fragmentTransaction.commit()
}
fun loadIdentifiers() {
val clientIdentifiersFragment: ClientIdentifiersFragment = ClientIdentifiersFragment.Companion.newInstance(clientId)
val fragmentTransaction = requireActivity().supportFragmentManager
.beginTransaction()
fragmentTransaction.addToBackStack(FragmentConstants.FRAG_CLIENT_DETAILS)
fragmentTransaction.replace(R.id.container, clientIdentifiersFragment)
fragmentTransaction.commit()
}
fun loadSurveys() {
val surveyListFragment = SurveyListFragment.newInstance(clientId)
val fragmentTransaction = requireActivity().supportFragmentManager
.beginTransaction()
fragmentTransaction.addToBackStack(FragmentConstants.FRAG_CLIENT_DETAILS)
fragmentTransaction.replace(R.id.container, surveyListFragment)
fragmentTransaction.commit()
}
fun addsavingsaccount() {
val savingsAccountFragment = SavingsAccountFragment.newInstance(clientId, false)
val fragmentTransaction = requireActivity().supportFragmentManager
.beginTransaction()
fragmentTransaction.addToBackStack(FragmentConstants.FRAG_CLIENT_DETAILS)
fragmentTransaction.replace(R.id.container, savingsAccountFragment)
fragmentTransaction.commit()
}
fun addloanaccount() {
val loanAccountFragment = LoanAccountFragment.newInstance(clientId)
val fragmentTransaction = requireActivity().supportFragmentManager
.beginTransaction()
fragmentTransaction.addToBackStack(FragmentConstants.FRAG_CLIENT_DETAILS)
fragmentTransaction.replace(R.id.container, loanAccountFragment)
fragmentTransaction.commit()
}
fun activateClient() {
val activateFragment = ActivateFragment.newInstance(clientId, Constants.ACTIVATE_CLIENT)
val fragmentTransaction = requireActivity().supportFragmentManager
.beginTransaction()
fragmentTransaction.addToBackStack(FragmentConstants.FRAG_CLIENT_DETAILS)
fragmentTransaction.replace(R.id.container, activateFragment)
fragmentTransaction.commit()
}
fun loadClientDataTables() {
val loanAccountFragment = DataTableFragment.newInstance(Constants.DATA_TABLE_NAME_CLIENT, clientId)
val fragmentTransaction = requireActivity().supportFragmentManager
.beginTransaction()
fragmentTransaction.addToBackStack(FragmentConstants.FRAG_CLIENT_DETAILS)
fragmentTransaction.replace(R.id.container, loanAccountFragment)
fragmentTransaction.commit()
}
fun loadSignUpload() {
val fragment = SignatureFragment()
val bundle = Bundle()
bundle.putInt(Constants.CLIENT_ID, clientId)
fragment.arguments = bundle
val fragmentTransaction = requireActivity().supportFragmentManager
.beginTransaction()
fragmentTransaction.addToBackStack(FragmentConstants.FRAG_CLIENT_DETAILS)
fragmentTransaction.replace(R.id.container, fragment).commit()
}
override fun showProgressbar(show: Boolean) {
if (show) {
rlClient!!.visibility = View.GONE
showMifosProgressBar()
} else {
rlClient!!.visibility = View.VISIBLE
hideMifosProgressBar()
}
}
override fun showClientInformation(client: Client?) {
if (client != null) {
setToolbarTitle(getString(R.string.client) + " - " + client.displayName)
isClientActive = client.isActive
requireActivity().invalidateOptionsMenu()
if (!client.isActive) {
llBottomPanel!!.visibility = View.VISIBLE
}
tv_fullName!!.text = client.displayName
tv_accountNumber!!.text = client.accountNo
tvGroup!!.text = client.groupNames
tv_externalId!!.text = client.externalId
tvMobileNo!!.text = client.mobileNo
if (TextUtils.isEmpty(client.accountNo)) rowAccount!!.visibility = View.GONE
if (TextUtils.isEmpty(client.externalId)) rowExternal!!.visibility = View.GONE
if (TextUtils.isEmpty(client.mobileNo)) rowMobileNo!!.visibility = View.GONE
if (TextUtils.isEmpty(client.groupNames)) rowGroup!!.visibility = View.GONE
try {
val dateString = Utils.getStringOfDate(
client.activationDate)
tv_activationDate!!.text = dateString
if (TextUtils.isEmpty(dateString)) rowActivation!!.visibility = View.GONE
} catch (e: IndexOutOfBoundsException) {
Toast.makeText(activity, getString(R.string.error_client_inactive),
Toast.LENGTH_SHORT).show()
tv_activationDate!!.text = ""
}
tv_office!!.text = client.officeName
if (TextUtils.isEmpty(client.officeName)) rowOffice!!.visibility = View.GONE
if (client.isImagePresent) {
loadClientProfileImage()
} else {
iv_clientImage!!.setImageDrawable(
ResourcesCompat.getDrawable(resources, R.drawable.ic_launcher, null))
pb_imageProgressBar!!.visibility = View.GONE
}
iv_clientImage!!.setOnClickListener { view ->
val menu = PopupMenu(requireActivity(), view)
menu.menuInflater.inflate(R.menu.client_image_popup, menu
.menu)
if (!client.isImagePresent) {
menu.menu.findItem(R.id.client_image_remove).isVisible = false
}
menu.setOnMenuItemClickListener { menuItem ->
when (menuItem.itemId) {
R.id.client_image_upload -> uploadClientImage()
R.id.client_image_capture -> captureClientImage()
R.id.client_image_remove -> mClientDetailsPresenter!!.deleteClientImage(clientId)
else -> Log.e("ClientDetailsFragment", "Unrecognized " +
"client " +
"image menu item")
}
true
}
menu.show()
}
//inflateClientsAccounts();
}
}
override fun showUploadImageSuccessfully(response: ResponseBody?, imagePath: String?) {
Toaster.show(rootView, R.string.client_image_updated)
iv_clientImage!!.setImageBitmap(BitmapFactory.decodeFile(imagePath))
}
override fun showUploadImageFailed(s: String?) {
Toaster.show(rootView, s)
loadClientProfileImage()
}
override fun showUploadImageProgressbar(b: Boolean) {
if (b) {
pb_imageProgressBar!!.visibility = View.VISIBLE
} else {
pb_imageProgressBar!!.visibility = View.GONE
}
}
fun loadClientProfileImage() {
pb_imageProgressBar!!.visibility = View.VISIBLE
ImageLoaderUtils.loadImage(activity, clientId, iv_clientImage)
pb_imageProgressBar!!.visibility = View.GONE
}
override fun showClientImageDeletedSuccessfully() {
Toaster.show(rootView, "Image deleted")
iv_clientImage!!.setImageDrawable(ContextCompat.getDrawable(requireActivity(), R.drawable.ic_launcher))
}
override fun showClientAccount(clientAccounts: ClientAccounts) {
// Proceed only when the fragment is added to the activity.
if (!isAdded) {
return
}
accountAccordion = AccountAccordion(activity)
if (clientAccounts.loanAccounts.size > 0) {
val section = AccountAccordion.Section.LOANS
val adapter = LoanAccountsListAdapter(requireActivity().applicationContext,
clientAccounts.loanAccounts)
section.connect(activity, adapter, AdapterView.OnItemClickListener { adapterView, view, i, l -> mListener!!.loadLoanAccountSummary(adapter.getItem(i).id) })
}
if (clientAccounts.nonRecurringSavingsAccounts.size > 0) {
val section = AccountAccordion.Section.SAVINGS
val adapter = SavingsAccountsListAdapter(requireActivity().applicationContext,
clientAccounts.nonRecurringSavingsAccounts)
section.connect(activity, adapter, AdapterView.OnItemClickListener { adapterView, view, i, l ->
mListener!!.loadSavingsAccountSummary(adapter.getItem(i).id,
adapter.getItem(i).depositType)
})
}
if (clientAccounts.recurringSavingsAccounts.size > 0) {
val section = AccountAccordion.Section.RECURRING
val adapter = SavingsAccountsListAdapter(requireActivity().applicationContext,
clientAccounts.recurringSavingsAccounts)
section.connect(activity, adapter, AdapterView.OnItemClickListener { adapterView, view, i, l ->
mListener!!.loadSavingsAccountSummary(adapter.getItem(i).id,
adapter.getItem(i).depositType)
})
}
}
override fun showFetchingError(s: String?) {
Toast.makeText(activity, s, Toast.LENGTH_SHORT).show()
}
interface OnFragmentInteractionListener {
fun loadLoanAccountSummary(loanAccountNumber: Int)
fun loadSavingsAccountSummary(savingsAccountNumber: Int, accountType: DepositType?)
}
private class AccountAccordion(private val context: Activity?) {
private var currentSection: Section? = null
fun setCurrentSection(currentSection: Section?) {
// close previous section
if (this.currentSection != null) {
this.currentSection!!.close(context)
}
this.currentSection = currentSection
// open new section
if (this.currentSection != null) {
this.currentSection!!.open(context)
}
}
enum class Section(private val sectionId: Int, private val textViewStringId: Int) {
LOANS(R.id.account_accordion_section_loans, R.string.loanAccounts), SAVINGS(R.id.account_accordion_section_savings, R.string.savingAccounts), RECURRING(R.id.account_accordion_section_recurring, R.string.recurringAccount);
private var mListViewCount = 0.0
fun getTextView(context: Activity?): TextView {
return getSectionView(context).findViewById<View>(R.id.tv_toggle_accounts) as TextView
}
fun getIconView(context: Activity?): IconTextView {
return getSectionView(context).findViewById<View>(R.id.tv_toggle_accounts_icon) as IconTextView
}
fun getListView(context: Activity?): ListView {
return getSectionView(context).findViewById<View>(R.id.lv_accounts) as ListView
}
fun getCountView(context: Activity?): TextView {
return getSectionView(context).findViewById<View>(R.id.tv_count_accounts) as TextView
}
fun getSectionView(context: Activity?): View {
return context!!.findViewById(sectionId)
}
fun connect(context: Activity?, adapter: ListAdapter, onItemClickListener: AdapterView.OnItemClickListener?) {
getCountView(context).text = adapter.count.toString()
val listView = getListView(context)
listView.adapter = adapter
listView.onItemClickListener = onItemClickListener
}
fun open(context: Activity?) {
val iconView = getIconView(context)
iconView.text = "{" + LIST_CLOSED_ICON.key() + "}"
mListViewCount = java.lang.Double.valueOf(getCountView(context)
.text
.toString())
val listView = getListView(context)
resizeListView(context, listView)
listView.visibility = View.VISIBLE
}
fun close(context: Activity?) {
val iconView = getIconView(context)
iconView.text = "{" + LIST_OPEN_ICON.key() + "}"
getListView(context).visibility = View.GONE
}
private fun configureSection(context: Activity?, accordion: AccountAccordion) {
val listView = getListView(context)
val textView = getTextView(context)
val iconView = getIconView(context)
val onClickListener = View.OnClickListener {
if (this@Section == accordion.currentSection) {
accordion.setCurrentSection(null)
} else if (listView != null && listView.count > 0) {
accordion.setCurrentSection(this@Section)
}
}
if (textView != null) {
textView.setOnClickListener(onClickListener)
textView.text = context!!.getString(textViewStringId)
}
iconView?.setOnClickListener(onClickListener)
listView?.setOnTouchListener { view, motionEvent ->
view.parent.requestDisallowInterceptTouchEvent(true)
false
}
// initialize section in closed state
close(context)
}
private fun resizeListView(context: Activity?, listView: ListView) {
if (mListViewCount < 4) {
//default listview height is 200dp,which displays 4 listview items.
// This calculates the required listview height
// if listview items are less than 4
val heightInDp = mListViewCount / 4 * 200
val heightInPx = heightInDp * context!!.resources
.displayMetrics.density
val params = listView.layoutParams
params.height = heightInPx.toInt()
listView.layoutParams = params
listView.requestLayout()
}
}
companion object {
private val LIST_OPEN_ICON = MaterialIcons.md_add_circle_outline
private val LIST_CLOSED_ICON = MaterialIcons.md_remove_circle_outline
fun configure(context: Activity?, accordion: AccountAccordion) {
for (section in values()) {
section.configureSection(context, accordion)
}
}
}
}
init {
Section.configure(context, this)
}
}
companion object {
// Intent response codes. Each response code must be a unique integer.
private const val CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 2
private const val UPLOAD_IMAGE_ACTIVITY_REQUEST_CODE = 1
private const val CHECK_PERMISSIONS = 1010
const val MENU_ITEM_DATA_TABLES = 1000
const val MENU_ITEM_PIN_POINT = 1001
const val MENU_ITEM_CLIENT_CHARGES = 1003
const val MENU_ITEM_ADD_SAVINGS_ACCOUNT = 1004
const val MENU_ITEM_ADD_LOAN_ACCOUNT = 1005
const val MENU_ITEM_DOCUMENTS = 1006
const val MENU_ITEM_UPLOAD_SIGN = 1010
const val MENU_ITEM_IDENTIFIERS = 1007
const val MENU_ITEM_SURVEYS = 1008
const val MENU_ITEM_NOTE = 1009
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param clientId Client's Id
*/
fun newInstance(clientId: Int): ClientDetailsFragment {
val fragment = ClientDetailsFragment()
val args = Bundle()
args.putInt(Constants.CLIENT_ID, clientId)
fragment.arguments = args
return fragment
}
}
} | mpl-2.0 | 12d3193eea4ddf6df7e304abf66a3c85 | 40.77937 | 233 | 0.646206 | 5.128561 | false | false | false | false |
tokenbrowser/token-android-client | app/src/main/java/com/toshi/view/adapter/TokenAdapter.kt | 1 | 2036 | /*
* 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.adapter
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import com.toshi.R
import com.toshi.model.network.token.ERCToken
import com.toshi.model.network.token.Token
import com.toshi.view.adapter.viewholder.TokenType
import com.toshi.view.adapter.viewholder.TokensViewHolder
class TokenAdapter(
private val tokenType: TokenType
) : BaseCompoundableAdapter<TokensViewHolder, Token>() {
var tokenListener: ((Token) -> Unit)? = null
var ERC721Listener: ((ERCToken) -> Unit)? = null
override fun compoundableBindViewHolder(viewHolder: RecyclerView.ViewHolder, adapterIndex: Int) {
val typedHolder = viewHolder as TokensViewHolder
onBindViewHolder(typedHolder, adapterIndex)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TokensViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.list_item__token, parent, false)
return TokensViewHolder(tokenType, itemView)
}
override fun onBindViewHolder(holder: TokensViewHolder, position: Int) {
val token = safelyAt(position)
?: throw AssertionError("No user at $position")
holder.setToken(token, tokenListener, ERC721Listener)
}
} | gpl-3.0 | 76d0bdea8c75df980ed6d2ed48af375e | 38.941176 | 108 | 0.730354 | 4.313559 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/osm/mapdata/MutableMapData.kt | 1 | 1236 | package de.westnordost.streetcomplete.data.osm.mapdata
open class MutableMapData() : MapData {
constructor(other: Iterable<Element>) : this() {
addAll(other)
}
protected val nodesById: MutableMap<Long, Node> = mutableMapOf()
protected val waysById: MutableMap<Long, Way> = mutableMapOf()
protected val relationsById: MutableMap<Long, Relation> = mutableMapOf()
override var boundingBox: BoundingBox? = null
override val nodes get() = nodesById.values
override val ways get() = waysById.values
override val relations get() = relationsById.values
override fun getNode(id: Long) = nodesById[id]
override fun getWay(id: Long) = waysById[id]
override fun getRelation(id: Long) = relationsById[id]
fun addAll(elements: Iterable<Element>) {
elements.forEach(this::add)
}
fun add(element: Element) {
when(element) {
is Node -> nodesById[element.id] = element
is Way -> waysById[element.id] = element
is Relation -> relationsById[element.id] = element
}
}
override fun iterator(): Iterator<Element> {
return (nodes.asSequence() + ways.asSequence() + relations.asSequence()).iterator()
}
}
| gpl-3.0 | 4dc63da3e416b889694e490f0e5ce5a6 | 32.405405 | 91 | 0.662621 | 4.262069 | false | false | false | false |
aleksey-zhidkov/jeb-k | src/main/kotlin/jeb/cfg/values.kt | 1 | 2725 | package jeb.cfg
import java.util.*
import kotlin.Boolean as KBoolean
import kotlin.String as KString
sealed class Json<out T : Any>(protected open val value: T,
private val cmp: (T, T) -> KBoolean = { value, other -> value == other }) {
class String(override public val value: KString) : Json<KString>(value) {
override fun toString(): KString = "\"$value\""
}
class Integer(override public val value: Int) : Json<Int>(value) {
override fun toString() = value.toString()
}
object True : Json.Boolean(true)
object False : Json.Boolean(false)
class Object(private val fields: LinkedHashMap<KString, Json<Any>>) : Json<LinkedHashMap<KString, Json<Any>>>(fields, Json.Object.compareValue) {
operator fun get(key: KString) = fields[key]
override fun toString(): KString =
fields.map { "\"${it.key}\":${it.value.toString()}" }.
joinToString(",", "{", "}")
companion object {
val compareValue: (LinkedHashMap<KString, Json<Any>>, LinkedHashMap<KString, Json<Any>>) -> kotlin.Boolean = { fields, other ->
fields.keys.zip(other.keys).all {
it.first == it.second && fields[it.first] == fields[it.first]
}
}
}
}
class Array(private val items: List<Json<Any>>) : Json<List<Json<Any>>>(items, compareValue), List<Json<Any>> by items {
override fun toString(): KString = items.joinToString(",", "[", "]")
inline fun <reified T> toListOf(): List<T> {
return map { it.value as T }
}
companion object {
val compareValue: (List<Json<*>>, List<Json<*>>) -> kotlin.Boolean = { value, other ->
value.zip(value).all { it.first == it.second }
}
}
}
open class Boolean(value: KBoolean) : Json<KBoolean>(value) {
override fun toString() = value.toString()
}
override fun equals(other: Any?): kotlin.Boolean {
if (this === other) return true
if (other?.javaClass != javaClass) return false
@Suppress("UNCHECKED_CAST")
val otherValue = (other as Json<T>).value
return cmp(value, otherValue)
}
override fun hashCode(): Int {
return value.hashCode()
}
}
fun Any.toJson(): Json<Any> {
return when (this) {
is KString -> Json.String(this)
is Int -> Json.Integer(this)
is KBoolean -> if (this) Json.True else Json.False
is List<*> -> Json.Array(this.map { it!!.toJson() })
else -> throw IllegalStateException("Could not render to json instances of ${this.javaClass}")
}
}
| apache-2.0 | 220c5cf76383497c69f2746924bdf491 | 28.945055 | 149 | 0.572844 | 4.205247 | false | false | false | false |
recurly/recurly-client-android | AndroidSdk/src/main/java/com/recurly/androidsdk/data/network/TokenService.kt | 1 | 2345 | package com.recurly.androidsdk.data.network
import com.recurly.androidsdk.data.model.tokenization.ErrorRecurly
import com.recurly.androidsdk.data.model.tokenization.TokenizationRequest
import com.recurly.androidsdk.data.model.tokenization.TokenizationResponse
import com.recurly.androidsdk.data.network.core.RetrofitHelper
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class TokenService {
private val retrofit = RetrofitHelper.getRetrofit()
/**
* @param TokenizationRequest
* @return TokenizationResponse
*
* If the api call succeeds the response will a TokenizationResponse
*
* If the api call fails the response will be an empty Response Object with everything set
* on empty
*
*/
suspend fun getToken(request: TokenizationRequest): TokenizationResponse {
return withContext(Dispatchers.IO) {
val response =
retrofit.create(RecurlyApiClient::class.java).recurlyTokenization(
first_name = request.firstName,
last_name = request.lastName,
company = request.company,
address1 = request.addressOne,
address2 = request.addressTwo,
city = request.city,
state = request.state,
postal_code = request.postalCode,
country = request.country,
phone = request.phone,
vat_number = request.vatNumber,
tax_identifier = request.taxIdentifier,
tax_identifier_type = request.taxIdentifierType,
number = request.cardNumber,
month = request.expirationMonth,
year = request.expirationYear,
cvv = request.cvvCode,
version = request.sdkVersion,
key = request.publicKey,
deviceId = request.deviceId,
sessionId = request.sessionId
)
response.body() ?: TokenizationResponse(
"", "", ErrorRecurly(
"", "", emptyList(),
emptyList()
)
)
}
}
} | mit | 01d045bac93cb6d2163963bbc688b9a6 | 37.779661 | 94 | 0.563326 | 5.664251 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/ui/NewPlayLocationsFragment.kt | 1 | 3972 | package com.boardgamegeek.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.doAfterTextChanged
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.RecyclerView
import com.boardgamegeek.R
import com.boardgamegeek.databinding.FragmentNewPlayLocationsBinding
import com.boardgamegeek.databinding.RowNewPlayLocationBinding
import com.boardgamegeek.entities.LocationEntity
import com.boardgamegeek.extensions.fadeIn
import com.boardgamegeek.extensions.fadeOut
import com.boardgamegeek.extensions.inflate
import com.boardgamegeek.ui.adapter.AutoUpdatableAdapter
import com.boardgamegeek.ui.viewmodel.NewPlayViewModel
import kotlin.properties.Delegates
class NewPlayLocationsFragment : Fragment() {
private var _binding: FragmentNewPlayLocationsBinding? = null
private val binding get() = _binding!!
private val viewModel by activityViewModels<NewPlayViewModel>()
private val adapter: LocationsAdapter by lazy { LocationsAdapter(viewModel) }
@Suppress("RedundantNullableReturnType")
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
_binding = FragmentNewPlayLocationsBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.recyclerView.setHasFixedSize(true)
binding.recyclerView.adapter = adapter
viewModel.locations.observe(viewLifecycleOwner) {
adapter.locations = it
binding.recyclerView.fadeIn()
if (it.isEmpty()) {
if (binding.filterEditText.text.isNullOrBlank()) {
binding.emptyView.setText(R.string.empty_new_play_locations)
} else {
binding.emptyView.setText(R.string.empty_new_play_locations_filter)
}
binding.emptyView.fadeIn()
} else {
binding.emptyView.fadeOut()
}
}
binding.filterEditText.doAfterTextChanged { viewModel.filterLocations(it.toString()) }
binding.next.setOnClickListener {
viewModel.setLocation(binding.filterEditText.text.toString())
}
}
override fun onResume() {
super.onResume()
(activity as? AppCompatActivity)?.supportActionBar?.setSubtitle(R.string.title_location)
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
private class LocationsAdapter(private val viewModel: NewPlayViewModel) : RecyclerView.Adapter<LocationsAdapter.LocationsViewHolder>(),
AutoUpdatableAdapter {
var locations: List<LocationEntity> by Delegates.observable(emptyList()) { _, oldValue, newValue ->
autoNotify(oldValue, newValue) { old, new ->
old.name == new.name
}
}
override fun getItemCount() = locations.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LocationsViewHolder {
return LocationsViewHolder(parent.inflate(R.layout.row_new_play_location))
}
override fun onBindViewHolder(holder: LocationsViewHolder, position: Int) {
holder.bind(locations.getOrNull(position))
}
inner class LocationsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val binding = RowNewPlayLocationBinding.bind(itemView)
fun bind(location: LocationEntity?) {
location?.let { l ->
binding.nameView.text = l.name
itemView.setOnClickListener { viewModel.setLocation(l.name) }
}
}
}
}
}
| gpl-3.0 | 48871dcab43e79db1106e0234dc3b8f0 | 37.941176 | 139 | 0.693353 | 5.145078 | false | false | false | false |
songzhw/Hello-kotlin | AdvancedJ/src/main/kotlin/utils/SecurityUtil.kt | 1 | 1040 | package utils
import java.security.MessageDigest
fun String.sha512() : String{
val bytes : ByteArray = MessageDigest.getInstance("SHA-512")
.digest(this.toByteArray())
return bytes.toHex()
}
fun ByteArray.toHex() : String{
val sb = StringBuilder()
this.forEach { value ->
val hexInt = value.toInt() and (0xFF)
val hexString = Integer.toHexString(hexInt)
if(hexString.length == 1){
sb.append("0")
}
sb.append(hexString)
}
return sb.toString()
}
fun String.salt() : String{
val pwdSalt = "biu-gO82nx_d" + this +"_8dnx0%sdc"
val pwdInSha = pwdSalt.sha512()
return pwdInSha
}
fun main(args: Array<String>) {
println("Renran4".salt()) //=> cfe3d11e25d864f9c5370ac839062c83e014ae261b5d7f8029348c448939780b5f3136f5974bf4d9219d6e742069ddf7860ecc1ca6b9e27d7b5ca3d259b4c5fc
println("594szw".salt()) //=> 54c57e3b29df8a913897885eb7706a70c41776ba20bfddadab21bf728b2be84966344b92f47fed2ceac37df8a3be9dd2d856cdf064a3df6beb984c8a83ecb349
} | apache-2.0 | f3caa2fa1392b53dac5150e06bb94e4d | 28.742857 | 163 | 0.700962 | 2.765957 | false | false | false | false |
Flank/fladle | buildSrc/src/test/java/com/osacky/flank/gradle/integration/FlankGradlePluginIntegrationTest.kt | 1 | 5112 | package com.osacky.flank.gradle.integration
import com.google.common.truth.Truth.assertThat
import org.gradle.testkit.runner.GradleRunner
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
class FlankGradlePluginIntegrationTest {
@get:Rule
var testProjectRoot = TemporaryFolder()
val minSupportGradleVersion = "5.5"
val oldVersion = "5.3.1"
fun writeBuildGradle(build: String) {
val file = testProjectRoot.newFile("build.gradle")
file.writeText(build)
}
@Test
fun testLowGradleVersionFailsBuild() {
writeBuildGradle(
"""plugins {
| id "com.osacky.fladle"
|}""".trimMargin()
)
val result = GradleRunner.create()
.withProjectDir(testProjectRoot.root)
.withPluginClasspath()
.withGradleVersion(oldVersion)
.buildAndFail()
assertThat(result.output).contains("Fladle requires at minimum version Gradle 5.5. Detected version Gradle 5.3.1")
}
@Test
fun testGradleSixZero() {
writeBuildGradle(
"""plugins {
| id "com.osacky.fladle"
|}""".trimMargin()
)
val result = GradleRunner.create()
.withProjectDir(testProjectRoot.root)
.withPluginClasspath()
.withGradleVersion("6.0")
.build()
assertThat(result.output).contains("SUCCESS")
}
@Test
fun testMinSupportedGradleVersionWorks() {
writeBuildGradle(
"""plugins {
| id "com.osacky.fladle"
|}""".trimMargin()
)
GradleRunner.create()
.withProjectDir(testProjectRoot.root)
.withPluginClasspath()
.withGradleVersion(minSupportGradleVersion)
.build()
}
@Test
fun testMissingServiceAccountWithProjectId() {
writeBuildGradle(
"""plugins {
| id "com.osacky.fladle"
|}
|
|fladle {
| projectId = "foo-project"
| debugApk = "foo"
| instrumentationApk = "fakeInstrument.apk"
|}""".trimMargin()
)
GradleRunner.create()
.withProjectDir(testProjectRoot.root)
.withPluginClasspath()
.withGradleVersion(minSupportGradleVersion)
.withArguments("printYml")
.build()
}
@Test
fun testMissingServiceAccountFailsBuild() {
writeBuildGradle(
"""plugins {
| id "com.osacky.fladle"
|}
|
|fladle {
| debugApk = "foo"
|}""".trimMargin()
)
val result = GradleRunner.create()
.withProjectDir(testProjectRoot.root)
.withPluginClasspath()
.withGradleVersion(minSupportGradleVersion)
.withArguments("printYml")
.buildAndFail()
assertThat(result.output).contains("ServiceAccountCredentials in fladle extension not set. https://github.com/runningcode/fladle#serviceaccountcredentials")
}
@Test
fun testMissingApkFailsBuild() {
writeBuildGradle(
"""plugins {
| id "com.osacky.fladle"
|}
|fladle {
| serviceAccountCredentials = project.layout.projectDirectory.file("foo")
|}
|""".trimMargin()
)
testProjectRoot.newFile("foo").writeText("{}")
val result = GradleRunner.create()
.withProjectDir(testProjectRoot.root)
.withPluginClasspath()
.withGradleVersion(minSupportGradleVersion)
.withArguments("runFlank")
.buildAndFail()
assertThat(result.output).contains("debugApk must be specified")
}
@Test
fun testMissingInstrumentationApkFailsBuild() {
writeBuildGradle(
"""plugins {
id "com.osacky.fladle"
}
fladle {
serviceAccountCredentials = project.layout.projectDirectory.file("foo")
debugApk = "test-debug.apk"
}
""".trimIndent()
)
testProjectRoot.newFile("foo").writeText("{}")
val result = GradleRunner.create()
.withProjectDir(testProjectRoot.root)
.withPluginClasspath()
.withGradleVersion(minSupportGradleVersion)
.withArguments("runFlank")
.buildAndFail()
assertThat(result.output).contains("Must specify either a instrumentationApk file or a roboScript file.")
}
@Test
fun testSpecifyingBothInstrumenationAndRoboscriptFailsBuild() {
writeBuildGradle(
"""plugins {
id "com.osacky.fladle"
}
fladle {
serviceAccountCredentials = project.layout.projectDirectory.file("foo")
debugApk = "test-debug.apk"
instrumentationApk = "instrumenation-debug.apk"
roboScript = "foo.script"
}
""".trimIndent()
)
testProjectRoot.newFile("foo").writeText("{}")
val result = GradleRunner.create()
.withProjectDir(testProjectRoot.root)
.withPluginClasspath()
.withGradleVersion(minSupportGradleVersion)
.withArguments("printYml")
.buildAndFail()
assertThat(result.output).contains("Both instrumentationApk file and roboScript file were specified, but only one is expected.")
}
}
| apache-2.0 | 12c9dd370b1a2158e8aa764aebe90321 | 28.045455 | 160 | 0.626956 | 5.021611 | false | true | false | false |
herolynx/elepantry-android | app/src/main/java/com/herolynx/elepantry/ext/google/drive/GoogleDriveResource.kt | 1 | 1908 | package com.herolynx.elepantry.ext.google.drive
import android.app.Activity
import android.net.Uri
import com.google.api.services.drive.Drive
import com.herolynx.elepantry.core.Result
import com.herolynx.elepantry.core.log.debug
import com.herolynx.elepantry.core.net.asInputStream
import com.herolynx.elepantry.core.ui.WebViewUtils
import com.herolynx.elepantry.drive.CloudResource
import com.herolynx.elepantry.ext.android.AppManager
import com.herolynx.elepantry.ext.android.Storage
import com.herolynx.elepantry.resources.core.model.Resource
import org.funktionale.tries.Try
import rx.Observable
import java.io.InputStream
class GoogleDriveResource(
private val metaInfo: Resource,
private val drive: Drive
) : CloudResource {
override fun preview(activity: Activity, beforeAction: () -> Unit, afterAction: () -> Unit): Try<Result> {
if (AppManager.isAppInstalled(activity, GoogleDrive.APP_PACKAGE_NAME)) {
return WebViewUtils.openLink(activity, metaInfo.downloadLink)
} else {
return download(activity, beforeAction, afterAction)
}
}
override fun download(activity: Activity, beforeAction: () -> Unit, afterAction: () -> Unit): Try<Result> = Try {
Storage.downloadAndOpen(
activity = activity,
fileName = metaInfo.uuid(),
download = { outputStream ->
debug("[GoogleDrive][Download] Downloading - resource: $metaInfo")
drive.files().get(metaInfo.id).executeMediaAndDownloadTo(outputStream)
-1L
},
beforeAction = beforeAction,
afterAction = afterAction
)
Result(true)
}
override fun thumbnail(): Observable<InputStream> = Uri.parse(metaInfo.thumbnailLink)
.asInputStream()
override fun metaInfo(): Resource = metaInfo
} | gpl-3.0 | 61436823ab2831feead9bcfa7ba15d8c | 37.18 | 117 | 0.681342 | 4.608696 | false | false | false | false |
SpineEventEngine/core-java | buildSrc/src/main/kotlin/io/spine/internal/gradle/javadoc/JavadocConfig.kt | 2 | 5404 | /*
* Copyright 2022, TeamDev. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.internal.gradle.javadoc
import java.io.File
import org.gradle.api.JavaVersion
import org.gradle.api.Project
import org.gradle.api.tasks.javadoc.Javadoc
import org.gradle.external.javadoc.StandardJavadocDocletOptions
/**
* Javadoc processing settings.
*
* This type is named with `Config` suffix to avoid its confusion with the standard `Javadoc` type.
*/
@Suppress("unused")
object JavadocConfig {
/**
* Link to the documentation for Java 11 Standard Library API.
*
* OpenJDK SE 11 is used for the reference.
*/
private const val standardLibraryAPI = "https://cr.openjdk.java.net/~iris/se/11/latestSpec/api/"
@Suppress("MemberVisibilityCanBePrivate") // opened to be visible from docs.
val tags = listOf(
JavadocTag("apiNote", "API Note"),
JavadocTag("implSpec", "Implementation Requirements"),
JavadocTag("implNote", "Implementation Note")
)
val encoding = Encoding("UTF-8")
fun applyTo(project: Project) {
val javadocTask = project.tasks.javadocTask()
discardJavaModulesInLinks(javadocTask)
val docletOptions = javadocTask.options as StandardJavadocDocletOptions
configureDoclet(docletOptions)
}
/**
* Discards using of Java 9 modules in URL links generated by javadoc for our codebase.
*
* This fixes navigation to classes through the search results.
*
* The issue appeared after migration to Java 11. When javadoc is generated for a project
* that does not declare Java 9 modules, search results contain broken links with appended
* `undefined` prefix to the URL. This `undefined` was meant to be a name of a Java 9 module.
*
* See: [Issue #334](https://github.com/SpineEventEngine/config/issues/334)
*/
private fun discardJavaModulesInLinks(javadoc: Javadoc) {
// We ask `Javadoc` task to modify "search.js" and override a method, responsible for
// the formation of URL prefixes. We can't specify the option "--no-module-directories",
// because it leads to discarding of all module prefixes in generated links. That means,
// links to the types from the standard library would not work, as they are declared
// within modules since Java 9.
val discardModulePrefix = """
getURLPrefix = function(ui) {
return "";
};
""".trimIndent()
javadoc.doLast {
val destinationDir = javadoc.destinationDir!!.absolutePath
val searchScript = File("$destinationDir/search.js")
searchScript.appendText(discardModulePrefix)
}
}
private fun configureDoclet(docletOptions: StandardJavadocDocletOptions) {
docletOptions.encoding = encoding.name
reduceParamWarnings(docletOptions)
registerCustomTags(docletOptions)
linkStandardLibraryAPI(docletOptions)
}
/**
* Configures `javadoc` tool to avoid numerous warnings for missing `@param` tags.
*
* As suggested by Stephen Colebourne:
* [https://blog.joda.org/2014/02/turning-off-doclint-in-jdk-8-javadoc.html]
*
* See also:
* [https://github.com/GPars/GPars/blob/master/build.gradle#L268]
*/
private fun reduceParamWarnings(docletOptions: StandardJavadocDocletOptions) {
if (JavaVersion.current().isJava8Compatible) {
docletOptions.addStringOption("Xdoclint:none", "-quiet")
}
}
/**
* Registers custom [tags] for the passed doclet options.
*/
fun registerCustomTags(docletOptions: StandardJavadocDocletOptions) {
docletOptions.tags = tags.map { it.toString() }
}
/**
* Links the documentation for Java 11 Standard Library API.
*
* This documentation is used to be referenced to when navigating to the types from the
* standard library (`String`, `List`, etc.).
*
* OpenJDK SE 11 is used for the reference.
*/
private fun linkStandardLibraryAPI(docletOptions: StandardJavadocDocletOptions) {
docletOptions.addStringOption("link", standardLibraryAPI)
}
}
| apache-2.0 | f42b27cae5372cd66101f5c09dce1eb8 | 37.877698 | 100 | 0.69319 | 4.564189 | false | false | false | false |
arturbosch/detekt | detekt-rules-style/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/style/UseIfEmptyOrIfBlankSpec.kt | 1 | 13599 | package io.gitlab.arturbosch.detekt.rules.style
import io.gitlab.arturbosch.detekt.rules.setupKotlinEnvironment
import io.gitlab.arturbosch.detekt.test.assertThat
import io.gitlab.arturbosch.detekt.test.compileAndLintWithContext
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
class UseIfEmptyOrIfBlankSpec : Spek({
setupKotlinEnvironment()
val env: KotlinCoreEnvironment by memoized()
val subject by memoized { UseIfEmptyOrIfBlank() }
describe("report UseIfEmptyOrIfBlank rule") {
it("String.isBlank") {
val code = """
class Api(val name: String)
fun test(api: Api) {
val name = if (api.name.isBlank()) "John" else api.name
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).hasSize(1)
assertThat(findings).hasSourceLocation(4, 29)
assertThat(findings[0]).hasMessage("This 'isBlank' call can be replaced with 'ifBlank'")
}
it("String.isNotBlank") {
val code = """
class Api(val name: String)
fun test(api: Api) {
val name = if (api.name.isNotBlank())
api.name
else
"John"
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).hasSize(1)
assertThat(findings).hasSourceLocation(4, 29)
assertThat(findings[0]).hasMessage("This 'isNotBlank' call can be replaced with 'ifBlank'")
}
it("String.isEmpty") {
val code = """
class Api(val name: String)
fun test(api: Api) {
val name = if (api.name.isEmpty()) "John" else api.name
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).hasSize(1)
assertThat(findings).hasSourceLocation(4, 29)
assertThat(findings[0]).hasMessage("This 'isEmpty' call can be replaced with 'ifEmpty'")
}
it("String.isNotEmpty") {
val code = """
class Api(val name: String)
fun test(api: Api) {
val name = if (api.name.isNotEmpty())
api.name
else
"John"
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).hasSize(1)
assertThat(findings).hasSourceLocation(4, 29)
assertThat(findings[0]).hasMessage("This 'isNotEmpty' call can be replaced with 'ifEmpty'")
}
it("List.isEmpty") {
val code = """
fun test(list: List<Int>): List<Int> {
return if (list.isEmpty()) {
listOf(1)
} else {
list
}
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).hasSize(1)
}
it("List.isNotEmpty") {
val code = """
fun test(list: List<Int>): List<Int> {
return if (list.isNotEmpty()) {
list
} else {
listOf(1)
}
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).hasSize(1)
}
it("Set.isEmpty") {
val code = """
fun test(set: Set<Int>): Set<Int> {
return if (set.isEmpty()) {
setOf(1)
} else {
set
}
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).hasSize(1)
}
it("Set.isNotEmpty") {
val code = """
fun test(set: Set<Int>): Set<Int> {
return if (set.isNotEmpty()) {
set
} else {
setOf(1)
}
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).hasSize(1)
}
it("Map.isEmpty") {
val code = """
fun test(map: Map<Int, Int>): Map<Int, Int> {
return if (map.isEmpty()) {
mapOf(1 to 2)
} else {
map
}
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).hasSize(1)
}
it("Map.isNotEmpty") {
val code = """
fun test(map: Map<Int, Int>): Map<Int, Int> {
return if (map.isNotEmpty()) {
map
} else {
mapOf(1 to 2)
}
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).hasSize(1)
}
it("Collection.isEmpty") {
val code = """
fun test(collection: Collection<Int>): Collection<Int> {
return if (collection.isEmpty()) {
listOf(1)
} else {
collection
}
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).hasSize(1)
}
it("Collection.isNotEmpty") {
val code = """
fun test(collection: Collection<Int>): Collection<Int> {
return if (collection.isNotEmpty()) {
collection
} else {
listOf(1)
}
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).hasSize(1)
}
it("implicit receiver") {
val code = """
fun String.test(): String {
return if (isBlank()) {
"foo"
} else {
this
}
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).hasSize(1)
}
it("default value block is not single statement") {
val code = """
fun test(list: List<Int>): List<Int> {
return if (list.isEmpty()) {
println()
listOf(1)
} else {
list
}
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).hasSize(1)
}
it("!isEmpty") {
val code = """
fun test(list: List<Int>): List<Int> {
return if (!list.isEmpty()) { // list.isNotEmpty()
list
} else {
listOf(1)
}
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).hasSize(1)
assertThat(findings[0]).hasMessage("This 'isEmpty' call can be replaced with 'ifEmpty'")
}
it("!isNotEmpty") {
val code = """
fun test(list: List<Int>): List<Int> {
return if (!list.isNotEmpty()) { // list.isEmpty()
listOf(1)
} else {
list
}
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).hasSize(1)
assertThat(findings[0]).hasMessage("This 'isNotEmpty' call can be replaced with 'ifEmpty'")
}
}
describe("does not report UseIfEmptyOrIfBlank rule") {
it("String.isNullOrBlank") {
val code = """
class Api(val name: String?)
fun test(api: Api) {
val name = if (api.name.isNullOrBlank()) "John" else api.name
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
it("List.isNullOrEmpty") {
val code = """
fun test2(list: List<Int>): List<Int> {
return if (list.isNullOrEmpty()) {
listOf(1)
} else {
list
}
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
it("Array.isEmpty") {
val code = """
fun test(arr: Array<String>): Array<String> {
return if (arr.isEmpty()) {
arrayOf("a")
} else {
arr
}
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
it("Array.isNotEmpty") {
val code = """
fun test(arr: Array<String>): Array<String> {
return if (arr.isNotEmpty()) {
arr
} else {
arrayOf("a")
}
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
it("IntArray.isEmpty") {
val code = """
fun test(arr: IntArray): IntArray {
return if (arr.isEmpty()) {
intArrayOf(1)
} else {
arr
}
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
it("IntArray.isNotEmpty") {
val code = """
fun test(arr: IntArray): IntArray {
return if (arr.isNotEmpty()) {
arr
} else {
intArrayOf(1)
}
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
it("else if") {
val code = """
fun test(list: List<Int>, b: Boolean): List<Int> {
return if (list.isEmpty()) {
listOf(1)
} else if (b) {
listOf(2)
} else {
list
}
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
it("no else") {
val code = """
fun test(list: List<Int>) {
if (list.isEmpty()) {
listOf(1)
}
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
it("not self value") {
val code = """
fun test(list: List<Int>): List<Int> {
return if (list.isEmpty()) {
listOf(1)
} else {
list + list
}
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
it("self value block is not single statement") {
val code = """
fun test(list: List<Int>): List<Int> {
return if (list.isEmpty()) {
listOf(1)
} else {
println()
list
}
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
it("condition is binary expression") {
val code = """
fun test(list: List<Int>): List<Int> {
return if (list.isEmpty() == true) {
listOf(1)
} else {
list
}
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
}
})
| apache-2.0 | 413f5e1f9fe45f6fe90f45333402c93e | 32.660891 | 103 | 0.413927 | 5.63806 | false | true | false | false |
nextcloud/android | app/src/main/java/com/nextcloud/client/etm/pages/EtmMigrations.kt | 1 | 2496 | package com.nextcloud.client.etm.pages
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import com.nextcloud.client.etm.EtmBaseFragment
import com.owncloud.android.R
import com.owncloud.android.databinding.FragmentEtmMigrationsBinding
import java.util.Locale
class EtmMigrations : EtmBaseFragment() {
private var _binding: FragmentEtmMigrationsBinding? = null
private val binding get() = _binding!!
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
_binding = FragmentEtmMigrationsBinding.inflate(inflater, container, false)
return binding.root
}
override fun onResume() {
super.onResume()
showStatus()
}
fun showStatus() {
val builder = StringBuilder()
val status = vm.migrationsStatus.toString().toLowerCase(Locale.US)
builder.append("Migration status: $status\n")
val lastMigratedVersion = if (vm.lastMigratedVersion >= 0) {
vm.lastMigratedVersion.toString()
} else {
"never"
}
builder.append("Last migrated version: $lastMigratedVersion\n")
builder.append("Migrations:\n")
vm.migrationsInfo.forEach {
val migrationStatus = if (it.applied) {
"applied"
} else {
"pending"
}
builder.append(" - ${it.id} ${it.description} - $migrationStatus\n")
}
binding.etmMigrationsText.text = builder.toString()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.fragment_etm_migrations, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.etm_migrations_delete -> {
onDeleteMigrationsClicked(); true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun onDeleteMigrationsClicked() {
vm.clearMigrations()
showStatus()
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
| gpl-2.0 | 0338b38120aed630282a5c99f252cb65 | 29.814815 | 116 | 0.652644 | 4.781609 | false | false | false | false |
cbeust/kobalt | modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/internal/BuildListeners.kt | 2 | 5736 | package com.beust.kobalt.internal
import com.beust.kobalt.Args
import com.beust.kobalt.AsciiArt
import com.beust.kobalt.api.*
import com.beust.kobalt.misc.kobaltLog
import java.util.concurrent.ConcurrentHashMap
/**
* Record timings and statuses for tasks and projects and display them at the end of the build.
*/
class BuildListeners : IBuildListener, IBuildReportContributor {
class ProfilerInfo(val taskName: String, val durationMillis: Long)
class ProjectInfo(val projectName: String, var durationMillis: Long = 0,
var shortMessage: String? = null, var longMessage: String? = null)
private val startTimes = ConcurrentHashMap<String, Long>()
private val timings = arrayListOf<ProfilerInfo>()
private val projectInfos = hashMapOf<String, ProjectInfo>()
private var hasFailures = false
private val args: Args get() = Kobalt.INJECTOR.getInstance(Args::class.java)
private var buildStartTime: Long? = null
// IBuildListener
override fun taskStart(project: Project, context: KobaltContext, taskName: String) {
startTimes.put(taskName, System.currentTimeMillis())
if (! projectInfos.containsKey(project.name)) {
projectInfos.put(project.name, ProjectInfo(project.name))
}
}
// IBuildListener
override fun taskEnd(project: Project, context: KobaltContext, taskName: String, info: IBuildListener.TaskEndInfo) {
val success = info.success
if (! success) hasFailures = true
startTimes[taskName]?.let {
val taskTime = System.currentTimeMillis() - it
timings.add(ProfilerInfo(taskName, taskTime))
projectInfos[project.name]?.let {
it.durationMillis += taskTime
if (info.shortMessage != null && it.shortMessage == null) it.shortMessage = info.shortMessage
if (info.longMessage != null && it.longMessage == null) it.longMessage = info.longMessage
}
}
}
private val projectStatuses = arrayListOf<Pair<Project, String>>()
// IBuildListener
override fun projectStart(project: Project, context: KobaltContext) {
if (buildStartTime == null) buildStartTime = System.currentTimeMillis()
}
// IBuildListener
override fun projectEnd(project: Project, context: KobaltContext, status: ProjectBuildStatus) {
val shortMessage = projectInfos[project.name]?.shortMessage
val statusText = status.toString() + (if (shortMessage != null) " ($shortMessage)" else "")
projectStatuses.add(Pair(project, statusText))
}
// IBuildReportContributor
override fun generateReport(context: KobaltContext) {
fun formatMillis(millis: Long, format: String) = String.format(format, millis.toDouble() / 1000)
fun formatMillisRight(millis: Long, length: Int) = formatMillis(millis, "%1\$$length.2f")
fun formatMillisLeft(millis: Long, length: Int) = formatMillis(millis, "%1\$-$length.2f")
fun millisToSeconds(millis: Long) = (millis.toDouble() / 1000).toInt()
val profiling = args.profiling
if (profiling) {
kobaltLog(1, "\n" + AsciiArt.horizontalSingleLine + " Timings (in seconds)")
timings.sortedByDescending { it.durationMillis }.forEach {
kobaltLog(1, formatMillisRight(it.durationMillis, 10) + " " + it.taskName)
}
kobaltLog(1, "\n")
}
// Calculate the longest short message so we can create a column long enough to contain it
val width = 12 + (projectInfos.values.map { it.shortMessage?.length ?: 0 }.maxBy { it } ?: 0)
fun col1(s: String) = String.format(" %1\$-30s", s)
fun col2(s: String) = String.format(" %1\$-${width}s", s)
fun col3(s: String) = String.format(" %1\$-8s", s)
// Only print the build report if there is more than one project and at least one of them failed
if (timings.any()) {
// if (timings.size > 1 && hasFailures) {
val line = listOf(col1("Project"), col2("Build status"), col3("Time"))
.joinToString(AsciiArt.verticalBar)
val table = StringBuffer()
table.append(AsciiArt.logBox(listOf(line), AsciiArt.bottomLeft2, AsciiArt.bottomRight2, indent = 10) + "\n")
projectStatuses.forEach { pair ->
val projectName = pair.first.name
val cl = listOf(col1(projectName), col2(pair.second),
col3(formatMillisLeft(projectInfos[projectName]!!.durationMillis, 8)))
.joinToString(AsciiArt.verticalBar)
table.append(" " + AsciiArt.verticalBar + " " + cl + " " + AsciiArt.verticalBar + "\n")
}
table.append(" " + AsciiArt.lowerBox(line.length))
kobaltLog(1, table.toString())
// }
}
val buildTime =
if (buildStartTime != null)
millisToSeconds(System.currentTimeMillis() - buildStartTime!!)
else
0
// BUILD SUCCESSFUL / FAILED message
val message =
if (hasFailures) {
String.format("BUILD FAILED", buildTime)
} else if (! args.sequential) {
val sequentialBuildTime = ((projectInfos.values.sumByDouble { it.durationMillis.toDouble() }) / 1000)
.toInt()
String.format("PARALLEL BUILD SUCCESSFUL (%d SECONDS), sequential build would have taken %d seconds",
buildTime, sequentialBuildTime)
} else {
String.format("BUILD SUCCESSFUL (%d SECONDS)", buildTime)
}
kobaltLog(1, message)
}
}
| apache-2.0 | bad5609cb58ff8b4838ad57f0b91c458 | 43.8125 | 120 | 0.624651 | 4.62954 | false | false | false | false |
fabmax/binparse | src/main/kotlin/de/fabmax/binparse/FieldDefFactory.kt | 1 | 3771 | package de.fabmax.binparse
import java.util.*
import kotlin.text.Regex
/**
* Created by max on 15.11.2015.
*/
abstract class FieldDefFactory {
companion object {
private val decimalRegex = Regex("([0-9]*)|(0x[0-9a-fA-F]*)|(0b[01]*)")
private val parserFactories = HashMap<String, FieldDefFactory>()
init {
parserFactories.put("int", IntDef.Factory(0, null))
parserFactories.put("bit", IntDef.Factory(1, IntDef.Signedness.UNSIGNED))
parserFactories.put("u08", IntDef.Factory(8, IntDef.Signedness.UNSIGNED))
parserFactories.put("u16", IntDef.Factory(16, IntDef.Signedness.UNSIGNED))
parserFactories.put("u32", IntDef.Factory(32, IntDef.Signedness.UNSIGNED))
parserFactories.put("u64", IntDef.Factory(64, IntDef.Signedness.UNSIGNED))
parserFactories.put("i08", IntDef.Factory(8, IntDef.Signedness.SIGNED))
parserFactories.put("i16", IntDef.Factory(16, IntDef.Signedness.SIGNED))
parserFactories.put("i32", IntDef.Factory(32, IntDef.Signedness.SIGNED))
parserFactories.put("i64", IntDef.Factory(64, IntDef.Signedness.SIGNED))
parserFactories.put("string", StringDef.Factory(null))
parserFactories.put("utf-8", StringDef.Factory(Charsets.UTF_8))
parserFactories.put("array", ArrayDef.Factory())
parserFactories.put("select", SelectDef.Factory())
}
fun createParser(definition: Item): FieldDef<*> {
try {
val fac = parserFactories[definition.value] ?:
throw IllegalArgumentException("Unknown type: " + definition.value)
val parser = fac.createParser(definition)
addQualifiers(definition, parser)
return parser
} catch (e: Exception) {
throw IllegalArgumentException("Failed to create parser for " + definition.identifier + ": "
+ definition.value, e)
}
}
fun addParserFactory(typeName: String, factory: FieldDefFactory) {
if (parserFactories.containsKey(typeName)) {
throw IllegalArgumentException("Type name is already registered")
}
parserFactories.put(typeName, factory)
}
fun isType(name: String): Boolean {
return parserFactories.containsKey(name)
}
private fun addQualifiers(definition: Item, fieldDef: FieldDef<*>) {
val qualifiers = definition.childrenMap["_qualifiers"] ?: return
qualifiers.value.splitToSequence('|').forEach {
val q = it.trim()
if (Field.QUALIFIERS.contains(q)) {
fieldDef.qualifiers.add(q)
} else {
throw IllegalArgumentException("Invalid / unknown qualifier: $q")
}
}
}
internal fun parseDecimal(string: String): Long? {
if (string.matches(decimalRegex)) {
if (string.startsWith("0x")) {
return java.lang.Long.parseLong(string.substring(2), 16);
} else if (string.startsWith("0b")) {
return java.lang.Long.parseLong(string.substring(2), 1);
} else {
return java.lang.Long.parseLong(string);
}
} else {
return null
}
}
internal fun getItem(items: Map<String, Item>, name: String): Item {
val item = items[name] ?: throw IllegalArgumentException("Missing attribute \"$name\"");
return item;
}
}
abstract fun createParser(definition: Item): FieldDef<*>;
}
| apache-2.0 | 22445be874ce968a4bde727d5894e101 | 38.694737 | 108 | 0.579952 | 4.872093 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/view/AppBarChildBehavior.kt | 1 | 15653 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[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 de.vanita5.twittnuker.util.view
import android.content.Context
import android.content.res.TypedArray
import android.graphics.Rect
import android.support.annotation.Keep
import android.support.annotation.StyleableRes
import android.support.design.widget.AppBarLayout
import android.support.design.widget.CoordinatorLayout
import android.support.v4.view.ViewCompat
import android.util.AttributeSet
import android.util.TypedValue
import android.view.View
import android.widget.TextView
import de.vanita5.twittnuker.R
import de.vanita5.twittnuker.extension.*
class AppBarChildBehavior(
context: Context,
attrs: AttributeSet? = null
) : CoordinatorLayout.Behavior<View>(context, attrs) {
private val appBarId: Int
private val toolbarId: Int
private val dependencyViewId: Int
private val targetViewId: Int
private val alignmentRule: Int
private val marginTop: Int
private val marginBottom: Int
private val marginLeft: Int
private val marginRight: Int
private val marginStart: Int
private val marginEnd: Int
private val transformation: ChildTransformation
private val dependencyRect = Rect()
private val layoutRect = Rect()
private val thisRect = Rect()
private val targetRect = Rect()
private val tempLocation = IntArray(2)
init {
val a = context.obtainStyledAttributes(attrs, R.styleable.AppBarChildBehavior)
appBarId = a.getResourceIdOrThrow(R.styleable.AppBarChildBehavior_behavior_appBarId, "appBarId")
toolbarId = a.getResourceIdOrThrow(R.styleable.AppBarChildBehavior_behavior_toolbarId, "toolbarId")
dependencyViewId = a.getResourceIdOrThrow(R.styleable.AppBarChildBehavior_behavior_dependencyViewId, "dependencyViewId")
targetViewId = a.getResourceIdOrThrow(R.styleable.AppBarChildBehavior_behavior_targetViewId, "targetViewId")
alignmentRule = a.getIntegerOrThrow(R.styleable.AppBarChildBehavior_behavior_alignmentRule, "alignmentRule")
marginTop = a.getDimensionPixelSize(R.styleable.AppBarChildBehavior_behavior_marginTop, 0)
marginBottom = a.getDimensionPixelSize(R.styleable.AppBarChildBehavior_behavior_marginBottom, 0)
marginLeft = a.getDimensionPixelSize(R.styleable.AppBarChildBehavior_behavior_marginLeft, 0)
marginRight = a.getDimensionPixelSize(R.styleable.AppBarChildBehavior_behavior_marginRight, 0)
marginStart = a.getDimensionPixelSize(R.styleable.AppBarChildBehavior_behavior_marginStart, 0)
marginEnd = a.getDimensionPixelSize(R.styleable.AppBarChildBehavior_behavior_marginEnd, 0)
transformation = a.getTransformation(R.styleable.AppBarChildBehavior_behavior_childTransformation)
a.recycle()
}
override fun layoutDependsOn(parent: CoordinatorLayout, child: View, dependency: View): Boolean {
return dependency.id == dependencyViewId
}
override fun onLayoutChild(parent: CoordinatorLayout, child: View, layoutDirection: Int): Boolean {
val target = parent.findViewById<View>(targetViewId)
val dependency = parent.getDependencies(child).first()
dependency.getFrameRelatedTo(dependencyRect, parent)
layoutRect.layoutRelatedTo(child, parent, dependencyRect, layoutDirection)
child.layout(layoutRect.left, layoutRect.top, layoutRect.right, layoutRect.bottom)
child.getFrameRelatedTo(thisRect, parent)
target.getFrameRelatedTo(targetRect, parent)
transformation.onChildLayoutChanged(child, dependency, target)
return true
}
override fun onDependentViewChanged(parent: CoordinatorLayout, child: View, dependency: View): Boolean {
val appBar = parent.findViewById<View>(appBarId)
val target = parent.findViewById<View>(targetViewId)
val toolbar = parent.findViewById<View>(toolbarId)
val behavior = (appBar.layoutParams as CoordinatorLayout.LayoutParams).behavior as AppBarLayout.Behavior
toolbar.getLocationOnScreen(tempLocation)
val offset = behavior.topAndBottomOffset
val percent = offset / (tempLocation[1] + toolbar.height - appBar.height).toFloat()
transformation.onTargetChanged(child, thisRect, target, targetRect, percent, offset)
return true
}
internal fun Rect.layoutRelatedTo(view: View, parent: CoordinatorLayout, frame: Rect, layoutDirection: Int) {
val verticalRule = alignmentRule and VERTICAL_MASK
val horizontalRule = alignmentRule and HORIZONTAL_MASK
set(0, 0, view.measuredWidth, view.measuredHeight)
when (verticalRule) {
ALIGNMENT_CENTER_VERTICAL -> {
offsetTopTo(frame.centerY() - view.measuredHeight / 2 + marginTop - marginBottom)
}
0, ALIGNMENT_TOP -> {
offsetTopTo(frame.top + marginTop)
}
ALIGNMENT_BOTTOM -> {
offsetBottomTo(frame.bottom - marginBottom)
}
ALIGNMENT_ABOVE -> {
offsetBottomTo(frame.top + marginTop - marginBottom)
}
ALIGNMENT_BELOW -> {
offsetTopTo(frame.bottom + marginTop - marginBottom)
}
ALIGNMENT_ABOVE_CENTER -> {
offsetBottomTo(frame.centerY() + marginTop - marginBottom)
}
ALIGNMENT_BELOW_CENTER -> {
offsetTopTo(frame.centerY() + marginTop - marginBottom)
}
else -> {
throw IllegalArgumentException("Illegal alignment flag ${Integer.toHexString(alignmentRule)}")
}
}
when (horizontalRule) {
ALIGNMENT_CENTER_HORIZONTAL -> {
offsetLeftTo(frame.centerX() - view.measuredWidth / 2
+ absoluteMarginLeft(layoutDirection) - absoluteMarginRight(layoutDirection))
}
0, ALIGNMENT_LEFT -> {
offsetLeftTo(frame.left + absoluteMarginLeft(layoutDirection))
}
ALIGNMENT_RIGHT -> {
offsetRightTo(frame.right - absoluteMarginRight(layoutDirection))
}
ALIGNMENT_TO_LEFT_OF -> {
offsetRightTo(frame.left + absoluteMarginLeft(layoutDirection)
- absoluteMarginRight(layoutDirection))
}
ALIGNMENT_TO_RIGHT_OF -> {
offsetLeftTo(frame.right + absoluteMarginLeft(layoutDirection)
- absoluteMarginRight(layoutDirection))
}
ALIGNMENT_TO_LEFT_OF_CENTER -> {
offsetRightTo(frame.centerX() + absoluteMarginLeft(layoutDirection)
- absoluteMarginRight(layoutDirection))
}
ALIGNMENT_TO_RIGHT_OF_CENTER -> {
offsetLeftTo(frame.centerX() + absoluteMarginLeft(layoutDirection)
- absoluteMarginRight(layoutDirection))
}
ALIGNMENT_START -> {
offsetStartTo(frame.getStart(layoutDirection)
+ relativeMarginStart(layoutDirection), layoutDirection)
}
ALIGNMENT_END -> {
offsetEndTo(frame.getEnd(layoutDirection)
- relativeMarginEnd(layoutDirection), layoutDirection)
}
ALIGNMENT_TO_START_OF -> {
offsetEndTo(frame.getStart(layoutDirection)
+ relativeMarginStart(layoutDirection) - relativeMarginEnd(layoutDirection),
layoutDirection)
}
ALIGNMENT_TO_END_OF -> {
offsetStartTo(frame.getEnd(layoutDirection)
+ relativeMarginStart(layoutDirection) - relativeMarginEnd(layoutDirection),
layoutDirection)
}
ALIGNMENT_TO_START_OF_CENTER -> {
offsetEndTo(frame.centerX() + relativeMarginStart(layoutDirection)
- relativeMarginEnd(layoutDirection), layoutDirection)
}
ALIGNMENT_TO_END_OF_CENTER -> {
offsetStartTo(frame.centerX() + relativeMarginStart(layoutDirection)
- relativeMarginEnd(layoutDirection), layoutDirection)
}
else -> {
throw IllegalArgumentException("Illegal alignment flag ${Integer.toHexString(alignmentRule)}")
}
}
left = left.coerceAtLeast(absoluteMarginLeft(layoutDirection) - frame.left)
right = right.coerceAtMost(parent.measuredWidth - absoluteMarginRight(layoutDirection) - frame.left)
// tempRect.top = tempRect.top.coerceAtLeast(marginTop - frame.top)
// tempRect.bottom = tempRect.bottom.coerceAtLeast(parent.measuredHeight - marginBottom - frame.top)
}
private fun absoluteMarginLeft(layoutDirection: Int): Int {
if (marginStart == 0 && marginEnd == 0) return marginLeft
if (layoutDirection == ViewCompat.LAYOUT_DIRECTION_RTL) {
return marginEnd
} else {
return marginStart
}
}
private fun absoluteMarginRight(layoutDirection: Int): Int {
if (marginStart == 0 && marginEnd == 0) return marginRight
if (layoutDirection == ViewCompat.LAYOUT_DIRECTION_RTL) {
return marginStart
} else {
return marginEnd
}
}
private fun relativeMarginStart(layoutDirection: Int): Int {
if (marginStart != 0) {
if (layoutDirection == ViewCompat.LAYOUT_DIRECTION_RTL) {
return -marginStart
} else {
return marginStart
}
} else {
if (layoutDirection == ViewCompat.LAYOUT_DIRECTION_RTL) {
return marginRight
} else {
return marginLeft
}
}
}
private fun relativeMarginEnd(layoutDirection: Int): Int {
if (marginEnd != 0) {
if (layoutDirection == ViewCompat.LAYOUT_DIRECTION_RTL) {
return -marginEnd
} else {
return marginEnd
}
} else {
if (layoutDirection == ViewCompat.LAYOUT_DIRECTION_RTL) {
return marginLeft
} else {
return marginRight
}
}
}
interface ChildTransformation {
fun onChildLayoutChanged(child: View, dependency: View, target: View) {}
fun onTargetChanged(child: View, frame: Rect, target: View, targetFrame: Rect, percent: Float, offset: Int)
}
open class ScaleTransformation : ChildTransformation {
override fun onTargetChanged(child: View, frame: Rect, target: View, targetFrame: Rect, percent: Float, offset: Int) {
child.pivotX = child.width.toFloat()
child.pivotY = child.height.toFloat()
child.scaleX = 1 - (frame.width() - targetFrame.width()) * percent / frame.width()
child.scaleY = 1 - (frame.height() - targetFrame.height()) * percent / frame.height()
child.translationX = (targetFrame.right - frame.right) * percent
child.translationY = -offset - (frame.bottom - offset - targetFrame.bottom) * percent
}
}
@Keep
open class TextViewTransformation : ChildTransformation {
private var sourceSize: Float = Float.NaN
private var destSize: Float = Float.NaN
private var viewLaidOut: Boolean = false
override fun onChildLayoutChanged(child: View, dependency: View, target: View) {
if (viewLaidOut) return
child as TextView
target as TextView
sourceSize = child.textSize
destSize = target.textSize
viewLaidOut = true
}
override fun onTargetChanged(child: View, frame: Rect, target: View, targetFrame: Rect, percent: Float, offset: Int) {
child as TextView
child.pivotX = child.width.toFloat()
child.pivotY = child.height.toFloat()
child.translationX = (targetFrame.left - frame.left) * percent
child.translationY = -offset - (frame.bottom - offset - targetFrame.bottom) * percent
child.setTextSize(TypedValue.COMPLEX_UNIT_PX, sourceSize + (destSize - sourceSize) * percent)
}
}
companion object {
private const val HORIZONTAL_MASK: Int = 0x0000FFFF
private const val VERTICAL_MASK: Int = 0xFFFF0000.toInt()
private const val HORIZONTAL_RELATIVE_FLAG: Int = 0x00001000
const val ALIGNMENT_LEFT: Int = 0x00000001
const val ALIGNMENT_RIGHT: Int = 0x00000002
const val ALIGNMENT_TO_LEFT_OF: Int = 0x00000004
const val ALIGNMENT_TO_RIGHT_OF: Int = 0x00000008
const val ALIGNMENT_TO_LEFT_OF_CENTER: Int = 0x00000010
const val ALIGNMENT_TO_RIGHT_OF_CENTER: Int = 0x00000020
const val ALIGNMENT_CENTER_HORIZONTAL: Int = ALIGNMENT_LEFT or ALIGNMENT_RIGHT
const val ALIGNMENT_START: Int = ALIGNMENT_LEFT or HORIZONTAL_RELATIVE_FLAG
const val ALIGNMENT_END: Int = ALIGNMENT_RIGHT or HORIZONTAL_RELATIVE_FLAG
const val ALIGNMENT_TO_START_OF: Int = ALIGNMENT_TO_LEFT_OF or HORIZONTAL_RELATIVE_FLAG
const val ALIGNMENT_TO_END_OF: Int = ALIGNMENT_TO_RIGHT_OF or HORIZONTAL_RELATIVE_FLAG
const val ALIGNMENT_TO_START_OF_CENTER: Int = ALIGNMENT_TO_LEFT_OF_CENTER or HORIZONTAL_RELATIVE_FLAG
const val ALIGNMENT_TO_END_OF_CENTER: Int = ALIGNMENT_TO_RIGHT_OF_CENTER or HORIZONTAL_RELATIVE_FLAG
const val ALIGNMENT_TOP: Int = 0x00010000
const val ALIGNMENT_BOTTOM: Int = 0x00020000
const val ALIGNMENT_ABOVE: Int = 0x00040000
const val ALIGNMENT_BELOW: Int = 0x00080000
const val ALIGNMENT_ABOVE_CENTER: Int = 0x00100000
const val ALIGNMENT_BELOW_CENTER: Int = 0x00200000
const val ALIGNMENT_CENTER_VERTICAL: Int = ALIGNMENT_TOP or ALIGNMENT_BOTTOM
private fun TypedArray.getIntegerOrThrow(@StyleableRes index: Int, name: String): Int {
if (!hasValue(index)) {
throw IllegalArgumentException("$name required")
}
return getInteger(index, 0)
}
private fun TypedArray.getResourceIdOrThrow(@StyleableRes index: Int, name: String): Int {
if (!hasValue(index)) {
throw IllegalArgumentException("$name required")
}
return getResourceId(index, 0)
}
private fun TypedArray.getTransformation(@StyleableRes index: Int): ChildTransformation {
val className = getString(index) ?: return ScaleTransformation()
return Class.forName(className).newInstance() as ChildTransformation
}
}
} | gpl-3.0 | f42fec3cf1beaa1d7998d694c06aa369 | 43.345609 | 128 | 0.650546 | 5.103684 | false | false | false | false |
BilledTrain380/sporttag-psa | app/dto/src/main/kotlin/ch/schulealtendorf/psa/dto/group/CoachDto.kt | 1 | 2084 | /*
* Copyright (c) 2019 by Nicolas Märchy
*
* This file is part of Sporttag PSA.
*
* Sporttag PSA is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Sporttag PSA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Sporttag PSA. If not, see <http://www.gnu.org/licenses/>.
*
* Diese Datei ist Teil von Sporttag PSA.
*
* Sporttag PSA ist Freie Software: Sie können es unter den Bedingungen
* der GNU General Public License, wie von der Free Software Foundation,
* Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren
* veröffentlichten Version, weiterverbreiten und/oder modifizieren.
*
* Sporttag PSA wird in der Hoffnung, dass es nützlich sein wird, aber
* OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite
* Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK.
* Siehe die GNU General Public License für weitere Details.
*
* Sie sollten eine Kopie der GNU General Public License zusammen mit diesem
* Programm erhalten haben. Wenn nicht, siehe <http://www.gnu.org/licenses/>.
*
*
*/
package ch.schulealtendorf.psa.dto.group
/**
* Data class representing a coach of a class.
*
* @author nmaerchy <[email protected]>
* @since 2.0.0
*/
data class CoachDto(
val id: Int,
val name: String
) {
companion object
fun toBuilder() = Builder(this)
class Builder internal constructor(
private val dto: CoachDto
) {
private var name = dto.name
fun setName(name: String): Builder {
this.name = name
return this
}
fun build() = dto.copy(name = name)
}
}
| gpl-3.0 | aab38d168db1ed4735d382a07bb28f18 | 30.907692 | 77 | 0.708293 | 4.241309 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/activity/InvalidAccountAlertActivity.kt | 1 | 2445 | package de.vanita5.twittnuker.activity
import android.accounts.AccountManager
import android.app.Dialog
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.FragmentActivity
import android.support.v7.app.AlertDialog
import de.vanita5.twittnuker.R
import de.vanita5.twittnuker.constant.IntentConstants.EXTRA_INTENT
import de.vanita5.twittnuker.extension.applyTheme
import de.vanita5.twittnuker.extension.model.isAccountValid
import de.vanita5.twittnuker.extension.onShow
import de.vanita5.twittnuker.fragment.BaseDialogFragment
import de.vanita5.twittnuker.model.util.AccountUtils
import de.vanita5.twittnuker.util.support.removeAccountSupport
class InvalidAccountAlertActivity : FragmentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val df = InvalidAccountAlertDialogFragment()
df.show(supportFragmentManager, "invalid_account_alert")
}
class InvalidAccountAlertDialogFragment : BaseDialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val builder = AlertDialog.Builder(context)
builder.setTitle(R.string.title_error_invalid_account)
builder.setMessage(R.string.message_error_invalid_account)
builder.setPositiveButton(android.R.string.ok) { _, _ ->
val am = AccountManager.get(context)
AccountUtils.getAccounts(am).filter { !am.isAccountValid(it) }.forEach { account ->
am.removeAccountSupport(account)
}
val intent = activity.intent.getParcelableExtra<Intent>(EXTRA_INTENT)
if (intent != null) {
activity.startActivity(intent)
}
}
builder.setNegativeButton(android.R.string.cancel) { _, _ ->
}
val dialog = builder.create()
dialog.onShow { it.applyTheme() }
return dialog
}
override fun onDismiss(dialog: DialogInterface?) {
super.onDismiss(dialog)
if (!activity.isFinishing) {
activity.finish()
}
}
override fun onCancel(dialog: DialogInterface?) {
super.onCancel(dialog)
if (!activity.isFinishing) {
activity.finish()
}
}
}
} | gpl-3.0 | a7801616a962d54d358eb9690d0fe5e1 | 36.060606 | 99 | 0.664213 | 4.89 | false | false | false | false |
exponent/exponent | packages/expo-modules-core/android/src/main/java/expo/modules/kotlin/records/RecordTypeConverter.kt | 2 | 2244 | package expo.modules.kotlin.records
import com.facebook.react.bridge.Dynamic
import expo.modules.kotlin.allocators.ObjectConstructor
import expo.modules.kotlin.allocators.ObjectConstructorFactory
import expo.modules.kotlin.exception.FieldCastException
import expo.modules.kotlin.exception.RecordCastException
import expo.modules.kotlin.exception.exceptionDecorator
import expo.modules.kotlin.recycle
import expo.modules.kotlin.types.TypeConverter
import expo.modules.kotlin.types.TypeConverterProvider
import kotlin.reflect.KClass
import kotlin.reflect.KType
import kotlin.reflect.full.findAnnotation
import kotlin.reflect.full.memberProperties
import kotlin.reflect.jvm.javaField
// TODO(@lukmccall): create all converters during initialization
class RecordTypeConverter<T : Record>(
private val converterProvider: TypeConverterProvider,
val type: KType,
) : TypeConverter<T>(type.isMarkedNullable) {
private val objectConstructorFactory = ObjectConstructorFactory()
override fun convertNonOptional(value: Dynamic): T = exceptionDecorator({ cause -> RecordCastException(type, cause) }) {
val jsMap = value.asMap()
val kClass = type.classifier as KClass<*>
val instance = getObjectConstructor(kClass.java).construct()
kClass
.memberProperties
.map { property ->
val filedInformation = property.findAnnotation<Field>() ?: return@map
val jsKey = filedInformation.key.takeUnless { it == "" } ?: property.name
if (!jsMap.hasKey(jsKey)) {
// TODO(@lukmccall): handle required keys
return@map
}
jsMap.getDynamic(jsKey).recycle {
val javaField = property.javaField!!
val elementConverter = converterProvider.obtainTypeConverter(property.returnType)
val casted = exceptionDecorator({ cause -> FieldCastException(property.name, property.returnType, type, cause) }) {
elementConverter.convert(this)
}
javaField.isAccessible = true
javaField.set(instance, casted)
}
}
@Suppress("UNCHECKED_CAST")
return instance as T
}
private fun <T> getObjectConstructor(clazz: Class<T>): ObjectConstructor<T> {
return objectConstructorFactory.get(clazz)
}
}
| bsd-3-clause | 22e2484a1c42f4f48f11d8e284d04648 | 35.193548 | 125 | 0.737968 | 4.560976 | false | false | false | false |
kittinunf/Fuel | fuel/src/test/kotlin/com/github/kittinunf/fuel/core/BodyRepresentationTest.kt | 1 | 7481 | package com.github.kittinunf.fuel.core
import com.github.kittinunf.fuel.core.requests.DefaultBody
import com.github.kittinunf.fuel.test.MockHttpTestCase
import com.github.kittinunf.fuel.util.decodeBase64
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Test
import org.mockserver.model.BinaryBody
import java.io.ByteArrayInputStream
import java.net.URLConnection
import java.util.Random
class BodyRepresentationTest : MockHttpTestCase() {
private val manager: FuelManager by lazy { FuelManager() }
@Test
fun emptyBodyRepresentation() {
assertThat(
DefaultBody.from({ ByteArrayInputStream(ByteArray(0)) }, { 0L }).asString("(unknown)"),
equalTo("(empty)")
)
}
@Test
fun unknownBytesRepresentation() {
val bytes = ByteArray(555 - 16)
.also { Random().nextBytes(it) }
.let { ByteArray(16).plus(it) }
mock.chain(
request = mock.request().withMethod(Method.GET.value).withPath("/bytes"),
response = mock.response().withBody(BinaryBody(bytes, null)).withHeader("Content-Type", "")
)
val (_, response, _) = manager.request(Method.GET, mock.path("bytes")).responseString()
assertThat(
response.body().asString(response[Headers.CONTENT_TYPE].lastOrNull()),
equalTo("(555 bytes of (unknown))")
)
}
@Test
fun guessContentType() {
val decodedImage = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVQYV2NgYAAAAAMAAWgmWQ0AAAAASUVORK5CYII=".decodeBase64()!!
assertThat(
DefaultBody
.from({ ByteArrayInputStream(decodedImage) }, { decodedImage.size.toLong() })
.asString(URLConnection.guessContentTypeFromStream(ByteArrayInputStream(decodedImage))),
equalTo("(${decodedImage.size} bytes of image/png)")
)
}
@Test
fun bytesRepresentationOfOctetStream() {
val contentTypes = listOf("application/octet-stream")
val content = ByteArray(555 - 16)
.also { Random().nextBytes(it) }
.let { ByteArray(16).plus(it) }
contentTypes.forEach { contentType ->
assertThat(
DefaultBody
.from({ ByteArrayInputStream(content) }, { content.size.toLong() })
.asString(contentType),
equalTo("(555 bytes of $contentType)")
)
}
}
@Test
fun bytesRepresentationOfMedia() {
val contentTypes = listOf(
"image/bmp", "image/gif", "image/jpeg", "image/png", "image/tiff", "image/webp", "image/x-icon",
"audio/aac", "audio/midi", "audio/x-midi", "audio/ogg", "audio/wav", "audio/webm", "audio/3gpp", "audio/3gpp2",
"video/mpeg", "video/ogg", "video/webm", "video/x-msvideo", "video/3gpp", "video/3gpp2",
"font/otf", "font/ttf", "font/woff", "font/woff2"
)
val content = ByteArray(555 - 16)
.also { Random().nextBytes(it) }
.let { ByteArray(16).plus(it) }
contentTypes.forEach { contentType ->
assertThat(
DefaultBody
.from({ ByteArrayInputStream(content) }, { content.size.toLong() })
.asString(contentType),
equalTo("(555 bytes of $contentType)")
)
}
}
@Test
fun textRepresentationOfYaml() {
val contentTypes = listOf("application/x-yaml", "text/yaml")
val content = "language: c\n"
contentTypes.forEach { contentType ->
assertThat(
DefaultBody
.from({ ByteArrayInputStream(content.toByteArray()) }, { content.length.toLong() })
.asString(contentType),
equalTo(content)
)
}
}
@Test
fun textRepresentationOfXml() {
val contentTypes = listOf("application/xml", "application/xhtml+xml", "application/vnd.fuel.test+xml", "image/svg+xml")
val content = "<html xmlns=\"http://www.w3.org/1999/xhtml\"/>"
contentTypes.forEach { contentType ->
assertThat(
DefaultBody
.from({ ByteArrayInputStream(content.toByteArray()) }, { content.length.toLong() })
.asString(contentType),
equalTo(content)
)
}
}
@Test
fun textRepresentationOfScripts() {
val contentTypes = listOf("application/javascript", "application/typescript", "application/vnd.coffeescript")
val content = "function test()"
contentTypes.forEach { contentType ->
assertThat(
DefaultBody
.from({ ByteArrayInputStream(content.toByteArray()) }, { content.length.toLong() })
.asString(contentType),
equalTo(content)
)
}
}
@Test
fun textRepresentationOfJson() {
val contentTypes = listOf("application/json")
val content = "{ \"foo\": 42 }"
contentTypes.forEach { contentType ->
assertThat(
DefaultBody
.from({ ByteArrayInputStream(content.toByteArray()) }, { content.length.toLong() })
.asString(contentType),
equalTo(content)
)
}
}
@Test
fun textRepresentationOfJsonWithUtf8Charset() {
val contentTypes = listOf("application/json;charset=utf-8", "application/json; charset=utf-8")
val content = "{ \"foo\": 42 }"
contentTypes.forEach { contentType ->
assertThat(
DefaultBody
.from({ ByteArrayInputStream(content.toByteArray()) }, { content.length.toLong() })
.asString(contentType),
equalTo(content)
)
}
}
@Test
fun textRepresentationOfCsv() {
val contentTypes = listOf("text/csv")
val content = "function test()"
contentTypes.forEach { contentType ->
assertThat(
DefaultBody
.from({ ByteArrayInputStream(content.toByteArray()) }, { content.length.toLong() })
.asString(contentType),
equalTo(content)
)
}
}
@Test
fun textRepresentationOfCsvWithUtf16beCharset() {
val contentTypes = listOf("application/csv; charset=utf-16be", "application/csv;charset=utf-16be")
val content = String("hello,world!".toByteArray(Charsets.UTF_16BE))
contentTypes.forEach { contentType ->
assertThat(
DefaultBody
.from({ ByteArrayInputStream(content.toByteArray()) }, { content.length.toLong() })
.asString(contentType),
equalTo("hello,world!")
)
}
}
@Test
fun textRepresentationOfTextTypes() {
val contentTypes = listOf("text/csv", "text/html", "text/calendar", "text/plain", "text/css")
val content = "maybe invalid but we don't care"
contentTypes.forEach { contentType ->
assertThat(
DefaultBody
.from({ ByteArrayInputStream(content.toByteArray()) }, { content.length.toLong() })
.asString(contentType),
equalTo(content)
)
}
}
} | mit | 220b97cdccfaefda0837c6653fff3c0a | 34.126761 | 138 | 0.56824 | 4.820232 | false | true | false | false |
androidx/androidx | compose/animation/animation/integration-tests/animation-demos/src/main/java/androidx/compose/animation/demos/layoutanimation/AnimateEnterExitDemo.kt | 3 | 6432 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.animation.demos.layoutanimation
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.EnterExitState
import androidx.compose.animation.ExitTransition
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.core.MutableTransitionState
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.spring
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInVertically
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Button
import androidx.compose.material.FloatingActionButton
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
/*
* This demo shows how to create a custom enter/exit animation for children of AnimatedVisibility
* using `AnimatedVisibilityScope.transition` combined with different `Enter/ExitTransition`
* for children of `AnimatedVisibility` using `Modifier.animateEnterExit`.
*
* APIs used:
* - MutableTransitionState
* - EnterExitState
* - AnimatedVisibility
* - AnimatedVisibilityScope
* - Modifier.animateEnterExit
*/
@Preview
@OptIn(ExperimentalAnimationApi::class)
@Composable
fun AnimateEnterExitDemo() {
Box {
Column(Modifier.fillMaxSize()) {
Spacer(Modifier.size(40.dp))
val mainContentVisible = remember { MutableTransitionState(true) }
Button(
modifier = Modifier.align(Alignment.CenterHorizontally),
onClick = { mainContentVisible.targetState = !mainContentVisible.targetState },
) {
Text("Toggle Visibility")
}
Spacer(Modifier.size(40.dp))
AnimatedVisibility(
visibleState = mainContentVisible,
modifier = Modifier.fillMaxSize(),
enter = fadeIn(),
exit = fadeOut()
) {
Box {
Column(Modifier.fillMaxSize()) {
colors.forEachIndexed { index, color ->
// Creates a custom enter/exit animation on scale using
// `AnimatedVisibilityScope.transition`
val scale by transition.animateFloat { enterExitState ->
when (enterExitState) {
EnterExitState.PreEnter -> 0.9f
EnterExitState.Visible -> 1.0f
EnterExitState.PostExit -> 0.5f
}
}
val staggeredSpring = remember {
spring<IntOffset>(
stiffness = Spring.StiffnessLow * (1f - index * 0.2f)
)
}
Box(
Modifier.weight(1f).animateEnterExit(
// Staggered slide-in from bottom, while the parent
// AnimatedVisibility fades in everything (including this child)
enter = slideInVertically(
initialOffsetY = { it },
animationSpec = staggeredSpring
),
// No built-in exit transition will be applied. It'll be
// faded out by parent AnimatedVisibility while scaling down
// by the scale animation.
exit = ExitTransition.None
).fillMaxWidth().padding(5.dp).graphicsLayer {
scaleX = scale
scaleY = scale
}.clip(RoundedCornerShape(20.dp)).background(color)
) {}
}
}
// This gets faded in/out by the parent AnimatedVisibility
FloatingActionButton(
onClick = {},
modifier = Modifier.align(Alignment.BottomEnd).padding(20.dp),
backgroundColor = MaterialTheme.colors.primary
) {
Icon(Icons.Default.Favorite, contentDescription = null)
}
}
}
}
}
}
private val colors = listOf(
Color(0xffff6f69),
Color(0xffffcc5c),
Color(0xff2a9d84),
Color(0xff264653)
)
| apache-2.0 | 6a4a3f413c53c3ac9a850aec9b6d0a1c | 43.054795 | 100 | 0.607432 | 5.544828 | false | false | false | false |
EmmyLua/IntelliJ-EmmyLua | src/main/java/com/tang/intellij/lua/psi/LuaFileUtil.kt | 2 | 5726 | /*
* Copyright (c) 2017. tangzx([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tang.intellij.lua.psi
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.FileIndexFacade
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.util.SmartList
import com.tang.intellij.lua.ext.ILuaFileResolver
import com.tang.intellij.lua.project.LuaSourceRootManager
import java.io.File
/**
*
* Created by tangzx on 2017/1/4.
*/
object LuaFileUtil {
val pluginFolder: File?
get() {
val descriptor = PluginManagerCore.getPlugin(PluginId.getId("com.tang"))
return descriptor?.path
}
val pluginVirtualDirectory: VirtualFile?
get() {
val descriptor = PluginManagerCore.getPlugin(PluginId.getId("com.tang"))
if (descriptor != null) {
val pluginPath = descriptor.path
val url = VfsUtil.pathToUrl(pluginPath.absolutePath)
return VirtualFileManager.getInstance().findFileByUrl(url)
}
return null
}
var PREDEFINED_KEY = Key.create<Boolean>("lua.lib.predefined")
fun fileEquals(f1: VirtualFile?, f2: VirtualFile?): Boolean {
return if (f1 == null || f2 == null) false else f1.path == f2.path
}
fun getAllAvailablePathsForMob(shortPath: String?, file: VirtualFile): List<String> {
val list = SmartList<String>()
val fullPath = file.canonicalPath
val extensions = LuaFileManager.getInstance().extensions
if (fullPath != null) {
for (ext in extensions) {
if (!fullPath.endsWith(ext)) {
continue
}
list.add(fullPath.substring(0, fullPath.length - ext.length))
}
}
if (shortPath != null) {
for (ext in extensions) {
if (!shortPath.endsWith(ext)) {
continue
}
val path = shortPath.substring(0, shortPath.length - ext.length)
list.add(path)
if (path.indexOf('/') != -1)
list.add(path.replace('/', '.'))
}
}
return list
}
fun findFile(project: Project, shortUrl: String?): VirtualFile? {
var fixedShortUrl = shortUrl ?: return null
// "./x.lua" => "x.lua"
if (fixedShortUrl.startsWith("./") || fixedShortUrl.startsWith(".\\")) {
fixedShortUrl = fixedShortUrl.substring(2)
}
val extensions = LuaFileManager.getInstance().extensions
return ILuaFileResolver.findLuaFile(project, fixedShortUrl, extensions)
}
fun getShortPath(project: Project, file: VirtualFile): String {
return VfsUtil.urlToPath(getShortUrl(project, file))
}
private fun getShortUrl(project: Project, file: VirtualFile): String {
val fileFullUrl = file.url
var fileShortUrl = fileFullUrl
val roots = LuaSourceRootManager.getInstance(project).getSourceRoots()
for (root in roots) {
val sourceRootUrl = root.url
if (fileFullUrl.startsWith(sourceRootUrl)) {
fileShortUrl = fileFullUrl.substring(sourceRootUrl.length + 1)
break
}
}
return fileShortUrl
}
private fun getSourceRoot(project: Project, file: VirtualFile): VirtualFile? {
val fileFullUrl = file.url
val roots = LuaSourceRootManager.getInstance(project).getSourceRoots()
for (root in roots) {
val sourceRootUrl = root.url
if (fileFullUrl.startsWith(sourceRootUrl)) {
return root
}
}
return null
}
fun getPluginVirtualFile(path: String): String? {
val directory = pluginVirtualDirectory
if (directory != null) {
var fullPath = directory.path + "/classes/" + path
if (File(fullPath).exists())
return fullPath
fullPath = directory.path + "/" + path
if (File(fullPath).exists())
return fullPath
}
return null
}
fun asRequirePath(project: Project, file: VirtualFile): String? {
val root = getSourceRoot(project, file) ?: return null
val list = mutableListOf<String>()
var item = file
while (item != root) {
if (item.isDirectory)
list.add(item.name)
else
list.add(FileUtil.getNameWithoutExtension(item.name))
item = item.parent
}
if (list.isEmpty())
return null
list.reverse()
return list.joinToString(".")
}
fun isStdLibFile(file: VirtualFile, project: Project): Boolean {
return file.getUserData(PREDEFINED_KEY) != null || FileIndexFacade.getInstance(project).isInLibraryClasses(file)
}
}
| apache-2.0 | f327cfe66dd972d720d72e1b5831d0a7 | 33.287425 | 120 | 0.616486 | 4.678105 | false | false | false | false |
Tvede-dk/CommonsenseAndroidKotlin | app/src/main/kotlin/csense/android/exampleApp/fragments/SimpleRecyclerDemo.kt | 1 | 3844 | package csense.android.exampleApp.fragments
import android.graphics.*
import android.support.v7.widget.*
import android.view.*
import com.commonsense.android.kotlin.system.logging.*
import com.commonsense.android.kotlin.views.*
import com.commonsense.android.kotlin.views.databinding.adapters.*
import com.commonsense.android.kotlin.views.databinding.fragments.*
import com.commonsense.android.kotlin.views.extensions.*
import com.commonsense.android.kotlin.views.features.*
import com.commonsense.android.kotlin.views.features.SectionRecyclerTransaction.*
import csense.android.exampleApp.R
import csense.android.exampleApp.databinding.*
/**
* Created by Kasper Tvede on 31-05-2017.
*/
open class SimpleRecyclerDemo : BaseDatabindingFragment<DemoRecyclerSimpleViewBinding>() {
override fun getInflater(): InflateBinding<DemoRecyclerSimpleViewBinding> = DemoRecyclerSimpleViewBinding::inflate
private val adapter by lazy {
context?.let { DefaultDataBindingRecyclerAdapter(it) }
}
override fun useBinding() {
val adapter = adapter ?: return
val context = context ?: return
adapter.clear()
for (section in 0 until 10) {
for (i in 0 until 10) {
adapter.add(SimpleListItemRender("First text is good text", section) {
val transaction = Builder(adapter).apply {
hideSection(section)
hideSection(section + 1)
hideSection(section + 2)
}.build()
transaction.applySafe()
showSnackbar(binding.root, R.string.app_name, R.string.app_name, 5000, onAction = {
transaction.resetSafe { logWarning("omg failure! list changed outside of modification") }
})
}, section)
adapter.add(SimpleListImageItemRender(Color.BLUE, section), section)
adapter.add(SimpleListItemRender("Whats up test ?", section) {}, section)
adapter.add(SimpleListImageItemRender(Color.RED, section), section)
}
}
binding.demoRecyclerSimpleViewRecyclerview.setup(adapter, LinearLayoutManager(context))
binding.demoRecyclerSimpleViewReset.setOnclickAsync {
for (i in 0 until adapter.sectionCount) {
adapter.showSection(i)
}
}
}
}
fun setColorUsingBackground(view: View, section: Int) {
val color = Color.rgb(section % 20 + 80, section % 50 + 50, section % 100 + 20)
view.setBackgroundColor(color)
}
open class SimpleListItemRender(text: String, private val section: Int, private val callback: () -> Unit)
: BaseRenderModel<String, SimpleListItemBinding>(text, SimpleListItemBinding::class.java) {
override fun renderFunction(view: SimpleListItemBinding, model: String, viewHolder: BaseViewHolderItem<SimpleListItemBinding>) {
view.simpleListText.text = "$model section - $section"
view.root.setOnclickAsync { callback() }
setColorUsingBackground(view.root, section)
}
override fun getInflaterFunction(): ViewInflatingFunction<SimpleListItemBinding> {
return SimpleListItemBinding::inflate
}
}
class SimpleListImageItemRender(color: Int, val section: Int) : BaseRenderModel<Int, SimpleListImageItemBinding>(color, SimpleListImageItemBinding::class.java) {
override fun renderFunction(view: SimpleListImageItemBinding, model: Int, viewHolder: BaseViewHolderItem<SimpleListImageItemBinding>) {
view.simpleListItemImageImage.colorFilter = PorterDuffColorFilter(model, PorterDuff.Mode.ADD)
setColorUsingBackground(view.root, section)
}
override fun getInflaterFunction(): ViewInflatingFunction<SimpleListImageItemBinding> = SimpleListImageItemBinding::inflate
}
| mit | ea7b7b4129eb8ca7f77b4181ac92563a | 42.681818 | 161 | 0.69641 | 4.805 | false | false | false | false |
VKCOM/vk-android-sdk | core/src/main/java/com/vk/api/sdk/internal/HttpMultipartEntry.kt | 1 | 2840 | /*******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2019 vk.com
*
* 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.vk.api.sdk.internal
import android.net.Uri
interface HttpMultipartEntry {
class File : HttpMultipartEntry {
var fileUri: Uri
var fileName: String? = null
constructor(fileUri: Uri) {
this.fileUri = fileUri
this.fileName = fileUri.lastPathSegment
}
constructor(fileUri: Uri, fileName: String) {
this.fileUri = fileUri
this.fileName = fileName
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is HttpMultipartEntry.File) return false
val that = other as HttpMultipartEntry.File?
return fileUri == that!!.fileUri
}
override fun hashCode(): Int {
return fileUri.hashCode()
}
override fun toString(): String {
return "File{fileUri='$fileUri'}"
}
}
class Text(var textValue: String) : HttpMultipartEntry {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is HttpMultipartEntry.Text) return false
val that = other as HttpMultipartEntry.Text?
return textValue == that!!.textValue
}
override fun hashCode(): Int {
return textValue.hashCode()
}
override fun toString(): String {
return "Text{" +
"textValue='" + textValue + '\''.toString() +
'}'.toString()
}
}
} | mit | 158265d7eba558f29593a2a8ee94b67e | 34.5125 | 81 | 0.600352 | 5.211009 | false | false | false | false |
westnordost/osmagent | app/src/main/java/de/westnordost/streetcomplete/quests/oneway/AddOneway.kt | 1 | 6170 | package de.westnordost.streetcomplete.quests.oneway
import android.util.Log
import de.westnordost.osmapi.map.data.BoundingBox
import de.westnordost.osmapi.map.data.Element
import de.westnordost.osmapi.map.data.LatLon
import de.westnordost.osmapi.map.data.Way
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.ElementGeometry
import de.westnordost.streetcomplete.data.osm.OsmElementQuestType
import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.osm.download.MapDataWithGeometryHandler
import de.westnordost.streetcomplete.data.osm.download.OverpassMapDataDao
import de.westnordost.streetcomplete.data.osm.tql.FiltersParser
import de.westnordost.streetcomplete.quests.oneway.data.TrafficFlowSegment
import de.westnordost.streetcomplete.quests.oneway.data.TrafficFlowSegmentsDao
import de.westnordost.streetcomplete.quests.oneway.data.WayTrafficFlowDao
class AddOneway(
private val overpassMapDataDao: OverpassMapDataDao,
private val trafficFlowSegmentsDao: TrafficFlowSegmentsDao,
private val db: WayTrafficFlowDao
) : OsmElementQuestType<OnewayAnswer> {
private val tagFilters =
" ways with highway ~ " +
"trunk|trunk_link|primary|primary_link|secondary|secondary_link|tertiary|tertiary_link|" +
"unclassified|residential|living_street|pedestrian|track|road" +
" and !oneway and junction != roundabout and area != yes" +
" and (access !~ private|no or (foot and foot !~ private|no)) "
override val commitMessage =
"Add whether this road is a one-way road, this road was marked as likely oneway by improveosm.org"
override val icon = R.drawable.ic_quest_oneway
override val hasMarkersAtEnds = true
private val filter by lazy { FiltersParser().parse(tagFilters) }
override fun getTitle(tags: Map<String, String>) = R.string.quest_oneway_title
override fun isApplicableTo(element: Element) =
filter.matches(element) && db.isForward(element.id) != null
override fun download(bbox: BoundingBox, handler: MapDataWithGeometryHandler): Boolean {
val trafficDirectionMap: Map<Long, List<TrafficFlowSegment>>
try {
trafficDirectionMap = trafficFlowSegmentsDao.get(bbox)
} catch (e: Exception) {
Log.e("AddOneway", "Unable to download traffic metadata", e)
return false
}
if (trafficDirectionMap.isEmpty()) return true
val query = "way(id:${trafficDirectionMap.keys.joinToString(",")}); out meta geom;"
overpassMapDataDao.getAndHandleQuota(query) { element, geometry ->
fun handle(element: Element, geometry: ElementGeometry?) {
if(geometry == null) return
// filter the data as ImproveOSM data may be outdated or catching too much
if (!filter.matches(element)) return
val way = element as? Way ?: return
val segments = trafficDirectionMap[way.id] ?: return
/* exclude rings because the driving direction can then not be determined reliably
from the improveosm data and the quest should stay simple, i.e not require the
user to input it in those cases. Additionally, whether a ring-road is a oneway or
not is less valuable information (for routing) and many times such a ring will
actually be a roundabout. Oneway information on roundabouts is superfluous.
See #1320 */
if(way.nodeIds.last() == way.nodeIds.first()) return
/* only create quest if direction can be clearly determined and is the same
direction for all segments belonging to one OSM way (because StreetComplete
cannot split ways up) */
val isForward = isForward(geometry.polylines[0], segments) ?: return
db.put(way.id, isForward)
handler.handle(element, geometry)
}
handle(element, geometry)
}
return true
}
/** returns true if all given [trafficFlowSegments] point forward in relation to the
* direction of the OSM [way] and false if they all point backward.
*
* If the segments point into different directions or their direction cannot be
* determined. returns null.
*/
private fun isForward(way: List<LatLon>,trafficFlowSegments: List<TrafficFlowSegment>): Boolean? {
var result: Boolean? = null
for (segment in trafficFlowSegments) {
val fromPositionIndex = findClosestPositionIndexOf(way, segment.fromPosition)
val toPositionIndex = findClosestPositionIndexOf(way, segment.toPosition)
if (fromPositionIndex == -1 || toPositionIndex == -1) return null
if (fromPositionIndex == toPositionIndex) return null
val forward = fromPositionIndex < toPositionIndex
if (result == null) {
result = forward
} else if (result != forward) {
return null
}
}
return result
}
private fun findClosestPositionIndexOf(positions: List<LatLon>, latlon: LatLon): Int {
var shortestDistance = 1.0
var result = -1
var index = 0
for (pos in positions) {
val distance = Math.hypot(
pos.longitude - latlon.longitude,
pos.latitude - latlon.latitude
)
if (distance < 0.00005 && distance < shortestDistance) {
shortestDistance = distance
result = index
}
index++
}
return result
}
override fun createForm() = AddOnewayForm()
override fun applyAnswerTo(answer: OnewayAnswer, changes: StringMapChangesBuilder) {
if (!answer.isOneway) {
changes.add("oneway", "no")
} else {
changes.add("oneway", if (db.isForward(answer.wayId)!!) "yes" else "-1")
}
}
override fun cleanMetadata() {
db.deleteUnreferenced()
}
}
| gpl-3.0 | e83442e5310fa78e855017103baac969 | 42.146853 | 106 | 0.658833 | 4.81655 | false | false | false | false |
UCSoftworks/LeafDb | leafdb-android/src/main/java/com/ucsoftworks/leafdb/android/LeafDbAndroidCursor.kt | 1 | 774 | package com.ucsoftworks.leafdb.android
import android.database.Cursor
import com.ucsoftworks.leafdb.wrapper.ILeafDbCursor
/**
* Created by Pasenchuk Victor on 25/08/2017
*/
internal class LeafDbAndroidCursor(private val cursor: Cursor) : ILeafDbCursor {
override val empty: Boolean
get() = !cursor.moveToNext()
override val isClosed: Boolean
get() = cursor.isClosed
override fun close() {
cursor.close()
}
override fun moveToNext() =
cursor.moveToNext()
override fun getString(index: Int): String
= cursor.getString(index)
override fun getLong(index: Int): Long
= cursor.getLong(index)
override fun getDouble(index: Int): Double
= cursor.getDouble(index)
}
| lgpl-3.0 | 5526427d962a0887f4a5640052ce59a6 | 21.764706 | 80 | 0.662791 | 4.372881 | false | false | false | false |
Heiner1/AndroidAPS | core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/data/AutosensData.kt | 1 | 6622 | package info.nightscout.androidaps.plugins.iob.iobCobCalculator.data
import android.content.Context
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.core.R
import info.nightscout.androidaps.database.entities.Carbs
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.shared.logging.AAPSLogger
import info.nightscout.shared.logging.LTag
import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults
import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DataPointWithLabelInterface
import info.nightscout.androidaps.plugins.general.overview.graphExtensions.PointsWithLabelGraphSeries
import info.nightscout.androidaps.plugins.general.overview.graphExtensions.Scale
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.interfaces.ResourceHelper
import info.nightscout.shared.sharedPreferences.SP
import java.util.*
import javax.inject.Inject
import kotlin.math.min
class AutosensData(injector: HasAndroidInjector) : DataPointWithLabelInterface {
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var sp: SP
@Inject lateinit var rh: ResourceHelper
@Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var dateUtil: DateUtil
inner class CarbsInPast {
var time: Long
var carbs: Double
var min5minCarbImpact = 0.0
var remaining: Double
constructor(t: Carbs, isAAPSOrWeighted: Boolean) {
time = t.timestamp
carbs = t.amount
remaining = t.amount
val profile = profileFunction.getProfile(t.timestamp)
if (isAAPSOrWeighted && profile != null) {
val maxAbsorptionHours = sp.getDouble(R.string.key_absorption_maxtime, Constants.DEFAULT_MAX_ABSORPTION_TIME)
val sens = profile.getIsfMgdl(t.timestamp)
val ic = profile.getIc(t.timestamp)
min5minCarbImpact = t.amount / (maxAbsorptionHours * 60 / 5) * sens / ic
aapsLogger.debug(
LTag.AUTOSENS,
"""Min 5m carbs impact for ${carbs}g @${dateUtil.dateAndTimeString(t.timestamp)} for ${maxAbsorptionHours}h calculated to $min5minCarbImpact ISF: $sens IC: $ic"""
)
} else {
min5minCarbImpact = sp.getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact)
}
}
internal constructor(other: CarbsInPast) {
time = other.time
carbs = other.carbs
min5minCarbImpact = other.min5minCarbImpact
remaining = other.remaining
}
override fun toString(): String =
String.format(Locale.ENGLISH, "CarbsInPast: time: %s carbs: %.02f min5minCI: %.02f remaining: %.2f", dateUtil.dateAndTimeString(time), carbs, min5minCarbImpact, remaining)
}
var time = 0L
var bg = 0.0 // mgdl
var chartTime: Long = 0
var pastSensitivity = ""
var deviation = 0.0
var validDeviation = false
var activeCarbsList: MutableList<CarbsInPast> = ArrayList()
var absorbed = 0.0
var carbsFromBolus = 0.0
var cob = 0.0
var bgi = 0.0
var delta = 0.0
var avgDelta = 0.0
var avgDeviation = 0.0
var autosensResult = AutosensResult()
var slopeFromMaxDeviation = 0.0
var slopeFromMinDeviation = 999.0
var usedMinCarbsImpact = 0.0
var failOverToMinAbsorptionRate = false
// Oref1
var absorbing = false
var mealCarbs = 0.0
var mealStartCounter = 999
var type = ""
var uam = false
var extraDeviation: MutableList<Double> = ArrayList()
override fun toString(): String {
return String.format(
Locale.ENGLISH,
"AutosensData: %s pastSensitivity=%s delta=%.02f avgDelta=%.02f bgi=%.02f deviation=%.02f avgDeviation=%.02f absorbed=%.02f carbsFromBolus=%.02f cob=%.02f autosensRatio=%.02f slopeFromMaxDeviation=%.02f slopeFromMinDeviation=%.02f activeCarbsList=%s",
dateUtil.dateAndTimeString(time),
pastSensitivity,
delta,
avgDelta,
bgi,
deviation,
avgDeviation,
absorbed,
carbsFromBolus,
cob,
autosensResult.ratio,
slopeFromMaxDeviation,
slopeFromMinDeviation,
activeCarbsList.toString()
)
}
fun cloneCarbsList(): MutableList<CarbsInPast> {
val newActiveCarbsList: MutableList<CarbsInPast> = ArrayList()
for (c in activeCarbsList) {
newActiveCarbsList.add(CarbsInPast(c))
}
return newActiveCarbsList
}
// remove carbs older than timeframe
fun removeOldCarbs(toTime: Long, isAAPSOrWeighted: Boolean) {
val maxAbsorptionHours: Double =
if (isAAPSOrWeighted) sp.getDouble(R.string.key_absorption_maxtime, Constants.DEFAULT_MAX_ABSORPTION_TIME)
else sp.getDouble(R.string.key_absorption_cutoff, Constants.DEFAULT_MAX_ABSORPTION_TIME)
var i = 0
while (i < activeCarbsList.size) {
val c = activeCarbsList[i]
if (c.time + maxAbsorptionHours * 60 * 60 * 1000L < toTime) {
activeCarbsList.removeAt(i--)
if (c.remaining > 0) cob -= c.remaining
aapsLogger.debug(LTag.AUTOSENS, "Removing carbs at " + dateUtil.dateAndTimeString(toTime) + " after " + maxAbsorptionHours + "h > " + c.toString())
}
i++
}
}
fun deductAbsorbedCarbs() {
var ac = absorbed
var i = 0
while (i < activeCarbsList.size && ac > 0) {
val c = activeCarbsList[i]
if (c.remaining > 0) {
val sub = min(ac, c.remaining)
c.remaining -= sub
ac -= sub
}
i++
}
}
// ------- DataPointWithLabelInterface ------
var scale: Scale? = null
override fun getX(): Double = chartTime.toDouble()
override fun getY(): Double = scale!!.transform(cob)
override fun setY(y: Double) {}
override val label: String = ""
override val duration = 0L
override val shape = PointsWithLabelGraphSeries.Shape.COB_FAIL_OVER
override val size = 0.5f
override fun color(context: Context?): Int {
return rh.gac(context,R.attr.cobColor)
}
init {
injector.androidInjector().inject(this)
}
} | agpl-3.0 | 564782b3bfdc7c4739ee35147d0f5c57 | 37.283237 | 265 | 0.649804 | 4.4 | false | false | false | false |
xiprox/Tensuu | app-student/src/main/java/tr/xip/scd/tensuu/student/ui/feature/main/StudentPresenter.kt | 1 | 3787 | package tr.xip.scd.tensuu.student.ui.feature.main
import android.annotation.SuppressLint
import android.view.MenuItem
import io.realm.Realm
import io.realm.SyncUser
import tr.xip.scd.tensuu.common.ui.mvp.SafeViewMvpPresenter
import tr.xip.scd.tensuu.realm.model.*
import tr.xip.scd.tensuu.realm.util.RealmUtils.syncedRealm
import tr.xip.scd.tensuu.student.R
import tr.xip.scd.tensuu.student.ui.feature.local.Credentials
class StudentPresenter : SafeViewMvpPresenter<StudentView>() {
private var realm: Realm? = null
private var student: Student? = null
override fun detachView(retainInstance: Boolean) {
super.detachView(retainInstance)
realm?.close()
}
fun init() {
if (SyncUser.currentUser() != null) {
realm = syncedRealm()
val student = realm!!.where(Student::class.java)
.equalTo(StudentFields.SSID, Credentials.id)
.equalTo(StudentFields.PASSWORD, Credentials.password)
.findFirst()
if (student != null) {
load()
} else {
goToLogin()
}
} else {
goToLogin()
}
}
private fun load() {
if (realm == null) return
student = realm!!.where(Student::class.java)
.equalTo(StudentFields.SSID, Credentials.id)
.equalTo(StudentFields.PASSWORD, Credentials.password)
.findFirst()
if (student != null) {
view?.setName(student?.fullName ?: "?")
view?.setSsid(student?.ssid)
view?.setGrade(student?.grade)
view?.setFloor(student?.floor)
setPoints()
setAdapter()
/* Notify for the initial state */
view?.notifyDateChanged()
} else {
view?.showToast("Couldn't find student")
view?.die()
}
}
private fun setPoints() {
if (realm == null) return
val period = realm!!.where(Period::class.java).findFirst()!!
var query = realm!!.where(Point::class.java)
.equalTo(PointFields.TO.SSID, student?.ssid)
if (period.start != 0L && period.end != 0L) {
query = query
.greaterThanOrEqualTo(PointFields.TIMESTAMP, period.start)
.lessThanOrEqualTo(PointFields.TIMESTAMP, period.end)
}
view?.setPoints(
100 + query.sum(PointFields.AMOUNT).toInt()
).toString()
}
private fun setAdapter() {
if (realm == null) return
val period = realm!!.where(Period::class.java).findFirst()!!
var query = realm!!.where(Point::class.java).equalTo(PointFields.TO.SSID, student?.ssid)
if (period.start != 0L && period.end != 0L) {
query = query
.greaterThan(PointFields.TIMESTAMP, period.start)
.lessThan(PointFields.TIMESTAMP, period.end)
}
view?.setAdapter(PointsAdapter(query.findAll()))
}
fun onDataChanged() {
setPoints()
view?.setFlipperChild(
if (view?.getAdapter()?.itemCount == 0) {
StudentActivity.FLIPPER_NO_POINTS
} else {
StudentActivity.FLIPPER_CONTENT
}
)
}
fun onSignedOut() {
Credentials.logout()
view?.startLoginActivity()
view?.die()
}
@SuppressLint("SimpleDateFormat")
fun onOptionsItemSelected(item: MenuItem?) {
when (item?.itemId) {
R.id.action_sign_out -> {
view?.showSignOutDialog()
}
}
}
fun goToLogin() {
view?.startLoginActivity()
view?.die()
}
} | gpl-3.0 | 218ab8f250d7d3127ad52d84f40bdb4c | 29.304 | 96 | 0.557433 | 4.601458 | false | false | false | false |
auth0/Auth0.Android | auth0/src/main/java/com/auth0/android/request/internal/BaseAuthenticationRequest.kt | 1 | 6882 | package com.auth0.android.request.internal
import android.text.TextUtils
import android.util.Log
import androidx.annotation.VisibleForTesting
import com.auth0.android.Auth0Exception
import com.auth0.android.authentication.AuthenticationException
import com.auth0.android.authentication.ParameterBuilder
import com.auth0.android.callback.Callback
import com.auth0.android.provider.*
import com.auth0.android.provider.IdTokenVerificationOptions
import com.auth0.android.provider.IdTokenVerifier
import com.auth0.android.request.AuthenticationRequest
import com.auth0.android.request.Request
import com.auth0.android.result.Credentials
import java.util.*
internal open class BaseAuthenticationRequest(
private val request: Request<Credentials, AuthenticationException>,
private val clientId: String, baseURL: String) : AuthenticationRequest {
private companion object {
private val TAG = BaseAuthenticationRequest::class.java.simpleName
private const val ERROR_VALUE_ID_TOKEN_VALIDATION_FAILED = "Could not verify the ID token"
}
private var _currentTimeInMillis: Long? = null
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
internal var validateClaims = false
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
internal var idTokenVerificationLeeway: Int? = null
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
internal var idTokenVerificationIssuer: String = baseURL
@set:VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
internal var currentTimeInMillis: Long
get() = if (_currentTimeInMillis != null) _currentTimeInMillis!! else System.currentTimeMillis()
set(value) {
_currentTimeInMillis = value
}
/**
* Sets the 'grant_type' parameter
*
* @param grantType grant type
* @return itself
*/
override fun setGrantType(grantType: String): AuthenticationRequest {
addParameter(ParameterBuilder.GRANT_TYPE_KEY, grantType)
return this
}
/**
* Sets the 'connection' parameter.
*
* @param connection name of the connection
* @return itself
*/
override fun setConnection(connection: String): AuthenticationRequest {
addParameter(ParameterBuilder.CONNECTION_KEY, connection)
return this
}
/**
* Sets the 'realm' parameter. A realm identifies the host against which the authentication will be made, and usually helps to know which username and password to use.
*
* @param realm name of the realm
* @return itself
*/
override fun setRealm(realm: String): AuthenticationRequest {
addParameter(ParameterBuilder.REALM_KEY, realm)
return this
}
/**
* Sets the 'scope' parameter.
*
* @param scope a scope value
* @return itself
*/
override fun setScope(scope: String): AuthenticationRequest {
addParameter(ParameterBuilder.SCOPE_KEY, scope)
return this
}
/**
* Sets the 'audience' parameter.
*
* @param audience an audience value
* @return itself
*/
override fun setAudience(audience: String): AuthenticationRequest {
addParameter(ParameterBuilder.AUDIENCE_KEY, audience)
return this
}
override fun validateClaims(): AuthenticationRequest {
this.validateClaims = true
return this
}
override fun withIdTokenVerificationLeeway(leeway: Int): AuthenticationRequest {
this.idTokenVerificationLeeway = leeway
return this
}
override fun withIdTokenVerificationIssuer(issuer: String): AuthenticationRequest {
this.idTokenVerificationIssuer = issuer
return this
}
override fun addParameters(parameters: Map<String, String>): AuthenticationRequest {
request.addParameters(parameters)
return this
}
override fun addParameter(name: String, value: String): AuthenticationRequest {
request.addParameter(name, value)
return this
}
override fun addHeader(name: String, value: String): AuthenticationRequest {
request.addHeader(name, value)
return this
}
override fun start(callback: Callback<Credentials, AuthenticationException>) {
warnClaimValidation()
request.start(object : Callback<Credentials, AuthenticationException> {
override fun onSuccess(result: Credentials) {
if(validateClaims) {
try {
verifyClaims(result.idToken)
} catch (e: AuthenticationException) {
callback.onFailure(e)
return
}
}
callback.onSuccess(result)
}
override fun onFailure(error: AuthenticationException) {
callback.onFailure(error)
}
})
}
@Throws(Auth0Exception::class)
override fun execute(): Credentials {
warnClaimValidation()
val credentials = request.execute()
if(validateClaims) {
verifyClaims(credentials.idToken)
}
return credentials
}
@JvmSynthetic
@Throws(Auth0Exception::class)
override suspend fun await(): Credentials {
warnClaimValidation()
val credentials = request.await()
if(validateClaims) {
verifyClaims(credentials.idToken)
}
return credentials
}
/**
* Used to verify the claims from the ID Token.
*
* @param idToken - The ID Token obtained through authentication
* @throws AuthenticationException - This is a exception wrapping around [TokenValidationException]
*/
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
internal fun verifyClaims(idToken: String) {
try {
if (TextUtils.isEmpty(idToken)) {
throw IdTokenMissingException()
}
val decodedIdToken: Jwt = try {
Jwt(idToken)
} catch (error: Exception) {
throw UnexpectedIdTokenException(error)
}
val options = IdTokenVerificationOptions(
idTokenVerificationIssuer,
clientId,
null
)
options.clockSkew = idTokenVerificationLeeway
options.clock = Date(currentTimeInMillis)
IdTokenVerifier().verify(decodedIdToken, options, false)
} catch (e: TokenValidationException) {
throw AuthenticationException(ERROR_VALUE_ID_TOKEN_VALIDATION_FAILED, e)
}
}
private fun warnClaimValidation() {
if(!validateClaims) {
Log.e(TAG, "The request is made without validating claims. Enable claim validation by calling AuthenticationRequest#validateClaims()")
}
}
} | mit | 400a9bec2f18b8ee79d35cfcb27113f6 | 32.412621 | 171 | 0.659111 | 5.368175 | false | true | false | false |
PolymerLabs/arcs | javatests/arcs/core/crdt/CrdtCountTest.kt | 1 | 5621 | /*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.crdt
import com.google.common.truth.Truth.assertThat
import kotlin.test.assertFailsWith
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
/** Tests for [CrdtCount]. */
@RunWith(JUnit4::class)
class CrdtCountTest {
lateinit var alice: CrdtCount
lateinit var bob: CrdtCount
@Before
fun setup() {
alice = CrdtCount()
bob = CrdtCount()
}
@Test
fun countInitializesToZero() {
assertThat(alice.consumerView).isEqualTo(0)
}
@Test
fun canApplyAnIncrementOp() {
assertTrue(
alice.applyOperation(CrdtCount.Operation.Increment("alice", VersionMap("alice" to 1)))
)
assertThat(alice.consumerView).isEqualTo(1)
}
@Test
fun canApplyAnIncrementOp_withPlusEquals() {
alice.forActor("alice") += 5
assertThat(alice.consumerView).isEqualTo(5)
}
@Test
fun canApplyTwoIncrementOps_fromDifferentActors() {
assertTrue(
alice.applyOperation(CrdtCount.Operation.Increment("alice", VersionMap("alice" to 1)))
)
assertTrue(
alice.applyOperation(CrdtCount.Operation.Increment("bob", VersionMap("bob" to 1)))
)
assertThat(alice.consumerView).isEqualTo(2)
}
@Test
fun canApplyTwoIncrementOps_fromSameActor() {
assertTrue(
alice.applyOperation(CrdtCount.Operation.Increment("alice", VersionMap("alice" to 1)))
)
assertTrue(
alice.applyOperation(CrdtCount.Operation.Increment("alice", VersionMap("alice" to 2)))
)
assertThat(alice.consumerView).isEqualTo(2)
}
@Test
fun canNotApplyTwoIncrementOps_fromSameActor_withSameVersions() {
assertTrue(
alice.applyOperation(CrdtCount.Operation.Increment("alice", VersionMap("alice" to 1)))
)
assertFalse(
alice.applyOperation(CrdtCount.Operation.Increment("alice", VersionMap("alice" to 1)))
)
assertThat(alice.consumerView).isEqualTo(1)
}
@Test
fun canApplyAMultiincrementOp() {
assertTrue(
alice.applyOperation(
CrdtCount.Operation.MultiIncrement("alice", VersionMap("alice" to 1), 10)
)
)
assertThat(alice.consumerView).isEqualTo(10)
}
@Test
fun mergesTwoCounts_withIncrementsFromDifferentActors() {
alice.forActor("alice") += 7
bob.forActor("bob") += 13
// merge bob into alice
val results = alice.merge(bob.data)
assertThat(alice.consumerView).isEqualTo(20)
assertThat(results.modelChange).isInstanceOf(CrdtChange.Operations::class.java)
assertThat((results.modelChange as CrdtChange.Operations)[0])
.isEqualTo(CrdtCount.Operation.MultiIncrement("bob", VersionMap("bob" to 1), 13))
assertThat(results.otherChange).isInstanceOf(CrdtChange.Operations::class.java)
assertThat((results.otherChange as CrdtChange.Operations)[0])
.isEqualTo(CrdtCount.Operation.MultiIncrement("alice", VersionMap("alice" to 1), 7))
bob.applyChanges(results.otherChange)
assertThat(bob.consumerView).isEqualTo(20)
}
@Test
fun mergesTwoCounts_withIncrementsFromTheSameActor() {
alice.forActor("alice") += 7
bob.merge(alice.data)
bob.forActor("alice") += 13
// merge bob into alice
val results = alice.merge(bob.data)
assertThat(alice.consumerView).isEqualTo(20)
assertThat(results.modelChange).isInstanceOf(CrdtChange.Operations::class.java)
assertThat((results.modelChange as CrdtChange.Operations)[0])
.isEqualTo(CrdtCount.Operation.MultiIncrement("alice", VersionMap("alice" to 2), 13))
assertThat(results.otherChange).isInstanceOf(CrdtChange.Operations::class.java)
// We already merged alice into bob.
assertThat((results.otherChange as CrdtChange.Operations)).isEmpty()
bob.applyChanges(results.otherChange)
assertThat(bob.consumerView).isEqualTo(20)
}
@Test
fun throwsOnDivergentModels() {
assertTrue(
alice.applyOperation(CrdtCount.Operation.MultiIncrement("alice", VersionMap("alice" to 1), 7))
)
assertTrue(
bob.applyOperation(CrdtCount.Operation.MultiIncrement("alice", VersionMap("alice" to 1), 13))
)
assertFailsWith<CrdtException> {
alice.merge(bob.data)
}
}
@Test
fun throwsOnApparentDecrement() {
assertTrue(
alice.applyOperation(CrdtCount.Operation.MultiIncrement("alice", VersionMap("alice" to 1), 7))
)
assertTrue(
bob.applyOperation(CrdtCount.Operation.Increment("alice", VersionMap("alice" to 1)))
)
assertTrue(
bob.applyOperation(CrdtCount.Operation.MultiIncrement("alice", VersionMap("alice" to 2), 3))
)
assertFailsWith<CrdtException> {
alice.merge(bob.data)
}
}
@Test
fun mergesSeveralActors() {
alice.forActor("a") += 6
alice.forActor("c") += 12
alice.forActor("d") += 22
// Two increments for 'e' on alice trumps the single increment on bob.
alice.forActor("e") += 4
alice.forActor("e") += 13
bob.forActor("b") += 5
// Vice versa for 'c'.
bob.forActor("c") += 12
bob.forActor("c") += 6
bob.forActor("d") += 22
bob.forActor("e") += 4
val results = alice.merge(bob.data)
assertThat(alice.consumerView).isEqualTo(68)
bob.applyChanges(results.otherChange)
assertThat(bob.consumerView).isEqualTo(68)
}
}
| bsd-3-clause | 67abd682f1b07a7de7520c3f4cad8fbc | 28.276042 | 100 | 0.70201 | 4.111924 | false | true | false | false |
Maccimo/intellij-community | plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/core/script/ucache/ScriptSdksBuilder.kt | 2 | 4868 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.core.script.ucache
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.JavaSdkType
import com.intellij.openapi.projectRoots.ProjectJdkTable
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.kotlin.idea.core.script.configuration.utils.ScriptClassRootsStorage
import org.jetbrains.kotlin.idea.core.script.scriptingWarnLog
import org.jetbrains.kotlin.idea.util.application.runReadAction
import java.nio.file.Path
class ScriptSdksBuilder(
val project: Project,
private val sdks: MutableMap<SdkId, Sdk?> = mutableMapOf(),
private val remove: Sdk? = null
) {
private val defaultSdk by lazy { getScriptDefaultSdk() }
fun build(): ScriptSdks {
val nonIndexedClassRoots = mutableSetOf<VirtualFile>()
val nonIndexedSourceRoots = mutableSetOf<VirtualFile>()
val nonIndexedSdks = sdks.values.filterNotNullTo(mutableSetOf())
runReadAction {
for (module in ModuleManager.getInstance(project).modules.filter { !it.isDisposed }) {
ProgressManager.checkCanceled()
if (nonIndexedSdks.isEmpty()) break
nonIndexedSdks.remove(ModuleRootManager.getInstance(module).sdk)
}
nonIndexedSdks.forEach {
nonIndexedClassRoots.addAll(it.rootProvider.getFiles(OrderRootType.CLASSES))
nonIndexedSourceRoots.addAll(it.rootProvider.getFiles(OrderRootType.SOURCES))
}
}
return ScriptSdks(sdks, nonIndexedClassRoots, nonIndexedSourceRoots)
}
@Deprecated("Don't use, used only from DefaultScriptingSupport for saving to storage")
fun addAll(other: ScriptSdksBuilder) {
sdks.putAll(other.sdks)
}
fun addAll(other: ScriptSdks) {
sdks.putAll(other.sdks)
}
// add sdk by home path with checking for removed sdk
fun addSdk(sdkId: SdkId): Sdk? {
val canonicalPath = sdkId.homeDirectory ?: return addDefaultSdk()
return addSdk(Path.of(canonicalPath))
}
fun addSdk(javaHome: Path?): Sdk? {
if (javaHome == null) return addDefaultSdk()
return sdks.getOrPut(SdkId(javaHome)) {
getScriptSdkByJavaHome(javaHome) ?: defaultSdk
}
}
private fun getScriptSdkByJavaHome(javaHome: Path): Sdk? {
// workaround for mismatched gradle wrapper and plugin version
val javaHomeVF = try {
VfsUtil.findFile(javaHome, true)
} catch (e: Throwable) {
null
} ?: return null
return runReadAction { ProjectJdkTable.getInstance() }.allJdks
.find { it.homeDirectory == javaHomeVF }
?.takeIf { it.canBeUsedForScript() }
}
fun addDefaultSdk(): Sdk? =
sdks.getOrPut(SdkId.default) { defaultSdk }
fun addSdkByName(sdkName: String) {
val sdk = runReadAction { ProjectJdkTable.getInstance() }.allJdks
.find { it.name == sdkName }
?.takeIf { it.canBeUsedForScript() }
?: defaultSdk
?: return
val homePath = sdk.homePath ?: return
sdks[SdkId(homePath)] = sdk
}
private fun getScriptDefaultSdk(): Sdk? {
val projectSdk = ProjectRootManager.getInstance(project).projectSdk?.takeIf { it.canBeUsedForScript() }
if (projectSdk != null) return projectSdk
val allJdks = runReadAction { ProjectJdkTable.getInstance() }.allJdks
val anyJavaSdk = allJdks.find { it.canBeUsedForScript() }
if (anyJavaSdk != null) {
return anyJavaSdk
}
scriptingWarnLog(
"Default Script SDK is null: " +
"projectSdk = ${ProjectRootManager.getInstance(project).projectSdk}, " +
"all sdks = ${allJdks.joinToString("\n")}"
)
return null
}
private fun Sdk.canBeUsedForScript() = this != remove && sdkType is JavaSdkType
fun toStorage(storage: ScriptClassRootsStorage) {
storage.sdks = sdks.values.mapNotNullTo(mutableSetOf()) { it?.name }
storage.defaultSdkUsed = sdks.containsKey(SdkId.default)
}
fun fromStorage(storage: ScriptClassRootsStorage) {
storage.sdks.forEach {
addSdkByName(it)
}
if (storage.defaultSdkUsed) {
addDefaultSdk()
}
}
}
| apache-2.0 | fb42a1b05c005528670d4b564314aa57 | 35.059259 | 158 | 0.66968 | 4.810277 | false | false | false | false |
PolymerLabs/arcs | java/arcs/core/data/CollectionType.kt | 1 | 1729 | /*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.data
import arcs.core.common.Referencable
import arcs.core.crdt.CrdtModel
import arcs.core.crdt.CrdtModelType
import arcs.core.crdt.CrdtSet
import arcs.core.crdt.CrdtSet.Data
import arcs.core.crdt.CrdtSet.IOperation
import arcs.core.type.Tag
import arcs.core.type.Type
import kotlin.reflect.KClass
/** Extension function to wrap any type in a collection type. */
fun <T : Type> T?.collectionOf(): CollectionType<T>? =
if (this == null) null else CollectionType(this)
/** [Type] representation of a collection. */
data class CollectionType<T : Type>(
val collectionType: T
) : Type,
Type.TypeContainer<T>,
EntitySchemaProviderType,
CrdtModelType<Data<Referencable>, IOperation<Referencable>, Set<Referencable>> {
override val tag = Tag.Collection
override val containedType: T
get() = collectionType
override val entitySchema: Schema?
get() = (collectionType as? EntitySchemaProviderType)?.entitySchema
override val crdtModelDataClass: KClass<*> = CrdtSet.DataImpl::class
override fun createCrdtModel():
CrdtModel<Data<Referencable>, IOperation<Referencable>, Set<Referencable>> {
return CrdtSet()
}
override fun toStringWithOptions(options: Type.ToStringOptions): String {
return if (options.pretty) {
"${collectionType.toStringWithOptions(options)} Collection"
} else {
"[${collectionType.toStringWithOptions(options)}]"
}
}
}
| bsd-3-clause | 490004d73e9328fc7b07c0b73599555c | 29.875 | 96 | 0.740312 | 4.07783 | false | false | false | false |
Maccimo/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/OptionalStringEntityImpl.kt | 3 | 5468 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class OptionalStringEntityImpl: OptionalStringEntity, WorkspaceEntityBase() {
companion object {
val connections = listOf<ConnectionId>(
)
}
@JvmField var _data: String? = null
override val data: String?
get() = _data
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: OptionalStringEntityData?): ModifiableWorkspaceEntityBase<OptionalStringEntity>(), OptionalStringEntity.Builder {
constructor(): this(OptionalStringEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity OptionalStringEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field OptionalStringEntity#entitySource should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
override var data: String?
get() = getEntityData().data
set(value) {
checkModificationAllowed()
getEntityData().data = value
changedProperty.add("data")
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override fun getEntityData(): OptionalStringEntityData = result ?: super.getEntityData() as OptionalStringEntityData
override fun getEntityClass(): Class<OptionalStringEntity> = OptionalStringEntity::class.java
}
}
class OptionalStringEntityData : WorkspaceEntityData<OptionalStringEntity>() {
var data: String? = null
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<OptionalStringEntity> {
val modifiable = OptionalStringEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): OptionalStringEntity {
val entity = OptionalStringEntityImpl()
entity._data = data
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return OptionalStringEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as OptionalStringEntityData
if (this.data != other.data) return false
if (this.entitySource != other.entitySource) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as OptionalStringEntityData
if (this.data != other.data) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + data.hashCode()
return result
}
} | apache-2.0 | 99cc11225da062afe439e66cab8a3a50 | 33.834395 | 143 | 0.649232 | 6.136925 | false | false | false | false |
PolymerLabs/arcs | java/arcs/sdk/wasm/WasmRuntimeClient.kt | 1 | 2287 | /*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.sdk.wasm
object WasmRuntimeClient {
fun <T : WasmEntity> singletonClear(
particle: WasmParticleImpl,
singleton: WasmSingletonImpl<T>
) = singletonClear(particle.toAddress(), singleton.toAddress())
fun <T : WasmEntity> singletonSet(
particle: WasmParticleImpl,
singleton: WasmSingletonImpl<T>,
encoded: NullTermByteArray
) = singletonSet(
particle.toAddress(),
singleton.toAddress(),
encoded.bytes.toWasmAddress()
)
fun <T : WasmEntity> collectionRemove(
particle: WasmParticleImpl,
collection: WasmCollectionImpl<T>,
encoded: NullTermByteArray
) = collectionRemove(
particle.toAddress(),
collection.toAddress(),
encoded.bytes.toWasmAddress()
)
fun <T : WasmEntity> collectionClear(
particle: WasmParticleImpl,
collection: WasmCollectionImpl<T>
) =
collectionClear(particle.toAddress(), collection.toAddress())
fun <T : WasmEntity> collectionStore(
particle: WasmParticleImpl,
collection: WasmCollectionImpl<T>,
encoded: NullTermByteArray
): String? {
val wasmId = collectionStore(
particle.toAddress(),
collection.toAddress(),
encoded.bytes.toWasmAddress()
)
return wasmId.toNullableKString()?.let { _free(wasmId); it }
}
fun log(msg: String) = arcs.sdk.wasm.log(msg)
fun onRenderOutput(particle: WasmParticleImpl, template: String?, model: NullTermByteArray?) =
onRenderOutput(
particle.toAddress(),
template.toWasmNullableString(),
model?.bytes?.toWasmAddress() ?: 0
)
fun serviceRequest(
particle: WasmParticleImpl,
call: String,
encoded: NullTermByteArray,
tag: String
) = serviceRequest(
particle.toAddress(),
call.toWasmString(),
encoded.bytes.toWasmAddress(),
tag.toWasmString()
)
fun resolveUrl(url: String): String {
val r: WasmString = resolveUrl(url.toWasmString())
val resolved = r.toKString()
_free(r)
return resolved
}
}
| bsd-3-clause | cfce771e2b2116252b2e94112f5e3e93 | 25.593023 | 96 | 0.695234 | 4.347909 | false | false | false | false |
brianegan/bansa | examples/todoList/src/main/kotlin/com/brianegan/bansa/todoList/applicationReducer.kt | 1 | 1095 | package com.brianegan.bansa.todoList
import com.brianegan.bansa.Reducer
import com.github.andrewoma.dexx.kollection.toImmutableList
val applicationReducer = Reducer <ApplicationState>{ state, action ->
when (action) {
is INIT -> ApplicationState()
is ADD ->
if (state.newTodoMessage.length > 0) {
state.copy(
newTodoMessage = "",
todos = state.todos.plus(Todo(action.message)))
} else {
state
}
is REMOVE -> state.copy(
todos = state.todos.filter({ it.id.equals(action.id) }).toImmutableList())
is TOGGLE_TODO -> state.copy(
todos = state.todos.map({
if (it.id.equals(action.id)) {
it.copy(completed = action.completed)
} else {
it
}
}).toImmutableList())
is UPDATE_NEW_TODO_MESSAGE -> state.copy(
newTodoMessage = action.message)
else -> state
}
}
| mit | 233064eadeddeb41db04c9c76b930aac | 34.322581 | 90 | 0.503196 | 4.76087 | false | false | false | false |
blindpirate/gradle | subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/codegen/ApiExtensionsJar.kt | 3 | 3795 | /*
* 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.codegen
import org.gradle.kotlin.dsl.support.loggerFor
import org.gradle.kotlin.dsl.support.compileToDirectory
import org.gradle.kotlin.dsl.support.zipTo
import com.google.common.annotations.VisibleForTesting
import org.gradle.api.internal.file.temp.TemporaryFileProvider
import java.io.File
@VisibleForTesting
fun generateApiExtensionsJar(
temporaryFileProvider: TemporaryFileProvider,
outputFile: File,
gradleJars: Collection<File>,
gradleApiMetadataJar: File,
onProgress: () -> Unit
) {
ApiExtensionsJarGenerator(
temporaryFileProvider,
gradleJars,
gradleApiMetadataJar,
onProgress
).generate(outputFile)
}
private
class ApiExtensionsJarGenerator(
val temporaryFileProvider: TemporaryFileProvider,
val gradleJars: Collection<File>,
val gradleApiMetadataJar: File,
val onProgress: () -> Unit = {}
) {
fun generate(outputFile: File) {
val tempDir = tempDirFor(outputFile)
compileExtensionsTo(tempDir)
zipTo(outputFile, tempDir)
}
private
fun tempDirFor(outputFile: File): File =
temporaryFileProvider.createTemporaryDirectory(outputFile.nameWithoutExtension, outputFile.extension).apply {
deleteOnExit()
}
private
fun compileExtensionsTo(outputDir: File) {
compileKotlinApiExtensionsTo(
outputDir,
sourceFilesFor(outputDir),
classPath = gradleJars
)
onProgress()
}
private
fun sourceFilesFor(outputDir: File) =
gradleApiExtensionsSourceFilesFor(outputDir) +
builtinPluginIdExtensionsSourceFileFor(outputDir)
private
fun gradleApiExtensionsSourceFilesFor(outputDir: File) =
writeGradleApiKotlinDslExtensionsTo(outputDir, gradleJars, gradleApiMetadataJar).also {
onProgress()
}
private
fun builtinPluginIdExtensionsSourceFileFor(outputDir: File) =
generatedSourceFile(outputDir, "BuiltinPluginIdExtensions.kt").apply {
writeBuiltinPluginIdExtensionsTo(this, gradleJars)
onProgress()
}
private
fun generatedSourceFile(outputDir: File, fileName: String) =
File(outputDir, sourceFileName(fileName)).apply {
parentFile.mkdirs()
}
private
fun sourceFileName(fileName: String) =
"$packageDir/$fileName"
private
val packageDir = kotlinDslPackagePath
}
internal
fun compileKotlinApiExtensionsTo(
outputDirectory: File,
sourceFiles: Collection<File>,
classPath: Collection<File>,
logger: org.slf4j.Logger = loggerFor<ApiExtensionsJarGenerator>()
) {
val success = compileToDirectory(
outputDirectory,
"gradle-api-extensions",
sourceFiles,
logger,
classPath = classPath
)
if (!success) {
throw IllegalStateException(
"Unable to compile Gradle Kotlin DSL API Extensions Jar\n" +
"\tFrom:\n" +
sourceFiles.joinToString("\n\t- ", prefix = "\t- ", postfix = "\n") +
"\tSee compiler logs for details."
)
}
}
| apache-2.0 | fdb2bc410f9f33816bbc5e837cfa4e29 | 27.533835 | 117 | 0.685112 | 4.87163 | false | false | false | false |
KotlinNLP/SimpleDNN | src/main/kotlin/com/kotlinnlp/simplednn/core/layers/models/attention/AttentionLayer.kt | 1 | 3737 | /* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package com.kotlinnlp.simplednn.core.layers.models.attention
import com.kotlinnlp.simplednn.core.arrays.AugmentedArray
import com.kotlinnlp.simplednn.core.functionalities.activations.ActivationFunction
import com.kotlinnlp.simplednn.core.functionalities.activations.SoftmaxBase
import com.kotlinnlp.simplednn.core.layers.Layer
import com.kotlinnlp.simplednn.core.layers.LayerType
import com.kotlinnlp.simplednn.core.layers.helpers.RelevanceHelper
import com.kotlinnlp.simplednn.core.layers.models.attention.attentionmechanism.AttentionMechanismLayer
import com.kotlinnlp.simplednn.core.layers.models.attention.attentionmechanism.AttentionMechanismLayerParameters
import com.kotlinnlp.simplednn.simplemath.ndarray.NDArray
import com.kotlinnlp.simplednn.simplemath.ndarray.Shape
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory
/**
* The Attention Layer Structure.
*
* @property inputArrays the input arrays of the layer
* @param inputType the input array type (default Dense)
* @param params the parameters which connect the input to the output
* @param activation the activation function of the layer (default SoftmaxBase)
* @property dropout the probability of dropout
*/
internal class AttentionLayer<InputNDArrayType : NDArray<InputNDArrayType>>(
val inputArrays: List<AugmentedArray<InputNDArrayType>>,
inputType: LayerType.Input,
val attentionArrays: List<AugmentedArray<DenseNDArray>>,
override val params: AttentionMechanismLayerParameters,
activation: ActivationFunction? = SoftmaxBase()
) : Layer<InputNDArrayType>(
inputArray = AugmentedArray(params.inputSize), // empty array (it should not be used)
inputType = inputType,
outputArray = AugmentedArray(values = DenseNDArrayFactory.zeros(Shape(inputArrays.first().size))),
params = params,
activationFunction = activation,
dropout = 0.0
) {
/**
* The helper which executes the forward
*/
override val forwardHelper = AttentionForwardHelper(layer = this)
/**
* The helper which executes the backward
*/
override val backwardHelper = AttentionBackwardHelper(layer = this)
/**
* The helper which calculates the relevance
*/
override val relevanceHelper: RelevanceHelper? = null
/**
* The attention mechanism.
*/
internal val attentionMechanism = AttentionMechanismLayer(
inputArrays = this.attentionArrays,
inputType = inputType,
params = this.params,
activation = SoftmaxBase()
).apply {
setParamsErrorsCollector([email protected]())
}
/**
* The attention scores.
*/
val attentionScores: AugmentedArray<DenseNDArray> get() = this.attentionMechanism.outputArray
/**
* The attention matrix.
*/
val attentionMatrix: AugmentedArray<DenseNDArray> get() = this.attentionMechanism.attentionMatrix
/**
* Essential requirements.
*/
init {
require(this.inputArrays.isNotEmpty()) { "The input array cannot be empty." }
require(this.attentionArrays.isNotEmpty()) { "The attention array cannot be empty." }
require(this.inputArrays.size == attentionArrays.size) {
"The input array must have the same length of the attention array."
}
this.inputArrays.first().size.let { inputSize ->
this.inputArrays.forEach { require(it.size == inputSize) }
}
}
}
| mpl-2.0 | a73a6a85282351d9db999b01f5fe52df | 36.747475 | 112 | 0.752208 | 4.653798 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/declarations/KotlinUMethod.kt | 1 | 5250 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.kotlin
import com.intellij.psi.*
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.kotlin.asJava.elements.KtLightElement
import org.jetbrains.kotlin.asJava.elements.KtLightMethod
import org.jetbrains.kotlin.asJava.elements.isGetter
import org.jetbrains.kotlin.asJava.elements.isSetter
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.utils.SmartList
import org.jetbrains.uast.*
import org.jetbrains.uast.kotlin.psi.UastKotlinPsiParameter
@ApiStatus.Internal
open class KotlinUMethod(
psi: PsiMethod,
final override val sourcePsi: KtDeclaration?,
givenParent: UElement?
) : KotlinAbstractUElement(givenParent), UMethod, UAnchorOwner, PsiMethod by psi {
constructor(
psi: KtLightMethod,
givenParent: UElement?
) : this(psi, getKotlinMemberOrigin(psi), givenParent)
override val uastParameters: List<UParameter> by lz {
fun parameterOrigin(psiParameter: PsiParameter?): KtElement? = when (psiParameter) {
is KtLightElement<*, *> -> psiParameter.kotlinOrigin
is UastKotlinPsiParameter -> psiParameter.ktParameter
else -> null
}
val lightParams = psi.parameterList.parameters
val receiver = receiverTypeReference ?: return@lz lightParams.map { KotlinUParameter(it, parameterOrigin(it), this) }
val receiverLight = lightParams.firstOrNull() ?: return@lz emptyList()
val uParameters = SmartList<UParameter>(KotlinReceiverUParameter(receiverLight, receiver, this))
lightParams.drop(1).mapTo(uParameters) { KotlinUParameter(it, parameterOrigin(it), this) }
uParameters
}
override val psi: PsiMethod = unwrap<UMethod, PsiMethod>(psi)
override val javaPsi = psi
override fun getSourceElement() = sourcePsi ?: this
private val kotlinOrigin = getKotlinMemberOrigin(psi.originalElement) ?: sourcePsi
override fun getContainingFile(): PsiFile? {
kotlinOrigin?.containingFile?.let { return it }
return unwrapFakeFileForLightClass(psi.containingFile)
}
override fun getNameIdentifier() = UastLightIdentifier(psi, kotlinOrigin)
override val uAnnotations: List<UAnnotation> by lz {
// NB: we can't use sourcePsi.annotationEntries directly due to annotation use-site targets. The given `psi` as a light element,
// which spans regular function, property accessors, etc., is already built with targeted annotation.
baseResolveProviderService.getPsiAnnotations(psi)
.mapNotNull { (it as? KtLightElement<*, *>)?.kotlinOrigin as? KtAnnotationEntry }
.map { baseResolveProviderService.baseKotlinConverter.convertAnnotation(it, this) }
}
protected val receiverTypeReference by lz {
when (sourcePsi) {
is KtCallableDeclaration -> sourcePsi
is KtPropertyAccessor -> sourcePsi.property
else -> null
}?.receiverTypeReference
}
override val uastAnchor: UIdentifier? by lz {
val identifierSourcePsi = when (val sourcePsi = sourcePsi) {
is PsiNameIdentifierOwner -> sourcePsi.nameIdentifier
is KtObjectDeclaration -> sourcePsi.getObjectKeyword()
is KtPropertyAccessor -> sourcePsi.namePlaceholder
else -> sourcePsi?.navigationElement
}
KotlinUIdentifier(nameIdentifier, identifierSourcePsi, this)
}
override val uastBody: UExpression? by lz {
if (kotlinOrigin?.canAnalyze() != true) return@lz null // EA-137193
val bodyExpression = when (sourcePsi) {
is KtFunction -> sourcePsi.bodyExpression
is KtPropertyAccessor -> sourcePsi.bodyExpression
is KtProperty -> when {
psi is KtLightMethod && psi.isGetter -> sourcePsi.getter?.bodyExpression
psi is KtLightMethod && psi.isSetter -> sourcePsi.setter?.bodyExpression
else -> null
}
else -> null
} ?: return@lz null
wrapExpressionBody(this, bodyExpression)
}
override val returnTypeReference: UTypeReferenceExpression? by lz {
(sourcePsi as? KtCallableDeclaration)?.typeReference?.let {
KotlinUTypeReferenceExpression(it, this) { javaPsi.returnType ?: UastErrorType }
}
}
companion object {
fun create(
psi: KtLightMethod,
givenParent: UElement?
): UMethod {
val kotlinOrigin = psi.kotlinOrigin
return when {
kotlinOrigin is KtConstructor<*> ->
KotlinConstructorUMethod(kotlinOrigin.containingClassOrObject, psi, givenParent)
kotlinOrigin is KtParameter && kotlinOrigin.getParentOfType<KtClass>(true)?.isAnnotation() == true ->
KotlinUAnnotationMethod(psi, givenParent)
else ->
KotlinUMethod(psi, givenParent)
}
}
}
}
| apache-2.0 | 730ca02bc2763c9aa0d6696fe8bfa437 | 41.33871 | 158 | 0.684762 | 5.549683 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceParameter/KotlinInplaceParameterIntroducer.kt | 1 | 10629 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.introduce.introduceParameter
import com.intellij.codeInsight.template.impl.TemplateManagerImpl
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.RangeMarker
import com.intellij.openapi.editor.impl.DocumentMarkupModel
import com.intellij.openapi.editor.markup.EffectType
import com.intellij.openapi.editor.markup.HighlighterTargetArea
import com.intellij.openapi.editor.markup.MarkupModel
import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.ui.JBColor
import com.intellij.ui.NonFocusableCheckBox
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.psi.unifier.toRange
import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinValVar
import org.jetbrains.kotlin.idea.refactoring.introduce.AbstractKotlinInplaceIntroducer
import org.jetbrains.kotlin.idea.refactoring.introduce.introduceVariable.KotlinInplaceVariableIntroducer
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext
import org.jetbrains.kotlin.psi.psiUtil.getValueParameterList
import org.jetbrains.kotlin.psi.psiUtil.getValueParameters
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.typeUtil.supertypes
import java.awt.Color
import javax.swing.JCheckBox
class KotlinInplaceParameterIntroducer(
val originalDescriptor: IntroduceParameterDescriptor,
val parameterType: KotlinType,
val suggestedNames: Array<out String>,
project: Project,
editor: Editor
) : AbstractKotlinInplaceIntroducer<KtParameter>(
null,
originalDescriptor.originalRange.elements.single() as KtExpression,
originalDescriptor.occurrencesToReplace.map { it.elements.single() as KtExpression }.toTypedArray(),
INTRODUCE_PARAMETER,
project,
editor
) {
companion object {
private val LOG = Logger.getInstance(KotlinInplaceParameterIntroducer::class.java)
}
enum class PreviewDecorator {
FOR_ADD() {
override val textAttributes: TextAttributes = with(TextAttributes()) {
effectType = EffectType.ROUNDED_BOX
effectColor = JBColor.RED
this
}
},
FOR_REMOVAL() {
override val textAttributes: TextAttributes = with(TextAttributes()) {
effectType = EffectType.STRIKEOUT
effectColor = Color.BLACK
this
}
};
protected abstract val textAttributes: TextAttributes
fun applyToRange(range: TextRange, markupModel: MarkupModel) {
markupModel.addRangeHighlighter(
range.startOffset,
range.endOffset,
0,
textAttributes,
HighlighterTargetArea.EXACT_RANGE
)
}
}
private inner class Preview(addedParameter: KtParameter?, currentName: String?) {
private val _rangesToRemove = ArrayList<TextRange>()
var addedRange: TextRange? = null
private set
var text: String = ""
private set
val rangesToRemove: List<TextRange> get() = _rangesToRemove
init {
val templateState = TemplateManagerImpl.getTemplateState(myEditor)
val currentType = if (templateState?.template != null) {
templateState.getVariableValue(KotlinInplaceVariableIntroducer.TYPE_REFERENCE_VARIABLE_NAME)?.text
} else null
val builder = StringBuilder()
with(descriptor) {
(callable as? KtFunction)?.receiverTypeReference?.let { receiverTypeRef ->
builder.append(receiverTypeRef.text).append('.')
if (!descriptor.withDefaultValue && receiverTypeRef in parametersToRemove) {
_rangesToRemove.add(TextRange(0, builder.length))
}
}
builder.append(callable.name)
val parameters = callable.getValueParameters()
builder.append("(")
for (i in parameters.indices) {
val parameter = parameters[i]
val parameterText = if (parameter == addedParameter) {
val parameterName = currentName ?: parameter.name
val parameterType = currentType ?: parameter.typeReference!!.text
descriptor = descriptor.copy(newParameterName = parameterName!!, newParameterTypeText = parameterType)
val modifier = if (valVar != KotlinValVar.None) "${valVar.keywordName} " else ""
val defaultValue = if (withDefaultValue) {
" = ${if (newArgumentValue is KtProperty) newArgumentValue.name else newArgumentValue.text}"
} else ""
"$modifier$parameterName: $parameterType$defaultValue"
} else parameter.text
builder.append(parameterText)
val range = TextRange(builder.length - parameterText.length, builder.length)
if (parameter == addedParameter) {
addedRange = range
} else if (!descriptor.withDefaultValue && parameter in parametersToRemove) {
_rangesToRemove.add(range)
}
if (i < parameters.lastIndex) {
builder.append(", ")
}
}
builder.append(")")
if (addedRange == null) {
LOG.error("Added parameter not found: ${callable.getElementTextWithContext()}")
}
}
text = builder.toString()
}
}
private var descriptor = originalDescriptor
private var replaceAllCheckBox: JCheckBox? = null
init {
initFormComponents {
addComponent(previewComponent)
val defaultValueCheckBox = NonFocusableCheckBox(KotlinBundle.message("checkbox.text.introduce.default.value"))
defaultValueCheckBox.isSelected = descriptor.withDefaultValue
defaultValueCheckBox.addActionListener {
descriptor = descriptor.copy(withDefaultValue = defaultValueCheckBox.isSelected)
updateTitle(variable)
}
addComponent(defaultValueCheckBox)
val occurrenceCount = descriptor.occurrencesToReplace.size
if (occurrenceCount > 1) {
val replaceAllCheckBox = NonFocusableCheckBox(
KotlinBundle.message("checkbox.text.replace.all.occurrences.0", occurrenceCount))
replaceAllCheckBox.isSelected = true
addComponent(replaceAllCheckBox)
[email protected] = replaceAllCheckBox
}
}
}
override fun getActionName() = "IntroduceParameter"
override fun checkLocalScope() = descriptor.callable
override fun getVariable() = originalDescriptor.callable.getValueParameters().lastOrNull()
override fun suggestNames(replaceAll: Boolean, variable: KtParameter?) = suggestedNames
override fun createFieldToStartTemplateOn(replaceAll: Boolean, names: Array<out String>): KtParameter {
return runWriteAction {
with(descriptor) {
val parameterList = callable.getValueParameterList()
?: (callable as KtClass).createPrimaryConstructorParameterListIfAbsent()
val parameter = KtPsiFactory(myProject).createParameter("$newParameterName: $newParameterTypeText")
parameterList.addParameter(parameter)
}
}
}
override fun deleteTemplateField(psiField: KtParameter) {
if (psiField.isValid) {
(psiField.parent as? KtParameterList)?.removeParameter(psiField)
}
}
override fun isReplaceAllOccurrences() = replaceAllCheckBox?.isSelected ?: true
override fun setReplaceAllOccurrences(allOccurrences: Boolean) {
replaceAllCheckBox?.isSelected = allOccurrences
}
override fun getComponent() = myWholePanel
override fun updateTitle(addedParameter: KtParameter?, currentName: String?) {
val preview = Preview(addedParameter, currentName)
val document = previewEditor.document
runWriteAction { document.setText(preview.text) }
val markupModel = DocumentMarkupModel.forDocument(document, myProject, true)
markupModel.removeAllHighlighters()
preview.rangesToRemove.forEach { PreviewDecorator.FOR_REMOVAL.applyToRange(it, markupModel) }
preview.addedRange?.let { PreviewDecorator.FOR_ADD.applyToRange(it, markupModel) }
revalidate()
}
override fun getRangeToRename(element: PsiElement): TextRange {
if (element is KtProperty) return element.nameIdentifier!!.textRange.shiftRight(-element.startOffset)
return super.getRangeToRename(element)
}
override fun createMarker(element: PsiElement): RangeMarker {
if (element is KtProperty) return super.createMarker(element.nameIdentifier)
return super.createMarker(element)
}
override fun performIntroduce() {
getDescriptorToRefactor(isReplaceAllOccurrences).performRefactoring()
}
private fun getDescriptorToRefactor(replaceAll: Boolean): IntroduceParameterDescriptor {
val originalRange = expr.toRange()
return descriptor.copy(
originalRange = originalRange,
occurrencesToReplace = if (replaceAll) occurrences.map { it.toRange() } else listOf(originalRange),
argumentValue = expr!!
)
}
fun switchToDialogUI() {
stopIntroduce(myEditor)
KotlinIntroduceParameterDialog(
myProject,
myEditor,
getDescriptorToRefactor(true),
myNameSuggestions.toTypedArray(),
listOf(parameterType) + parameterType.supertypes(),
KotlinIntroduceParameterHelper.Default
).show()
}
}
| apache-2.0 | 7c2b72a1b4c7d983437b2d6e5d5dc6b4 | 40.03861 | 158 | 0.662621 | 5.937989 | false | false | false | false |
kloener/visor-android | app/src/main/java/de/visorapp/visor/SettingsActivity.kt | 1 | 4267 | package de.visorapp.visor
import android.hardware.Camera
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CameraManager
import android.os.Build
import android.os.Bundle
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.preference.DropDownPreference
import androidx.preference.PreferenceFragmentCompat
import kotlin.math.max
class SettingsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.settings_activity)
supportFragmentManager
.beginTransaction()
.replace(R.id.settings, SettingsFragment())
.commit()
supportActionBar?.setDisplayHomeAsUpEnabled(true)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
super.onBackPressed()
return true
}
}
return super.onOptionsItemSelected(item)
}
class SettingsFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.root_preferences, rootKey)
initPreviewResolutionWidth()
initCameraChooser()
}
private fun initCameraChooser() {
val visorSurface = VisorSurface.getInstance()
val numberOfCameras = Camera.getNumberOfCameras()
var entryValues: MutableList<CharSequence> = ArrayList()
var entries: MutableList<CharSequence> = ArrayList()
val manager: CameraManager
var haveMain = false
var haveSelfie = false
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
manager = context?.getSystemService(CAMERA_SERVICE) as CameraManager
manager.cameraIdList.forEach {
val cameraCharacteristics = manager.getCameraCharacteristics(it)
entryValues.add(it)
if (!haveMain && cameraCharacteristics.get(CameraCharacteristics.LENS_FACING) == Camera.CameraInfo.CAMERA_FACING_FRONT) {
entries.add(resources.getString(R.string.main_camera))
haveMain = true
} else if (!haveSelfie && cameraCharacteristics.get(CameraCharacteristics.LENS_FACING) == Camera.CameraInfo.CAMERA_FACING_BACK) {
entries.add(resources.getString(R.string.selfie_camera))
haveSelfie = true
} else
entries.add(resources.getString(R.string.wide_or_other_camera))
}
} else {
entryValues = MutableList(numberOfCameras) { i -> i.toString() }
entries = entryValues
}
val cameraIdPreference = findPreference<DropDownPreference>(resources.getString(R.string.key_preference_camera_id))
if (cameraIdPreference != null) {
cameraIdPreference.entries = entries.toTypedArray()
cameraIdPreference.entryValues = entryValues.toTypedArray()
cameraIdPreference.setValueIndex(visorSurface.preferredCameraId)
}
}
private fun initPreviewResolutionWidth() {
val visorSurface = VisorSurface.getInstance()
val availablePreviewWidths: Array<CharSequence>? = visorSurface.availablePreviewWidths
val previewResolutionPreference = findPreference<DropDownPreference>(resources.getString(R.string.key_preference_preview_resolution))
if (previewResolutionPreference != null && availablePreviewWidths != null) {
previewResolutionPreference.entries = availablePreviewWidths
previewResolutionPreference.entryValues = availablePreviewWidths
val currentPreviewWidth = visorSurface.cameraPreviewWidth
val currentIndex = max(0, availablePreviewWidths.indexOf(currentPreviewWidth.toString()))
previewResolutionPreference.setValueIndex(currentIndex)
}
}
}
} | apache-2.0 | 07532ecf8645cd9bfb2da019f15a0a49 | 45.391304 | 149 | 0.650809 | 5.789688 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/roots/KotlinNonJvmSourceRootConverterProvider.kt | 5 | 10943 | // 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.roots
import com.intellij.conversion.*
import com.intellij.conversion.impl.ConversionContextImpl
import com.intellij.openapi.roots.ExternalProjectSystemRegistry
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.impl.libraries.ApplicationLibraryTable
import com.intellij.openapi.roots.impl.libraries.LibraryEx
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.roots.libraries.LibraryKindRegistry
import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar
import com.intellij.openapi.roots.libraries.PersistentLibraryKind
import com.intellij.openapi.vfs.JarFileSystem
import com.intellij.openapi.vfs.VirtualFile
import org.jdom.Element
import org.jetbrains.jps.model.JpsElement
import org.jetbrains.jps.model.JpsElementFactory
import org.jetbrains.jps.model.java.JavaResourceRootType
import org.jetbrains.jps.model.java.JavaSourceRootType
import org.jetbrains.jps.model.module.JpsModuleSourceRootType
import org.jetbrains.jps.model.module.JpsTypedModuleSourceRoot
import org.jetbrains.jps.model.serialization.facet.JpsFacetSerializer
import org.jetbrains.jps.model.serialization.module.JpsModuleRootModelSerializer.*
import org.jetbrains.kotlin.config.getFacetPlatformByConfigurationElement
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.platforms.KotlinJavaScriptStdlibDetectorFacility
import org.jetbrains.kotlin.idea.base.platforms.KotlinJvmStdlibDetectorFacility
import org.jetbrains.kotlin.idea.base.projectStructure.getMigratedSourceRootTypeWithProperties
import org.jetbrains.kotlin.idea.facet.KotlinFacetType
import org.jetbrains.kotlin.platform.CommonPlatforms
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.isCommon
import org.jetbrains.kotlin.platform.js.JsPlatforms
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.utils.PathUtil
import java.util.*
private val rootTypesToMigrate: List<JpsModuleSourceRootType<*>> = listOf(
JavaSourceRootType.SOURCE,
JavaSourceRootType.TEST_SOURCE,
JavaResourceRootType.RESOURCE,
JavaResourceRootType.TEST_RESOURCE
)
// TODO(dsavvinov): review how it behaves in HMPP environment
private val PLATFORM_TO_STDLIB_DETECTORS: Map<TargetPlatform, (Array<VirtualFile>) -> Boolean> = mapOf(
JvmPlatforms.unspecifiedJvmPlatform to { roots: Array<VirtualFile> ->
KotlinJvmStdlibDetectorFacility.getStdlibJar(roots.toList()) != null
},
JsPlatforms.defaultJsPlatform to { roots: Array<VirtualFile> ->
KotlinJavaScriptStdlibDetectorFacility.getStdlibJar(roots.toList()) != null
},
CommonPlatforms.defaultCommonPlatform to { roots: Array<VirtualFile> ->
roots.any { PathUtil.KOTLIN_STDLIB_COMMON_JAR_PATTERN.matcher(it.name).matches() }
}
)
internal class KotlinNonJvmSourceRootConverterProvider : ConverterProvider() {
sealed class LibInfo {
class ByXml(
private val element: Element,
private val conversionContext: ConversionContext,
private val moduleSettings: ModuleSettings
) : LibInfo() {
override val explicitKind: PersistentLibraryKind<*>?
get() = LibraryKindRegistry.getInstance().findKindById(element.getAttributeValue("type")) as? PersistentLibraryKind<*>
override fun getRoots(): Array<VirtualFile> {
val contextImpl = conversionContext as? ConversionContextImpl ?: return VirtualFile.EMPTY_ARRAY
val classRoots = contextImpl.getClassRootUrls(element, moduleSettings)
val jarFileSystem = JarFileSystem.getInstance()
return classRoots
.map {
if (it.startsWith(JarFileSystem.PROTOCOL_PREFIX)) {
jarFileSystem.findFileByPath(it.substring(JarFileSystem.PROTOCOL_PREFIX.length))
} else {
null
}
}
.filter(Objects::nonNull)
.toArray{ arrayOfNulls<VirtualFile>(it) }
}
}
class ByLibrary(private val library: Library) : LibInfo() {
override val explicitKind: PersistentLibraryKind<*>?
get() = (library as? LibraryEx)?.kind
override fun getRoots(): Array<VirtualFile> = library.getFiles(OrderRootType.CLASSES)
}
abstract val explicitKind: PersistentLibraryKind<*>?
abstract fun getRoots(): Array<VirtualFile>
val stdlibPlatform: TargetPlatform? by lazy {
val roots = getRoots()
for ((platform, detector) in PLATFORM_TO_STDLIB_DETECTORS) {
if (detector.invoke(roots)) {
return@lazy platform
}
}
return@lazy null
}
}
class ConverterImpl(private val context: ConversionContext) : ProjectConverter() {
private val projectLibrariesByName by lazy {
context.projectLibrariesSettings.projectLibraries.groupBy { it.getAttributeValue(NAME_ATTRIBUTE) }
}
private fun findGlobalLibrary(name: String) = ApplicationLibraryTable.getApplicationTable().getLibraryByName(name)
private fun findProjectLibrary(name: String) = projectLibrariesByName[name]?.firstOrNull()
private fun createLibInfo(orderEntryElement: Element, moduleSettings: ModuleSettings): LibInfo? {
return when (orderEntryElement.getAttributeValue("type")) {
MODULE_LIBRARY_TYPE -> {
orderEntryElement.getChild(LIBRARY_TAG)?.let { LibInfo.ByXml(it, context, moduleSettings) }
}
LIBRARY_TYPE -> {
val libraryName = orderEntryElement.getAttributeValue(NAME_ATTRIBUTE) ?: return null
when (orderEntryElement.getAttributeValue(LEVEL_ATTRIBUTE)) {
LibraryTablesRegistrar.PROJECT_LEVEL ->
findProjectLibrary(libraryName)?.let { LibInfo.ByXml(it, context, moduleSettings) }
LibraryTablesRegistrar.APPLICATION_LEVEL ->
findGlobalLibrary(libraryName)?.let { LibInfo.ByLibrary(it) }
else ->
null
}
}
else -> null
}
}
override fun createModuleFileConverter(): ConversionProcessor<ModuleSettings> {
return object : ConversionProcessor<ModuleSettings>() {
private fun ModuleSettings.detectPlatformByFacet(): TargetPlatform? {
return getFacetElement(KotlinFacetType.ID)
?.getChild(JpsFacetSerializer.CONFIGURATION_TAG)
?.getFacetPlatformByConfigurationElement()
}
private fun detectPlatformByDependencies(moduleSettings: ModuleSettings): TargetPlatform? {
var hasCommonStdlib = false
moduleSettings.orderEntries
.asSequence()
.mapNotNull { createLibInfo(it, moduleSettings) }
.forEach {
val stdlibPlatform = it.stdlibPlatform
if (stdlibPlatform != null) {
if (stdlibPlatform.isCommon()) {
hasCommonStdlib = true
} else {
return stdlibPlatform
}
}
}
return if (hasCommonStdlib) CommonPlatforms.defaultCommonPlatform else null
}
private fun ModuleSettings.detectPlatform(): TargetPlatform {
return detectPlatformByFacet()
?: detectPlatformByDependencies(this)
?: JvmPlatforms.unspecifiedJvmPlatform
}
private fun ModuleSettings.getSourceFolderElements(): List<Element> {
val rootManagerElement = getComponentElement(ModuleSettings.MODULE_ROOT_MANAGER_COMPONENT) ?: return emptyList()
return rootManagerElement
.getChildren(CONTENT_TAG)
.flatMap { it.getChildren(SOURCE_FOLDER_TAG) }
}
private fun ModuleSettings.isExternalModule(): Boolean {
return when {
rootElement.getAttributeValue(ExternalProjectSystemRegistry.EXTERNAL_SYSTEM_ID_KEY) != null -> true
rootElement.getAttributeValue(ExternalProjectSystemRegistry.IS_MAVEN_MODULE_KEY)?.toBoolean() ?: false -> true
else -> false
}
}
override fun isConversionNeeded(settings: ModuleSettings): Boolean {
if (settings.isExternalModule()) return false
val hasMigrationRoots = settings.getSourceFolderElements().any {
loadSourceRoot(it).rootType in rootTypesToMigrate
}
if (!hasMigrationRoots) {
return false
}
val targetPlatform = settings.detectPlatform()
return (!targetPlatform.isJvm())
}
override fun process(settings: ModuleSettings) {
for (sourceFolder in settings.getSourceFolderElements()) {
val contentRoot = sourceFolder.parent as? Element ?: continue
val oldSourceRoot = loadSourceRoot(sourceFolder)
val (newRootType, data) = oldSourceRoot.getMigratedSourceRootTypeWithProperties() ?: continue
val url = sourceFolder.getAttributeValue(URL_ATTRIBUTE)!!
@Suppress("UNCHECKED_CAST")
val newSourceRoot = JpsElementFactory.getInstance().createModuleSourceRoot(url, newRootType, data)
as? JpsTypedModuleSourceRoot<JpsElement> ?: continue
contentRoot.removeContent(sourceFolder)
saveSourceRoot(contentRoot, url, newSourceRoot)
}
}
}
}
}
override fun getConversionDescription() =
KotlinBundle.message("roots.description.text.update.source.roots.for.non.jvm.modules.in.kotlin.project")
override fun createConverter(context: ConversionContext) = ConverterImpl(context)
} | apache-2.0 | 782995939ab2ccb86e5135523bd70f95 | 47.424779 | 134 | 0.633282 | 5.861275 | false | false | false | false |
DeskChan/DeskChan | src/main/kotlin/info/deskchan/MessageData/DeskChan/RequestSay.kt | 2 | 2176 | package info.deskchan.MessageData.DeskChan
import info.deskchan.core.MessageData
/**
* Say phrase by the character with specific intent
*
* If response is requested, phrase will be sent as response. Phrase will be sent to DeskChan:say otherwise.
*
* @property intent Intent for phrase. If provided more than one, as much phrases as intents count will be generated.
* @property characterImage Emotion sprite name for character to use when saying phrase. Sprite will be selected by character system if no name provided.
* @property priority Priority for message
* @property tags Tags to filter phrase
*/
@MessageData.Tag("DeskChan:request-say")
@MessageData.RequiresResponse
class RequestSay : MessageData {
private var intent: Any
fun getIntent() = intent
/** Set intents list for phrase. As much phrases as intents count will be generated. **/
fun setIntent(value: Collection<String>) {
intent = value.toMutableList()
}
/** Set intent for phrase. **/
fun setIntent(value: Any){
intent = value.toString()
}
var characterImage: String? = null
var priority: Long? = null
set(value){
priority = java.lang.Long.max(value?: 0L, 0L)
}
var tags: Map<String, String>? = null
constructor(intent: String){
this.intent = intent
}
constructor(intent: String, characterImage: String) : this(intent) {
this.characterImage = characterImage
}
constructor(intent: String, characterImage: Say.Sprite) : this(intent) {
this.characterImage = characterImage.toString()
}
constructor(intents: Collection<String>){
this.intent = intents
}
constructor(intent: Collection<String>, characterImage: String) : this(intent) {
this.characterImage = characterImage
}
constructor(text: Collection<String>, characterImage: Say.Sprite) : this(text) {
this.characterImage = characterImage.toString()
}
fun setCharacterImage(characterImage: Say.Sprite){
this.characterImage = characterImage.toString()
}
companion object {
val ResponseFormat: Map<String, Any>? = null
}
} | lgpl-3.0 | 7f594e09bcaea73a8bc98870a93188fd | 28.821918 | 153 | 0.684743 | 4.514523 | false | false | false | false |
jk1/intellij-community | platform/platform-tests/testSrc/com/intellij/ui/layout/migLayoutDebugDumper.kt | 4 | 4338 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui.layout
import com.intellij.configurationStore.serialize
import com.intellij.ui.dumpComponentBounds
import com.intellij.ui.getComponentKey
import com.intellij.ui.layout.migLayout.patched.*
import com.intellij.util.xmlb.SkipDefaultsSerializationFilter
import net.miginfocom.layout.*
import org.yaml.snakeyaml.DumperOptions
import org.yaml.snakeyaml.Yaml
import org.yaml.snakeyaml.introspector.Property
import org.yaml.snakeyaml.nodes.NodeTuple
import org.yaml.snakeyaml.nodes.Tag
import org.yaml.snakeyaml.representer.Representer
import java.awt.Container
import java.awt.Rectangle
private val filter by lazy {
object : Representer() {
private val emptyLC = LC()
private val emptyAC = AC()
private val emptyCC = CC()
private val emptyDimConstraint = DimConstraint()
private val emptyBoundSize = BoundSize.NULL_SIZE
private val xmlSerializationFilter = SkipDefaultsSerializationFilter(emptyAC, emptyCC, emptyDimConstraint, emptyBoundSize, UnitValue(Float.MIN_VALUE * Math.random().toFloat(), UnitValue.CM, "") /* no default value, some unique unit value */)
override fun representJavaBeanProperty(bean: Any, property: Property, propertyValue: Any?, customTag: Tag?): NodeTuple? {
if (propertyValue == null || property.name == "animSpec") {
return null
}
if (bean is Rectangle && (!property.isWritable || property.name == "size" || property.name == "location")) {
return null
}
if (bean is BoundSize && property.name == "unset") {
return null
}
if (bean is UnitValue) {
if (property.name == "unitString") {
if (propertyValue != "px" && bean.value != 0f) {
throw RuntimeException("Only px must be used")
}
return null
}
if (property.name == "unit" && bean.value != 0f) {
if (propertyValue != UnitValue.PIXEL) {
throw RuntimeException("Only px must be used")
}
return null
}
if (property.name == "operation" && propertyValue == 100) {
// ignore static operation
return null
}
}
val emptyBean = when (bean) {
is AC -> emptyAC
is CC -> emptyCC
is DimConstraint -> emptyDimConstraint
is BoundSize -> emptyBoundSize
is LC -> emptyLC
else -> null
}
if (emptyBean != null) {
val oldValue = property.get(emptyBean)
if (oldValue == propertyValue) {
return null
}
if (propertyValue is DimConstraint && propertyValue.serialize(xmlSerializationFilter) == null) {
return null
}
}
return super.representJavaBeanProperty(bean, property, propertyValue, customTag)
}
}
}
private fun dumpCellBounds(layout: MigLayout): Any {
val gridField = MigLayout::class.java.getDeclaredField("grid")
gridField.isAccessible = true
return MigLayoutTestUtil.getRectangles(gridField.get(layout) as Grid)
}
@Suppress("UNCHECKED_CAST")
internal fun serializeLayout(component: Container, isIncludeCellBounds: Boolean = true): String {
val layout = component.layout as MigLayout
val componentConstrains = LinkedHashMap<String, Any>()
val componentToConstraints = layout.getComponentConstraints()
for ((index, c) in component.components.withIndex()) {
componentConstrains.put(getComponentKey(c, index), componentToConstraints.get(c)!!)
}
val dumperOptions = DumperOptions()
dumperOptions.isAllowReadOnlyProperties = true
dumperOptions.lineBreak = DumperOptions.LineBreak.UNIX
val yaml = Yaml(filter, dumperOptions)
return yaml.dump(linkedMapOf(
"layoutConstraints" to layout.layoutConstraints,
"rowConstraints" to layout.rowConstraints,
"columnConstraints" to layout.columnConstraints,
"componentConstrains" to componentConstrains,
"cellBounds" to if (isIncludeCellBounds) dumpCellBounds(layout) else null,
"componentBounds" to dumpComponentBounds(component)
))
.replace("constaints", "constraints")
.replace(" !!net.miginfocom.layout.CC", "")
.replace(" !!net.miginfocom.layout.AC", "")
.replace(" !!net.miginfocom.layout.LC", "")
} | apache-2.0 | 06f3707dd29536ad80b6a37ed2d89988 | 36.08547 | 245 | 0.688566 | 4.449231 | false | false | false | false |
NiciDieNase/chaosflix | common/src/main/java/de/nicidienase/chaosflix/common/mediadata/entities/streaming/Room.kt | 1 | 2855 | package de.nicidienase.chaosflix.common.mediadata.entities.streaming
import android.os.Parcel
import android.os.Parcelable
import androidx.annotation.Keep
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import kotlin.collections.HashMap
@Keep
@JsonIgnoreProperties(ignoreUnknown = true)
data class Room(
var slug: String,
var schedulename: String,
var thumb: String,
var link: String,
var display: String,
var talks: Map<String, StreamEvent>?,
var streams: List<Stream>
) : Parcelable {
private constructor(input: Parcel) : this(
slug = input.readString() ?: "",
schedulename = input.readString() ?: "",
thumb = input.readString() ?: "",
link = input.readString() ?: "",
display = input.readString() ?: "",
talks = readMap(input),
streams = input.createTypedArrayList<Stream>(Stream.CREATOR)?.filterNotNull() ?: emptyList())
override fun describeContents(): Int {
return 0
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeString(slug)
dest.writeString(schedulename)
dest.writeString(thumb)
dest.writeString(link)
dest.writeString(display)
val talkKeys = talks?.keys?.toTypedArray()
dest.writeStringArray(talkKeys)
val talks = talkKeys?.map { talks?.get(it) }?.toTypedArray()
dest.writeTypedArray(talks, 0)
dest.writeTypedList(streams)
}
companion object CREATOR : Parcelable.Creator<Room> {
override fun createFromParcel(`in`: Parcel): Room {
return Room(`in`)
}
override fun newArray(size: Int): Array<Room?> {
return arrayOfNulls(size)
}
fun readMap(input: Parcel): MutableMap<String, StreamEvent>? {
val keys = input.createStringArray()
val urls = input.createTypedArray(StreamEvent.CREATOR)
if (keys == null || urls == null) {
return null
}
val result = HashMap<String, StreamEvent>()
for (i in 0 until keys.size - 1) {
val key = keys[i]
val value = urls[i]
if (key != null && value != null) {
result.put(key, value)
}
}
return result
}
val dummyObject: Room
get() {
val dummy = Room(
"dummy_room",
"Dummy Room",
"https://static.media.ccc.de/media/unknown.png",
"",
"Dummy Room",
HashMap(),
ArrayList())
dummy.streams = listOf(Stream.dummyObject)
return dummy
}
}
}
| mit | 996ee531d77c9bfd99388d656288645c | 31.443182 | 105 | 0.54676 | 4.913941 | false | true | false | false |
ktorio/ktor | ktor-server/ktor-server-test-host/jvm/src/io/ktor/server/testing/FreePorts.kt | 1 | 2353 | /*
* Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.server.testing
import org.slf4j.*
import java.net.*
import java.util.*
import kotlin.collections.*
import kotlin.concurrent.*
internal object FreePorts {
private val CAPACITY = 20
private val CAPACITY_LOW = 10
private val found = Collections.synchronizedSet(HashSet<Int>())
private val free = Collections.synchronizedList(LinkedList<Int>())
init {
allocate(CAPACITY)
}
public fun select(): Int {
if (free.size < CAPACITY_LOW) {
thread(name = "free-port-population") {
allocate(CAPACITY - free.size)
}
}
while (true) {
try {
return free.removeAt(0)
} catch (expected: IndexOutOfBoundsException) {
// may happen if concurrently removed
allocate(CAPACITY)
}
}
}
public fun recycle(port: Int) {
if (port in found && checkFreePort(port)) {
free.add(port)
}
}
private fun allocate(count: Int) {
if (count <= 0) return
val sockets = ArrayList<ServerSocket>()
try {
for (repeat in 1..count) {
try {
val socket = ServerSocket(0, 1)
sockets.add(socket)
} catch (ignore: Throwable) {
log("Waiting for free ports")
Thread.sleep(1000)
}
}
} finally {
sockets.removeAll {
try {
it.close()
!found.add(it.localPort)
} catch (ignore: Throwable) {
true
}
}
log("Waiting for ports cleanup")
Thread.sleep(1000)
sockets.forEach {
free.add(it.localPort)
}
}
}
private fun checkFreePort(port: Int): Boolean {
try {
ServerSocket(port).close()
return true
} catch (unableToBind: Throwable) {
return false
}
}
private fun log(message: String) {
LoggerFactory.getLogger(FreePorts::class.java).info(message)
}
}
| apache-2.0 | aac7aee6fef1972a5c654ac604da65b4 | 24.576087 | 119 | 0.505312 | 4.715431 | false | false | false | false |
jk1/Intellij-idea-mail | src/main/kotlin/github/jk1/smtpidea/store/OutboxFolder.kt | 1 | 1707 | package github.jk1.smtpidea.store
import github.jk1.smtpidea.server.smtp.MailSession
import java.util.ArrayList
import javax.swing.SwingUtilities
import java.text.SimpleDateFormat
import java.text.DateFormat
/**
*
*/
public object OutboxFolder : MessageFolder<MailSession>(){
private val format: DateFormat = SimpleDateFormat("DD MMM HH:mm:ss")
private val columns: Array<String> = array<String>("Received", "IP", "From (Envelope)", "Recipients (Envelope)")
public val mails: MutableList<MailSession> = ArrayList<MailSession>()
public override fun add(message: MailSession) {
SwingUtilities.invokeLater({
OutboxFolder.mails.add(message)
OutboxFolder.fireTableDataChanged()
})
}
public override fun clear() {
SwingUtilities.invokeLater({
OutboxFolder.mails.clear()
OutboxFolder.fireTableDataChanged()
})
}
override fun getMessages() = mails
override fun messageCount() = mails.size
public override fun get(i: Int): MailSession {
return mails.get(i)
}
public override fun getColumnCount() = 4
public override fun getRowCount() : Int = messageCount();
public override fun getColumnName(column: Int) = columns[column]
public override fun getValueAt(rowIndex: Int, columnIndex: Int): Any? {
val info : MailSession = mails.get(rowIndex)
when (columnIndex) {
0 -> return format.format(info.receivedDate)
1 -> return info.ip
2 -> return info.envelopeFrom
3 -> return info.envelopeRecipients
}
throw IllegalStateException("No value defined for column $columnIndex")
}
} | gpl-2.0 | 8fa8c1167af3ac50ff6e7f610ce84a86 | 28.964912 | 116 | 0.667252 | 4.754875 | false | false | false | false |
ktoolz/rezult | src/main/kotlin/com/github/ktoolz/rezult/Result.kt | 1 | 20649 | /*
* Rezult - KToolZ
*
* Copyright (c) 2016
*
* 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.
*/
@file:JvmName("ResultToolbox")
package com.github.ktoolz.rezult
import com.github.ktoolz.rezult.exceptions.ResultException
import java.util.*
import java.util.function.Consumer
// ----------------------------------------------------------------
// Property extensions for lambdas to retrieve results
// ----------------------------------------------------------------
/**
* Property extension on lambdas with no parameters.
*
* Provides the same lambda but returning a [Result] of the original return type.
*/
val <T> (() -> T).lambdaresult: () -> Result<T> get() = { Result.of(this) }
/**
* Property extension on lambdas with no parameters.
*
* Provides a [Result] containing the value returned by the lambda execution.
*/
val <T> (() -> T).result: Result<T> get() = Result.of(this)
/**
* Extension on lambdas with no parameters.
*
* Provides a [Result] containing the value returned by the lambda execution.
*/
fun <T> (() -> T).toResult(): Result<T> = Result.of(this)
/**
* Property extension on lambdas with one parameter.
*
* Provides the same lambda but returning a [Result] of the original return type.
*/
val <T, A> ((A) -> T).lambdaresult: (A) -> Result<T> get() = { a -> Result.of({ this(a) }) }
/**
* Property extension on lambdas with two parameters.
*
* Provides the same lambda but returning a [Result] of the original return type.
*/
val <T, A, B> ((A, B) -> T).result: (A, B) -> Result<T> get() = { a, b -> Result.of({ this(a, b) }) }
/**
* Property extension on lambdas with three parameters.
*
* Provides the same lambda but returning a [Result] of the original return type.
*/
val <T, A, B, C> ((A, B, C) -> T).result: (A, B, C) -> Result<T> get() = { a, b, c -> Result.of({ this(a, b, c) }) }
/**
* Property extension on lambdas with four parameters.
*
* Provides the same lambda but returning a [Result] of the original return type.
*/
val <T, A, B, C, D> ((A, B, C, D) -> T).result: (A, B, C, D) -> Result<T> get() = { a, b, c, d ->
Result.of({ this(a, b, c, d) })
}
// ----------------------------------------------------------------
// Type extensions for creating results easily
// ----------------------------------------------------------------
/**
* Extension on any type.
*
* Provides a success [Result] out of the type.
*
* @return a [Result] object (success) linked to this type.
*/
fun <T> T.toResult() = Result.success(this)
/**
* Extension for [Exception].
*
* Provides a failure [Result] out of the exception.
*
* @return a [Result] object (failure) linked to this [Exception].
*/
fun <T : Exception, V> T.toResult() = Result.failure<V>(this)
/**
* Extension on any type.
*
* Provides a validate method allowing to validate a value from a lambda, and creates a [Result] out of the validation.
*
* @param[errorMessage] an error message to be used in the [Result] if the validation fails.
* @param[validator] a lambda to be applied on the type and returning a [Boolean] value, validating its content.
*
* @return a [Result] object containing the result of the validation.
*/
@JvmOverloads
fun <T> T.validate(errorMessage: String = "Validation error", validator: T.() -> Boolean): Result<T> =
toResult().validate(errorMessage, validator)
// ----------------------------------------------------------------
// Extensions for manipulating Results on few types
// ----------------------------------------------------------------
/**
* Extension on boolean [Result].
*
* Allows to use the `!` operator on boolean [Result] directly. Will keep the [Result] status (failures won't change).
*
* @return a [Result] object containing the opposite [Boolean] (if success), or the same failure [Result].
*/
operator fun Result<Boolean>.not() = onSuccess { Result.success(!it) }
/**
* Extension on boolean [Result].
*
* Allows to check if a boolean [Result] is true or not. If it's true, it'll return the same result. Otherwise it'll return a failure.
*
* @return the same [Result] object if the boolean is true, a failure otherwise.
*/
fun Result<Boolean>.isTrue() = validate { this }
/**
* Extension on [IntRange] for [Result].
*
* Allows to check if a [Result] is contained in a particular range using the `in` operator. Will keep the [Result] status (failures won't change).
*
* @param[value] the [Result] we'd like to see in the range.
*
* @return true if the [Result] value is contained in the range.
*/
operator fun IntRange.contains(value: Result<Int>) =
value.validate { [email protected](this) }.isSuccess()
// ----------------------------------------------------------------
// Definition of Result and its operations
// ----------------------------------------------------------------
/**
* A wrapper to any operation call.
*
* Allows to check if a particular call is a Success or a Failure, and chain other operations on this [Result].
*
* @author jean-marc, aurelie, antoine
*/
sealed class Result<T> {
// ----------------------------------------------------------------
// Basic operations
// ----------------------------------------------------------------
/**
* Defines if the [Result] is a Success.
*
* @return true if the [Result] is a Success.
*/
abstract fun isSuccess(): Boolean
/**
* Opposite of [isSuccess]. Defines if the [Result] is a Failure.
*
* @return true if the [Result] is a Failure.
*/
fun isFailure(): Boolean = !isSuccess()
// ----------------------------------------------------------------
// Success operations
// ----------------------------------------------------------------
/**
* Executes an operation on a Success result, and returns a new [Result] containing that operation's response.
*
* @param[operation] an operation to be applied on the [Result] value, returning a new [Result] (that might have another type).
*
* @return the [Result] coming from the operation applied to this [Result] value.
*/
abstract fun <U> onSuccess(operation: (T) -> Result<U>): Result<U>
/**
* Executes an operation on a Success result, as if we had a `with (success)`, and returns a new [Result] containing that operation's response.
*
* @param[operation] an operation to be applied on the [Result] value, returning a new [Result] (that might have another type).
*
* @return the [Result] coming from the operation applied to this [Result] value.
*
* @see [onSuccess] - it does the same but is maybe a bit easier to use / more clear to use.
*/
fun <U> withSuccess(operation: T.() -> Result<U>) = onSuccess(operation)
/**
* Executes a log operation (returning nothing) on a Success result.
*
* @param[operation] an operation to be applied on the [Result] value, returning nothing. Basically to be used for logging purpose or something like this.
*
* @return the same [Result] you had in a first time.
*/
@JvmName("_logSuccessKotlin")
fun logSuccess(operation: T.() -> Unit): Result<T> = withSuccess { [email protected] { operation() } }
/**
* Same as [logSuccess(operation: T.() -> Unit): Result<T>] but with a more java friendly object
*/
fun logSuccess(operation: Consumer<T>): Result<T> = withSuccess {
[email protected] {
operation.accept(this@withSuccess)
}
}
/**
* Tries to execute an operation which returns a new [Result] on a Success result.
* It'll return the same first [Result] object if the operation is ok, but it'll return a failure if the operation returned a failed result.
*
* @param[operation] an operation to be applied on the [Result] value, returning a new [Result]. The result of this operation will be used in order to check if we should return the same object or not.
*
* @return the same [Result] if the operation is successful, or a failure if the operation result isn't a success.
*/
fun <U> tryWithSuccess(operation: T.() -> Result<U>): Result<T> = withSuccess {
@Suppress("UNCHECKED_CAST")
operation().let {
when (it) {
is Success -> this@Result
else -> it as Result<T> // It's a failure so we don't care about the cast because there is no value of this type
}
}
}
// ----------------------------------------------------------------
// Failure operations
// ----------------------------------------------------------------
/**
* Executes an operation on a Failure exception, and returns a new [Result] containing the operation's response.
*
* The new [Result] must have the same type as the one you specified previously.
*
* @param[operation] an operation to be applied on the [Result] exception, retuning a new [Result] (with the same type).
*
* @return the [Result] coming from the operation applied to this [Result] exception.
*/
abstract fun onFailure(operation: (Throwable) -> Result<T>): Result<T>
/**
* Executes an operation on a Failure exception, as if we had a `with (failure)`, and returns a new [Result] containing that operation's response.
*
* @param[operation] an operation to be applied on the [Result] exception, returning a new [Result] (with the same type).
*
* @return the [Result] coming from the operation applied to this [Result] exception.
*/
fun withFailure(operation: Throwable.() -> Result<T>) = onFailure(operation)
/**
* Executes a log operation (returning nothing) on a Failure exception.
*
* @param[operation] an operation to be applied on the [Result] exception, returning nothing. Basically to be used for logging purpose or something like this.
*
* @return the same [Result] you had in a first time.
*/
@JvmName("_logFailureKotlin")
fun logFailure(operation: Throwable.() -> Unit): Result<T> = withFailure { [email protected] { operation() } }
/**
* Same as [logFailure(operation: Exception.() -> Unit): Result<T>] but with a more java friendly object
*/
fun logFailure(operation: Consumer<Throwable>): Result<T> = withFailure {
[email protected] {
operation.accept(this@withFailure)
}
}
// ----------------------------------------------------------------
// Common operations
// ----------------------------------------------------------------
/**
* Validates a [Result] using a simple lambda expression, and turn the [Result] in a failure if the [Result] value isn't matching a particular validation.
*
* Cannot be used for *false positive* where you'd like to turn an [Exception] into a Success.
*
* @param[errorMessage] an error message you want to specify if the validation fails - that will be used in the created failure.
* @param[validator] an operation to be applied on the [Result] value validating its content that will return a [Boolean].
*
* @return the same [Result] if the validation was ok, or a new [Result] failure if the validation was not ok.
*/
@JvmOverloads
fun validate(errorMessage: String = "Validation error", validator: T.() -> Boolean): Result<T> =
withSuccess {
if (this.validator()) this@Result
else failure(ResultException(errorMessage))
}
/**
* Retrieves a [Result] value (if the [Result] is a success) or will call the provided [backup] operation to retrieve a backup value.
*
* @param[backup] an operation allowing to retrieve a backup value in case the [Result] is a Failure.
*
* @return the [Result] value if the result is a Success, otherwise the result of the [backup] operation.
*/
abstract fun getOrElse(backup: () -> T): T
/**
* Retrieves a [Result] value (if the [Result] is a success) or will return the provided [backupValue].
*
* @param[backupValue] a backup value to be returned in case the [Result] is a Failure.
*
* @return the [Result] value if the result is a Success, otherwise the provided [backupValue].
*
* @see [getOrElse] - same operation using a provider.
*/
fun getOrElse(backupValue: T) = getOrElse({ backupValue })
/**
* Calls [getOrElse] in a better looking way.
*
* Basically just calls [getOrElse].
*
* @param[backup] a backup value to be returned in case the [Result] is a Failure.
*
* @return the [Result] value if the result is a Success, otherwise the provided [backup].
*
* @see [getOrElse] - operation which is actually called.
*/
infix fun or(backup: T) = getOrElse(backup)
/**
* Checks if a [Result] value contains a provided [value]. Will obviously be false if the [Result] is a Failure.
*
* @param[value] the value you'd like to find in the [Result].
*
* @return true if the [Result] is a Success and actually contains the [value], false otherwise.
*/
abstract operator infix fun contains(value: T): Boolean
// ----------------------------------------------------------------
// Companion object
// ----------------------------------------------------------------
/**
* Just a simple companion object for [Result]
*/
companion object {
// ----------------------------------------------------------------
// Helpers for creating Result objects
// ----------------------------------------------------------------
/**
* Creates a Success result from a value.
*
* @param[value] the value to be used for creating the Success object.
*
* @return a Success object containing the provided [value].
*/
@JvmStatic
fun <T> success(value: T): Result<T> = Success(value)
/**
* Creates a Failure result from an [Exception].
*
* @param[exception] the [Exception] to be used for creating the Failure object.
*
* @return a Failure object containing the provided [exception].
*/
@JvmStatic
fun <T> failure(exception: Throwable): Result<T> = Failure(exception)
/**
* Creates a Failure result from a message. It'll internally wrap that message in a [ResultException].
*
* @param[message] the failure message to be used for creating the [ResultException].
*
* @return a Failure object containing a [ResultException] using the provided [message].
*/
@JvmStatic
fun <T> failure(message: String): Result<T> = Failure(ResultException(message))
// ----------------------------------------------------------------
// Methods for executing operations and creating results
// ----------------------------------------------------------------
/**
* Executes the provided [operation] and computes a [Result] object out of it.
*
* It basically catches [Exception] while executing the operation, and returns a Failure if there's an [Exception].
*
* @param[operation] the operation to be executed and which will lead to a [Result] object creation.
*
* @return a Success object containing the result of the [operation] if there's no [Exception] raised. Otherwise it'll return a Failure containing that [Exception].
*/
@JvmStatic
fun <T> of(operation: () -> T): Result<T> =
try {
Success(operation())
} catch(e: Exception) {
Failure(e)
}
/**
* Executes all the provided [actions] and returns the first Success result if there's one. Otherwise, it'll just return a Failure.
*
* @param[actions] a list of operations to be executed till one is a Success.
*
* @return the first Success coming for the [actions] execution, a Failure if none of the [actions] creates a Success.
*/
@JvmStatic
fun <T> chain(vararg actions: () -> Result<T>): Result<T> =
try {
// asSequence turn the evaluation to lazy mode
actions.asSequence().map { it() }.first { it.isSuccess() }
} catch (e: NoSuchElementException) {
failure("All failed")
}
}
// ----------------------------------------------------------------
// Implementation of Success object
// ----------------------------------------------------------------
/**
* A wrapper for any successful operation execution, containing the final result of that execution.
*
* @propertySuccess the actual value of the [Result].
*
* @see [Result].
*/
private class Success<T>(val success: T) : Result<T>() {
/**
* @see [Result.isSuccess].
*/
override fun isSuccess() = true
/**
* @see [Result.onSuccess].
*/
override fun <U> onSuccess(operation: (T) -> Result<U>): Result<U> =
try {
operation(success)
} catch (e: Exception) {
failure(e)
}
/**
* @see [Result.onFailure].
*/
override fun onFailure(operation: (Throwable) -> Result<T>): Result<T> = this
/**
* @see [Result.getOrElse].
*/
override fun getOrElse(backup: () -> T): T = success
/**
* @see [Result.contains].
*/
override fun contains(value: T): Boolean = success == value
/**
* Returns the value of the success in a formatted [String].
*
* @return the value of the [Result] in a formatted [String].
*/
override fun toString(): String = "Success[$success]"
}
// ----------------------------------------------------------------
// Implementation of Failure object
// ----------------------------------------------------------------
/**
* A wrapper for any failed operation execution, containing the [Exception] which caused the failure of that execution.
*
* @propertyFailure the [Exception] that caused the failure of the operation execution.
*
* @see [Result].
*/
private class Failure<T>(val failure: Throwable) : Result<T>() {
/**
* @see [Result.isSuccess].
*/
override fun isSuccess(): Boolean = false
/**
* @see [Result.onSuccess].
*/
override fun <U> onSuccess(operation: (T) -> Result<U>): Result<U> = Failure(failure)
/**
* @see [Result.onFailure].
*/
override fun onFailure(operation: (Throwable) -> Result<T>): Result<T> =
try {
operation(failure)
} catch (e: Exception) {
failure(e)
}
/**
* @see [Result.getOrElse].
*/
override fun getOrElse(backup: () -> T): T = backup()
/**
* @see [Result.contains].
*/
override fun contains(value: T): Boolean = false
/**
* Returns the name of the [Exception] in a formatted [String].
*
* @return the name of the [Exception] in a formatted [String].
*/
override fun toString(): String = "Failure[${failure.javaClass}]"
}
}
| mit | 6b604e436523f17c61d1e0a1d19e18cb | 38.182163 | 463 | 0.568115 | 4.538242 | false | false | false | false |
nlgcoin/guldencoin-official | src/frontend/android/unity_wallet/app/src/main/java/com/gulden/unity_wallet/ui/ShowRecoveryPhraseActivity.kt | 2 | 7061 | package com.gulden.unity_wallet.ui
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableString
import android.text.style.BackgroundColorSpan
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.appcompat.view.ActionMode
import androidx.appcompat.widget.ShareActionProvider
import androidx.core.view.MenuItemCompat
import com.gulden.jniunifiedbackend.ILibraryController
import com.gulden.unity_wallet.*
import com.gulden.unity_wallet.util.AppBaseActivity
import com.gulden.unity_wallet.util.gotoWalletActivity
import com.gulden.unity_wallet.util.setFauxButtonEnabledState
import kotlinx.android.synthetic.main.activity_show_recovery_phrase.*
import org.jetbrains.anko.sdk27.coroutines.onClick
private const val TAG = "show-recovery-activity"
class ShowRecoveryPhraseActivity : AppBaseActivity(), UnityCore.Observer
{
private val erasedWallet = UnityCore.instance.isCoreReady()
//fixme: (GULDEN) Change to char[] to we can securely wipe.
private var recoveryPhrase: String? = null
internal var recoveryPhraseTrimmed: String? = null
private var shareActionProvider: ShareActionProvider? = null
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_show_recovery_phrase)
recoveryPhrase = intent.getStringExtra(this.packageName + "recovery_phrase_with_birth")
recoveryPhraseTrimmed = intent.getStringExtra(this.packageName + "recovery_phrase")
recovery_phrase_text_view.run {
//TODO: Reintroduce showing birth time here if/when we decide we want it in future
text = recoveryPhraseTrimmed
onClick { setFocusOnRecoveryPhrase() }
}
supportActionBar?.hide()
updateView()
UnityCore.instance.addObserver(this, fun (callback:() -> Unit) { runOnUiThread { callback() }})
}
override fun onOptionsItemSelected(item: MenuItem): Boolean
{
when (item.itemId)
{
android.R.id.home ->
{
finish()
return true
}
}
return super.onOptionsItemSelected(item)
}
override fun onDestroy()
{
UnityCore.instance.removeObserver(this)
//fixme: (GULDEN) Securely wipe.
recoveryPhrase = ""
recoveryPhraseTrimmed = ""
super.onDestroy()
}
override fun onWalletReady() {
if (!erasedWallet)
gotoWalletActivity(this)
}
override fun onWalletCreate() {
// do nothing, we are supposed to sit here until the wallet was created
}
@Suppress("UNUSED_PARAMETER")
fun onAcceptRecoveryPhrase(view: View)
{
// Only allow user to move on once they have acknowledged writing the recovery phrase down.
if (!acknowledge_recovery_phrase.isChecked)
{
Toast.makeText(applicationContext, "Write down your recovery phrase", Toast.LENGTH_LONG).show()
return
}
button_accept_recovery_phrase.visibility = View.INVISIBLE
// TODO must have core started and createWallet signal
Authentication.instance.chooseAccessCode(
this,
null,
action = fun(password: CharArray) {
if (UnityCore.instance.isCoreReady()) {
if (ILibraryController.ContinueWalletFromRecoveryPhrase(recoveryPhrase, password.joinToString(""))) {
gotoWalletActivity(this)
} else {
internalErrorAlert(this, "$TAG continuation failed")
}
} else {
// Create the new wallet, a coreReady event will follow which will proceed to the main activity
if (!ILibraryController.InitWalletFromRecoveryPhrase(recoveryPhrase, password.joinToString("")))
internalErrorAlert(this, "$TAG init failed")
}
},
cancelled = fun() {button_accept_recovery_phrase.visibility = View.VISIBLE}
)
}
@Suppress("UNUSED_PARAMETER")
fun onAcknowledgeRecoveryPhrase(view: View)
{
updateView()
}
private fun updateView()
{
setFauxButtonEnabledState(button_accept_recovery_phrase, acknowledge_recovery_phrase.isChecked)
}
internal inner class ActionBarCallBack : ActionMode.Callback
{
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean
{
return if (item.itemId == R.id.item_copy_to_clipboard)
{
val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clip = ClipData.newPlainText("backup", recoveryPhraseTrimmed)
clipboard.setPrimaryClip(clip)
mode.finish()
Toast.makeText(applicationContext, R.string.recovery_phrase_copy, Toast.LENGTH_LONG).show()
true
}
else false
}
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean
{
mode.menuInflater.inflate(R.menu.share_menu, menu)
// Handle buy button
val itemBuy = menu.findItem(R.id.item_buy_gulden)
itemBuy.isVisible = false
// Handle copy button
//MenuItem itemCopy = menu.findItem(R.id.item_copy_to_clipboard);
// Handle share button
val itemShare = menu.findItem(R.id.action_share)
shareActionProvider = ShareActionProvider(this@ShowRecoveryPhraseActivity)
MenuItemCompat.setActionProvider(itemShare, shareActionProvider)
val intent = Intent(Intent.ACTION_SEND)
intent.type = "text/plain"
intent.putExtra(Intent.EXTRA_TEXT, recoveryPhraseTrimmed)
shareActionProvider!!.setShareIntent(intent)
@Suppress("DEPRECATION")
val color = resources.getColor(R.color.colorPrimary)
val spannableString = SpannableString(recovery_phrase_text_view.text)
spannableString.setSpan(BackgroundColorSpan(color), 0, recovery_phrase_text_view.text.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
recovery_phrase_text_view.text = spannableString
return true
}
override fun onDestroyActionMode(mode: ActionMode)
{
shareActionProvider = null
recovery_phrase_text_view.text = recoveryPhraseTrimmed ?: ""
}
override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean
{
return false
}
}
private fun setFocusOnRecoveryPhrase()
{
startSupportActionMode(ActionBarCallBack())
}
}
| mit | f972aae858a51aafbc8f3b9f387cabb5 | 34.129353 | 141 | 0.646367 | 5.120377 | false | false | false | false |
dahlstrom-g/intellij-community | platform/testFramework/extensions/src/com/intellij/testFramework/rules/InMemoryFsRule.kt | 9 | 2249 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.testFramework.rules
import com.github.marschall.memoryfilesystem.MemoryFileSystemBuilder
import org.junit.jupiter.api.extension.AfterEachCallback
import org.junit.jupiter.api.extension.BeforeEachCallback
import org.junit.jupiter.api.extension.ExtensionContext
import org.junit.rules.ExternalResource
import org.junit.runner.Description
import org.junit.runners.model.Statement
import java.net.URLEncoder
import java.nio.file.FileSystem
import java.nio.file.Path
import kotlin.properties.Delegates
class InMemoryFsRule(private val windows: Boolean = false) : ExternalResource() {
private var _fs: FileSystem? = null
private var sanitizedName: String by Delegates.notNull()
override fun apply(base: Statement, description: Description): Statement {
sanitizedName = URLEncoder.encode(description.methodName, Charsets.UTF_8.name())
return super.apply(base, description)
}
val fs: FileSystem
get() {
if (_fs == null) {
_fs = (if (windows) MemoryFileSystemBuilder.newWindows().setCurrentWorkingDirectory("C:\\")
else MemoryFileSystemBuilder.newLinux().setCurrentWorkingDirectory("/")).build(sanitizedName)
}
return _fs!!
}
override fun after() {
_fs?.close()
_fs = null
}
}
class InMemoryFsExtension(private val windows: Boolean = false) : BeforeEachCallback, AfterEachCallback {
private var _fs: FileSystem? = null
private var sanitizedName: String by Delegates.notNull()
val root: Path
get() {
return fs.getPath("/")
}
val fs: FileSystem
get() {
if (_fs == null) {
_fs = (if (windows) MemoryFileSystemBuilder.newWindows().setCurrentWorkingDirectory("C:\\")
else MemoryFileSystemBuilder.newLinux().setCurrentWorkingDirectory("/")).build(sanitizedName)
}
return _fs!!
}
override fun beforeEach(context: ExtensionContext) {
sanitizedName = URLEncoder.encode(context.displayName, Charsets.UTF_8.name())
}
override fun afterEach(context: ExtensionContext) {
(_fs ?: return).close()
_fs = null
}
} | apache-2.0 | ec59521ec4e9253bc20076aef8f7fd90 | 33.090909 | 158 | 0.722543 | 4.418468 | false | false | false | false |
dahlstrom-g/intellij-community | platform/platform-impl/src/com/intellij/toolWindow/ToolWindowPaneState.kt | 8 | 1114 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.toolWindow
import com.intellij.openapi.ui.Splitter
import com.intellij.openapi.util.Pair
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.WindowInfo
import it.unimi.dsi.fastutil.objects.Object2FloatOpenHashMap
internal class ToolWindowPaneState {
private val idToSplitProportion = Object2FloatOpenHashMap<String>()
var maximizedProportion: Pair<ToolWindow, Int>? = null
var isStripesOverlaid = false
fun getPreferredSplitProportion(id: String?, defaultValue: Float): Float {
val f = idToSplitProportion.getFloat(id)
return if (f == 0f) defaultValue else f
}
fun addSplitProportion(info: WindowInfo, component: InternalDecoratorImpl?, splitter: Splitter) {
if (info.isSplit && component != null) {
idToSplitProportion.put(component.toolWindow.id, splitter.proportion)
}
}
fun isMaximized(window: ToolWindow): Boolean {
return maximizedProportion != null && maximizedProportion!!.first === window
}
} | apache-2.0 | 5dcbff89d1f144426242ab4849390e17 | 36.166667 | 120 | 0.768402 | 4.351563 | false | false | false | false |
phylame/jem | imabw/src/main/kotlin/jem/imabw/ui/Dashboard.kt | 1 | 6562 | /*
* Copyright 2015-2017 Peng Wan <[email protected]>
*
* This file is part of Jem.
*
* 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 jem.imabw.ui
import javafx.geometry.Pos
import javafx.scene.Scene
import javafx.scene.control.Label
import javafx.scene.control.SplitPane
import javafx.scene.control.Tooltip
import javafx.scene.layout.BorderPane
import javafx.scene.layout.HBox
import jclp.EventBus
import jclp.log.Log
import jclp.text.ifNotEmpty
import jclp.text.or
import jem.Attributes
import jem.author
import jem.imabw.Imabw
import jem.imabw.UISettings
import jem.imabw.Workbench
import jem.imabw.WorkflowEvent
import jem.title
import mala.App
import mala.ixin.*
import java.util.*
class Dashboard : IApplication(UISettings), CommandHandler {
private val tagId = "Dashboard"
lateinit var contentPane: SplitPane
lateinit var designer: AppDesigner
lateinit var accelerators: Properties
override fun init() {
Imabw.register(this)
}
override fun setup(scene: Scene, appPane: AppPane) {
designer = App.assets.designerFor("ui/designer.json")!!
scene.stylesheets += UISettings.stylesheetUri or { App.assets.resourceFor("ui/default.css")!!.toExternalForm() }
appPane.setup(designer, actionMap, menuMap)
accelerators = App.assets.propertiesFor("ui/keys.properties")!!
actionMap.updateAccelerators(accelerators)
appPane.statusBar?.right = Indicator
contentPane = SplitPane().also { split ->
split.id = "main-split-pane"
split.items.addAll(ContentsPane, EditorPane)
split.setDividerPosition(0, 0.24)
SplitPane.setResizableWithParent(ContentsPane, false)
appPane.center = split
}
initActions()
restoreState()
EventBus.register<WorkflowEvent> { refreshTitle() }
statusText = App.tr("status.ready")
}
override fun restoreState() {
super.restoreState()
ContentsPane.isVisible = UISettings.navigationBarVisible
if (!ContentsPane.isVisible) contentPane.items.remove(0, 1)
}
override fun saveState() {
super.saveState()
UISettings.navigationBarVisible = ContentsPane.isVisible
}
internal fun dispose() {
saveState()
stage.close()
}
private fun initActions() {
actionMap["showToolbar"]?.selectedProperty?.bindBidirectional(appPane.toolBar!!.visibleProperty())
actionMap["showStatusBar"]?.selectedProperty?.bindBidirectional(appPane.statusBar!!.visibleProperty())
actionMap["showNavigateBar"]?.selectedProperty?.bindBidirectional(ContentsPane.visibleProperty())
actionMap["toggleFullScreen"]?.let { action ->
stage.fullScreenProperty().addListener { _, _, value -> action.isSelected = value }
action.selectedProperty.addListener { _, _, value -> stage.isFullScreen = value }
}
}
private fun refreshTitle() {
val work = Workbench.work!!
val book = work.book
with(StringBuilder()) {
if (work.isModified) {
append("*")
}
append(book.title)
append(" - ")
book.author.ifNotEmpty {
append("[")
append(it.replace(Attributes.VALUE_SEPARATOR, " & "))
append("] - ")
}
work.path?.let {
append(it)
append(" - ")
}
append("PW Imabw ")
append(Imabw.version)
stage.title = toString()
}
}
override fun handle(command: String, source: Any): Boolean {
when (command) {
"showToolbar", "showStatusBar", "toggleFullScreen" -> Unit // bound with property
"showNavigateBar" -> {
if (!ContentsPane.isVisible) {
contentPane.items.remove(0, 1)
} else {
contentPane.items.add(0, ContentsPane)
contentPane.setDividerPosition(0, 0.24)
}
}
in editActions -> stage.scene.focusOwner.let {
(it as? EditAware)?.onEdit(command) ?: Log.d(tagId) { "focused object is not editable: $it" }
}
else -> return false
}
return true
}
}
object Indicator : HBox() {
val caret = Label().apply { tooltip = Tooltip(App.tr("status.caret.toast")) }
val words = Label().apply { tooltip = Tooltip(App.tr("status.words.toast")) }
val mime = Label().apply { tooltip = Tooltip(App.tr("status.mime.toast")) }
init {
id = "indicator"
alignment = Pos.CENTER
BorderPane.setAlignment(this, Pos.CENTER)
children.addAll(caret, words, mime)
IxIn.newAction("lock").toButton(Imabw, Style.TOGGLE, hideText = true).also { children += it }
IxIn.newAction("gc").toButton(Imabw, hideText = true).also { children += it }
reset()
}
fun reset() {
updateCaret(-1, -1, 0)
updateWords(-1)
updateMime("")
}
fun updateCaret(row: Int, column: Int, selection: Int) {
if (row < 0) {
caret.isVisible = false
} else {
caret.isVisible = true
caret.text = when {
selection > 0 -> "$row:$column/$selection"
else -> "$row:$column"
}
}
}
fun updateWords(count: Int) {
if (count < 0) {
words.isVisible = false
} else {
words.isVisible = true
words.text = count.toString()
}
}
fun updateMime(type: String) {
if (type.isEmpty()) {
mime.isVisible = false
} else {
mime.isVisible = true
mime.text = type
}
}
}
private val editActions = arrayOf(
"undo", "redo", "cut", "copy", "paste", "delete", "selectAll", "find", "replace", "findNext", "findPrevious"
)
interface EditAware {
fun onEdit(command: String)
}
| apache-2.0 | 4b33693e2a238127028723806ca643c7 | 30.099526 | 120 | 0.603017 | 4.460911 | false | false | false | false |
cbeust/klaxon | klaxon/src/main/kotlin/com/beust/klaxon/Klaxon.kt | 1 | 11231 | package com.beust.klaxon
import com.beust.klaxon.internal.ConverterFinder
import java.io.*
import java.nio.charset.Charset
import kotlin.collections.set
import kotlin.reflect.KClass
import kotlin.reflect.KProperty
import kotlin.reflect.KTypeProjection
import kotlin.reflect.full.createType
import kotlin.reflect.full.functions
import kotlin.reflect.jvm.javaField
import kotlin.reflect.jvm.javaMethod
import kotlin.reflect.jvm.javaType
class Klaxon(
val instanceSettings: KlaxonSettings = KlaxonSettings()
) : ConverterFinder {
/**
* Parse a JsonReader into a JsonObject.
*/
@Suppress("unused")
fun parseJsonObject(reader: JsonReader)
= parser().parse(reader) as JsonObject
/**
* Parse a Reader into a JsonObject.
*/
@Suppress("unused")
fun parseJsonObject(reader: Reader)
= parser().parse(reader) as JsonObject
/**
* Parse a Reader into a JsonArray.
*/
@Suppress("unused")
fun parseJsonArray(reader: Reader)
= parser().parse(reader) as JsonArray<*>
/**
* Parse a JSON string into an object.
*/
@Suppress("unused")
inline fun <reified T> parse(json: String): T?
= maybeParse(parser(T::class).parse(StringReader(json)) as JsonObject)
/**
* Parse a JSON string into a List.
*/
@Suppress("unused")
inline fun <reified T> parseArray(json: String): List<T>?
= parseFromJsonArray(parser(T::class).parse(StringReader(json)) as JsonArray<*>)
/**
* Parse a JSON file into an object.
*/
@Suppress("unused")
inline fun <reified T> parse(file: File): T? = FileReader(file).use { reader ->
maybeParse(parser(T::class).parse(reader) as JsonObject)
}
/**
* Parse a JSON file into a List.
*/
@Suppress("unused")
inline fun <reified T> parseArray(file: File): List<T>? = FileReader(file).use { reader ->
parseFromJsonArray(parser(T::class).parse(reader) as JsonArray<*>)
}
/**
* Parse an InputStream into an object.
*/
@Suppress("unused")
inline fun <reified T> parse(inputStream: InputStream): T? {
return maybeParse(parser(T::class).parse(toReader(inputStream)) as JsonObject)
}
/**
* Parse an InputStream into a List.
*/
@Suppress("unused")
inline fun <reified T> parseArray(inputStream: InputStream): List<T>?
= parseFromJsonArray(parser(T::class).parse(toReader(inputStream)) as JsonArray<*>)
/**
* Parse a JsonReader into an object.
*/
@Suppress("unused")
inline fun <reified T> parse(jsonReader: JsonReader): T? {
val p = parser(T::class, jsonReader.lexer, streaming = true)
return maybeParse(p.parse(jsonReader) as JsonObject)
}
/**
* Parse a JsonReader into a List.
*/
@Suppress("unused")
inline fun <reified T> parseArray(jsonReader: JsonReader): List<T>? {
val p = parser(T::class, jsonReader.lexer, streaming = true)
return parseFromJsonArray(p.parse(jsonReader) as JsonArray<*>)
}
/**
* Parse a Reader into an object.
*/
@Suppress("unused")
inline fun <reified T> parse(reader: Reader): T? {
return maybeParse(parser(T::class).parse(reader) as JsonObject)
}
/**
* Parse a Reader into a List.
*/
@Suppress("unused")
inline fun <reified T> parseArray(reader: Reader): List<T>? {
return parseFromJsonArray(parser(T::class).parse(reader) as JsonArray<*>)
}
/**
* Parse a JsonObject into an object.
*/
inline fun <reified T> parseFromJsonObject(map: JsonObject): T?
= fromJsonObject(map, T::class.java, T::class) as T?
inline fun <reified T> parseFromJsonArray(map: JsonArray<*>): List<T>? {
val result = arrayListOf<Any?>()
map.forEach { jo ->
if (jo is JsonObject) {
val t = parseFromJsonObject<T>(jo)
if (t != null) result.add(t)
else throw KlaxonException("Couldn't convert $jo")
} else if (jo != null) {
val converter = findConverterFromClass(T::class.java, null)
val convertedValue = converter.fromJson(JsonValue(jo, null, null, this))
result.add(convertedValue)
} else {
throw KlaxonException("Couldn't convert $jo")
}
}
@Suppress("UNCHECKED_CAST")
return result as List<T>
}
inline fun <reified T> maybeParse(map: JsonObject): T? = parseFromJsonObject(map)
fun toReader(inputStream: InputStream, charset: Charset = Charsets.UTF_8)
= inputStream.reader(charset)
@Suppress("MemberVisibilityCanBePrivate")
val pathMatchers = arrayListOf<PathMatcher>()
fun pathMatcher(po: PathMatcher): Klaxon {
pathMatchers.add(po)
return this
}
val propertyStrategies = arrayListOf<PropertyStrategy>()
fun propertyStrategy(ps: PropertyStrategy): Klaxon {
propertyStrategies.add(ps)
return this
}
/**
* A map of a path to the JSON value that this path was found at.
*/
private val allPaths = hashMapOf<String, Any>()
inner class DefaultPathMatcher(private val paths: Set<String>) : PathMatcher {
override fun pathMatches(path: String) : Boolean {
return paths.contains(path)
}
override fun onMatch(path: String, value: Any) { allPaths[path] = value }
}
fun parser(kc: KClass<*>? = null, passedLexer: Lexer? = null, streaming: Boolean = false): Parser {
val result = Annotations.findJsonPaths(kc)
if (result.any()) {
// If we found at least one @Json(path = ...), add the DefaultPathMatcher with a list
// of all these paths we need to watch for (we don't want to do that if no path
// matching was requested since matching these paths slows down parsing).
pathMatchers.add(DefaultPathMatcher(result.toSet()))
}
return Parser.default(pathMatchers, passedLexer, streaming)
}
private val DEFAULT_CONVERTER = DefaultConverter(this, allPaths)
private val converters = arrayListOf<Converter>(EnumConverter(), DEFAULT_CONVERTER)
/**
* Add a type converter. The converter is analyzed to find out which type it converts
* and then that info is transferred to `converterMap`. Reflection is necessary to locate
* the toJson() function since there is no way to define Converter in a totally generic
* way that will compile.
*/
fun converter(converter: Converter): Klaxon {
converters.add(0, converter)
return this
}
/**
* Field type converters that convert fields with a marker annotation.
*/
private val fieldTypeMap = hashMapOf<KClass<out Annotation>, Converter>()
fun fieldConverter(annotation: KClass<out Annotation>, converter: Converter): Klaxon {
fieldTypeMap[annotation] = converter
return this
}
var fieldRenamer: FieldRenamer? = null
/**
* Defines a field renamer.
*/
fun fieldRenamer(renamer: FieldRenamer): Klaxon {
fieldRenamer = renamer
return this
}
/**
* @return a converter that will turn `value` into a `JsonObject`. If a non-null property is
* passed, inspect that property for annotations that would override the type converter
* we need to use to convert it.
*/
override fun findConverter(value: Any, prop: KProperty<*>?): Converter {
val result = findConverterFromClass(value::class.java, prop)
log("Value: $value, converter: $result")
return result
}
/**
* Given a Kotlin class and a property where the object should be stored, returns a `Converter` for that type.
*/
fun findConverterFromClass(cls: Class<*>, prop: KProperty<*>?) : Converter {
fun annotationsForProp(prop: KProperty<*>, kc: Class<*>): Array<out Annotation> {
val result = kc.declaredFields.firstOrNull { it.name == prop.name }?.declaredAnnotations ?: arrayOf()
return result
}
var propertyClass: Class<*>? = null
val propConverter : Converter? =
if (prop != null && prop.returnType.classifier is KClass<*>) {
propertyClass = (prop.returnType.classifier as KClass<*>).java
val dc = prop.getter.javaMethod?.declaringClass ?: prop.javaField?.declaringClass
annotationsForProp(prop, dc!!).mapNotNull {
fieldTypeMap[it.annotationClass]
}.firstOrNull()
} else {
null
}
val result = propConverter
?: findBestConverter(cls, prop)
?: (if (propertyClass != null) findBestConverter(propertyClass, prop) else null)
?: DEFAULT_CONVERTER
// That last DEFAULT_CONVERTER above is not necessary since the default converter is part of the
// list of converters by default and if all other converters fail, that one will apply
// (since it is associated to the Object type), however, Kotlin doesn't know that and
// will assume the result is nullable without it
log("findConverterFromClass $cls returning $result")
return result
}
private fun findBestConverter(cls: Class<*>, prop: KProperty<*>?) : Converter? {
val toConvert = prop?.returnType?.javaType as? Class<*> ?: cls
return converters.firstOrNull { it.canConvert(toConvert) }
}
fun toJsonString(value: Any?, prop: KProperty<*>? = null): String
= if (value == null) "null" else toJsonString(value, findConverter(value, prop))
private fun toJsonString(value: Any, converter: Any /* can be Converter or Converter */)
: String {
// It's not possible to safely call converter.toJson(value) since its parameter is generic,
// so use reflection
val toJsonMethod = converter::class.functions.firstOrNull { it.name == "toJson" }
val result =
if (toJsonMethod != null) {
toJsonMethod.call(converter, value) as String
} else {
throw KlaxonException("Couldn't find a toJson() function on converter $converter")
}
return result
}
/**
* Convert a JsonObject into a real value.
*/
fun fromJsonObject(jsonObject: JsonObject, cls: Class<*>, kc: KClass<*>): Any {
// If the user provided a type converter, use it, otherwise try to instantiate the object ourselves.
val classConverter = findConverterFromClass(cls, null)
val types = kc.typeParameters.map { KTypeProjection.invariant(it.createType()) }
val type =
if (kc.typeParameters.any()) kc.createType(types)
else kc.createType()
return classConverter.fromJson(JsonValue(jsonObject, cls, type, this@Klaxon)) as Any
}
/**
* Convert the parameter into a JsonObject
*/
@Suppress("unused")
fun toJsonObject(obj: Any) = JsonValue.convertToJsonObject(obj, this)
fun log(s: String) {
if (Debug.verbose) println(s)
}
}
| apache-2.0 | 83d97f8b9c16515f7fac7780fbbb285e | 35.11254 | 114 | 0.628083 | 4.593456 | false | false | false | false |
paplorinc/intellij-community | platform/testFramework/extensions/src/com/intellij/testFramework/assertions/PathAssertEx.kt | 3 | 2374 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.testFramework.assertions
import com.intellij.openapi.util.text.StringUtilRt
import com.intellij.util.io.readText
import com.intellij.util.io.size
import junit.framework.ComparisonFailure
import org.assertj.core.api.AbstractStringAssert
import org.assertj.core.api.PathAssert
import org.assertj.core.internal.ComparatorBasedComparisonStrategy
import org.assertj.core.internal.Iterables
import java.nio.file.Files
import java.nio.file.LinkOption
import java.nio.file.Path
import java.util.*
class PathAssertEx(actual: Path?) : PathAssert(actual) {
override fun doesNotExist(): PathAssert {
isNotNull
if (Files.exists(actual, LinkOption.NOFOLLOW_LINKS)) {
var error = "Expecting path:\n\t${actual}\nnot to exist"
if (actual.size() < 16 * 1024) {
error += ", content:\n\n${actual.readText()}\n"
}
failWithMessage(error)
}
return this
}
override fun hasContent(expected: String) = isEqualTo(expected)
fun isEqualTo(expected: String): PathAssertEx {
isNotNull
isRegularFile
val expectedContent = expected.trimIndent()
val actualContent = StringUtilRt.convertLineSeparators(actual.readText())
if (actualContent != expectedContent) {
throw ComparisonFailure(null, expectedContent, actualContent)
}
return this
}
fun hasChildren(vararg names: String) {
paths.assertIsDirectory(info, actual)
Iterables(ComparatorBasedComparisonStrategy(Comparator<Any> { o1, o2 ->
if (o1 is Path && o2 is Path) {
o1.compareTo(o2)
}
else if (o1 is String && o2 is String) {
o1.compareTo(o2)
}
else if (o1 is String) {
if ((o2 as Path).endsWith(o1)) 0 else -1
}
else {
if ((o1 as Path).endsWith(o2 as String)) 0 else -1
}
}))
.assertContainsOnly(info, Files.newDirectoryStream(actual).use { it.toList() }, names)
}
}
class StringAssertEx(actual: String?) : AbstractStringAssert<StringAssertEx>(actual, StringAssertEx::class.java) {
fun isEqualTo(expected: Path) {
isNotNull
compareFileContent(actual, expected)
}
fun toMatchSnapshot(snapshotFile: Path) {
isNotNull
compareFileContent(actual, snapshotFile)
}
} | apache-2.0 | c3aa88b53e53a92b4e276cd6ba521d4b | 28.6875 | 140 | 0.704297 | 4.037415 | false | false | false | false |
google/intellij-community | plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/core/script/configuration/utils/DefaultBackgroundExecutor.kt | 2 | 8407 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.core.script.configuration.utils
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.progress.util.BackgroundTaskUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.Alarm
import com.intellij.util.containers.HashSetQueue
import org.jetbrains.kotlin.idea.base.scripting.KotlinBaseScriptingBundle
import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable
import org.jetbrains.kotlin.idea.core.script.configuration.CompositeScriptConfigurationManager
import org.jetbrains.kotlin.idea.core.script.configuration.utils.DefaultBackgroundExecutor.Companion.PROGRESS_INDICATOR_DELAY
import org.jetbrains.kotlin.idea.core.script.configuration.utils.DefaultBackgroundExecutor.Companion.PROGRESS_INDICATOR_MIN_QUEUE
import org.jetbrains.kotlin.idea.core.script.scriptingDebugLog
import java.util.*
import javax.swing.SwingUtilities
/**
* Sequentially loads script configuration in background.
* Loading tasks scheduled by calling [ensureScheduled].
*
* Progress indicator will be shown after [PROGRESS_INDICATOR_DELAY] ms or if
* more then [PROGRESS_INDICATOR_MIN_QUEUE] tasks scheduled.
*
* States:
* silentWorker underProgressWorker
* - sleep
* - silent x
* - silent and under progress x x
* - under progress x
*/
internal class DefaultBackgroundExecutor(
val project: Project,
val manager: CompositeScriptConfigurationManager
) : BackgroundExecutor {
companion object {
const val PROGRESS_INDICATOR_DELAY = 1000
const val PROGRESS_INDICATOR_MIN_QUEUE = 3
}
val rootsManager get() = manager.updater
private val work = Any()
private val queue: Queue<LoadTask> = HashSetQueue()
/**
* Let's fix queue size when progress bar displayed.
* Progress for rest items will be counted from zero
*/
private var currentProgressSize: Int = 0
private var currentProgressDone: Int = 0
private var silentWorker: SilentWorker? = null
private var underProgressWorker: UnderProgressWorker? = null
private val longRunningAlarm = Alarm(Alarm.ThreadToUse.POOLED_THREAD, KotlinPluginDisposable.getInstance(project))
private var longRunningAlarmRequested = false
private var inTransaction: Boolean = false
private var currentFile: VirtualFile? = null
class LoadTask(val key: VirtualFile, val actions: () -> Unit) {
override fun equals(other: Any?) =
this === other || (other is LoadTask && key == other.key)
override fun hashCode() = key.hashCode()
}
@Synchronized
override fun ensureScheduled(key: VirtualFile, actions: () -> Unit) {
val task = LoadTask(key, actions)
if (queue.add(task)) {
scriptingDebugLog(task.key) { "added to update queue" }
// If the queue is longer than PROGRESS_INDICATOR_MIN_QUEUE, show progress and cancel button
if (queue.size > PROGRESS_INDICATOR_MIN_QUEUE) {
requireUnderProgressWorker()
} else {
requireSilentWorker()
if (!longRunningAlarmRequested) {
longRunningAlarmRequested = true
longRunningAlarm.addRequest(
{
longRunningAlarmRequested = false
requireUnderProgressWorker()
},
PROGRESS_INDICATOR_DELAY
)
}
}
}
}
@Synchronized
private fun requireSilentWorker() {
if (silentWorker == null && underProgressWorker == null) {
silentWorker = SilentWorker().also { it.start() }
}
}
@Synchronized
private fun requireUnderProgressWorker() {
if (queue.isEmpty() && silentWorker == null) return
silentWorker?.stopGracefully()
if (underProgressWorker == null) {
underProgressWorker = UnderProgressWorker().also { it.start() }
restartProgressBar()
updateProgress()
}
}
@Synchronized
private fun restartProgressBar() {
currentProgressSize = queue.size
currentProgressDone = 0
}
@Synchronized
fun updateProgress() {
underProgressWorker?.progressIndicator?.let {
it.text2 = currentFile?.path ?: ""
if (queue.size == 0) {
// last file
it.isIndeterminate = true
} else {
it.isIndeterminate = false
if (currentProgressDone > currentProgressSize) {
restartProgressBar()
}
it.fraction = currentProgressDone.toDouble() / currentProgressSize.toDouble()
}
}
}
@Synchronized
private fun ensureInTransaction() {
if (inTransaction) return
inTransaction = true
rootsManager.beginUpdating()
}
@Synchronized
private fun endBatch() {
check(inTransaction)
rootsManager.commit()
inTransaction = false
}
private abstract inner class Worker {
private var shouldStop = false
open fun start() {
ensureInTransaction()
}
fun stopGracefully() {
shouldStop = true
}
protected open fun checkCancelled() = false
protected abstract fun close()
protected fun run() {
try {
while (true) {
// prevent parallel work in both silent and under progress
synchronized(work) {
val next = synchronized(this@DefaultBackgroundExecutor) {
if (shouldStop) return
if (checkCancelled()) {
queue.clear()
endBatch()
return
} else if (queue.isEmpty()) {
endBatch()
return
}
queue.poll()?.also {
currentFile = it.key
currentProgressDone++
updateProgress()
}
}
next?.actions?.invoke()
synchronized(work) {
currentFile = null
}
}
}
} finally {
close()
}
}
}
private inner class UnderProgressWorker : Worker() {
var progressIndicator: ProgressIndicator? = null
override fun start() {
super.start()
object : Task.Backgroundable(project, KotlinBaseScriptingBundle.message("text.kotlin.loading.script.configuration"), true) {
override fun run(indicator: ProgressIndicator) {
progressIndicator = indicator
updateProgress()
run()
}
}.queue()
}
override fun checkCancelled(): Boolean = progressIndicator?.isCanceled == true
override fun close() {
synchronized(this@DefaultBackgroundExecutor) {
underProgressWorker = null
progressIndicator = null
}
}
}
private inner class SilentWorker : Worker() {
override fun start() {
super.start()
// executeOnPooledThread requires read lock, and we may fail to acquire it
SwingUtilities.invokeLater {
BackgroundTaskUtil.executeOnPooledThread(KotlinPluginDisposable.getInstance(project)) {
run()
}
}
}
override fun close() {
synchronized(this@DefaultBackgroundExecutor) {
silentWorker = null
}
}
}
}
| apache-2.0 | 4d27443127c9bcbb9ac502b209f2f76f | 32.899194 | 158 | 0.570834 | 5.770075 | false | false | false | false |
google/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ChildSingleSecondEntityImpl.kt | 1 | 10258 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToAbstractOneParent
import com.intellij.workspaceModel.storage.impl.updateOneToAbstractOneParentOfChild
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Abstract
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ChildSingleSecondEntityImpl(val dataSource: ChildSingleSecondEntityData) : ChildSingleSecondEntity, WorkspaceEntityBase() {
companion object {
internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(ParentSingleAbEntity::class.java,
ChildSingleAbstractBaseEntity::class.java,
ConnectionId.ConnectionType.ABSTRACT_ONE_TO_ONE, false)
val connections = listOf<ConnectionId>(
PARENTENTITY_CONNECTION_ID,
)
}
override val commonData: String
get() = dataSource.commonData
override val parentEntity: ParentSingleAbEntity
get() = snapshot.extractOneToAbstractOneParent(PARENTENTITY_CONNECTION_ID, this)!!
override val secondData: String
get() = dataSource.secondData
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: ChildSingleSecondEntityData?) : ModifiableWorkspaceEntityBase<ChildSingleSecondEntity>(), ChildSingleSecondEntity.Builder {
constructor() : this(ChildSingleSecondEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ChildSingleSecondEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isCommonDataInitialized()) {
error("Field ChildSingleAbstractBaseEntity#commonData should be initialized")
}
if (_diff != null) {
if (_diff.extractOneToAbstractOneParent<WorkspaceEntityBase>(PARENTENTITY_CONNECTION_ID, this) == null) {
error("Field ChildSingleAbstractBaseEntity#parentEntity should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] == null) {
error("Field ChildSingleAbstractBaseEntity#parentEntity should be initialized")
}
}
if (!getEntityData().isSecondDataInitialized()) {
error("Field ChildSingleSecondEntity#secondData should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as ChildSingleSecondEntity
this.entitySource = dataSource.entitySource
this.commonData = dataSource.commonData
this.secondData = dataSource.secondData
if (parents != null) {
this.parentEntity = parents.filterIsInstance<ParentSingleAbEntity>().single()
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var commonData: String
get() = getEntityData().commonData
set(value) {
checkModificationAllowed()
getEntityData().commonData = value
changedProperty.add("commonData")
}
override var parentEntity: ParentSingleAbEntity
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToAbstractOneParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false,
PARENTENTITY_CONNECTION_ID)]!! as ParentSingleAbEntity
}
else {
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as ParentSingleAbEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToAbstractOneParentOfChild(PARENTENTITY_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value
}
changedProperty.add("parentEntity")
}
override var secondData: String
get() = getEntityData().secondData
set(value) {
checkModificationAllowed()
getEntityData().secondData = value
changedProperty.add("secondData")
}
override fun getEntityData(): ChildSingleSecondEntityData = result ?: super.getEntityData() as ChildSingleSecondEntityData
override fun getEntityClass(): Class<ChildSingleSecondEntity> = ChildSingleSecondEntity::class.java
}
}
class ChildSingleSecondEntityData : WorkspaceEntityData<ChildSingleSecondEntity>() {
lateinit var commonData: String
lateinit var secondData: String
fun isCommonDataInitialized(): Boolean = ::commonData.isInitialized
fun isSecondDataInitialized(): Boolean = ::secondData.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ChildSingleSecondEntity> {
val modifiable = ChildSingleSecondEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): ChildSingleSecondEntity {
return getCached(snapshot) {
val entity = ChildSingleSecondEntityImpl(this)
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ChildSingleSecondEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return ChildSingleSecondEntity(commonData, secondData, entitySource) {
this.parentEntity = parents.filterIsInstance<ParentSingleAbEntity>().single()
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
res.add(ParentSingleAbEntity::class.java)
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ChildSingleSecondEntityData
if (this.entitySource != other.entitySource) return false
if (this.commonData != other.commonData) return false
if (this.secondData != other.secondData) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ChildSingleSecondEntityData
if (this.commonData != other.commonData) return false
if (this.secondData != other.secondData) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + commonData.hashCode()
result = 31 * result + secondData.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + commonData.hashCode()
result = 31 * result + secondData.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | d50f7fc4430cafdcd5044921feb99d05 | 36.713235 | 165 | 0.705206 | 5.727527 | false | false | false | false |
google/intellij-community | plugins/ide-features-trainer/src/training/featuresSuggester/settings/FeatureSuggesterSettings.kt | 4 | 4461 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package training.featuresSuggester.settings
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.RoamingType
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.util.registry.Registry
import training.featuresSuggester.suggesters.FeatureSuggester
import java.time.Instant
import java.time.ZoneId
import java.util.concurrent.TimeUnit
import kotlin.math.max
import kotlin.math.min
@State(
name = "FeatureSuggesterSettings",
storages = [Storage("FeatureSuggester.xml", roamingType = RoamingType.DISABLED)]
)
class FeatureSuggesterSettings : PersistentStateComponent<FeatureSuggesterSettings> {
var suggesters: MutableMap<String, Boolean> = run {
val enabled = isSuggestersEnabledByDefault
FeatureSuggester.suggesters.associate { internalId(it.id) to enabled }.toMutableMap()
}
// SuggesterId to the last time this suggestion was shown
var suggestionLastShownTime: MutableMap<String, Long> = mutableMapOf()
// List of timestamps (millis) of the first IDE session start for the last days
var workingDays: MutableList<Long> = mutableListOf()
val isAnySuggesterEnabled: Boolean
get() = suggesters.any { it.value }
private val isSuggestersEnabledByDefault: Boolean
get() = Registry.`is`("feature.suggester.enable.suggesters", false)
private fun internalId(suggesterId: String): String {
return if (isSuggestersEnabledByDefault) suggesterId else suggesterId + "_"
}
override fun getState(): FeatureSuggesterSettings {
return this
}
override fun loadState(state: FeatureSuggesterSettings) {
// leave default settings if loading settings contains something different
// needed in case when suggesters enabled default is changed
val oldSettingsFound = state.suggesters.any { !suggesters.containsKey(it.key) }
if (!oldSettingsFound) {
suggesters = state.suggesters
}
suggestionLastShownTime = state.suggestionLastShownTime
workingDays = state.workingDays
}
fun isEnabled(suggesterId: String): Boolean {
return suggesters[internalId(suggesterId)] == true
}
fun setEnabled(suggesterId: String, enabled: Boolean) {
suggesters[internalId(suggesterId)] = enabled
}
fun updateSuggestionShownTime(suggesterId: String) {
suggestionLastShownTime[suggesterId] = System.currentTimeMillis()
}
fun getSuggestionLastShownTime(suggesterId: String) = suggestionLastShownTime[suggesterId] ?: 0L
fun updateWorkingDays() {
val curTime = System.currentTimeMillis()
val lastTime = workingDays.lastOrNull()
if (lastTime == null) {
workingDays.add(curTime)
}
else if (curTime.toLocalDate() != lastTime.toLocalDate()) {
val numToRemove = workingDays.size - maxSuggestingIntervalDays + 1
if (numToRemove > 0) {
workingDays.subList(0, numToRemove).clear()
}
workingDays.add(curTime)
}
}
/**
* Return the start time of session happened [oldestDayNum] working days (when user performed any action) ago.
* If there is no information about so old sessions it will return at least the current time minus [oldestDayNum] days
* (it is required for migration of existing users).
* So returned time always will be earlier then time [oldestDayNum] days ago.
*/
fun getOldestWorkingDayStartMillis(oldestDayNum: Int): Long {
val simpleOldestTime = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(oldestDayNum.toLong())
return if (workingDays.isNotEmpty()) {
val ind = max(0, workingDays.size - oldestDayNum)
min(workingDays[ind], simpleOldestTime)
}
else simpleOldestTime
}
private fun Long.toLocalDate() = Instant.ofEpochMilli(this).atZone(ZoneId.systemDefault()).toLocalDate()
companion object {
@JvmStatic
fun instance(): FeatureSuggesterSettings {
return ApplicationManager.getApplication().getService(FeatureSuggesterSettings::class.java)
}
private val maxSuggestingIntervalDays: Int by lazy {
FeatureSuggester.suggesters.maxOfOrNull { it.minSuggestingIntervalDays } ?: run {
thisLogger().error("Failed to find registered suggesters")
14
}
}
}
}
| apache-2.0 | e8a5609d91a81b1d8f3c1389385d59c8 | 36.487395 | 120 | 0.751177 | 4.817495 | false | false | false | false |
Atsky/haskell-idea-plugin | plugin/src/org/jetbrains/haskell/debugger/protocol/EvalCommand.kt | 1 | 1098 | package org.jetbrains.haskell.debugger.protocol
import org.jetbrains.haskell.debugger.parser.ShowOutput
import java.util.Deque
import org.jetbrains.haskell.debugger.parser.GHCiParser
import com.intellij.xdebugger.evaluation.XDebuggerEvaluator
import org.jetbrains.haskell.debugger.frames.HsDebugValue
import org.jetbrains.haskell.debugger.parser.LocalBinding
import org.jetbrains.haskell.debugger.parser.ParseResult
import org.json.simple.JSONObject
import org.jetbrains.haskell.debugger.parser.EvalResult
import org.jetbrains.haskell.debugger.parser.JSONConverter
/**
* Created by vlad on 8/1/14.
*/
class EvalCommand(val force: Boolean, val expression: String, callback: CommandCallback<EvalResult?>)
: RealTimeCommand<EvalResult?>(callback) {
override fun getText(): String = ":eval ${if (force) 1 else 0} ${expression.trim()}\n"
override fun parseGHCiOutput(output: Deque<String?>) = null
override fun parseJSONOutput(output: JSONObject): EvalResult? =
if (JSONConverter.checkExceptionFromJSON(output) == null) JSONConverter.evalResultFromJSON(output) else null
} | apache-2.0 | a60fa6ab24a49774fc82b657a35c9891 | 41.269231 | 120 | 0.798725 | 4.174905 | false | false | false | false |
JetBrains/intellij-community | platform/diagnostic/src/startUpPerformanceReporter/IdeIdeaFormatWriter.kt | 1 | 8528 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplaceGetOrSet", "ReplacePutWithAssignment")
package com.intellij.diagnostic.startUpPerformanceReporter
import com.fasterxml.jackson.core.JsonGenerator
import com.intellij.diagnostic.ActivityImpl
import com.intellij.diagnostic.StartUpMeasurer
import com.intellij.diagnostic.ThreadNameManager
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.ide.plugins.cl.PluginAwareClassLoader
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.diagnostic.Logger
import com.intellij.psi.tree.IElementType
import com.intellij.ui.icons.IconLoadMeasurer
import com.intellij.util.io.jackson.array
import com.intellij.util.io.jackson.obj
import com.intellij.util.lang.ClassPath
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap
import it.unimi.dsi.fastutil.objects.Object2LongMap
import org.bouncycastle.crypto.generators.Argon2BytesGenerator
import org.bouncycastle.crypto.params.Argon2Parameters
import java.lang.invoke.MethodHandles
import java.lang.invoke.MethodType
import java.lang.management.ManagementFactory
import java.time.ZoneId
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.util.*
import java.util.concurrent.TimeUnit
internal class IdeIdeaFormatWriter(activities: Map<String, MutableList<ActivityImpl>>,
private val pluginCostMap: MutableMap<String, Object2LongMap<String>>,
threadNameManager: ThreadNameManager) : IdeaFormatWriter(activities, threadNameManager,
StartUpPerformanceReporter.VERSION) {
val publicStatMetrics = Object2IntOpenHashMap<String>()
init {
publicStatMetrics.defaultReturnValue(-1)
}
fun writeToLog(log: Logger) {
stringWriter.write("\n=== Stop: StartUp Measurement ===")
log.info(stringWriter.toString())
}
override fun writeAppInfo(writer: JsonGenerator) {
val appInfo = ApplicationInfo.getInstance()
writer.writeStringField("build", appInfo.build.asStringWithoutProductCode())
writer.writeStringField("buildDate", ZonedDateTime.ofInstant(appInfo.buildDate.toInstant(), ZoneId.systemDefault()).format(DateTimeFormatter.RFC_1123_DATE_TIME))
writer.writeStringField("productCode", appInfo.build.productCode)
// see CDSManager from platform-impl
@Suppress("SpellCheckingInspection")
if (ManagementFactory.getRuntimeMXBean().inputArguments.any { it == "-Xshare:auto" || it == "-Xshare:on" }) {
writer.writeBooleanField("cds", true)
}
}
override fun writeProjectName(writer: JsonGenerator, projectName: String) {
writer.writeStringField("project", System.getProperty("idea.performanceReport.projectName") ?: safeHashValue(projectName))
}
override fun writeExtraData(writer: JsonGenerator) {
val stats = getClassAndResourceLoadingStats()
writer.obj("classLoading") {
val time = stats.getValue("classLoadingTime")
writer.writeNumberField("time", TimeUnit.NANOSECONDS.toMillis(time))
val defineTime = stats.getValue("classDefineTime")
writer.writeNumberField("searchTime", TimeUnit.NANOSECONDS.toMillis(time - defineTime))
writer.writeNumberField("defineTime", TimeUnit.NANOSECONDS.toMillis(defineTime))
writer.writeNumberField("count", stats.getValue("classRequests"))
}
writer.obj("resourceLoading") {
writer.writeNumberField("time", TimeUnit.NANOSECONDS.toMillis(stats.getValue("resourceLoadingTime")))
writer.writeNumberField("count", stats.getValue("resourceRequests"))
}
writer.obj("langLoading") {
val allTypes = IElementType.enumerate(IElementType.TRUE)
writer.writeNumberField("elementTypeCount", allTypes.size)
}
writeServiceStats(writer)
writeIcons(writer)
}
private fun getClassAndResourceLoadingStats(): Map<String, Long> {
// data from bootstrap classloader
val classLoader = IdeIdeaFormatWriter::class.java.classLoader
@Suppress("UNCHECKED_CAST")
val stats = MethodHandles.lookup()
.findVirtual(classLoader::class.java, "getLoadingStats", MethodType.methodType(Map::class.java))
.bindTo(classLoader).invokeExact() as MutableMap<String, Long>
// data from core classloader
val coreStats = ClassPath.getLoadingStats()
if (coreStats.get("identity") != stats.get("identity")) {
for (entry in coreStats.entries) {
val v1 = stats.getValue(entry.key)
if (v1 != entry.value) {
stats.put(entry.key, v1 + entry.value)
}
}
}
return stats
}
override fun writeTotalDuration(writer: JsonGenerator, end: Long, timeOffset: Long): Long {
val totalDurationActual = super.writeTotalDuration(writer, end, timeOffset)
publicStatMetrics.put("totalDuration", totalDurationActual.toInt())
return totalDurationActual
}
override fun beforeActivityWrite(item: ActivityImpl, ownOrTotalDuration: Long, fieldName: String) {
item.pluginId?.let {
StartUpMeasurer.doAddPluginCost(it, item.category?.name ?: "unknown", ownOrTotalDuration, pluginCostMap)
}
if (fieldName == "items") {
when (val itemName = item.name) {
"splash initialization" -> {
publicStatMetrics["splash"] = TimeUnit.NANOSECONDS.toMillis(ownOrTotalDuration).toInt()
}
"bootstrap", "app initialization" -> {
publicStatMetrics[itemName] = TimeUnit.NANOSECONDS.toMillis(ownOrTotalDuration).toInt()
}
"project frame initialization" -> {
publicStatMetrics["projectFrameVisible"] = TimeUnit.NANOSECONDS.toMillis(item.start - StartUpMeasurer.getStartTime()).toInt()
}
}
}
}
}
private fun writeIcons(writer: JsonGenerator) {
writer.array("icons") {
for (stat in IconLoadMeasurer.getStats()) {
writer.obj {
writer.writeStringField("name", stat.name)
writer.writeNumberField("count", stat.count)
writer.writeNumberField("time", TimeUnit.NANOSECONDS.toMillis(stat.totalDuration))
}
}
}
}
private fun safeHashValue(value: String): String {
val generator = Argon2BytesGenerator()
generator.init(Argon2Parameters.Builder(Argon2Parameters.ARGON2_id).build())
// 160 bit is enough for uniqueness
val result = ByteArray(20)
generator.generateBytes(value.toByteArray(), result, 0, result.size)
return Base64.getEncoder().withoutPadding().encodeToString(result)
}
private fun writeServiceStats(writer: JsonGenerator) {
class StatItem(val name: String) {
var app = 0
var project = 0
var module = 0
}
// components can be inferred from data, but to verify that items reported correctly (and because for items threshold is applied (not all are reported))
val component = StatItem("component")
val service = StatItem("service")
val pluginSet = PluginManagerCore.getPluginSet()
for (plugin in pluginSet.getEnabledModules()) {
service.app += plugin.appContainerDescriptor.services.size
service.project += plugin.projectContainerDescriptor.services.size
service.module += plugin.moduleContainerDescriptor.services.size
component.app += plugin.appContainerDescriptor.components?.size ?: 0
component.project += plugin.projectContainerDescriptor.components?.size ?: 0
component.module += plugin.moduleContainerDescriptor.components?.size ?: 0
}
writer.obj("stats") {
writer.writeNumberField("plugin", pluginSet.enabledPlugins.size)
for (statItem in listOf(component, service)) {
writer.obj(statItem.name) {
writer.writeNumberField("app", statItem.app)
writer.writeNumberField("project", statItem.project)
writer.writeNumberField("module", statItem.module)
}
}
}
writer.array("plugins") {
for (plugin in pluginSet.enabledPlugins) {
val classLoader = plugin.pluginClassLoader as? PluginAwareClassLoader ?: continue
if (classLoader.loadedClassCount == 0L) {
continue
}
writer.obj {
writer.writeStringField("id", plugin.pluginId.idString)
writer.writeNumberField("classCount", classLoader.loadedClassCount)
writer.writeNumberField("classLoadingEdtTime", TimeUnit.NANOSECONDS.toMillis(classLoader.edtTime))
writer.writeNumberField("classLoadingBackgroundTime", TimeUnit.NANOSECONDS.toMillis(classLoader.backgroundTime))
}
}
}
} | apache-2.0 | afbf10d5bebe27cccf2222fd6dbdbab1 | 40.808824 | 165 | 0.728893 | 4.724654 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/domain/course_search/analytic/CourseContentSearchedAnalyticEvent.kt | 1 | 871 | package org.stepik.android.domain.course_search.analytic
import org.stepik.android.domain.base.analytic.AnalyticEvent
import ru.nobird.app.core.model.mapOfNotNull
class CourseContentSearchedAnalyticEvent(
val courseId: Long,
val courseTitle: String,
val query: String,
val suggestion: String? = null
) : AnalyticEvent {
companion object {
private const val PARAM_COURSE = "course"
private const val PARAM_TITLE = "title"
private const val PARAM_QUERY = "query"
private const val PARAM_SUGGESTION = "suggestion"
}
override val name: String =
"Course content searched"
override val params: Map<String, Any> =
mapOfNotNull(
PARAM_COURSE to courseId,
PARAM_TITLE to courseTitle,
PARAM_QUERY to query,
PARAM_SUGGESTION to suggestion
)
} | apache-2.0 | 78ce574ddfec69de6f00acf7f92dab36 | 29.068966 | 60 | 0.668197 | 4.536458 | false | false | false | false |
zpao/buck | src/com/facebook/buck/multitenant/query/FsAgnosticSourcePath.kt | 1 | 1717 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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.facebook.buck.multitenant.query
import com.facebook.buck.core.path.ForwardRelativePath
import com.facebook.buck.core.sourcepath.SourcePath
import com.facebook.buck.multitenant.fs.FsAgnosticPath
/**
* Implementation of [SourcePath] that makes sense in the context of
* `com.facebook.buck.multitenant`. It is designed to be used with
* [com.facebook.buck.query.QueryFileTarget].
*/
data class FsAgnosticSourcePath(private val path: ForwardRelativePath) : SourcePath {
companion object {
/**
* @param path must be a normalized, relative path.
*/
fun of(path: String): FsAgnosticSourcePath = FsAgnosticSourcePath(FsAgnosticPath.of(path))
}
override fun compareTo(other: SourcePath): Int {
if (this === other) {
return 0
}
val classComparison = compareClasses(other)
if (classComparison != 0) {
return classComparison
}
val that = other as FsAgnosticSourcePath
return path.compareTo(that.path)
}
override fun toString(): String = path.toString()
}
| apache-2.0 | 1653dc2c4c7da600929e1375338b8e84 | 32.666667 | 98 | 0.699476 | 4.31407 | false | false | false | false |
pokk/MusicDiskPlayer | musicdiskplayer/src/main/java/com/devrapid/musicdiskplayer/RotatedCircleImageView.kt | 1 | 4764 | package com.devrapid.musicdiskplayer
import android.animation.ObjectAnimator
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.LinearInterpolator
import com.mikhaellopez.circularimageview.CircularImageView
/**
* [CircleImageView] with rotated animation.
*
* @author jieyi
* @since 7/4/17
*/
open class RotatedCircleImageView
@JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0):
CircularImageView(context, attrs, defStyleAttr) {
companion object {
private const val ONE_ROUND_ROTATE_TIME = 10
private const val TIME_MILLION = 1000L
private const val A_CIRCLE_ANGEL = 360f
}
//region Variables of setting
var onClickCallback: ((RotatedCircleImageView) -> Unit)? = null
// Basically this's that controlling the rotating speed.
var oneRoundTime = ONE_ROUND_ROTATE_TIME.toLong()
private set(value) {
field = value * TIME_MILLION
}
var isPauseState = false
//endregion
private val rotateAnimator by lazy {
ObjectAnimator.ofFloat(this, "rotation", 0f, A_CIRCLE_ANGEL).apply {
interpolator = LinearInterpolator()
duration = oneRoundTime
repeatCount = Animation.INFINITE
}
}
init {
context.obtainStyledAttributes(attrs, R.styleable.RotatedCircleImageView, defStyleAttr, 0).also {
oneRoundTime = it.getInteger(R.styleable.RotatedCircleImageView_rotate_sec, ONE_ROUND_ROTATE_TIME).toLong()
}.recycle()
setOnClickListener {
rotateAnimator.let {
isPauseState = when {
!it.isStarted -> {
it.start()
false
}
it.isPaused -> {
it.resume()
false
}
it.isRunning -> {
it.pause()
true
}
else -> true
}
}
onClickCallback?.let { it(this@RotatedCircleImageView) }
}
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val square = minOf(ViewGroup.getDefaultSize(suggestedMinimumWidth, widthMeasureSpec),
ViewGroup.getDefaultSize(suggestedMinimumHeight, heightMeasureSpec))
setMeasuredDimension(square, square)
}
override fun onTouchEvent(e: MotionEvent): Boolean {
when (e.action) {
// Checking the clicking is inside of circle imageview.
MotionEvent.ACTION_DOWN -> return isInCircleRange(e.x, e.y)
MotionEvent.ACTION_UP -> {
if (isInCircleRange(e.x, e.y)) {
// After confirming the clicking is inside of the image.
performClick()
return true
}
}
}
return false
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
onClickCallback = null
}
/**
* Start the rotating animation of the circle image.
*/
fun start() {
// According to the state then start the animation.
if (!rotateAnimator.isStarted) {
rotateAnimator.start()
}
else if (rotateAnimator.isPaused) {
rotateAnimator.resume()
}
else {
return
}
isPauseState = false
}
/**
* Stop the rotating animation of the circle image.
*/
fun stop() {
if (rotateAnimator.isRunning) {
rotateAnimator.pause()
isPauseState = true
}
}
/**
* Check the position [x] & [y] is inside the circle.
*
* @param x x-coordination.
* @param y y-coordination.
* @return [true] if the position of clicking is in the circle range ; otherwise [false].
*/
private fun isInCircleRange(x: Float, y: Float): Boolean =
width / 2 > distance(x, y, pivotX, pivotY)
/**
* Calculating the distance between two positions.
*
* @param sX a position's x-coordination.
* @param sY a position's y-coordination.
* @param eX another position's x-coordination.
* @param eY another position's y-coordination.
* @return the distance length.
*/
private fun distance(sX: Float, sY: Float, eX: Float, eY: Float): Double =
Math.sqrt(Math.pow((sX - eX).toDouble(), 2.0) + Math.pow((sY - eY).toDouble(), 2.0))
} | apache-2.0 | fa8d6d8af845434e03513f5d27624e29 | 30.556291 | 119 | 0.586692 | 4.856269 | false | false | false | false |
leafclick/intellij-community | plugins/built-in-help/src/com/jetbrains/builtInHelp/search/HelpIndexProcessor.kt | 1 | 1600 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.builtInHelp.search
import org.apache.commons.compress.utils.IOUtils
import org.apache.lucene.analysis.standard.StandardAnalyzer
import org.apache.lucene.store.FSDirectory
import org.jetbrains.annotations.NotNull
import java.io.FileOutputStream
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
abstract class HelpIndexProcessor {
companion object {
val resources = arrayOf("_0.cfe", "_0.cfs", "_0.si", "segments_1")
val STORAGE_PREFIX = "/search/"
val EMPTY_RESULT = "[]"
}
val analyzer: StandardAnalyzer = StandardAnalyzer()
fun deployIndex(): FSDirectory? {
val indexDir: Path? = Files.createTempDirectory("search-index")
var result: FSDirectory? = null
if (indexDir != null) {
for (resourceName in resources) {
val input = HelpSearch::class.java.getResourceAsStream(
STORAGE_PREFIX + resourceName)
val fos: FileOutputStream = FileOutputStream(Paths.get(indexDir.toAbsolutePath().toString(), resourceName).toFile())
IOUtils.copy(input, fos)
fos.flush()
fos.close()
input.close()
}
result = FSDirectory.open(indexDir)
}
return result
}
fun releaseIndex(indexDirectory: FSDirectory) {
val path = indexDirectory.directory
for (f in path.toFile().listFiles()) f.delete()
Files.delete(path)
}
@NotNull
abstract fun process(query: String, maxResults: Int): String
} | apache-2.0 | 4a05461ced0c014302bd45557f6174a1 | 31.02 | 140 | 0.706875 | 4.145078 | false | false | false | false |
zdary/intellij-community | plugins/devkit/devkit-core/src/util/ExtensionLocator.kt | 3 | 4764 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.devkit.util
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiClass
import com.intellij.psi.SmartPointerManager
import com.intellij.psi.search.PsiSearchHelper
import com.intellij.psi.search.UsageSearchContext
import com.intellij.psi.util.ClassUtil
import com.intellij.psi.xml.XmlTag
import com.intellij.util.SmartList
import com.intellij.util.xml.DomManager
import org.jetbrains.idea.devkit.dom.Extension
import org.jetbrains.idea.devkit.dom.ExtensionPoint
import java.util.*
fun locateExtensionsByPsiClass(psiClass: PsiClass): List<ExtensionCandidate> {
return findExtensionsByClassName(psiClass.project, ClassUtil.getJVMClassName(psiClass) ?: return emptyList())
}
fun locateExtensionsByExtensionPoint(extensionPoint: ExtensionPoint): List<ExtensionCandidate> {
return ExtensionByExtensionPointLocator(extensionPoint.xmlTag.project, extensionPoint, null).findCandidates()
}
fun locateExtensionsByExtensionPointAndId(extensionPoint: ExtensionPoint, extensionId: String): ExtensionLocator {
return ExtensionByExtensionPointLocator(extensionPoint.xmlTag.project, extensionPoint, extensionId)
}
internal fun processExtensionDeclarations(name: String, project: Project, strictMatch: Boolean = true, callback: (Extension, XmlTag) -> Boolean) {
val scope = PluginRelatedLocatorsUtils.getCandidatesScope(project)
val searchWord = name.substringBeforeLast('$')
if (searchWord.isEmpty()) return
PsiSearchHelper.getInstance(project).processElementsWithWord(
{ element, offsetInElement ->
val elementAtOffset = (element as? XmlTag)?.findElementAt(offsetInElement) ?: return@processElementsWithWord true
if (strictMatch) {
if (!elementAtOffset.textMatches(name)) {
return@processElementsWithWord true
}
}
else if (!StringUtil.contains(elementAtOffset.text, name)) {
return@processElementsWithWord true
}
val extension = DomManager.getDomManager(project).getDomElement(element) as? Extension ?: return@processElementsWithWord true
callback(extension, element)
}, scope, searchWord, UsageSearchContext.IN_FOREIGN_LANGUAGES, /* case-sensitive = */ true)
}
private fun findExtensionsByClassName(project: Project, className: String): List<ExtensionCandidate> {
val result = Collections.synchronizedList(SmartList<ExtensionCandidate>())
val smartPointerManager by lazy { SmartPointerManager.getInstance(project) }
processExtensionsByClassName(project, className) { tag, _ ->
result.add(ExtensionCandidate(smartPointerManager.createSmartPsiElementPointer(tag)))
true
}
return result
}
internal inline fun processExtensionsByClassName(project: Project, className: String, crossinline processor: (XmlTag, ExtensionPoint) -> Boolean) {
processExtensionDeclarations(className, project) { extension, tag ->
extension.extensionPoint?.let { processor(tag, it) } ?: true
}
}
internal class ExtensionByExtensionPointLocator(private val project: Project,
extensionPoint: ExtensionPoint,
private val extensionId: String?) : ExtensionLocator() {
private val pointQualifiedName = extensionPoint.effectiveQualifiedName
private fun processCandidates(processor: (XmlTag) -> Boolean) {
// We must search for the last part of EP name, because for instance 'com.intellij.console.folding' extension
// may be declared as <extensions defaultExtensionNs="com"><intellij.console.folding ...
val epNameToSearch = StringUtil.substringAfterLast(pointQualifiedName, ".") ?: return
processExtensionDeclarations(epNameToSearch, project, false /* not strict match */) { extension, tag ->
val ep = extension.extensionPoint ?: return@processExtensionDeclarations true
if (ep.effectiveQualifiedName == pointQualifiedName && (extensionId == null || extensionId == extension.id.stringValue)) {
// stop after the first found candidate if ID is specified
processor(tag) && extensionId == null
}
else {
true
}
}
}
override fun findCandidates(): List<ExtensionCandidate> {
val result = Collections.synchronizedList(SmartList<ExtensionCandidate>())
val smartPointerManager by lazy { SmartPointerManager.getInstance(project) }
processCandidates {
result.add(ExtensionCandidate(smartPointerManager.createSmartPsiElementPointer(it)))
}
return result
}
}
sealed class ExtensionLocator {
abstract fun findCandidates(): List<ExtensionCandidate>
} | apache-2.0 | e119c4aaa153fd4a9c8664963f93dae4 | 46.65 | 147 | 0.759446 | 5.195202 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/ranges/literal/inexactToMaxValue.kt | 2 | 2219 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS
// TODO: muted automatically, investigate should it be ran for NATIVE or not
// IGNORE_BACKEND: NATIVE
// Auto-generated by org.jetbrains.kotlin.generators.tests.GenerateRangesCodegenTestData. DO NOT EDIT!
// WITH_RUNTIME
import java.lang.Integer.MAX_VALUE as MaxI
import java.lang.Integer.MIN_VALUE as MinI
import java.lang.Byte.MAX_VALUE as MaxB
import java.lang.Byte.MIN_VALUE as MinB
import java.lang.Short.MAX_VALUE as MaxS
import java.lang.Short.MIN_VALUE as MinS
import java.lang.Long.MAX_VALUE as MaxL
import java.lang.Long.MIN_VALUE as MinL
import java.lang.Character.MAX_VALUE as MaxC
import java.lang.Character.MIN_VALUE as MinC
fun box(): String {
val list1 = ArrayList<Int>()
for (i in (MaxI - 5)..MaxI step 3) {
list1.add(i)
if (list1.size > 23) break
}
if (list1 != listOf<Int>(MaxI - 5, MaxI - 2)) {
return "Wrong elements for (MaxI - 5)..MaxI step 3: $list1"
}
val list2 = ArrayList<Int>()
for (i in (MaxB - 5).toByte()..MaxB step 3) {
list2.add(i)
if (list2.size > 23) break
}
if (list2 != listOf<Int>((MaxB - 5).toInt(), (MaxB - 2).toInt())) {
return "Wrong elements for (MaxB - 5).toByte()..MaxB step 3: $list2"
}
val list3 = ArrayList<Int>()
for (i in (MaxS - 5).toShort()..MaxS step 3) {
list3.add(i)
if (list3.size > 23) break
}
if (list3 != listOf<Int>((MaxS - 5).toInt(), (MaxS - 2).toInt())) {
return "Wrong elements for (MaxS - 5).toShort()..MaxS step 3: $list3"
}
val list4 = ArrayList<Long>()
for (i in (MaxL - 5).toLong()..MaxL step 3) {
list4.add(i)
if (list4.size > 23) break
}
if (list4 != listOf<Long>((MaxL - 5).toLong(), (MaxL - 2).toLong())) {
return "Wrong elements for (MaxL - 5).toLong()..MaxL step 3: $list4"
}
val list5 = ArrayList<Char>()
for (i in (MaxC - 5)..MaxC step 3) {
list5.add(i)
if (list5.size > 23) break
}
if (list5 != listOf<Char>((MaxC - 5), (MaxC - 2))) {
return "Wrong elements for (MaxC - 5)..MaxC step 3: $list5"
}
return "OK"
}
| apache-2.0 | 49ab763294a99fef6f83ea9aaf591f4e | 31.15942 | 102 | 0.607932 | 3.229985 | false | false | false | false |
exponent/exponent | packages/expo-image-manipulator/android/src/main/java/expo/modules/imagemanipulator/arguments/SaveOptions.kt | 2 | 910 | package expo.modules.imagemanipulator.arguments
import expo.modules.core.arguments.ReadableArguments
import android.graphics.Bitmap.CompressFormat
private const val KEY_BASE64 = "base64"
private const val KEY_COMPRESS = "compress"
private const val KEY_FORMAT = "format"
data class SaveOptions(
val base64: Boolean,
val compress: Double,
val format: CompressFormat
) {
companion object {
fun fromArguments(arguments: ReadableArguments): SaveOptions {
val base64 = arguments.getBoolean(KEY_BASE64, false)
val compress = arguments.getDouble(KEY_COMPRESS, 1.0)
val format = toCompressFormat(arguments.getString(KEY_FORMAT, "jpeg"))
return SaveOptions(base64, compress, format)
}
}
}
fun toCompressFormat(format: String): CompressFormat {
return when (format) {
"jpeg" -> CompressFormat.JPEG
"png" -> CompressFormat.PNG
else -> CompressFormat.JPEG
}
}
| bsd-3-clause | 1b054f12009361b8bb87b6e4c9ecd543 | 28.354839 | 76 | 0.737363 | 4.099099 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/RemoveNullableFix.kt | 1 | 2707 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtNullableType
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
class RemoveNullableFix(
element: KtNullableType,
private val typeOfError: NullableKind
) : KotlinQuickFixAction<KtNullableType>(element) {
enum class NullableKind(@Nls val message: String) {
REDUNDANT(KotlinBundle.message("remove.redundant")),
SUPERTYPE(KotlinBundle.message("text.remove.question")),
USELESS(KotlinBundle.message("remove.useless")),
PROPERTY(KotlinBundle.message("make.not.nullable"))
}
override fun getFamilyName() = KotlinBundle.message("text.remove.question")
override fun getText() = typeOfError.message
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val type = element.innerType ?: error("No inner type " + element.text + ", should have been rejected in createFactory()")
element.replace(type)
}
class Factory(private val typeOfError: NullableKind) : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtNullableType>? {
val nullType = diagnostic.psiElement.getNonStrictParentOfType<KtNullableType>()
if (nullType?.innerType == null) return null
return RemoveNullableFix(nullType, typeOfError)
}
}
object LATEINIT_FACTORY : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtNullableType>? {
val lateinitElement = Errors.INAPPLICABLE_LATEINIT_MODIFIER.cast(diagnostic).psiElement
val property = lateinitElement.getStrictParentOfType<KtProperty>() ?: return null
val typeReference = property.typeReference ?: return null
val typeElement = (typeReference.typeElement ?: return null) as? KtNullableType ?: return null
if (typeElement.innerType == null) return null
return RemoveNullableFix(typeElement, NullableKind.PROPERTY)
}
}
}
| apache-2.0 | fdc2486a1c210b24cd810828812bb666 | 47.339286 | 158 | 0.741411 | 4.966972 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/jvm-debugger/eval4j/src/org/jetbrains/eval4j/jdi/jdiValues.kt | 6 | 4028 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.eval4j.jdi
import com.sun.jdi.ClassObjectReference
import com.sun.jdi.VirtualMachine
import org.jetbrains.eval4j.*
import org.jetbrains.org.objectweb.asm.Opcodes.ACC_STATIC
import org.jetbrains.org.objectweb.asm.Type
import org.jetbrains.org.objectweb.asm.tree.MethodNode
import org.jetbrains.org.objectweb.asm.tree.analysis.Frame
import com.sun.jdi.BooleanValue as jdi_BooleanValue
import com.sun.jdi.ByteValue as jdi_ByteValue
import com.sun.jdi.CharValue as jdi_CharValue
import com.sun.jdi.DoubleValue as jdi_DoubleValue
import com.sun.jdi.FloatValue as jdi_FloatValue
import com.sun.jdi.IntegerValue as jdi_IntegerValue
import com.sun.jdi.LongValue as jdi_LongValue
import com.sun.jdi.ObjectReference as jdi_ObjectReference
import com.sun.jdi.ShortValue as jdi_ShortValue
import com.sun.jdi.Type as jdi_Type
import com.sun.jdi.Value as jdi_Value
import com.sun.jdi.VoidValue as jdi_VoidValue
fun makeInitialFrame(methodNode: MethodNode, arguments: List<Value>): Frame<Value> {
val isStatic = (methodNode.access and ACC_STATIC) != 0
val params = Type.getArgumentTypes(methodNode.desc)
assert(arguments.size == (if (isStatic) params.size else params.size + 1)) {
"Wrong number of arguments for $methodNode: $arguments"
}
val frame = Frame<Value>(methodNode.maxLocals, methodNode.maxStack)
frame.setReturn(makeNotInitializedValue(Type.getReturnType(methodNode.desc)))
var index = 0
for (arg in arguments) {
frame.setLocal(index++, arg)
if (arg.size == 2) {
frame.setLocal(index++, NOT_A_VALUE)
}
}
while (index < methodNode.maxLocals) {
frame.setLocal(index++, NOT_A_VALUE)
}
return frame
}
class JDIFailureException(message: String?, cause: Throwable? = null) : RuntimeException(message, cause)
fun jdi_ObjectReference?.asValue(): ObjectValue {
return when (this) {
null -> NULL_VALUE
else -> ObjectValue(this, type().asType())
}
}
fun jdi_Value?.asValue(): Value {
return when (this) {
null -> NULL_VALUE
is jdi_VoidValue -> VOID_VALUE
is jdi_BooleanValue -> IntValue(intValue(), Type.BOOLEAN_TYPE)
is jdi_ByteValue -> IntValue(intValue(), Type.BYTE_TYPE)
is jdi_ShortValue -> IntValue(intValue(), Type.SHORT_TYPE)
is jdi_CharValue -> IntValue(intValue(), Type.CHAR_TYPE)
is jdi_IntegerValue -> IntValue(intValue(), Type.INT_TYPE)
is jdi_LongValue -> LongValue(longValue())
is jdi_FloatValue -> FloatValue(floatValue())
is jdi_DoubleValue -> DoubleValue(doubleValue())
is jdi_ObjectReference -> this.asValue()
else -> throw JDIFailureException("Unknown value: $this")
}
}
fun jdi_Type.asType(): Type = Type.getType(this.signature())
val Value.jdiObj: jdi_ObjectReference?
get() = this.obj() as jdi_ObjectReference?
val Value.jdiClass: ClassObjectReference?
get() = this.jdiObj as ClassObjectReference?
fun Value.asJdiValue(vm: VirtualMachine, expectedType: Type): jdi_Value? {
return when (this) {
NULL_VALUE -> null
VOID_VALUE -> vm.mirrorOfVoid()
is IntValue -> when (expectedType) {
Type.BOOLEAN_TYPE -> vm.mirrorOf(boolean)
Type.BYTE_TYPE -> vm.mirrorOf(int.toByte())
Type.SHORT_TYPE -> vm.mirrorOf(int.toShort())
Type.CHAR_TYPE -> vm.mirrorOf(int.toChar())
Type.INT_TYPE -> vm.mirrorOf(int)
else -> throw JDIFailureException("Unknown value type: $this")
}
is LongValue -> vm.mirrorOf(value)
is FloatValue -> vm.mirrorOf(value)
is DoubleValue -> vm.mirrorOf(value)
is ObjectValue -> value as jdi_ObjectReference
is NewObjectValue -> this.obj() as jdi_ObjectReference
else -> throw JDIFailureException("Unknown value: $this")
}
} | apache-2.0 | 490451942b3443936774385639ee8969 | 37.740385 | 158 | 0.690417 | 3.960669 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/projectModel/Model.kt | 1 | 6044 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.projectModel
import com.intellij.openapi.roots.libraries.PersistentLibraryKind
import org.jetbrains.kotlin.idea.base.platforms.KotlinCommonLibraryKind
import org.jetbrains.kotlin.idea.base.platforms.KotlinJavaScriptLibraryKind
import org.jetbrains.kotlin.idea.base.plugin.artifacts.TestKotlinArtifacts
import org.jetbrains.kotlin.idea.test.IDEA_TEST_DATA_DIR
import org.jetbrains.kotlin.platform.CommonPlatforms
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.js.JsPlatforms
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
import org.jetbrains.kotlin.utils.Printer
import java.io.File
open class ProjectResolveModel(val modules: List<ResolveModule>) {
open class Builder {
val modules: MutableList<ResolveModule.Builder> = mutableListOf()
open fun build(): ProjectResolveModel = ProjectResolveModel(modules.map { it.build() })
}
}
open class ResolveModule(
val name: String,
val root: File,
val platform: TargetPlatform,
val dependencies: List<ResolveDependency>,
val testRoot: File? = null,
val additionalCompilerArgs: String? = null
) {
final override fun toString(): String {
return buildString { renderDescription(Printer(this)) }
}
open fun renderDescription(printer: Printer) {
printer.println("Module $name")
printer.pushIndent()
printer.println("platform=$platform")
printer.println("root=${root.absolutePath}")
if (testRoot != null) printer.println("testRoot=${testRoot.absolutePath}")
printer.println("dependencies=${dependencies.joinToString { it.to.name }}")
if (additionalCompilerArgs != null) printer.println("additionalCompilerArgs=$additionalCompilerArgs")
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as ResolveModule
if (name != other.name) return false
return true
}
override fun hashCode(): Int {
return name.hashCode()
}
open class Builder {
private var state: State = State.NOT_BUILT
private var cachedResult: ResolveModule? = null
var name: String? = null
var root: File? = null
var platform: TargetPlatform? = null
val dependencies: MutableList<ResolveDependency.Builder> = mutableListOf()
var testRoot: File? = null
var additionalCompilerArgs: String? = null
open fun build(): ResolveModule {
if (state == State.BUILT) return cachedResult!!
require(state == State.NOT_BUILT) { "Re-building module $this with name $name (root at $root)" }
state = State.BUILDING
val builtDependencies = dependencies.map { it.build() }
cachedResult = ResolveModule(name!!, root!!, platform!!, builtDependencies, testRoot, additionalCompilerArgs= additionalCompilerArgs)
state = State.BUILT
return cachedResult!!
}
enum class State {
NOT_BUILT,
BUILDING,
BUILT
}
}
}
sealed class ResolveLibrary(
name: String,
root: File,
platform: TargetPlatform,
val kind: PersistentLibraryKind<*>?
) : ResolveModule(name, root, platform, emptyList()) {
class Builder(val target: ResolveLibrary) : ResolveModule.Builder() {
override fun build(): ResolveModule = target
}
}
sealed class Stdlib(
name: String,
root: File,
platform: TargetPlatform,
kind: PersistentLibraryKind<*>?
) : ResolveLibrary(name, root, platform, kind) {
object CommonStdlib : Stdlib(
"stdlib-common",
TestKotlinArtifacts.kotlinStdlibCommon,
CommonPlatforms.defaultCommonPlatform,
KotlinCommonLibraryKind
)
object JvmStdlib : Stdlib(
"stdlib-jvm",
TestKotlinArtifacts.kotlinStdlib,
JvmPlatforms.defaultJvmPlatform,
null
)
object JsStdlib : Stdlib(
"stdlib-js",
TestKotlinArtifacts.kotlinStdlibJs,
JsPlatforms.defaultJsPlatform,
KotlinJavaScriptLibraryKind
)
}
sealed class KotlinTest(
name: String,
root: File,
platform: TargetPlatform,
kind: PersistentLibraryKind<*>?
) : ResolveLibrary(name, root, platform, kind) {
object JsKotlinTest : KotlinTest(
"kotlin-test-js",
TestKotlinArtifacts.kotlinTestJs,
JsPlatforms.defaultJsPlatform,
KotlinJavaScriptLibraryKind
)
object JvmKotlinTest : KotlinTest(
"kotlin-test-jvm",
TestKotlinArtifacts.kotlinTestJunit,
JvmPlatforms.defaultJvmPlatform,
null
)
object JustKotlinTest : KotlinTest(
"kotlin-test",
TestKotlinArtifacts.kotlinTest,
JvmPlatforms.defaultJvmPlatform,
null
)
object Junit : KotlinTest(
"junit",
File("$IDEA_TEST_DATA_DIR/lib/junit-4.12.jar"),
JvmPlatforms.defaultJvmPlatform,
null
)
}
interface ResolveSdk
object FullJdk : ResolveLibrary(
"full-jdk",
File("fake file for full jdk"),
JvmPlatforms.defaultJvmPlatform,
null
), ResolveSdk
object MockJdk : ResolveLibrary(
"mock-jdk",
File("fake file for mock jdk"),
JvmPlatforms.defaultJvmPlatform,
null
), ResolveSdk
object KotlinSdk : ResolveLibrary(
"kotlin-sdk",
File("fake file for kotlin sdk"),
CommonPlatforms.defaultCommonPlatform,
null,
), ResolveSdk
open class ResolveDependency(val to: ResolveModule, val kind: Kind) {
open class Builder {
var to: ResolveModule.Builder = ResolveModule.Builder()
var kind: Kind? = null
open fun build(): ResolveDependency = ResolveDependency(to.build(), kind!!)
}
enum class Kind {
DEPENDS_ON,
DEPENDENCY,
}
} | apache-2.0 | ba7475010cea3fa28ea7de2ffef94c8e | 28.34466 | 158 | 0.673561 | 4.913821 | false | true | false | false |
dpisarenko/econsim-tr01 | src/test/java/cc/altruix/econsimtr01/ch0201/Sim3Tests.kt | 1 | 2331 | /*
* Copyright 2012-2016 Dmitri Pisarenko
*
* WWW: http://altruix.cc
* E-Mail: [email protected]
* Skype: dp118m (voice calls must be scheduled in advance)
*
* Physical address:
*
* 4-i Rostovskii pereulok 2/1/20
* 119121 Moscow
* Russian Federation
*
* This file is part of econsim-tr01.
*
* econsim-tr01 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.
*
* econsim-tr01 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 econsim-tr01. If not, see <http://www.gnu.org/licenses/>.
*
*/
package cc.altruix.econsimtr01.ch0201
import cc.altruix.econsimtr01.ResourceFlow
import cc.altruix.econsimtr01.shouldBe
import cc.altruix.econsimtr01.simulationRunLogic
import org.junit.Test
import java.io.File
import java.util.*
/**
* Created by pisarenko on 18.04.2016.
*/
class Sim3Tests {
@Test
fun test() {
val flows = LinkedList<ResourceFlow>()
val log = StringBuilder()
val simParametersProvider = Sim3ParametersProvider(
File("src/test/resources/ch0201Sim3Tests.params.pl").readText()
)
val sim = Sim3(
log,
flows,
simParametersProvider
)
simulationRunLogic(sim,
log,
simParametersProvider.resources,
flows,
"src/test/resources/ch0201/sim03/Sim3Tests.test.pl.expected.txt",
"src/test/resources/ch0201/sim03/Sim3Tests.test.csv.expected.txt",
"src/test/resources/ch0201/sim03/Sim3Tests.test.flows.actual.png",
Sim2TimeSeriesCreator()
)
}
@Test
fun flowF8IsCreated() {
val simParametersProvider = Sim3ParametersProvider(
File("src/test/resources/ch0201Sim3Tests.params.pl").readText()
)
simParametersProvider.flows.filter { it.id == "f8" }.count().shouldBe(1)
}
} | gpl-3.0 | ab4ba65b0f1fab4dec2d56febd64ac88 | 30.945205 | 82 | 0.659374 | 3.991438 | false | true | false | false |
dkrivoruchko/ScreenStream | mjpeg/src/main/kotlin/info/dvkr/screenstream/mjpeg/state/helper/NetworkHelper.kt | 1 | 4954 | package info.dvkr.screenstream.mjpeg.state.helper
import android.annotation.SuppressLint
import android.content.Context
import android.content.res.Resources
import android.net.wifi.WifiManager
import androidx.core.content.ContextCompat
import com.elvishew.xlog.XLog
import info.dvkr.screenstream.common.getLog
import info.dvkr.screenstream.mjpeg.NetInterface
import java.net.*
import java.util.*
@SuppressLint("WifiManagerPotentialLeak")
class NetworkHelper(context: Context) {
private val networkInterfaceCommonNameArray =
arrayOf("lo", "eth", "lan", "wlan", "en", "p2p", "net", "ppp", "wigig", "ap", "rmnet", "rmnet_data")
private val defaultWifiRegexArray: Array<Regex> = arrayOf(
Regex("wlan\\d"),
Regex("ap\\d"),
Regex("wigig\\d"),
Regex("softap\\.?\\d")
)
@SuppressLint("DiscouragedApi")
private val wifiRegexArray: Array<Regex> =
Resources.getSystem().getIdentifier("config_tether_wifi_regexs", "array", "android").let { tetherId ->
context.applicationContext.resources.getStringArray(tetherId).map { it.toRegex() }.toTypedArray()
}
private val wifiManager: WifiManager = ContextCompat.getSystemService(context, WifiManager::class.java)!!
private fun getNetworkInterfacesWithFallBack(): Enumeration<NetworkInterface> {
try {
return NetworkInterface.getNetworkInterfaces()
} catch (ex: Exception) {
XLog.w(getLog("getNetworkInterfacesWithFallBack.getNetworkInterfaces", ex.toString()))
}
val netList = mutableListOf<NetworkInterface>()
(0..7).forEach { index ->
try {
val networkInterface: NetworkInterface? = NetworkInterface.getByIndex(index)
if (networkInterface != null) netList.add(networkInterface)
else if (index > 3) {
if (netList.isNotEmpty()) return Collections.enumeration(netList)
return@forEach
}
} catch (ex: SocketException) {
XLog.e(getLog("getNetworkInterfacesWithFallBack.getByIndex#$index:", ex.toString()))
}
}
networkInterfaceCommonNameArray.forEach { commonName ->
try {
val networkInterface: NetworkInterface? = NetworkInterface.getByName(commonName)
if (networkInterface != null) netList.add(networkInterface)
(0..15).forEach { index ->
val networkInterfaceIndexed: NetworkInterface? = NetworkInterface.getByName("$commonName$index")
if (networkInterfaceIndexed != null) netList.add(networkInterfaceIndexed)
}
} catch (ex: SocketException) {
XLog.e(getLog("getNetworkInterfacesWithFallBack.commonName#$commonName:", ex.toString()))
}
}
return Collections.enumeration(netList)
}
fun getNetInterfaces(
useWiFiOnly: Boolean, enableIPv6: Boolean, enableLocalHost: Boolean, localHostOnly: Boolean
): List<NetInterface> {
XLog.d(getLog("getNetInterfaces", "Invoked"))
val netInterfaceList = mutableListOf<NetInterface>()
getNetworkInterfacesWithFallBack().asSequence()
.flatMap { networkInterface ->
networkInterface.inetAddresses.asSequence().filterNotNull()
.filter { !it.isLinkLocalAddress && !it.isMulticastAddress }
.filter { enableLocalHost || it.isLoopbackAddress.not() }
.filter { localHostOnly.not() || it.isLoopbackAddress }
.filter { (it is Inet4Address) || (enableIPv6 && (it is Inet6Address)) }
.map { if (it is Inet6Address) Inet6Address.getByAddress(it.address) else it }
.map { NetInterface(networkInterface.displayName, it) }
}
.filter { netInterface ->
(enableLocalHost && netInterface.address.isLoopbackAddress) || useWiFiOnly.not() || (
defaultWifiRegexArray.any { it.matches(netInterface.name) } ||
wifiRegexArray.any { it.matches(netInterface.name) }
)
}
.toCollection(netInterfaceList)
if (netInterfaceList.isEmpty() && wifiConnected()) netInterfaceList.add(getWiFiNetAddress())
return netInterfaceList
}
@Suppress("DEPRECATION")
private fun wifiConnected() = wifiManager.connectionInfo.ipAddress != 0
@Suppress("DEPRECATION")
private fun getWiFiNetAddress(): NetInterface {
XLog.d(getLog("getWiFiNetAddress", "Invoked"))
val ipInt = wifiManager.connectionInfo.ipAddress
val ipByteArray = ByteArray(4) { i -> (ipInt.shr(i * 8).and(255)).toByte() }
val inet4Address = InetAddress.getByAddress(ipByteArray) as Inet4Address
return NetInterface("wlan0", inet4Address)
}
} | mit | e61198e83a714bc5d2625854342b5c36 | 41.715517 | 116 | 0.633024 | 4.885602 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/KotlinInlinePropertyProcessor.kt | 3 | 8124 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.inline
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.psi.search.LocalSearchScope
import com.intellij.refactoring.HelpID
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.util.CommonRefactoringUtil
import com.intellij.usageView.UsageInfo
import com.intellij.util.containers.MultiMap
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeInliner.CodeToInline
import org.jetbrains.kotlin.idea.codeInliner.PropertyUsageReplacementStrategy
import org.jetbrains.kotlin.idea.codeInliner.UsageReplacementStrategy
import org.jetbrains.kotlin.idea.findUsages.ReferencesSearchScopeHelper
import org.jetbrains.kotlin.idea.references.readWriteAccess
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtBinaryExpression
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.psiUtil.getAssignmentByLHS
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis
import org.jetbrains.kotlin.resolve.references.ReferenceAccess
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class KotlinInlinePropertyProcessor(
declaration: KtProperty,
reference: PsiReference?,
inlineThisOnly: Boolean,
private val deleteAfter: Boolean,
private val isWhenSubjectVariable: Boolean,
editor: Editor?,
private val statementToDelete: KtBinaryExpression?,
project: Project,
) : AbstractKotlinInlineNamedDeclarationProcessor<KtProperty>(
declaration = declaration,
reference = reference,
inlineThisOnly = inlineThisOnly,
deleteAfter = deleteAfter && !isWhenSubjectVariable,
editor = editor,
project = project,
) {
override fun createReplacementStrategy(): UsageReplacementStrategy? {
return createReplacementStrategyForProperty(declaration, editor, myProject)
}
override fun postAction() {
if (deleteAfter && isWhenSubjectVariable && declaration.isWritable) {
declaration.initializer?.let { declaration.replace(it) }
}
}
override fun postDeleteAction() {
statementToDelete?.delete()
}
override fun additionalPreprocessUsages(usages: Array<out UsageInfo>, conflicts: MultiMap<PsiElement, String>) {
val initializer by lazy { extractInitialization(declaration).initializerOrNull?.assignment?.left }
for (usage in usages) {
val expression = usage.element?.writeOrReadWriteExpression ?: continue
if (expression != initializer) {
conflicts.putValue(expression, KotlinBundle.message("unsupported.usage.0", expression.parent.text))
}
}
}
class Initializer(val value: KtExpression, val assignment: KtBinaryExpression?)
class Initialization private constructor(
private val value: KtExpression?,
private val assignment: KtBinaryExpression?,
@Nls private val error: String,
) {
val initializerOrNull: Initializer?
get() = value?.let { Initializer(value, assignment) }
fun getInitializerOrShowErrorHint(project: Project, editor: Editor?): Initializer? {
val initializer = initializerOrNull
if (initializer != null) return initializer
CommonRefactoringUtil.showErrorHint(
project,
editor,
error,
KotlinBundle.message("title.inline.property"),
HelpID.INLINE_VARIABLE,
)
return null
}
companion object {
fun createError(@Nls error: String): Initialization = Initialization(
value = null,
assignment = null,
error = error,
)
fun createInitializer(value: KtExpression, assignment: KtBinaryExpression?): Initialization = Initialization(
value = value,
assignment = assignment,
error = "",
)
}
}
companion object {
fun extractInitialization(property: KtProperty): Initialization {
val definitionScope = property.parent ?: kotlin.run {
return createInitializationWithError(property.name!!, emptyList())
}
val writeUsages = mutableListOf<KtExpression>()
ReferencesSearchScopeHelper.search(property, LocalSearchScope(definitionScope)).forEach {
val expression = it.element.writeOrReadWriteExpression ?: return@forEach
writeUsages += expression
}
val initializerInDeclaration = property.initializer
if (initializerInDeclaration != null) {
if (writeUsages.isNotEmpty()) {
return createInitializationWithError(property.name!!, writeUsages)
}
return Initialization.createInitializer(initializerInDeclaration, assignment = null)
}
val assignment = writeUsages.singleOrNull()?.getAssignmentByLHS()?.takeIf { it.operationToken == KtTokens.EQ }
val initializer = assignment?.right
if (initializer == null) {
return createInitializationWithError(property.name!!, writeUsages)
}
return Initialization.createInitializer(initializer, assignment)
}
private fun createInitializationWithError(name: String, assignments: Collection<PsiElement>): Initialization {
val key = if (assignments.isEmpty()) "variable.has.no.initializer" else "variable.has.no.dominating.definition"
val message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message(key, name))
return Initialization.createError(message)
}
}
}
fun createReplacementStrategyForProperty(
property: KtProperty,
editor: Editor?,
project: Project,
fallbackToSuperCall: Boolean = false,
): UsageReplacementStrategy? {
val getter = property.getter?.takeIf { it.hasBody() }
val setter = property.setter?.takeIf { it.hasBody() }
val readReplacement: CodeToInline?
val writeReplacement: CodeToInline?
if (getter == null && setter == null) {
val value = KotlinInlinePropertyProcessor.extractInitialization(property).getInitializerOrShowErrorHint(project, editor)?.value
?: return null
readReplacement = buildCodeToInline(
declaration = property,
bodyOrInitializer = value,
isBlockBody = false,
editor = editor,
fallbackToSuperCall = fallbackToSuperCall,
) ?: return null
writeReplacement = null
} else {
readReplacement = getter?.let {
buildCodeToInline(
declaration = getter,
bodyOrInitializer = getter.bodyExpression!!,
isBlockBody = getter.hasBlockBody(),
editor = editor,
fallbackToSuperCall = fallbackToSuperCall,
) ?: return null
}
writeReplacement = setter?.let {
buildCodeToInline(
declaration = setter,
bodyOrInitializer = setter.bodyExpression!!,
isBlockBody = setter.hasBlockBody(),
editor = editor,
fallbackToSuperCall = fallbackToSuperCall,
) ?: return null
}
}
return PropertyUsageReplacementStrategy(readReplacement, writeReplacement)
}
private val PsiElement.writeOrReadWriteExpression: KtExpression?
get() = this.safeAs<KtExpression>()
?.getQualifiedExpressionForSelectorOrThis()
?.takeIf { it.readWriteAccess(useResolveForReadWrite = true) != ReferenceAccess.READ }
| apache-2.0 | 15a34d05f7112f34265155e7c8f77fcf | 39.41791 | 158 | 0.680084 | 5.606625 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/AbstractCopyPasteTest.kt | 3 | 1964 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea
import com.intellij.codeInsight.CodeInsightSettings
import com.intellij.openapi.util.io.FileUtil
import com.intellij.psi.PsiFile
import com.intellij.util.ThrowableRunnable
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.idea.test.runAll
import org.jetbrains.kotlin.psi.KtFile
abstract class AbstractCopyPasteTest : KotlinLightCodeInsightFixtureTestCase() {
private var savedImportsOnPasteSetting: Int = 0
private val DEFAULT_TO_FILE_TEXT = "package to\n\n<caret>"
override fun setUp() {
super.setUp()
savedImportsOnPasteSetting = CodeInsightSettings.getInstance().ADD_IMPORTS_ON_PASTE
CodeInsightSettings.getInstance().ADD_IMPORTS_ON_PASTE = CodeInsightSettings.YES
}
override fun tearDown() {
runAll(
ThrowableRunnable { CodeInsightSettings.getInstance().ADD_IMPORTS_ON_PASTE = savedImportsOnPasteSetting },
ThrowableRunnable { super.tearDown() }
)
}
protected fun configureByDependencyIfExists(dependencyFileName: String): PsiFile? {
val file = testDataFile(dependencyFileName)
if (!file.exists()) return null
return if (dependencyFileName.endsWith(".java")) {
//allow test framework to put it under right directory
myFixture.addClass(FileUtil.loadFile(file, true)).containingFile
} else {
myFixture.configureByFile(dependencyFileName)
}
}
protected fun configureTargetFile(fileName: String): KtFile {
return if (testDataFile(fileName).exists()) {
myFixture.configureByFile(fileName) as KtFile
} else {
myFixture.configureByText(fileName, DEFAULT_TO_FILE_TEXT) as KtFile
}
}
}
| apache-2.0 | 468e1834f4fa514924f9d4a6e1a9d6a3 | 39.081633 | 158 | 0.717413 | 5.061856 | false | true | false | false |
alisle/Penella | src/main/java/org/penella/structures/SortedLinkList.kt | 1 | 3722 | package org.penella.structures
import org.slf4j.Logger
import org.slf4j.LoggerFactory
/**
* 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.
*
* Created by alisle on 10/12/16.
*/
class SortedLinkList<T : Comparable<T>> {
companion object {
private val log: Logger = LoggerFactory.getLogger(SortedLinkList::class.java)
}
class Node<T : Comparable<T>>(val value: Comparable<T>) {
var next: Node<T>? = null
var previous: Node<T>? = null
}
private var head: Node<T>? = null
private var tail: Node<T>? = null
private var count: Long = 0
var isEmpty : Boolean = head == null
fun first(): Node<T>? = head
fun last(): Node<T>? = tail
fun length():Long = count
fun pop() : Comparable<T>? {
if(count > 0) {
count--
val node = head
head = node?.next
return node?.value
}
return null
}
fun remove() : Comparable<T>? {
if(count > 0) {
count--
val node = tail
tail = node?.previous
return node?.value
}
return null
}
fun add(insertValue: T) {
var found : Boolean = false
var currentNode = head;
if(head == null) {
val insertNode = addNode(null, null, insertValue)
tail = insertNode
return
}
while(!found) {
val currentValue = currentNode?.value
when(currentValue?.compareTo(insertValue)){
-1 -> {
if (currentNode == tail) {
val insertNode = addNode(tail, null, insertValue)
tail = insertNode
found = true
} else {
currentNode = currentNode?.next
}
}
0 -> found = true
1 -> {
addNode(currentNode?.previous, currentNode, insertValue)
found = true
}
}
}
}
private fun addNode(previous: Node<T>?, next: Node<T>?, value : T ) : Node<T> {
count++
val node = Node(value)
node.previous = previous
node.previous?.next = node
node.next = next
next?.previous = node
if(next == head) {
head = node
}
return node
}
fun get(where: Int) : Comparable<T>? {
if( count > 0 && where < count) {
val diff = count - where
if(diff < where) {
if((where + 1L) == count) {
return tail?.value
}
var munch = count
var node = tail;
while(munch > where) {
node = node?.previous
munch--
}
return node?.value
} else {
var munch = 0
var node = head
while(munch < where) {
node = node?.next
munch++
}
return node?.value
}
}
return null;
}
} | apache-2.0 | 1a544094937ab0b861f036983f29e370 | 24.854167 | 85 | 0.485492 | 4.635118 | false | false | false | false |
vovagrechka/fucking-everything | attic/alraune/alraune-back/src/servePollForUpdates.kt | 1 | 4047 | package alraune.back
import vgrechka.*
//fun servePollForUpdates() {
// val pageToUpdate = rctx.ftb.shit.pagePath
// when (pageToUpdate) {
// AlkPagePath.adminOrders -> {
// val initiallyRenderedDatas = rctx.ftb.shit.initiallyRenderedOrderDatas
// if (initiallyRenderedDatas.isEmpty()) return
//
// val currentOrders = AlkDB.selectOrdersWithParams(Params_barney(
// addShitAfterWhere = {qb->
// qb.text("and ${AlUAOrder_Meta.uuid} in (")
// for ((index, ov) in initiallyRenderedDatas.withIndex()) {
// qb.param(ov.orderUUID)
// if (index < initiallyRenderedDatas.lastIndex)
// qb.text(",")
// }
// qb.text(")")
// },
// limit = initiallyRenderedDatas.size,
// checkLimitExactlyMatchesActualByTryingToSelectOneMore = true))
//
// class ChangedPieceOfShit(val initiallyRenderedData: AlInitiallyRenderedOrderData,
// val currentOrder: AlUAOrderWithParams)
// val changedPiecesOfShit = mutableListOf<ChangedPieceOfShit>()
// for (initiallyRenderedData in initiallyRenderedDatas) {
// val currentOrder = currentOrders.find {it.entity.uuid == initiallyRenderedData.orderUUID}
// if (currentOrder != null && currentOrder.entity.version > initiallyRenderedData.version.toLong()) {
// changedPiecesOfShit += ChangedPieceOfShit(initiallyRenderedData, currentOrder)
// }
// }
// // clog("------------- changed -------------\n$changedShit")
//
// rctx.commands += AlBackToFrontCommandPile()-{o->
// o.opcode = AlBackToFrontCommandOpcode.Eval
// o.script = buildString {
// ln("!function() {")
// for (piece in changedPiecesOfShit) {
// fun stateChangedTo(what: AlUAOrderState) =
// piece.currentOrder.params.state == what && piece.initiallyRenderedData.state != what
//
// class Alice(val itemMarkClass: AlCSS.Pack, val labelClass: AlCSS.Pack, val labelTitle: String)
// val alice = when {
// stateChangedTo(AlUAOrderState.RETURNED_TO_CUSTOMER_FOR_FIXING) -> Alice(
// itemMarkClass = AlCSS.carla.itemMark.danger,
// labelClass = AlCSS.carla.topRightTitleLabel.danger,
// labelTitle = t("TOTE", "Завернут")
// )
// else -> Alice(
// itemMarkClass = AlCSS.carla.itemMark.something,
// labelClass = AlCSS.carla.topRightTitleLabel.something,
// labelTitle = t("TOTE", "Изменен")
// )
// }
// ln("""
//var a = alraune
//var jItem = a.byIDSingle('${AlDomid.item}-${piece.initiallyRenderedData.orderUUID}')
//jItem.removeClass('${AlCSS.carla.itemMark.all.joinToString(" ")}')
//jItem.addClass('${alice.itemMarkClass}')
//var jExistingLabels = a.checkNoneOrSingleJQ(jItem.find('.${AlCSS.carla.topRightTitleLabel.common}'), '04eb6782-cdd5-4c25-a555-ed04300ea39e')
//jExistingLabels.remove()
//var jTitle = a.checkSingleJQ(jItem.find('.${AlCSS.carla.title}'), 'b38f11ea-91fb-47db-a705-9dbd8f34932d')
//jTitle.append('<div class="${AlCSS.carla.topRightTitleLabel.common} ${alice.labelClass}">${alice.labelTitle}</div>')
// """)
// }
// ln("}()")
// }
// }
// }
// else -> {
// rctx.log.warn("Why the fuck do I get [${AlFrontToBackCommandOpcode.PollForUpdates}] for page [$pageToUpdate]")
// }
// }
//}
| apache-2.0 | 09c10e8685dc168d41130f5a30ec7152 | 50.037975 | 142 | 0.529266 | 4.430769 | false | false | false | false |
blan4/MangaReader | app/src/main/java/org/seniorsigan/mangareader/ui/fragments/MangaListFragment.kt | 1 | 2959 | package org.seniorsigan.mangareader.ui.fragments
import android.content.Context
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import org.jetbrains.anko.find
import org.jetbrains.anko.support.v4.onRefresh
import org.jetbrains.anko.support.v4.onUiThread
import org.seniorsigan.mangareader.App
import org.seniorsigan.mangareader.R
import org.seniorsigan.mangareader.TAG
import org.seniorsigan.mangareader.adapters.ArrayListAdapter
import org.seniorsigan.mangareader.adapters.MangaViewHolder
import org.seniorsigan.mangareader.models.MangaItem
class MangaListFragment : Fragment() {
private lateinit var refresh: SwipeRefreshLayout
private lateinit var listView: RecyclerView
private lateinit var progressBar: ProgressBar
private val adapter = ArrayListAdapter(MangaViewHolder::class.java, R.layout.manga_item)
lateinit var onItemClickListener: OnItemClickListener
override fun onAttach(context: Context?) {
super.onAttach(context)
try {
onItemClickListener = activity as OnItemClickListener
} catch (e: ClassCastException) {
throw ClassCastException("$activity must implement OnItemClickListener");
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val rootView = inflater.inflate(R.layout.fragment_manga_list, container, false)
with(rootView, {
refresh = find<SwipeRefreshLayout>(R.id.refresh_manga_list)
listView = find<RecyclerView>(R.id.rv_manga_list)
progressBar = find<ProgressBar>(R.id.progressBar)
})
listView.layoutManager = GridLayoutManager(context, 2)
adapter.onItemClickListener = { manga -> onItemClickListener.onItemClick(manga) }
listView.adapter = adapter
return rootView
}
override fun onStart() {
super.onStart()
refresh.onRefresh {
renderList()
}
renderList()
}
fun renderList() {
App.mangaSearchController.findAll(App.mangaSourceRepository.currentName, { response ->
if (activity == null) return@findAll
onUiThread {
if (response.error == null) {
adapter.update(response.data)
refresh.isRefreshing = false
progressBar.visibility = View.GONE
} else {
Log.e(TAG, response.error)
}
}
})
}
interface OnItemClickListener {
fun onItemClick(item: MangaItem)
}
}
| mit | c370de0b0cea81525c5bee25ff81a625 | 34.22619 | 116 | 0.697195 | 4.956449 | false | false | false | false |
hsz/idea-gitignore | src/main/kotlin/mobi/hsz/idea/gitignore/psi/impl/IgnoreEntryExtImpl.kt | 1 | 2150 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package mobi.hsz.idea.gitignore.psi.impl
import com.intellij.lang.ASTNode
import com.intellij.openapi.util.text.StringUtil
import mobi.hsz.idea.gitignore.IgnoreBundle.Syntax
import mobi.hsz.idea.gitignore.lang.IgnoreLanguage
import mobi.hsz.idea.gitignore.psi.IgnoreElementImpl
import mobi.hsz.idea.gitignore.psi.IgnoreEntry
import mobi.hsz.idea.gitignore.psi.IgnoreEntryFile
import mobi.hsz.idea.gitignore.psi.IgnoreNegation
import mobi.hsz.idea.gitignore.psi.IgnoreTypes
import mobi.hsz.idea.gitignore.util.Glob
/**
* Custom [IgnoreElementImpl] implementation.
*/
abstract class IgnoreEntryExtImpl(node: ASTNode) : IgnoreElementImpl(node), IgnoreEntry {
/**
* Checks if the first child is negated - i.e. `!file.txt` entry.
*
* @return first child is negated
*/
override val isNegated
get() = firstChild is IgnoreNegation
/**
* Checks if current entry is a directory - i.e. `dir/`.
*
* @return is directory
*/
val isDirectory
get() = this is IgnoreEntryFile
/**
* Returns element syntax.
*
* @return syntax
*/
override val syntax: Syntax
get() {
var previous = prevSibling
while (previous != null) {
if (previous.node.elementType == IgnoreTypes.SYNTAX) {
Syntax.find((previous as IgnoreSyntaxImpl).value.text)?.let {
return it
}
}
previous = previous.prevSibling
}
return (containingFile.language as IgnoreLanguage).defaultSyntax
}
/**
* Returns entry value without leading `!` if entry is negated.
*
* @return entry value without `!` negation sign
*/
override val value
get() = text.takeIf { !isNegated } ?: StringUtil.trimStart(text, "!")
/**
* Returns entries pattern.
*
* @return pattern
*/
override val pattern
get() = Glob.createPattern(this)
}
| mit | 1f1ca7cb172ba0426487e2b2db09b25c | 29.714286 | 140 | 0.635349 | 4.369919 | false | false | false | false |
bmaslakov/kotlin-algorithm-club | src/main/io/uuddlrlrba/ktalgs/datastructures/tree/BinaryTree.kt | 1 | 2309 | /*
* Copyright (c) 2017 Kotlin Algorithm Club
*
* 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 io.uuddlrlrba.ktalgs.datastructures.tree
import io.uuddlrlrba.ktalgs.datastructures.Queue
class BinaryTree(var value: Int, var left: BinaryTree?, var right: BinaryTree?) {
constructor(value: Int): this(value, null, null)
fun size(): Int {
var size = 1
if (left != null) {
size += left!!.size()
}
if (right != null) {
size += right!!.size()
}
return size
}
fun height(): Int {
val left = if (left == null) 0 else left!!.height()
val right = if (right == null) 0 else right!!.height()
return maxOf(left, right) + 1
}
fun add(value: Int) {
// adds the on the first empty level
val queue = Queue<BinaryTree>()
queue.add(this)
while (!queue.isEmpty()) {
val x = queue.poll()
if (x.left == null) {
x.left = BinaryTree(value)
return
} else if (x.right == null) {
x.right = BinaryTree(value)
return
} else {
queue.add(x.left!!)
queue.add(x.right!!)
}
}
}
}
| mit | eea6f3f208206297b03fc94c341aa716 | 34.523077 | 81 | 0.620615 | 4.389734 | false | false | false | false |
hazuki0x0/YuzuBrowser | legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/action/manager/SoftButtonActionArrayFile.kt | 1 | 3371 | /*
* Copyright (C) 2017-2019 Hazuki
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jp.hazuki.yuzubrowser.legacy.action.manager
import android.content.Context
import com.squareup.moshi.JsonReader
import com.squareup.moshi.JsonWriter
import jp.hazuki.yuzubrowser.legacy.action.ActionFile
import jp.hazuki.yuzubrowser.legacy.action.SingleAction
import java.io.File
import java.io.IOException
import java.util.*
class SoftButtonActionArrayFile(private val FOLDER_NAME: String, private val id: Int) : ActionFile() {
val list: MutableList<SoftButtonActionFile> = ArrayList()
fun add(action: SingleAction) {
val array = SoftButtonActionFile()
array.press.add(action)
list.add(array)
}
fun add(action: SingleAction, longPress: SingleAction) {
val array = SoftButtonActionFile()
array.press.add(action)
array.lpress.add(longPress)
list.add(array)
}
fun add(action: SoftButtonActionFile) {
val array = SoftButtonActionFile()
array.press.addAll(action.press)
array.lpress.addAll(action.lpress)
array.up.addAll(action.up)
array.down.addAll(action.down)
array.left.addAll(action.left)
array.right.addAll(action.right)
list.add(array)
}
operator fun get(no: Int): SoftButtonActionFile {
return list[no]
}
fun getActionList(no: Int): SoftButtonActionFile {
if (no < 0)
throw IllegalArgumentException("no < 0")
expand(no + 1)
return list[no]
}
fun expand(size: Int): Int {
if (size < 0)
throw IllegalArgumentException("size < 0")
for (i in list.size - size..-1)
list.add(SoftButtonActionFile())
return list.size
}
override fun getFile(context: Context): File {
return File(context.getDir(FOLDER_NAME, Context.MODE_PRIVATE), id.toString() + ".dat")
}
override fun reset() {
list.clear()
}
@Throws(IOException::class)
override fun load(reader: JsonReader): Boolean {
if (reader.peek() != JsonReader.Token.BEGIN_ARRAY) return false
reader.beginArray()
while (reader.hasNext()) {
val action = SoftButtonActionFile()
if (!action.load(reader)) {
return if (reader.peek() == JsonReader.Token.END_ARRAY)
break
else
false
}
list.add(action)
}
reader.endArray()
return true
}
@Throws(IOException::class)
override fun write(writer: JsonWriter): Boolean {
writer.beginArray()
list.forEach { it.write(writer) }
writer.endArray()
return true
}
companion object {
private const val serialVersionUID = -8451972340596132660L
}
}
| apache-2.0 | cb30ef5fb04c04be7ec32f6c4ced674e | 29.098214 | 102 | 0.639573 | 4.283355 | false | false | false | false |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/taint/TaintAnalysis.kt | 1 | 13804 | package org.evomaster.core.taint
import org.evomaster.client.java.controller.api.dto.AdditionalInfoDto
import org.evomaster.client.java.instrumentation.shared.StringSpecialization
import org.evomaster.client.java.instrumentation.shared.StringSpecializationInfo
import org.evomaster.client.java.instrumentation.shared.TaintInputName
import org.evomaster.client.java.instrumentation.shared.TaintType
import org.evomaster.core.database.DbAction
import org.evomaster.core.logging.LoggingUtil
import org.evomaster.core.problem.rest.RestActionBuilderV3
import org.evomaster.core.problem.rest.RestCallAction
import org.evomaster.core.search.Action
import org.evomaster.core.search.Individual
import org.evomaster.core.search.gene.collection.*
import org.evomaster.core.search.gene.interfaces.TaintableGene
import org.evomaster.core.search.gene.regex.RegexGene
import org.evomaster.core.search.gene.string.StringGene
import org.evomaster.core.search.service.Randomness
import org.slf4j.Logger
import org.slf4j.LoggerFactory
object TaintAnalysis {
private val log: Logger = LoggerFactory.getLogger(TaintAnalysis::class.java)
fun getRegexTaintedValues(action: Action): List<String> {
return action.seeTopGenes()
.flatMap { it.flatView() }
.filterIsInstance<StringGene>()
.filter { it.getSpecializationGene() != null && it.getSpecializationGene() is RegexGene }
.map { it.getSpecializationGene()!!.getValueAsRawString() }
}
/**
* Analyze if any tainted value was used in the SUT in some special way.
* If that happened, then such info would end up in the AdditionalInfoDto.
* Then, we would extend the genotype (but not the phenotype!!!) of this test.
*/
fun doTaintAnalysis(individual: Individual,
additionalInfoList: List<AdditionalInfoDto>,
randomness: Randomness) {
if (individual.seeMainExecutableActions().size < additionalInfoList.size) {
throw IllegalArgumentException("Less main actions than info entries")
}
if (log.isTraceEnabled) {
log.trace("do taint analysis for individual which contains dbactions: {} and rest actions: {}",
individual.seeInitializingActions().joinToString(",") {
if (it is DbAction) it.getResolvedName() else it.getName()
},
individual.seeAllActions().joinToString(",") {
if (it is RestCallAction) it.resolvedPath() else it.getName()
}
)
log.trace("do taint analysis for {} additionalInfoList: {}",
additionalInfoList.size, additionalInfoList.flatMap { a -> a.stringSpecializations.keys }.joinToString(","))
}
/*
The old approach of checking the taint only for current main action was quite limiting:
1) it would ignore taint in SQL actions
2) a previous HTTP call could put a tainted value in the DB, read by a following action.
So, regardless of the main action in which the taint was detected, we check its gene in ALL
actions in the individual, including _previous_ ones. An optimization would be to ignore the _following_
actions.
Ideally, it should not be a problem, as tainted values are supposed to be unique. This is not currently
enforce, so with low chances it could happened that 2 different genes have same tainted value.
"Likely" rare, and "likely" with little to no side-effects if it happens (we ll see if it ll be indeed
the case).
Note, even if we force the invariant that 2 genes cannot share the same taint in a individual, we cannot guarantee
of the taint values detected in the SUT. The string there might be manipulated (although it is _extremely_ unlike
that a manipulated taint would still pass the taint regex check...)
*/
val allTaintableGenes: List<TaintableGene> =
individual.seeAllActions()
.flatMap { a ->
a.seeTopGenes().flatMap { it.flatView() }
.filterIsInstance<TaintableGene>()
}
val inputVariables = individual.seeAllActions()
.flatMap { getRegexTaintedValues(it) }
.toSet()
for (element in additionalInfoList) {
if (element.stringSpecializations == null || element.stringSpecializations.isEmpty()) {
continue
}
val specsMap = element.stringSpecializations.entries
.map {
it.key to it.value.map { s ->
StringSpecializationInfo(
StringSpecialization.valueOf(s.stringSpecialization),
s.value,
TaintType.valueOf(s.type)
)
}
}.toMap()
handleSingleGenes(specsMap, allTaintableGenes, randomness, inputVariables)
handleMultiGenes(specsMap, allTaintableGenes, randomness, inputVariables)
handleTaintedArrays(specsMap, allTaintableGenes, randomness, inputVariables)
}
}
private fun handleTaintedArrays(
specsMap: Map<String, List<StringSpecializationInfo>>,
allTaintableGenes: List<TaintableGene>,
randomness: Randomness,
inputVariables: Set<String>) {
val taintedArrays = allTaintableGenes.filterIsInstance<TaintedArrayGene>()
if (taintedArrays.isEmpty()) {
return
}
for (entry in specsMap.entries) {
val taintedInput = entry.key
val specs = entry.value
if (specs.isEmpty()) {
throw IllegalArgumentException("No specialization info for value $taintedInput")
}
val genes = taintedArrays.filter { it.getPossiblyTaintedValue().equals(taintedInput, true) }
if (genes.isEmpty()) {
continue
}
if (specs.size > 1) {
log.warn("More than one possible specialization for tainted array '$taintedInput': $specs")
}
val s = specs.find { it.stringSpecialization == StringSpecialization.JSON_OBJECT }
?: randomness.choose(specs)
val template = if (s.stringSpecialization == StringSpecialization.JSON_OBJECT) {
val schema = s.value
val t = schema.subSequence(0, schema.indexOf(":")).trim().toString()
val ref = t.subSequence(1, t.length - 1).toString()
RestActionBuilderV3.createObjectGenesForDTOs(ref, schema)
} else {
/*
TODO this could be more sophisticated, like considering numeric and boolean arrays as well,
and already initializing the values in array with some of taints.
but, as this "likely" would be rare (ie JSON array of non-objects as root element in parsing),
no need for now.
*/
StringGene("element")
}
genes.forEach {
it.resolveTaint(
ArrayGene(it.name, template.copy()).apply { doInitialize(randomness) }
)
}
}
}
private fun handleMultiGenes(
specsMap: Map<String, List<StringSpecializationInfo>>,
allTaintableGenes: List<TaintableGene>,
randomness: Randomness,
inputVariables: Set<String>) {
val specs = specsMap.entries
.flatMap { it.value }
.filter { it.type == TaintType.PARTIAL_MATCH }
.toSet()
for (s in specs) {
val genes = allTaintableGenes.filter {
specsMap.entries
.filter { e -> e.key.contains(it.getPossiblyTaintedValue(), true) }
.any { e -> e.value.any { d -> d == s } }
}.filterIsInstance<StringGene>()
if (genes.size <= 1) {
continue
}
/*
TODO handling this properly is very complex. Something to do in the future,
but for now we just keep a very basic, ad-hoc solution
*/
if (!s.stringSpecialization.isRegex || genes.size != 2) {
continue
}
/*
TODO we just handle for now this special case, but we would need a general approach
*/
val divider = "\\Q-\\E"
val pos = s.value.indexOf(divider)
if (pos < 0) {
continue
}
val left = "(" + s.value.subSequence(0, pos).toString() + ")$"
val right = "^(" + s.value.subSequence(pos + divider.length, s.value.length).toString() + ")"
val taintInput = specsMap.entries.first { it.value.any { it == s } }.key
val choices = if (taintInput.indexOf(genes[0].getValueAsRawString()) == 0) {
listOf(left, right)
} else {
listOf(right, left)
}
try {
genes[0].addSpecializations(
genes[0].getValueAsRawString(),
listOf(StringSpecializationInfo(StringSpecialization.REGEX_WHOLE, choices[0])),
randomness)
genes[1].addSpecializations(
genes[1].getValueAsRawString(),
listOf(StringSpecializationInfo(StringSpecialization.REGEX_WHOLE, choices[1])),
randomness)
} catch (e: Exception) {
LoggingUtil.uniqueWarn(log, "Cannot handle partial match on regex: ${s.value}")
}
}
}
private fun handleSingleGenes(
specsMap: Map<String, List<StringSpecializationInfo>>,
allTaintableGenes: List<TaintableGene>,
randomness: Randomness,
inputVariables: Set<String>) {
for (entry in specsMap.entries) {
val taintedInput = entry.key
if (entry.value.isEmpty()) {
throw IllegalArgumentException("No specialization info for value $taintedInput")
}
//TODO what was the difference between these 2?
val fullMatch = specsMap[taintedInput]!!.filter { it.type == TaintType.FULL_MATCH }
val partialMatch = specsMap[taintedInput]!!.filter { it.type == TaintType.PARTIAL_MATCH }
if (fullMatch.isNotEmpty()) {
val genes = allTaintableGenes
.filter {
(TaintInputName.isTaintInput(it.getPossiblyTaintedValue())
|| inputVariables.contains(it.getPossiblyTaintedValue()))
&& it.getPossiblyTaintedValue().equals(taintedInput, true)
}
.filterIsInstance<StringGene>()
addSpecializationToGene(genes, taintedInput, fullMatch, randomness)
}
//partial match on single genes
if (partialMatch.isNotEmpty()) {
val genes = allTaintableGenes
.filter {
(TaintInputName.isTaintInput(it.getPossiblyTaintedValue())
|| inputVariables.contains(it.getPossiblyTaintedValue()))
&& taintedInput.contains(it.getPossiblyTaintedValue(), true)
}
.filterIsInstance<StringGene>()
addSpecializationToGene(genes, taintedInput, partialMatch, randomness)
}
}
}
private fun addSpecializationToGene(
genes: List<StringGene>,
taintedInput: String,
specializations: List<StringSpecializationInfo>,
randomness: Randomness
) {
if (genes.isEmpty()) {
/*
This can happen if the taint input is manipulated, but still with
same prefix and postfix. However, it would be extremely rare, and for sure
not in any of E2E, unless we explicitly write one for it
*/
log.warn("No taint input found '{}'", taintedInput)
/*
FIXME put back once debug issue on Linux.
The issue is that H2 is caching requests... our fix for that work on local machines (including
Linux) but fails somehow on CI
*/
//assert(false) // crash in tests, but not production
} else {
if (genes.size > 1
&& TaintInputName.isTaintInput(taintedInput)
&& genes.none { x -> genes.any { y -> x.isDirectBoundWith(y) || x.is2DepthDirectBoundWith(y) || x.isAnyParentBoundWith(y) } }
) {
//shouldn't really be a problem... but let keep track for it, for now at least.
// note, cannot really guarantee that a taint from regex is unique, as regex could generate
// any kind of string...
// also if genes are bound, then of course going to be more than 2...
log.warn("More than 2 genes have the taint '{}'", taintedInput)
//FIXME possible bug in binding handling.
// assert(false)
}
genes.forEach { it.addSpecializations(taintedInput, specializations, randomness) }
}
}
} | lgpl-3.0 | 150265a1202568db78eb95c4637cd4f5 | 41.608025 | 145 | 0.573747 | 5.406972 | false | false | false | false |
YouriAckx/AdventOfCode | 2017/src/day09/part2/part02.kt | 1 | 959 | package day09.part2
import java.io.File
private data class State(val garbages: Int, val ignoreNext: Boolean, val inGarbage: Boolean) {
fun increase() = this.copy(garbages = garbages + 1)
}
private fun countGarbage(s: String): Int =
s.toCharArray()
.fold(State(garbages = 0, ignoreNext = false, inGarbage = false), { state, c -> handle(state, c) })
.garbages
private fun handle(state: State, c: Char): State {
return if (state.ignoreNext) {
state.copy(ignoreNext = false)
} else {
when (c) {
'!' -> state.copy(ignoreNext = true)
'<' -> if (state.inGarbage) state.increase() else state.copy(inGarbage = true)
'>' -> state.copy(inGarbage = false)
else -> if (state.inGarbage) state.increase() else state
}
}
}
fun main(args: Array<String>) {
val input = File("src/day09/input.txt").readLines().first()
println(countGarbage(input))
}
| gpl-3.0 | bddfdeb164f31cde9d4029fd666293e2 | 30.966667 | 111 | 0.607925 | 3.525735 | false | false | false | false |
ibinti/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/impl/FirstStarter.kt | 3 | 2920 | /*
* 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.testGuiFramework.impl
import com.intellij.openapi.util.ClassLoaderUtil
import com.intellij.util.lang.UrlClassLoader
import java.net.URL
import kotlin.concurrent.thread
class FirstStarter {
}
fun main(args: Array<String>) {
startRobotRoutine()
startIdeMainRoutine(args)
}
private fun startIdeMainRoutine(args: Array<String>) {
val defaultClassloader = FirstStarter::class.java.classLoader
Thread.currentThread().contextClassLoader = defaultClassloader
val ideMainClass = Class.forName("com.intellij.idea.Main", true, defaultClassloader)
val mainMethod = ideMainClass.getMethod("main", Array<String>::class.java)
mainMethod.isAccessible = true
mainMethod.invoke(null, args)
}
private fun startRobotRoutine() {
val robotClassLoader = createRobotClassLoader()
fun awtIsNotStarted()
= !(Thread.getAllStackTraces().keys.any { thread -> thread.name.toLowerCase().contains("awt-eventqueue") })
thread(name = "Wait Awt and Start", contextClassLoader = robotClassLoader) {
while (awtIsNotStarted()) Thread.sleep(100)
val companion = Class.forName("com.intellij.testGuiFramework.impl.FirstStart\$Companion", true, robotClassLoader)
val firstStartClass = Class.forName("com.intellij.testGuiFramework.impl.FirstStart", true, robotClassLoader)
val value = firstStartClass.getField("Companion").get(Any())
val method = companion.getDeclaredMethod("guessIdeAndStartRobot")
method.isAccessible = true
method.invoke(value)
}
}
fun createRobotClassLoader(): UrlClassLoader {
val builder = UrlClassLoader.build()
.urls(getUrlOfBaseClassLoader())
.allowLock()
.usePersistentClasspathIndexForLocalClassDirectories()
.useCache()
ClassLoaderUtil.addPlatformLoaderParentIfOnJdk9(builder)
val newClassLoader = builder.get()
return newClassLoader!!
}
fun getUrlOfBaseClassLoader(): List<URL> {
val classLoader = Thread.currentThread().contextClassLoader
val urlClassLoaderClass = classLoader.javaClass
val getUrlsMethod = urlClassLoaderClass.methods.filter { it.name.toLowerCase() == "geturls" }.firstOrNull()!!
@Suppress("UNCHECKED_CAST")
val urlsListOrArray = getUrlsMethod.invoke(classLoader)
if (urlsListOrArray is Array<*>) return urlsListOrArray.toList() as List<URL>
else return urlsListOrArray as List<URL>
} | apache-2.0 | 7d1861644498eea6f4ba3ea00465def9 | 34.621951 | 117 | 0.765068 | 4.332344 | false | false | false | false |
savoirfairelinux/ring-client-android | ring-android/app/src/main/java/cx/ring/client/MediaViewerFragment.kt | 1 | 2391 | /*
* Copyright (C) 2004-2021 Savoir-faire Linux Inc.
*
* Author: Adrien Béraud <[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, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package cx.ring.client
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.fragment.app.Fragment
import com.bumptech.glide.load.resource.bitmap.CenterInside
import cx.ring.R
import cx.ring.utils.GlideApp
import cx.ring.utils.GlideOptions
/**
* A placeholder fragment containing a simple view.
*/
class MediaViewerFragment : Fragment() {
private var mUri: Uri? = null
private var mImage: ImageView? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
val view = inflater.inflate(R.layout.fragment_media_viewer, container, false) as ViewGroup
mImage = view.findViewById(R.id.image)
showImage()
return view
}
override fun onDestroyView() {
super.onDestroyView()
mImage = null
}
override fun onStart() {
super.onStart()
val activity = activity ?: return
mUri = activity.intent.data
showImage()
}
private fun showImage() {
mUri?.let {uri ->
activity?.let {a ->
mImage?.let {image ->
GlideApp.with(a)
.load(uri)
.apply(PICTURE_OPTIONS)
.into(image)
}
}
}
}
companion object {
private val PICTURE_OPTIONS = GlideOptions().transform(CenterInside())
}
} | gpl-3.0 | 5f5aa39a66b50c7d714ffb535cac734e | 30.460526 | 115 | 0.660251 | 4.361314 | false | false | false | false |
sonnytron/FitTrainerBasic | mobile/src/main/java/com/sonnyrodriguez/fittrainer/fittrainerbasic/models/LocalStatObject.kt | 1 | 2450 | package com.sonnyrodriguez.fittrainer.fittrainerbasic.models
import com.sonnyrodriguez.fittrainer.fittrainerbasic.database.WorkoutHistoryObject
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit
data class LocalStatObject(val title: String,
val dateString: String,
val totalExercisesString: String,
val muscleGroups: String,
val durationString: String) {
companion object {
fun durationString(workoutHistoryObject: WorkoutHistoryObject): String {
val timeDifferenceInMs = Date(workoutHistoryObject.timeEnded).time - Date(workoutHistoryObject.timeStarted).time
val days = TimeUnit.MILLISECONDS.toDays(timeDifferenceInMs)
val hours = TimeUnit.MILLISECONDS.toHours(timeDifferenceInMs) - TimeUnit.DAYS.toHours(days)
val minutes = TimeUnit.MILLISECONDS.toMinutes(timeDifferenceInMs) - TimeUnit.HOURS.toMinutes(hours)
val seconds = TimeUnit.MILLISECONDS.toSeconds(timeDifferenceInMs) - TimeUnit.MINUTES.toSeconds(minutes)
if (minutes > 0) {
return "$minutes minutes, $seconds seconds"
} else {
return "$seconds seconds"
}
}
fun dateCompleteString(workoutHistoryObject: WorkoutHistoryObject): String {
val dateDone = Date(workoutHistoryObject.timeStarted)
return SimpleDateFormat("MM/dd/yyyy", Locale.getDefault()).format(dateDone)
}
fun totalExercisesDone(workoutHistoryObject: WorkoutHistoryObject): String {
var titles = ""
workoutHistoryObject.names.forEachIndexed { index, titleString ->
if (index == 0) {
titles = "$titleString"
} else {
titles = "$titles, $titleString"
}
}
return titles
}
fun musclesString(workoutHistoryObject: WorkoutHistoryObject): String {
var muscles = ""
workoutHistoryObject.muscles.forEach {
muscles = "${muscles},${MuscleEnum.fromMuscleNumber(it.toInt()).title}"
}
return muscles
}
fun totalCount(workoutHistoryObject: WorkoutHistoryObject): String {
return "${workoutHistoryObject.exercises.count()} exercises"
}
}
}
| apache-2.0 | 17f36a46f20133a38c925bdb0e60ef63 | 42.75 | 124 | 0.622857 | 5.606407 | false | false | false | false |
BlueBoxWare/LibGDXPlugin | src/test/testdata/annotationUtils/KotlinClass.kt | 1 | 1068 | @MyAnnotation(argsNoDefault = ["foo", "oof"], arg = "bar")
var string: String? = "foo"
@MyAnnotation(argNoDefault = "object")
object KotlinObject {
fun m() {
}
@MyAnnotation(args = arrayOf("123", "456"), argsNoDefault = ["789"])
fun annotatedMethod() {
}
val s = ""
@MyAnnotation(arg = "xyz")
val t = ""
fun f(): KotlinClass {
return KotlinClass()
}
}
@MyAnnotation(argNoDefault = "kotlin", args = ["123"])
open class KotlinClass {
@MyAnnotation(args = ["a", "b"])
val string: String? = "string"
@MyAnnotation(args = arrayOf("a", "b"))
val kotlinClass = KotlinClass()
val kotlinClassNA: KotlinClass? = KotlinClass()
fun m() {}
@MyAnnotation(args = ["me", "thod"])
fun annotatedMethod() {}
companion object {
@MyAnnotation(argsNoDefault = ["xyz"])
val s = ""
fun coMethod() {}
fun f(): KotlinClass? {
@MyAnnotation(arg = "local")
val l = 3
return KotlinClass()
}
@MyAnnotation(argsNoDefault = arrayOf("g"))
fun g() {}
}
}
class SubClass: KotlinClass() {
} | apache-2.0 | 4b7c2821c21d2b323b6a255356dbedd9 | 15.446154 | 70 | 0.59176 | 3.682759 | false | false | false | false |
arora-aman/MultiThreadDownloader | multithreaddownloader/src/main/java/com/aman_arora/multi_thread_downloader/downloader/DownloadTask.kt | 1 | 2482 | package com.aman_arora.multi_thread_downloader.downloader
import com.aman_arora.multi_thread_downloader.downloader.IDownloadTask.OnDownloadTaskEventListener
import java.io.BufferedInputStream
import java.io.File
import java.io.FileOutputStream
import java.net.HttpURLConnection
import java.net.URL
internal class DownloadTask(val webUrl: URL, val thread: Int, val startByte: Long, val endByte: Long?,
val partFile: File, val listener: OnDownloadTaskEventListener) : IDownloadTask {
private val partSize = endByte?.minus(startByte)?.plus(1)
private var isPaused = false
internal var isDownloaded = false
override fun run() {
if (endByte != null && this.startByte + partFile.length() >= endByte) {
return
}
val httpConnection = getHttpConnection(this.startByte + partFile.length(), endByte)
httpConnection.connect()
val isr = BufferedInputStream(httpConnection.inputStream)
val outputStream = FileOutputStream(partFile, true)
val byteInputBuffer = ByteArray(1024)
var bytesRead: Int
var progress: Float
var totalRead = partFile.length()
while (true) {
synchronized(isPaused) {
if (isPaused) {
isr.close()
return
}
bytesRead = isr.read(byteInputBuffer)
if (bytesRead == -1) {
if (endByte == null || partFile.length() == partSize) {
isDownloaded = true
listener.onDownloadComplete()
}
return
}
outputStream.write(byteInputBuffer, 0, bytesRead)
totalRead += bytesRead
if (partSize != null) {
progress = totalRead.toFloat().div(partSize)
listener.onProgressUpdated(thread, progress)
}
}
}
}
override fun stopDownload() = synchronized(isPaused) {
if (isPaused) {
throw IllegalStateException()
}
isPaused = true
return@synchronized
}
private fun getHttpConnection(startByte: Long,endByte: Long?): HttpURLConnection {
val httpConnection = webUrl.openConnection() as HttpURLConnection
httpConnection.setRequestProperty("Range", "bytes=$startByte-$endByte")
return httpConnection
}
} | mit | 6fde4559c1431a8f83ba6cb64d7b17af | 32.554054 | 108 | 0.594279 | 5.372294 | false | false | false | false |
googlecodelabs/android-compose-codelabs | AdvancedStateAndSideEffectsCodelab/app/src/main/java/androidx/compose/samples/crane/base/ExploreSection.kt | 1 | 6052 | /*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.samples.crane.base
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
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.foundation.shape.RoundedCornerShape
import androidx.compose.material.Divider
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.samples.crane.R
import androidx.compose.samples.crane.data.ExploreModel
import androidx.compose.samples.crane.home.OnExploreItemClicked
import androidx.compose.samples.crane.ui.BottomSheetShape
import androidx.compose.samples.crane.ui.crane_caption
import androidx.compose.samples.crane.ui.crane_divider_color
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.res.painterResource
import androidx.compose.ui.unit.dp
import coil.annotation.ExperimentalCoilApi
import coil.compose.AsyncImagePainter
import coil.compose.rememberAsyncImagePainter
import coil.compose.rememberImagePainter
import coil.request.ImageRequest
import coil.request.ImageRequest.Builder
import com.google.accompanist.insets.navigationBarsHeight
@Composable
fun ExploreSection(
modifier: Modifier = Modifier,
title: String,
exploreList: List<ExploreModel>,
onItemClicked: OnExploreItemClicked
) {
Surface(modifier = modifier.fillMaxSize(), color = Color.White, shape = BottomSheetShape) {
Column(modifier = Modifier.padding(start = 24.dp, top = 20.dp, end = 24.dp)) {
Text(
text = title,
style = MaterialTheme.typography.caption.copy(color = crane_caption)
)
Spacer(Modifier.height(8.dp))
// TODO Codelab: derivedStateOf step
// TODO: Show "Scroll to top" button when the first item of the list is not visible
val listState = rememberLazyListState()
ExploreList(exploreList, onItemClicked, listState = listState)
}
}
}
@Composable
private fun ExploreList(
exploreList: List<ExploreModel>,
onItemClicked: OnExploreItemClicked,
modifier: Modifier = Modifier,
listState: LazyListState = rememberLazyListState()
) {
LazyColumn(modifier = modifier, state = listState) {
items(exploreList) { exploreItem ->
Column(Modifier.fillParentMaxWidth()) {
ExploreItem(
modifier = Modifier.fillParentMaxWidth(),
item = exploreItem,
onItemClicked = onItemClicked
)
Divider(color = crane_divider_color)
}
}
item {
Spacer(modifier = Modifier.navigationBarsHeight())
}
}
}
@OptIn(ExperimentalCoilApi::class)
@Composable
private fun ExploreItem(
modifier: Modifier = Modifier,
item: ExploreModel,
onItemClicked: OnExploreItemClicked
) {
Row(
modifier = modifier
.clickable { onItemClicked(item) }
.padding(top = 12.dp, bottom = 12.dp)
) {
ExploreImageContainer {
Box {
val painter = rememberAsyncImagePainter(
model = Builder(LocalContext.current)
.data(item.imageUrl)
.crossfade(true)
.build()
)
Image(
painter = painter,
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxSize(),
)
if (painter.state is AsyncImagePainter.State.Loading) {
Image(
painter = painterResource(id = R.drawable.ic_crane_logo),
contentDescription = null,
modifier = Modifier
.size(36.dp)
.align(Alignment.Center),
)
}
}
}
Spacer(Modifier.width(24.dp))
Column {
Text(
text = item.city.nameToDisplay,
style = MaterialTheme.typography.h6
)
Spacer(Modifier.height(8.dp))
Text(
text = item.description,
style = MaterialTheme.typography.caption.copy(color = crane_caption)
)
}
}
}
@Composable
private fun ExploreImageContainer(content: @Composable () -> Unit) {
Surface(Modifier.size(width = 60.dp, height = 60.dp), RoundedCornerShape(4.dp)) {
content()
}
}
| apache-2.0 | 63a6d43ffa17bfb8204ab807093b69a6 | 35.678788 | 95 | 0.665235 | 4.810811 | false | false | false | false |
nickthecoder/tickle | tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/scripts/Language.kt | 1 | 3741 | /*
Tickle
Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.tickle.scripts
import java.io.File
import java.lang.ref.WeakReference
import java.lang.reflect.Modifier
/**
* The base class for scripting languages, allowing game code to be dynamically loaded.
*
* Note, you game's main entry point should register the script language(s) you require e.g. :
*
* GroovyLanguage().register()
*
* Also, you must add the path(s) where script files are located.
* However, the default launchers: Tickle and EditorMain will do the following automatically :
*
* ScriptManager.setClasspath(File(resourcesFile.parent, "scripts"))
*/
abstract class Language {
abstract val fileExtension: String
abstract val name: String
/**
* Key is the name of the filename without extension.
* Value is the Class contained in that file.
* Note. the filename is used, rather than the Class.name, because Kotlin creates classes with names like :
* Line_3$ExampleRole. Grr.
*/
private val classes = mutableMapOf<String, Class<*>>()
/**
* Note, when a script is reloaded, this map will contain the old and new classes,
* and therefore will grow larger than [classes] map.
* A WeakReference is used so that old (unused) classes can be garbage collected.
*/
private val classToName = mutableMapOf<WeakReference<Class<*>>, String>()
open fun register() {
ScriptManager.register(this)
}
abstract fun setClasspath(directory: File)
/**
* Clear all classes, ready for them to be reloaded
*/
open fun clear() {
classes.clear()
classToName.clear()
}
abstract fun loadScript(file: File): Class<*>
fun addScript(file: File) {
val klass = loadScript(file)
val name = file.nameWithoutExtension
classes[name] = klass
classToName[WeakReference(klass)] = name
}
fun classForName(name: String): Class<*>? {
return classes[name]
}
fun nameForClass(klass: Class<*>): String? {
for ((weakKlass, name) in classToName) {
if (weakKlass.get() === klass) {
return name
}
}
return null
}
/**
* Returns classes known by this script language, that are sub-classes of the type given.
* For example, it can be used to find all the scripted Roles, or scripted Directors etc.
*/
fun subTypes(type: Class<*>): List<Class<*>> {
return classes.filter {
!it.value.isInterface && !Modifier.isAbstract(it.value.modifiers) && type.isAssignableFrom(it.value)
}.toSortedMap().map { it.value }
}
fun createScript(scriptDirectory: File, scriptName: String, type: Class<*>? = null): File {
val file = File(scriptDirectory, scriptName + ".${fileExtension}")
if (!scriptDirectory.exists()) {
scriptDirectory.mkdirs()
}
file.writeText(generateScript(scriptName, type))
ScriptManager.load(file)
return file
}
abstract fun generateScript(name: String, type: Class<*>?): String
}
| gpl-3.0 | 23683efdb286db9e3c4bf8c32db26d28 | 31.530435 | 112 | 0.669874 | 4.380562 | false | false | false | false |
cketti/k-9 | app/k9mail/src/main/java/com/fsck/k9/backends/RealOAuth2TokenProvider.kt | 1 | 2807 | package com.fsck.k9.backends
import android.content.Context
import com.fsck.k9.Account
import com.fsck.k9.mail.AuthenticationFailedException
import com.fsck.k9.mail.oauth.OAuth2TokenProvider
import com.fsck.k9.preferences.AccountManager
import java.io.IOException
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import net.openid.appauth.AuthState
import net.openid.appauth.AuthorizationException
import net.openid.appauth.AuthorizationException.AuthorizationRequestErrors
import net.openid.appauth.AuthorizationException.GeneralErrors
import net.openid.appauth.AuthorizationService
class RealOAuth2TokenProvider(
context: Context,
private val accountManager: AccountManager,
private val account: Account
) : OAuth2TokenProvider {
private val authService = AuthorizationService(context)
private var requestFreshToken = false
override fun getToken(timeoutMillis: Long): String {
val latch = CountDownLatch(1)
var token: String? = null
var exception: AuthorizationException? = null
val authState = account.oAuthState?.let { AuthState.jsonDeserialize(it) }
?: throw AuthenticationFailedException("Login required")
if (requestFreshToken) {
authState.needsTokenRefresh = true
}
val oldAccessToken = authState.accessToken
authState.performActionWithFreshTokens(authService) { accessToken: String?, _, authException: AuthorizationException? ->
token = accessToken
exception = authException
latch.countDown()
}
latch.await(timeoutMillis, TimeUnit.MILLISECONDS)
val authException = exception
if (authException == GeneralErrors.NETWORK_ERROR ||
authException == GeneralErrors.SERVER_ERROR ||
authException == AuthorizationRequestErrors.SERVER_ERROR ||
authException == AuthorizationRequestErrors.TEMPORARILY_UNAVAILABLE
) {
throw IOException("Error while fetching an access token", authException)
} else if (authException != null) {
account.oAuthState = null
accountManager.saveAccount(account)
throw AuthenticationFailedException(
message = "Failed to fetch an access token",
throwable = authException,
messageFromServer = authException.error
)
} else if (token != oldAccessToken) {
requestFreshToken = false
account.oAuthState = authState.jsonSerializeString()
accountManager.saveAccount(account)
}
return token ?: throw AuthenticationFailedException("Failed to fetch an access token")
}
override fun invalidateToken() {
requestFreshToken = true
}
}
| apache-2.0 | 5a8741ed83db4ca6de0cf0c0185e7e0d | 35.934211 | 128 | 0.700392 | 5.336502 | false | false | false | false |
FWDekker/intellij-randomness | src/test/kotlin/com/fwdekker/randomness/ui/JSpinnerRangeTest.kt | 1 | 1826 | package com.fwdekker.randomness.ui
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.assertj.swing.edt.FailOnThreadViolationRepaintManager
import org.assertj.swing.edt.GuiActionRunner
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import javax.swing.JSpinner
/**
* Unit tests for the extension functions in `JSpinnerHelperKt`.
*/
object JSpinnerRangeTest : Spek({
beforeGroup {
FailOnThreadViolationRepaintManager.install()
}
describe("constructor") {
it("throws an exception if the range is negative") {
assertThatThrownBy { bindSpinners(createJSpinner(), createJSpinner(), -37.20) }
.isInstanceOf(IllegalArgumentException::class.java)
.hasMessage("maxRange must be a positive number.")
}
}
describe("automatic range correction") {
it("updates the minimum spinner if the maximum goes below its value") {
val min = createJSpinner(150.38)
val max = createJSpinner(244.54)
bindSpinners(min, max)
GuiActionRunner.execute { max.value = -284.85 }
assertThat(min.value).isEqualTo(-284.85)
}
it("updates the maximum spinner if the minimum goes above its value") {
val min = createJSpinner(-656.88)
val max = createJSpinner(105.41)
bindSpinners(min, max)
GuiActionRunner.execute { min.value = 684.41 }
assertThat(max.value).isEqualTo(684.41)
}
}
})
private fun createJSpinner() =
GuiActionRunner.execute<JSpinner> { JSpinner() }
private fun createJSpinner(value: Double) =
GuiActionRunner.execute<JSpinner> { JSpinner().also { it.value = value } }
| mit | e6ab22a4aa5f10b21f0b3fdc24b36f60 | 31.035088 | 91 | 0.672508 | 4.622785 | false | false | false | false |
MichaelRocks/lightsaber | processor/src/main/java/io/michaelrocks/lightsaber/processor/analysis/Analyzer.kt | 1 | 1979 | /*
* Copyright 2020 Michael Rozumyanskiy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.michaelrocks.lightsaber.processor.analysis
import io.michaelrocks.grip.Grip
import io.michaelrocks.lightsaber.processor.ErrorReporter
import io.michaelrocks.lightsaber.processor.model.InjectionContext
import java.io.File
class Analyzer(
private val grip: Grip,
private val errorReporter: ErrorReporter,
private val projectName: String
) {
fun analyze(files: Collection<File>): InjectionContext {
val analyzerHelper = AnalyzerHelperImpl(grip.classRegistry, ScopeRegistry(), errorReporter)
val (injectableTargets, providableTargets) = InjectionTargetsAnalyzerImpl(grip, analyzerHelper, errorReporter).analyze(files)
val bindingRegistry = BindingsAnalyzerImpl(grip, analyzerHelper, errorReporter).analyze(files)
val factories = FactoriesAnalyzerImpl(grip, analyzerHelper, errorReporter, projectName).analyze(files)
val moduleProviderParser = ModuleProviderParserImpl(grip, errorReporter)
val moduleParser = ModuleParserImpl(grip, moduleProviderParser, bindingRegistry, analyzerHelper, projectName)
val moduleRegistry = ModuleRegistryImpl(grip, moduleParser, errorReporter, providableTargets, factories, files)
val components = ComponentsAnalyzerImpl(grip, moduleRegistry, errorReporter).analyze(files)
return InjectionContext(components, injectableTargets, providableTargets, factories, bindingRegistry.bindings)
}
}
| apache-2.0 | da13973e706ed8fe570e5e67dc4db43e | 47.268293 | 129 | 0.795856 | 4.72315 | false | false | false | false |
JustinMullin/drifter-kotlin | src/main/kotlin/xyz/jmullin/drifter/rendering/shader/ShaderSet.kt | 1 | 9019 | package xyz.jmullin.drifter.rendering.shader
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.glutils.ShaderProgram
import com.badlogic.gdx.math.Matrix3
import com.badlogic.gdx.math.Matrix4
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.math.Vector3
import xyz.jmullin.drifter.debug.log
import xyz.jmullin.drifter.extensions.drifter
import xyz.jmullin.drifter.rendering.shader.delegate.UniformDelegate
/**
* Given files to load shader definitions from, compiles and wraps a [[ShaderProgram]] and functionality
* for reloading the program. Define init() and tick() methods to set shader uniforms.
*
* @param fragmentShaderName Filename of the fragment shader to load.
* @param vertexShaderName Filename of the vertex shader to load.
*/
open class ShaderSet(private val fragmentShaderName: String, private val vertexShaderName: String = "default") {
var uniforms = emptyList<ShaderUniform<*>>()
private val vert = Gdx.files.internal("shader/$vertexShaderName.vert")!!
private val frag = Gdx.files.internal("shader/$fragmentShaderName.frag")!!
/**
* System ms time at which this shader was last compiled.
*/
private var lastCompileTime = 0L
/**
* The loaded shader program.
*/
var program: ShaderProgram? = null
init {
compile()
}
/**
* Compile the shader program from the specified source.
*/
private fun compile() {
program = ShaderProgram(vert, frag).apply {
if(isCompiled) {
log("Shader ($frag, $vert) compiled successfully.")
} else {
log("Shader ($frag, $vert) failed to compile:\n${log.split("\n").joinToString("\n") { "\t" + it }}")
}
}
lastCompileTime = System.currentTimeMillis()
}
/**
* Reload the shader from source if the files have been changed since compilation.
*/
private fun refresh() {
if (vert.lastModified() > lastCompileTime || frag.lastModified() > lastCompileTime) {
compile()
log("Reloaded shader $fragmentShaderName / $vertexShaderName.")
}
}
fun update() {
if(drifter().devMode) {
refresh()
}
uniforms.forEach(ShaderUniform<*>::setFromTick)
tick()
}
/**
* Extend to set shader parameters on a tick-by-tick basis.
*/
open fun tick() {}
}
/**
* Uniform delegates intended for use in member assignment.
*/
val ShaderSet.booleanUniform get() = UniformDelegate.make(this) { name -> BooleanUniform(program!!, name, null) }
val ShaderSet.intUniform get() = UniformDelegate.make(this) { name -> IntUniform(program!!, name, null) }
val ShaderSet.floatUniform get() = UniformDelegate.make(this) { name -> FloatUniform(program!!, name, null) }
val ShaderSet.vector2Uniform get() = UniformDelegate.make(this) { name -> Vector2Uniform(program!!, name, null) }
val ShaderSet.vector3Uniform get() = UniformDelegate.make(this) { name -> Vector3Uniform(program!!, name, null) }
val ShaderSet.matrix3Uniform get() = UniformDelegate.make(this) { name -> Matrix3Uniform(program!!, name, null) }
val ShaderSet.matrix4Uniform get() = UniformDelegate.make(this) { name -> Matrix4Uniform(program!!, name, null) }
val ShaderSet.colorUniform get() = UniformDelegate.make(this) { name -> ColorUniform(program!!, name, null) }
val ShaderSet.booleanArrayUniform get() = UniformDelegate.make(this) { name -> ArrayUniform(program!!, name, Uniforms.boolean, null) }
val ShaderSet.intArrayUniform get() = UniformDelegate.make(this) { name -> ArrayUniform(program!!, name, Uniforms.int, null) }
val ShaderSet.floatArrayUniform get() = UniformDelegate.make(this) { name -> ArrayUniform(program!!, name, Uniforms.float, null) }
val ShaderSet.vector2ArrayUniform get() = UniformDelegate.make(this) { name -> ArrayUniform(program!!, name, Uniforms.vector2, null) }
val ShaderSet.vector3ArrayUniform get() = UniformDelegate.make(this) { name -> ArrayUniform(program!!, name, Uniforms.vector3, null) }
val ShaderSet.matrix3ArrayUniform get() = UniformDelegate.make(this) { name -> ArrayUniform(program!!, name, Uniforms.matrix3, null) }
val ShaderSet.matrix4ArrayUniform get() = UniformDelegate.make(this) { name -> ArrayUniform(program!!, name, Uniforms.matrix4, null) }
val ShaderSet.colorArrayUniform get() = UniformDelegate.make(this) { name -> ArrayUniform(program!!, name, Uniforms.color, null) }
/**
* Uniform registrars intended for use in side-effecting shader declarations.
*/
fun ShaderSet.booleanUniform(name: String, tick: (() -> Boolean)?) = BooleanUniform(program!!, name, tick).apply { uniforms += this }
fun ShaderSet.intUniform(name: String, tick: (() -> Int)?) = IntUniform(program!!, name, tick).apply { uniforms += this }
fun ShaderSet.floatUniform(name: String, tick: (() -> Float)?) = FloatUniform(program!!, name, tick).apply { uniforms += this }
fun ShaderSet.vector2Uniform(name: String, tick: (() -> Vector2)?) = Vector2Uniform(program!!, name, tick).apply { uniforms += this }
fun ShaderSet.vector3Uniform(name: String, tick: (() -> Vector3)?) = Vector3Uniform(program!!, name, tick).apply { uniforms += this }
fun ShaderSet.matrix3Uniform(name: String, tick: (() -> Matrix3)?) = Matrix3Uniform(program!!, name, tick).apply { uniforms += this }
fun ShaderSet.matrix4Uniform(name: String, tick: (() -> Matrix4)?) = Matrix4Uniform(program!!, name, tick).apply { uniforms += this }
fun ShaderSet.colorUniform(name: String, tick: (() -> Color)?) = ColorUniform(program!!, name, tick).apply { uniforms += this }
fun ShaderSet.booleanArrayUniform(name: String, tick: (() -> List<Boolean>)?) = ArrayUniform(program!!, name, Uniforms.boolean, tick).apply { uniforms += this }
fun ShaderSet.intArrayUniform(name: String, tick: (() -> List<Int>)?) = ArrayUniform(program!!, name, Uniforms.int, tick).apply { uniforms += this }
fun ShaderSet.floatArrayUniform(name: String, tick: (() -> List<Float>)?) = ArrayUniform(program!!, name, Uniforms.float, tick).apply { uniforms += this }
fun ShaderSet.vector2ArrayUniform(name: String, tick: (() -> List<Vector2>)?) = ArrayUniform(program!!, name, Uniforms.vector2, tick).apply { uniforms += this }
fun ShaderSet.vector3ArrayUniform(name: String, tick: (() -> List<Vector3>)?) = ArrayUniform(program!!, name, Uniforms.vector3, tick).apply { uniforms += this }
fun ShaderSet.matrix3ArrayUniform(name: String, tick: (() -> List<Matrix3>)?) = ArrayUniform(program!!, name, Uniforms.matrix3, tick).apply { uniforms += this }
fun ShaderSet.matrix4ArrayUniform(name: String, tick: (() -> List<Matrix4>)?) = ArrayUniform(program!!, name, Uniforms.matrix4, tick).apply { uniforms += this }
fun ShaderSet.colorArrayUniform(name: String, tick: (() -> List<Color>)?) = ArrayUniform(program!!, name, Uniforms.color, tick).apply { uniforms += this }
fun ShaderSet.booleanUniform(name: String, v: Boolean) = BooleanUniform(program!!, name, { v }).apply { uniforms += this }
fun ShaderSet.intUniform(name: String, v: Int) = IntUniform(program!!, name, { v }).apply { uniforms += this }
fun ShaderSet.floatUniform(name: String, v: Float) = FloatUniform(program!!, name, { v }).apply { uniforms += this }
fun ShaderSet.vector2Uniform(name: String, v: Vector2) = Vector2Uniform(program!!, name, { v }).apply { uniforms += this }
fun ShaderSet.vector3Uniform(name: String, v: Vector3) = Vector3Uniform(program!!, name, { v }).apply { uniforms += this }
fun ShaderSet.matrix3Uniform(name: String, v: Matrix3) = Matrix3Uniform(program!!, name, { v }).apply { uniforms += this }
fun ShaderSet.matrix4Uniform(name: String, v: Matrix4) = Matrix4Uniform(program!!, name, { v }).apply { uniforms += this }
fun ShaderSet.colorUniform(name: String, v: Color) = ColorUniform(program!!, name, { v }).apply { uniforms += this }
fun ShaderSet.booleanArrayUniform(name: String, v: List<Boolean>) = ArrayUniform(program!!, name, Uniforms.boolean, { v }).apply { uniforms += this }
fun ShaderSet.intArrayUniform(name: String, v: List<Int>) = ArrayUniform(program!!, name, Uniforms.int, { v }).apply { uniforms += this }
fun ShaderSet.floatArrayUniform(name: String, v: List<Float>) = ArrayUniform(program!!, name, Uniforms.float, { v }).apply { uniforms += this }
fun ShaderSet.vector2ArrayUniform(name: String, v: List<Vector2>) = ArrayUniform(program!!, name, Uniforms.vector2, { v }).apply { uniforms += this }
fun ShaderSet.vector3ArrayUniform(name: String, v: List<Vector3>) = ArrayUniform(program!!, name, Uniforms.vector3, { v }).apply { uniforms += this }
fun ShaderSet.matrix3ArrayUniform(name: String, v: List<Matrix3>) = ArrayUniform(program!!, name, Uniforms.matrix3, { v }).apply { uniforms += this }
fun ShaderSet.matrix4ArrayUniform(name: String, v: List<Matrix4>) = ArrayUniform(program!!, name, Uniforms.matrix4, { v }).apply { uniforms += this }
fun ShaderSet.colorArrayUniform(name: String, v: List<Color>) = ArrayUniform(program!!, name, Uniforms.color, { v }).apply { uniforms += this }
| mit | 5f57325796db9c1177f64b8f615a13fd | 65.807407 | 160 | 0.701186 | 4.006664 | false | false | false | false |
vsch/SmartData | src/com/vladsch/smart/SmartDataScope.kt | 1 | 33172 | /*
* Copyright (c) 2015-2020 Vladimir Schneider <[email protected]>
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
@file:Suppress("UNCHECKED_CAST")
package com.vladsch.smart
import java.util.*
enum class SmartScopes(val flags: Int) {
SELF(1),
PARENT(2),
ANCESTORS(4),
CHILDREN(8),
DESCENDANTS(16),
RESULT_TOP(32), // result always in top scope, else SELF
INDICES(64); // across indices within a scope, maybe?
companion object : BitSetEnum<SmartScopes>(SmartScopes::class.java, { it.flags }) {
@JvmStatic val SELF_DOWN = setOf(SELF, CHILDREN, DESCENDANTS)
@JvmStatic val TOP_DOWN = setOf(RESULT_TOP, SELF, CHILDREN, DESCENDANTS)
fun isValidSet(scope: SmartScopes): Boolean = isValidSet(scope.flags)
fun isValidSet(scopes: Set<SmartScopes>): Boolean = isValidSet(asFlags(scopes))
fun isValidSet(flags: Int): Boolean = !(isAncestorsSet(flags) && isDescendantSet(flags)) && !isIndicesSet(flags)
fun isIndicesSet(scope: SmartScopes): Boolean = isIndicesSet(scope.flags)
fun isIndicesSet(scopes: Set<SmartScopes>): Boolean = isIndicesSet(asFlags(scopes))
fun isIndicesSet(flags: Int): Boolean = flags and INDICES.flags > 0
fun isAncestorsSet(scope: SmartScopes): Boolean = isAncestorsSet(scope.flags)
fun isAncestorsSet(scopes: Set<SmartScopes>): Boolean = isAncestorsSet(asFlags(scopes))
fun isAncestorsSet(flags: Int): Boolean = flags and (PARENT.flags or ANCESTORS.flags) > 0
fun isDescendantSet(scope: SmartScopes): Boolean = isDescendantSet(scope.flags)
fun isDescendantSet(scopes: Set<SmartScopes>): Boolean = isDescendantSet(asFlags(scopes))
fun isDescendantSet(flags: Int): Boolean = flags and (CHILDREN.flags or DESCENDANTS.flags) > 0
}
}
@Suppress("UNCHECKED_CAST")
abstract class SmartDataKey<V : Any>(id: String, nullValue: V, scopes: Set<SmartScopes>) {
val myId: String = id
val myNullValue: V = nullValue
val myNullData: SmartImmutableData<V>
val myScopes: Int
fun onInit() {
SmartDataScopeManager.registerKey(this)
}
val isIndependent: Boolean get() = dependencies.isEmpty() || dependencies.size == 1 && dependencies.first() == this
abstract val dependencies: List<SmartDataKey<*>>
abstract fun createData(result: SmartDataScope, sources: Set<SmartDataScope>, indices: Set<Int>)
fun values(data: SmartDataScope): HashMap<Int, SmartVersionedDataHolder<V>> {
return data.getValues(this) as HashMap<Int, SmartVersionedDataHolder<V>>
}
fun value(cache: SmartDataScope, index: Int): SmartVersionedDataHolder<V>? {
return cache.getValue(this, index) as SmartVersionedDataHolder<V>?
}
fun value(value: Any): V {
return value as V
}
fun value(values: HashMap<SmartDataKey<*>, *>): V {
return (values[this] ?: myNullValue) as V
}
fun list(list: List<*>): List<V> {
return list as List<V>
}
fun createValues(): HashMap<Int, SmartVersionedDataHolder<V>> {
return HashMap()
}
fun createDataAlias(): SmartVersionedDataAlias<V> {
return SmartVersionedDataAlias(myNullData)
}
fun createDataAlias(data: SmartVersionedDataHolder<*>): SmartVersionedDataAlias<V> {
return SmartVersionedDataAlias(data as SmartVersionedDataHolder<V>)
}
fun createDataAlias(scope: SmartDataScope, index: Int): SmartVersionedDataAlias<V> {
val alias = SmartVersionedDataAlias(myNullData)
scope.setValue(this, index, alias)
return alias
}
fun createData(): SmartVersionedDataHolder<V> {
return SmartVolatileData(myNullValue)
}
fun createList(): ArrayList<V> {
return ArrayList()
}
override fun toString(): String {
return super.toString() + " id: $myId"
}
fun addItem(list: ArrayList<*>, item: Any) {
(list as ArrayList<V>).add(item as V)
}
fun setAlias(item: SmartVersionedDataAlias<*>, value: SmartVersionedDataHolder<V>) {
(item as SmartVersionedDataAlias<V>).alias = value
}
fun setAlias(item: SmartVersionedDataAlias<*>, scope: SmartDataScope, index: Int) {
val value = scope.getValue(this, index) as SmartVersionedDataHolder<V>? ?: myNullData
(item as SmartVersionedDataAlias<V>).alias = if (value is SmartVersionedDataAlias<V>) value.alias else value
}
fun setNullData(scope: SmartDataScope, index: Int) {
scope.setValue(this, index, myNullData)
}
fun setValue(scope: SmartDataScope, index: Int, value: SmartVersionedDataHolder<*>) {
scope.setValue(this, index, value as SmartVersionedDataHolder<V>)
}
fun dataPoint(scope: SmartDataScope, index: Int): SmartVersionedDataAlias<V> {
return scope.dataPoint(this, index) as SmartVersionedDataAlias<V>
}
init {
this.myNullData = SmartImmutableData("$myId.nullValue", nullValue)
this.myScopes = SmartScopes.asFlags(scopes)
}
}
// values computed from corresponding parent values
open class SmartVolatileDataKey<V : Any>(id: String, nullValue: V) : SmartDataKey<V>(id, nullValue, setOf(SmartScopes.SELF)) {
override val dependencies: List<SmartDataKey<*>>
get() = listOf()
init {
onInit()
}
open operator fun set(scope: SmartDataScope, index: Int, value: V) {
val dataPoint = scope.getRawValue(this, index)
if (dataPoint == null) {
scope.setValue(this, index, SmartVolatileData(myId, value))
} else if (dataPoint is SmartVersionedVolatileDataHolder<*>) {
(dataPoint as SmartVersionedVolatileDataHolder<V>).set(value)
} else {
throw IllegalStateException("non alias or volatile data point for volatile data key")
}
}
open operator fun get(scope: SmartDataScope, index: Int): V {
return ((scope.getRawValue(this, index) ?: myNullData) as SmartVersionedDataHolder<V>).get()
}
override fun createData(result: SmartDataScope, sources: Set<SmartDataScope>, indices: Set<Int>) {
// only first set will be used since there can only be one self
for (source in sources) {
for (index in indices) {
// val dependent = value(source, index) ?: throw IllegalStateException("Dependent data for dataKey $this for $source[$index] is missing")
// val resultItem = result.getValue(this, index)
result.setValue(this, index, myNullData)
}
break
}
}
}
open class SmartParentComputedDataKey<V : Any>(id: String, nullValue: V, val computable: DataValueComputable<V, V>) : SmartDataKey<V>(id, nullValue, setOf(SmartScopes.PARENT)) {
constructor(id: String, nullValue: V, computable: (V) -> V) : this(id, nullValue, DataValueComputable { computable(it) })
val myComputable: IterableDataComputable<V> = IterableDataComputable { computable.compute(it.first()) }
override val dependencies: List<SmartDataKey<*>>
get() = listOf(this)
init {
onInit()
}
override fun createData(result: SmartDataScope, sources: Set<SmartDataScope>, indices: Set<Int>) {
// only first set will be used since there can only be one parent
for (source in sources) {
for (index in indices) {
val dependent = value(source, index) ?: throw IllegalStateException("Dependent data for dataKey $this for $source[$index] is missing")
// val resultItem = result.getValue(this, index)
result.setValue(this, index, SmartVectorData(listOf(dependent), myComputable))
}
break
}
}
}
open class SmartComputedDataKey<V : Any>(id: String, nullValue: V, override val dependencies: List<SmartDataKey<*>>, scopes: Set<SmartScopes>, val computable: DataValueComputable<HashMap<SmartDataKey<*>, List<*>>, V>) : SmartDataKey<V>(id, nullValue, scopes) {
constructor(id: String, nullValue: V, dependencies: List<SmartDataKey<*>>, scopes: Set<SmartScopes>, computable: (dependencies: HashMap<SmartDataKey<*>, List<*>>) -> V) : this(id, nullValue, dependencies, scopes, DataValueComputable { computable(it) })
val myComputable: DataValueComputable<Iterable<SmartVersionedDataHolder<*>>, V> = DataValueComputable {
// here we create a hash map of by out dependent keys to lists of passed in source scopes
val params = HashMap<SmartDataKey<*>, List<*>>()
val iterator = it.iterator()
do {
for (depKey in dependencies) {
val list = params[depKey] as ArrayList<*>? ?: depKey.createList()
depKey.addItem(list, iterator.next())
}
} while (iterator.hasNext())
computable.compute(params)
}
init {
if (SmartScopes.isValidSet(this.myScopes)) throw IllegalArgumentException("Scopes cannot contain both parent/ancestors and children/descendants")
onInit()
}
override fun createData(result: SmartDataScope, sources: Set<SmartDataScope>, indices: Set<Int>) {
for (index in indices) {
val dependents = ArrayList<SmartVersionedDataHolder<*>>()
for (dependencyKey in dependencies) {
for (source in sources) {
val dependent = dependencyKey.value(source, index) ?: throw IllegalStateException("Dependent data for dataKey $this for $source[$index] is missing")
dependents.add(dependent)
}
}
result.setValue(this, index, SmartIterableData(dependents, myComputable))
}
}
}
open class SmartDependentDataKey<V : Any>(id: String, nullValue: V, override val dependencies: List<SmartDataKey<*>>, scope: SmartScopes, val computable: DataValueComputable<HashMap<SmartDataKey<*>, *>, V>) : SmartDataKey<V>(id, nullValue, setOf(scope)) {
constructor(id: String, nullValue: V, dependencies: List<SmartDataKey<*>>, scope: SmartScopes, computable: (dependencies: HashMap<SmartDataKey<*>, *>) -> V) : this(id, nullValue, dependencies, scope, DataValueComputable { computable(it) })
val myComputable: DataValueComputable<Iterable<SmartVersionedDataHolder<*>>, V> = DataValueComputable {
// here we create a hash map of by out dependent keys to lists of passed in source scopes
val params = HashMap<SmartDataKey<*>, Any>()
val iterator = it.iterator()
for (depKey in dependencies) {
params[depKey] = iterator.next().get()
}
if (iterator.hasNext()) throw IllegalStateException("iterator hasNext() is true after all parameters have been used up")
computable.compute(params)
}
init {
if (scope != SmartScopes.SELF && scope != SmartScopes.PARENT) throw IllegalArgumentException("TransformedDataKey can only be applied to SELF or PARENT scope")
onInit()
}
override fun createData(result: SmartDataScope, sources: Set<SmartDataScope>, indices: Set<Int>) {
for (index in indices) {
val dependents = ArrayList<SmartVersionedDataHolder<*>>()
for (dependencyKey in dependencies) {
for (source in sources) {
val dependent = dependencyKey.value(source, index) ?: throw IllegalStateException("Dependent data for dataKey $this for $source[$index] is missing")
dependents.add(dependent)
break
}
}
result.setValue(this, index, SmartIterableData(dependents, myComputable))
}
}
}
open class SmartTransformedDataKey<V : Any, R : Any>(id: String, nullValue: V, dependency: SmartDataKey<R>, scope: SmartScopes, computable: DataValueComputable<R, V>) : SmartDependentDataKey<V>(id, nullValue, listOf(dependency), scope, DataValueComputable { computable.compute(dependency.value(it[dependency]!!)) }) {
constructor(id: String, nullValue: V, dependency: SmartDataKey<R>, scope: SmartScopes, computable: (R) -> V) : this(id, nullValue, dependency, scope, DataValueComputable { computable(it) })
}
open class SmartVectorDataKey<V : Any>(id: String, nullValue: V, override val dependencies: List<SmartDataKey<V>>, scopes: Set<SmartScopes>, computable: IterableDataComputable<V>) : SmartDataKey<V>(id, nullValue, scopes) {
constructor(id: String, nullValue: V, dependencies: List<SmartDataKey<V>>, scope: SmartScopes, computable: IterableDataComputable<V>) : this(id, nullValue, dependencies, setOf(scope, SmartScopes.SELF), computable)
constructor(id: String, nullValue: V, dependency: SmartDataKey<V>, scopes: Set<SmartScopes>, computable: IterableDataComputable<V>) : this(id, nullValue, listOf(dependency), scopes, computable)
constructor(id: String, nullValue: V, dependencies: List<SmartDataKey<V>>, scopes: Set<SmartScopes>, computable: (Iterable<V>) -> V) : this(id, nullValue, dependencies, scopes, IterableDataComputable { computable(it) })
constructor(id: String, nullValue: V, dependencies: List<SmartDataKey<V>>, scope: SmartScopes, computable: (Iterable<V>) -> V) : this(id, nullValue, dependencies, setOf(scope, SmartScopes.SELF), computable)
constructor(id: String, nullValue: V, dependency: SmartDataKey<V>, scopes: Set<SmartScopes>, computable: (Iterable<V>) -> V) : this(id, nullValue, listOf(dependency), scopes, computable)
private val myComputable = computable
init {
onInit()
}
override fun createData(result: SmartDataScope, sources: Set<SmartDataScope>, indices: Set<Int>) {
for (index in indices) {
if (SmartDataScopeManager.INSTANCE.trace) println("creating connections for $myId[$index] on scope: ${result.name}")
val dependents = ArrayList<SmartVersionedDataHolder<V>>()
for (source in sources) {
for (dataKey in dependencies) {
val dependent = dataKey.value(source, index) ?: throw IllegalStateException("Dependent data for dataKey $this for $source[$index] is missing")
if (SmartDataScopeManager.INSTANCE.trace) println("adding dependent: $dependent")
dependents.add(dependent)
}
}
result.setValue(this, index, SmartVectorData(dependents, myComputable))
if (SmartDataScopeManager.INSTANCE.trace) println("created connections for $myId[$index] on scope: ${result.name}")
}
}
}
open class SmartAggregatedScopesDataKey<V : Any>(id: String, nullValue: V, dataKey: SmartDataKey<V>, scopes: Set<SmartScopes>, computable: IterableDataComputable<V>) :
SmartVectorDataKey<V>(id, nullValue, listOf(dataKey), scopes, computable) {
constructor(id: String, nullValue: V, dataKey: SmartDataKey<V>, scopes: Set<SmartScopes>, computable: (Iterable<V>) -> V) : this(id, nullValue, dataKey, scopes, IterableDataComputable { computable(it) })
}
open class SmartAggregatedDependenciesDataKey<V : Any>(id: String, nullValue: V, dependencies: List<SmartDataKey<V>>, isTopScope: Boolean, computable: IterableDataComputable<V>) :
SmartVectorDataKey<V>(id, nullValue, dependencies, if (isTopScope) setOf(SmartScopes.RESULT_TOP, SmartScopes.SELF) else setOf(SmartScopes.SELF), computable) {
constructor(id: String, nullValue: V, dependencies: List<SmartDataKey<V>>, isTopScope: Boolean, computable: (Iterable<V>) -> V) : this(id, nullValue, dependencies, isTopScope, IterableDataComputable { computable(it) })
}
class SmartLatestDataKey<V : Any>(id: String, nullValue: V, val dataKey: SmartDataKey<V>, scopes: Set<SmartScopes>) : SmartDataKey<V>(id, nullValue, scopes) {
override val dependencies: List<SmartDataKey<V>>
get() = listOf(dataKey)
init {
onInit()
}
override fun createData(result: SmartDataScope, sources: Set<SmartDataScope>, indices: Set<Int>) {
for (index in indices) {
val dependents = ArrayList<SmartVersionedDataHolder<V>>()
for (source in sources) {
val dependent = dataKey.value(source, index) ?: throw IllegalStateException("Dependent data for dataKey $this for $source[$index] is missing")
dependents.add(dependent)
}
result.setValue(this, index, SmartLatestDependentData(dependents))
}
}
}
class SmartDataScopeManager {
companion object {
@JvmField val INSTANCE = SmartDataScopeManager()
val dependentKeys: Map<SmartDataKey<*>, Set<SmartDataKey<*>>> get() = INSTANCE.dependentKeys
val keyComputeLevel: Map<SmartDataKey<*>, Int> get() = INSTANCE.keyComputeLevel
fun computeKeyOrder(keys: Set<SmartDataKey<*>>): List<List<SmartDataKey<*>>> = INSTANCE.computeKeyOrder(keys)
fun registerKey(dataKey: SmartDataKey<*>) {
INSTANCE.registerKey(dataKey)
}
fun resolveDependencies() {
INSTANCE.resolveDependencies()
}
fun createDataScope(name: String): SmartDataScope = INSTANCE.createDataScope(name)
}
private val myKeys = HashSet<SmartDataKey<*>>()
private val myIndependentKeys = HashSet<SmartDataKey<*>>()
private val myDependentKeys = HashMap<SmartDataKey<*>, HashSet<SmartDataKey<*>>>()
private var myDependenciesResolved = true
// private var myKeyDependencyMap = HashMap<SmartDataKey<*>, HashSet<SmartDataKey<*>>>()
private var myComputeLevel = HashMap<SmartDataKey<*>, Int>()
private var myTrace = false
var trace: Boolean
get() = myTrace
set(value) {
myTrace = value
}
val dependentKeys: Map<SmartDataKey<*>, Set<SmartDataKey<*>>> get() {
return myDependentKeys
}
// val dependencyMap: Map<SmartDataKey<*>, Set<SmartDataKey<*>>> get() {
// if (!myDependenciesResolved) resolveDependencies()
// return myKeyDependencyMap
// }
val keyComputeLevel: Map<SmartDataKey<*>, Int> get() {
if (!myDependenciesResolved) resolveDependencies()
return myComputeLevel
}
fun computeKeyOrder(keys: Set<SmartDataKey<*>>): List<List<SmartDataKey<*>>> {
val needKeys = HashSet<SmartDataKey<*>>()
needKeys.addAll(keys)
for (key in keys) {
needKeys.addAll(key.dependencies)
}
val orderedKeyList = HashMap<Int, ArrayList<SmartDataKey<*>>>()
for (entry in keyComputeLevel) {
if (needKeys.contains(entry.key)) {
orderedKeyList.putIfMissing(entry.value, { arrayListOf() })
orderedKeyList[entry.value]!!.add(entry.key)
}
}
val resultList = arrayListOf<List<SmartDataKey<*>>>()
for (computeLevel in orderedKeyList.keys.sorted()) {
val list = orderedKeyList[computeLevel] ?: continue
resultList.add(list)
}
return resultList
}
fun registerKey(dataKey: SmartDataKey<*>) {
myKeys.add(dataKey)
myDependenciesResolved = false
if (dataKey.isIndependent) {
myIndependentKeys.add(dataKey)
} else {
val resultDeps: Set<SmartDataKey<*>> = myDependentKeys[dataKey] ?: setOf()
for (sourceKey in dataKey.dependencies) {
myDependentKeys.putIfMissing(sourceKey, { HashSet() })
myDependentKeys[sourceKey]!!.add(dataKey)
if (resultDeps.contains(sourceKey)) {
throw IllegalArgumentException("sourceKey $sourceKey has resultKey $dataKey as dependency, circular dependency in $dataKey")
}
}
}
}
fun createDataScope(name: String): SmartDataScope {
return SmartDataScope(name, null)
}
@Suppress("UNCHECKED_CAST")
fun resolveDependencies() {
// compute dependency levels so that we can take a consumer key and get a list of keys that must be computed, sorted by order
// of these computations
val unresolvedKeys = myKeys.clone() as HashSet<SmartDataKey<*>>
val resolvedKeys = myIndependentKeys.clone() as HashSet<SmartDataKey<*>>
myComputeLevel = HashMap<SmartDataKey<*>, Int>()
myComputeLevel.putAll(myIndependentKeys.map { Pair(it, 0) })
var computeOrder = 1
unresolvedKeys.removeAll(myIndependentKeys)
while (!unresolvedKeys.isEmpty()) {
// take out all the keys that no longer have any dependencies that are not computed
val currentKeys = unresolvedKeys.filter { it.dependencies.intersect(unresolvedKeys).isEmpty() }
if (currentKeys.isEmpty()) throw IllegalStateException("computation level has no keys, means remaining have circular dependencies")
resolvedKeys.addAll(currentKeys)
unresolvedKeys.removeAll(currentKeys)
myComputeLevel.putAll(currentKeys.map { Pair(it, computeOrder) })
computeOrder++
}
myDependenciesResolved = true
}
}
// if the data point has a consumer then the corresponding entry will contain a SmartVersionedDataAlias, else it will contain null
// so when a version data point provider is computed and the data point has non-null non-alias then it is a conflict and exception time
//
// all points that are provided have to be in existence before the call to finalizeAllScopes(), at which point all computed data keys that provide
// consumed data will have their inputs computed, and the inputs of those computed points, until every consumer can be satisfied.
// if there is an input for which only a non-computed key exists then that data point will get the key's nullValue and be immutable data.
//
// data points for which no consumers exist will not be created, and will not cause intermediate data points be created nor computed
//
open class SmartDataScope(val name: String, val parent: SmartDataScope?) {
protected val myValues = HashMap<SmartDataKey<*>, HashMap<Int, SmartVersionedDataHolder<*>>>()
protected val myChildren = HashSet<SmartDataScope>() // children
protected val myDescendants = HashSet<SmartDataScope>() // descendants
protected val myAncestors = HashSet<SmartDataScope>() // ancestors
protected val myConsumers = HashMap<SmartDataKey<*>, ArrayList<Int>>() // list of indices per key for which consumers are available for this iteration
val children: Set<SmartDataScope> get() = myChildren
val descendants: Set<SmartDataScope> get() = myDescendants
val ancestors: Set<SmartDataScope> get() = myAncestors
val consumers: Map<SmartDataKey<*>, List<Int>> get() = myConsumers
val level: Int
init {
parent?.addChild(this)
level = (parent?.level ?: -1) + 1
}
fun addChild(scope: SmartDataScope) {
myChildren.add(scope)
parent?.addDescendant(scope)
}
fun addDescendant(scope: SmartDataScope) {
myDescendants.add(scope)
scope.addAncestor(this)
parent?.addDescendant(scope)
}
fun addAncestor(scope: SmartDataScope) {
myAncestors.add(scope)
}
fun createDataScope(name: String): SmartDataScope {
return SmartDataScope(name, this)
}
fun getValues(key: SmartDataKey<*>): Map<Int, SmartVersionedDataHolder<*>>? {
return myValues[key]
}
fun getValue(key: SmartDataKey<*>, index: Int): SmartVersionedDataHolder<*>? {
val value = getRawValue(key, index) ?: parent?.getValue(key, index)
return if (value is SmartVersionedDataAlias<*>) value.alias else value
}
fun getRawValue(key: SmartDataKey<*>, index: Int): SmartVersionedDataHolder<*>? {
val value = myValues[key] ?: return null
return value[index]
}
fun <V : Any> setValue(key: SmartDataKey<V>, index: Int, value: SmartVersionedDataHolder<V>) {
var valList = myValues[key]
if (valList == null) {
valList = hashMapOf(Pair(index, value))
myValues.put(key, valList)
} else {
val item = valList[index]
if (item != null) {
if (item is SmartVersionedDataAlias<*>) {
if (value is SmartVersionedDataAlias<*>) throw IllegalStateException("data point in $name for $key already has an alias $item, second alias $value is in error")
key.setAlias(item, value)
} else {
throw IllegalStateException("data point in $name for $key already has a data value $item, second value $value is in error")
}
} else {
valList.put(index, value)
}
}
}
private fun canSetDataPoint(key: SmartDataKey<*>, index: Int): Boolean {
val item = getRawValue(key, index)
return item == null || item is SmartVersionedDataAlias<*>
}
open operator fun get(dataKey: SmartDataKey<*>, index: Int): SmartVersionedDataHolder<*> = dataPoint(dataKey, index)
open operator fun set(dataKey: SmartDataKey<*>, index: Int, value: SmartVersionedDataHolder<*>) {
dataKey.setValue(this, index, value)
}
open operator fun set(dataKey: SmartDataKey<*>, value: SmartVersionedDataHolder<*>) {
val index = myValues[dataKey]?.size ?: 0
dataKey.setValue(this, index, value)
}
fun dataPoint(dataKey: SmartDataKey<*>, index: Int): SmartVersionedDataHolder<*> {
var dataPoint = getRawValue(dataKey, index)
if (dataPoint == null) {
// not yet computed
dataPoint = dataKey.createDataAlias(this, index)
myConsumers.putIfMissing(dataKey, { arrayListOf() })
myConsumers[dataKey]!!.add(index)
}
return dataPoint
}
private fun addConsumedScopes(keys: HashMap<SmartDataKey<*>, HashSet<SmartDataScope>>) {
for (entry in myConsumers) {
keys.putIfMissing(entry.key, { HashSet() })
val scopesSet = keys[entry.key]!!
// include self in computations if scopes were added on our behalf
if (addKeyScopes(entry.key.myScopes, scopesSet) > 0) scopesSet.add(this)
}
}
private fun addKeyScopes(scopes: Int, scopesSet: HashSet<SmartDataScope>): Int {
var count = 0
if (scopes.and(SmartScopes.ANCESTORS.flags) > 0) {
scopesSet.addAll(myAncestors)
count += myAncestors.size
}
if (parent != null && scopes.and(SmartScopes.PARENT.flags) > 0) {
scopesSet.add(parent)
count++
}
if (scopes.and(SmartScopes.SELF.flags) > 0) {
scopesSet.add(this)
count++
}
if (scopes.and(SmartScopes.CHILDREN.flags) > 0) {
scopesSet.addAll(myChildren)
count += myChildren.size
}
if (scopes.and(SmartScopes.DESCENDANTS.flags) > 0) {
scopesSet.addAll(myDescendants)
count += myDescendants.size
}
return count
}
private fun addConsumedKeyIndices(dataKey: SmartDataKey<*>, scopesSet: Set<SmartDataScope>, indices: HashSet<Int>) {
for (scope in scopesSet) {
scope.addKeyIndices(dataKey, indices)
}
}
private fun addKeyIndices(dataKey: SmartDataKey<*>, indicesSet: HashSet<Int>) {
val indices = myConsumers[dataKey] ?: return
for (index in indices) {
val rawValue = getRawValue(dataKey, index)
if (rawValue == null || (rawValue is SmartVersionedDataAlias<*> && rawValue.alias === dataKey.myNullData)) {
indicesSet.add(index)
}
}
}
private fun addConsumedKeys(keys: HashSet<SmartDataKey<*>>) {
for (entry in myConsumers) {
keys.add(entry.key)
}
}
/**
* used to create smart data relationships
*
* can only be invoked from top level scope
*/
fun finalizeAllScopes() {
if (parent != null) throw IllegalStateException("finalizeScope can only be invoked on top level dataScope object")
val consumedKeys = HashSet<SmartDataKey<*>>()
val keyScopes = myChildren.union(myDescendants).union(setOf(this))
for (scope in keyScopes) {
scope.addConsumedKeys(consumedKeys)
}
val computeKeys = SmartDataScopeManager.computeKeyOrder(consumedKeys)
// compute the keys in order
for (keyList in computeKeys) {
for (key in keyList) {
finalizeKey(key, consumedKeys)
}
}
// copy parent values to child consumers that have defaults
finalizeParentProvided()
// FIX: validate that all have been computed before clearing consumers for possible next batch
traceAndClear()
for (scope in keyScopes) {
scope.traceAndClear()
}
}
private fun traceAndClear() {
if (SmartDataScopeManager.INSTANCE.trace) {
for ((dataKey, indices) in consumers) {
print("$name: consumer of ${dataKey.myId} ")
for (index in indices) {
print("[$index: ${dataKey.value(this, index)?.get()}] ")
}
println()
}
}
myConsumers.clear()
}
private fun finalizeParentProvided() {
if (parent != null) {
for (entry in myConsumers) {
for (index in entry.value) {
val value = getRawValue(entry.key, index)
if (value is SmartVersionedDataAlias<*>) {
if (value.alias === entry.key.myNullData) {
// see if the parent has a value
entry.key.setAlias(value, parent, index)
}
}
}
}
}
for (scope in children) {
scope.finalizeParentProvided()
}
}
private fun finalizeKey(dataKey: SmartDataKey<*>, consumedKeys: Set<SmartDataKey<*>>) {
if (parent != null) throw IllegalStateException("finalizeKey should only be called from top level scope")
val keyScopes = myChildren.union(myDescendants).union(setOf(this))
val indicesSet = HashSet<Int>()
val dependents = SmartDataScopeManager.dependentKeys[dataKey] ?: setOf()
addConsumedKeyIndices(dataKey, keyScopes, indicesSet)
for (dependentKey in dependents) {
addConsumedKeyIndices(dependentKey, keyScopes, indicesSet)
}
if (!indicesSet.isEmpty()) {
// we add a value at the top level for all dependencies of this key if one does not exist, this will provide the missing default for all descendants
for (key in dataKey.dependencies) {
for (index in indicesSet) {
if (getValue(key, index) == null) {
key.setNullData(this, index)
}
}
}
// now we compute
if (dataKey.myScopes and SmartScopes.RESULT_TOP.flags > 0) {
// results go to the top scope
finalizeKeyScope(dataKey, consumedKeys, keyScopes, indicesSet)
} else {
// results go to the individual scopes, finalization is done top down
val sortedScopes = keyScopes.sortedBy { it.level }
for (scope in sortedScopes) {
scope.finalizeKeyScope(dataKey, consumedKeys, keyScopes, indicesSet)
}
}
}
}
@Suppress("UNUSED_PARAMETER")
private fun finalizeKeyScope(dataKey: SmartDataKey<*>, consumedKeys: Set<SmartDataKey<*>>, allScopeSet: Set<SmartDataScope>, allIndicesSet: Set<Int>) {
val scopesSet = HashSet<SmartDataScope>()
addKeyScopes(dataKey.myScopes, scopesSet)
if (!scopesSet.isEmpty()) {
val indicesSet = HashSet<Int>()
for (index in allIndicesSet) {
if (canSetDataPoint(dataKey, index)) indicesSet.add(index)
}
if (!indicesSet.isEmpty()) {
if (SmartDataScopeManager.INSTANCE.trace) println("finalizing $name[$dataKey] indices $indicesSet on ${scopesSet.fold("") { a, b -> a + " " + b.name }}")
dataKey.createData(this, scopesSet, indicesSet)
}
}
}
}
| apache-2.0 | 43e54953a5933bcd27631e6d0a015ab4 | 41.043093 | 317 | 0.644459 | 4.84475 | false | false | false | false |
marvec/engine | lumeer-core/src/main/kotlin/io/lumeer/core/adapter/PermissionAdapter.kt | 2 | 27537 | /*
* Lumeer: Modern Data Definition and Processing Platform
*
* Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates.
*
* 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 io.lumeer.core.adapter
import io.lumeer.api.model.*
import io.lumeer.api.model.Collection
import io.lumeer.api.model.common.Resource
import io.lumeer.api.model.viewConfig.FormConfig
import io.lumeer.api.util.PermissionUtils
import io.lumeer.core.exception.NoDocumentPermissionException
import io.lumeer.core.exception.NoLinkInstancePermissionException
import io.lumeer.core.exception.NoPermissionException
import io.lumeer.core.exception.NoResourcePermissionException
import io.lumeer.core.util.DocumentUtils
import io.lumeer.core.util.FunctionRuleJsParser
import io.lumeer.core.util.LinkInstanceUtils
import io.lumeer.core.util.QueryUtils
import io.lumeer.storage.api.dao.*
class PermissionAdapter(
private val userDao: UserDao,
private val groupDao: GroupDao,
private val viewDao: ViewDao,
private val linkTypeDao: LinkTypeDao,
private val collectionDao: CollectionDao
) {
private val usersCache = mutableMapOf<String, List<User>>()
private val viewCache = mutableMapOf<String, View>()
private val collectionCache = mutableMapOf<String, Collection>()
private val userCache = mutableMapOf<String, User>()
private val groupsCache = mutableMapOf<String, List<Group>>()
private val linkTypes = lazy { linkTypeDao.allLinkTypes }
private val collections = lazy { collectionDao.allCollections }
private var currentViewId: String? = null
fun setViewId(viewId: String) {
currentViewId = viewId
}
fun getViewId() = currentViewId
fun activeView(): View? {
if (currentViewId.orEmpty().isNotEmpty()) {
return getView(currentViewId!!)
}
return null
}
fun invalidateUserCache() {
usersCache.clear()
userCache.clear()
groupsCache.clear()
}
fun invalidateCollectionCache() {
collectionCache.clear()
}
fun isPublic(organization: Organization?, project: Project?) = project?.isPublic ?: false
fun canReadAllInWorkspace(organization: Organization, project: Project?, userId: String): Boolean {
val user = getUser(userId)
val groups = PermissionUtils.getUserGroups(organization, user, getGroups(organization.id))
if (PermissionUtils.getUserRolesInResource(organization, user, groups).any { role -> role.isTransitive && role.type === RoleType.Read }) {
return true
}
return project?.let { PermissionUtils.getUserRolesInResource(it, user, groups).any { role -> role.isTransitive && role.type === RoleType.Read } } ?: false
}
fun getOrganizationUsersByRole(organization: Organization, roleType: RoleType): Set<String> {
return PermissionUtils.getOrganizationUsersByRole(organization, getUsers(organization.id), getGroups(organization.id), roleType)
}
fun getOrganizationReadersDifference(organization1: Organization, organization2: Organization): RolesDifference {
return PermissionUtils.getOrganizationUsersDifferenceByRole(organization1, organization2, getUsers(organization1.id), getGroups(organization1.id), RoleType.Read)
}
fun getProjectUsersByRole(organization: Organization, project: Project?, roleType: RoleType): Set<String> {
return PermissionUtils.getProjectUsersByRole(organization, project, getUsers(organization.id), getGroups(organization.id), roleType)
}
fun getProjectReadersDifference(organization: Organization, project1: Project, project2: Project): RolesDifference {
return PermissionUtils.getProjectUsersDifferenceByRole(organization, project1, project2, getUsers(organization.id), getGroups(organization.id), RoleType.Read)
}
fun <T : Resource> getResourceUsersByRole(organization: Organization, project: Project?, resource: T, roleType: RoleType): Set<String> {
return PermissionUtils.getResourceUsersByRole(organization, project, resource, getUsers(organization.id), getGroups(organization.id), roleType)
}
fun getLinkTypeUsersByRole(organization: Organization, project: Project?, linkType: LinkType, roleType: RoleType): Set<String> {
return PermissionUtils.getLinkTypeUsersByRole(organization, project, linkType, getLinkTypeCollections(linkType), getUsers(organization.id), getGroups(organization.id), roleType)
}
fun <T : Resource> getResourceReadersDifference(organization: Organization?, project: Project?, resource1: T, resource2: T): RolesDifference {
if (resource1.type == ResourceType.ORGANIZATION) {
return getOrganizationReadersDifference(resource1 as Organization, resource2 as Organization)
}
if (organization != null) {
if (resource1.type == ResourceType.PROJECT) {
return getProjectReadersDifference(organization, resource1 as Project, resource2 as Project)
}
return PermissionUtils.getResourceUsersDifferenceByRole(organization, project, resource1, resource2, getUsers(organization.id), getGroups(organization.id), RoleType.Read)
}
return RolesDifference(setOf(), setOf())
}
fun getLinkTypeReadersDifference(organization: Organization, project: Project?, linkType1: LinkType, linkType2: LinkType): RolesDifference {
return PermissionUtils.getLinkTypeUsersDifferenceByRole(organization, project, linkType1, linkType2, getLinkTypeCollections(linkType1), getUsers(organization.id), getGroups(organization.id), RoleType.Read)
}
fun <T : Resource> getUserRolesInResource(organization: Organization?, project: Project?, resource: T, userId: String): Set<RoleType> {
return getUserRolesInResource(organization, project, resource, getUser(userId))
}
fun <T : Resource> getUserRolesInResource(organization: Organization?, project: Project?, resource: T, user: User): Set<RoleType> {
return PermissionUtils.getUserRolesInResource(organization, project, resource, user, getGroups(organization?.id ?: resource.id))
}
fun <T : Resource> getUserRolesInResource(organization: Organization?, project: Project?, resource: T, group: Group): Set<RoleType> {
return PermissionUtils.getGroupRolesInResource(organization, project, resource, group)
}
fun getUserRolesInCollectionWithView(organization: Organization?, project: Project?, collection: Collection, user: User): Set<RoleType> {
val view = activeView()
if (view != null) {
val viewRoles = getUserRolesInResource(organization, project, view, user)
val authorId = view.authorId.orEmpty()
val collectionIds = QueryUtils.getViewCollectionIds(view, linkTypes.value)
if (collectionIds.contains(collection.id) && authorId.isNotEmpty()) { // does the view contain the collection?
val authorRoles = getUserRolesInResource(organization, project, collection, authorId)
return viewRoles.intersect(authorRoles)
}
}
return emptySet()
}
fun getUserRolesInLinkTypeWithView(organization: Organization, project: Project?, linkType: LinkType, user: User): Set<RoleType> {
val view = activeView()
if (view != null) {
val viewRoles = getUserRolesInResource(organization, project, view, user)
val authorId = view.authorId.orEmpty()
val linkTypeIds = view.allLinkTypeIds
if (linkTypeIds.contains(linkType.id) && authorId.isNotEmpty()) { // does the view contain the linkType?
val authorRoles = getUserRolesInLinkType(organization, project, linkType, getUser(authorId))
return viewRoles.intersect(authorRoles)
}
}
return emptySet()
}
fun getUserRolesInLinkType(organization: Organization, project: Project?, linkType: LinkType, userId: String): Set<RoleType> {
return getUserRolesInLinkType(organization, project, linkType, getUser(userId))
}
fun getUserRolesInLinkType(organization: Organization, project: Project?, linkType: LinkType, user: User): Set<RoleType> {
return getUserRolesInLinkType(organization, project, linkType, getLinkTypeCollections(linkType), user)
}
fun getUserRolesInLinkType(organization: Organization, project: Project?, linkType: LinkType, collections: List<Collection>, userId: String): Set<RoleType> {
return getUserRolesInLinkType(organization, project, linkType, collections, getUser(userId))
}
fun getUserRolesInLinkType(organization: Organization, project: Project?, linkType: LinkType, collections: List<Collection>, user: User): Set<RoleType> {
return PermissionUtils.getUserRolesInLinkType(organization, project, linkType, collections, user, getGroups(organization.id))
}
fun checkRole(organization: Organization?, project: Project?, resource: Resource, role: RoleType, userId: String) {
if (!hasRole(organization, project, resource, role, userId)) {
throw NoResourcePermissionException(resource)
}
}
fun checkAllRoles(organization: Organization?, project: Project?, resource: Resource, roles: Set<RoleType>, userId: String) {
if (!hasAllRoles(organization, project, resource, roles, userId)) {
throw NoResourcePermissionException(resource)
}
}
fun hasAllRoles(organization: Organization?, project: Project?, resource: Resource, roles: Set<RoleType>, userId: String): Boolean {
return roles.all { hasRole(organization, project, resource, it, userId) }
}
fun checkAnyRole(organization: Organization?, project: Project?, resource: Resource, roles: Set<RoleType>, userId: String) {
if (!hasAnyRole(organization, project, resource, roles, userId)) {
throw NoResourcePermissionException(resource)
}
}
fun hasAnyRole(organization: Organization?, project: Project?, resource: Resource, roles: Set<RoleType>, userId: String): Boolean {
return roles.any { hasRole(organization, project, resource, it, userId) }
}
fun checkRoleInCollectionWithView(organization: Organization?, project: Project?, collection: Collection, role: RoleType, userId: String) {
if (!hasRoleInCollectionWithView(organization, project, collection, role, userId)) {
throw NoResourcePermissionException(collection)
}
}
fun hasRoleInCollectionWithView(organization: Organization?, project: Project?, collection: Collection, role: RoleType, userId: String): Boolean {
return hasRole(organization, project, collection, role, userId) || hasRoleInCollectionViaView(organization, project, collection, role, role, userId, activeView())
}
fun hasAnyRoleInCollectionWithView(organization: Organization?, project: Project?, collection: Collection, roles: List<RoleType>, userId: String): Boolean {
return roles.any { hasRoleInCollectionWithView(organization, project, collection, it, userId) }
}
fun checkCanDelete(organization: Organization?, project: Project?, resource: Resource, userId: String) {
if (!hasRole(organization, project, resource, RoleType.Manage, userId) || resource.isNonRemovable) {
throw NoResourcePermissionException(resource)
}
}
fun checkCanDelete(organization: Organization, project: Project?, linkType: LinkType, userId: String) {
if (!hasRole(organization, project, linkType, getLinkTypeCollections(linkType), RoleType.Manage, userId)) {
throw NoPermissionException(ResourceType.LINK_TYPE.toString())
}
}
private fun hasRoleInCollectionViaView(organization: Organization?, project: Project?, collection: Collection, role: RoleType, viewRole: RoleType, userId: String, view: View?): Boolean {
if (view != null && (hasRole(organization, project, view, viewRole, userId) || hasExtendedPermissionsInCollectionViaView(organization, project, collection, role, userId, view))) { // does user have access to the view?
val authorId = view.authorId.orEmpty()
val collectionIds = QueryUtils.getViewCollectionIds(view, linkTypes.value)
if (collectionIds.contains(collection.id) && authorId.isNotEmpty()) { // does the view contain the collection?
if (hasRole(organization, project, collection, role, authorId)) { // has the view author access to the collection?
return true // grant access
}
}
}
return false
}
private fun hasExtendedPermissionsInCollectionViaView(organization: Organization?, project: Project?, collection: Collection, role: RoleType, userId: String, view: View?): Boolean {
if (view?.perspective == Perspective.Form) {
val additionalIds = QueryUtils.getViewAdditionalCollectionIds(view, linkTypes.value)
if (additionalIds.contains(collection.id)) {
return when (role) {
RoleType.DataRead -> hasAnyRole(organization, project, view, setOf(RoleType.DataContribute, RoleType.DataWrite), userId)
else -> false
}
}
}
return false
}
fun checkCanReadDocument(organization: Organization, project: Project?, document: Document?, collection: Collection, userId: String) {
if (!canReadDocument(organization, project, document, collection, userId)) {
throw NoDocumentPermissionException(document)
}
}
fun canReadDocument(organization: Organization, project: Project?, document: Document?, collection: Collection, userId: String): Boolean {
if (document == null) return false
return (hasRoleInCollectionWithView(organization, project, collection, RoleType.Read, userId) && hasRoleInCollectionWithView(organization, project, collection, RoleType.DataRead, userId))
|| (canReadWorkspace(organization, project, userId) && isDocumentOwner(organization, project, document, collection, userId))
}
fun checkCanReadLinkInstance(organization: Organization, project: Project?, linkInstance: LinkInstance?, linkType: LinkType, userId: String) {
if (!canReadLinkInstance(organization, project, linkInstance, linkType, userId)) {
throw NoLinkInstancePermissionException(linkInstance)
}
}
fun canReadLinkInstance(organization: Organization, project: Project?, linkInstance: LinkInstance?, linkType: LinkType, userId: String): Boolean {
if (linkInstance == null) return false
return (hasRoleInLinkTypeWithView(organization, project, linkType, RoleType.Read, userId) && hasRoleInLinkTypeWithView(organization, project, linkType, RoleType.DataRead, userId))
|| (canReadWorkspace(organization, project, userId) && isLinkOwner(organization, project, linkInstance, linkType, userId))
}
fun checkCanCreateDocuments(organization: Organization, project: Project?, collection: Collection, userId: String) {
if (!canCreateDocuments(organization, project, collection, userId)) {
throw NoResourcePermissionException(collection)
}
}
fun checkCanCreateLinkInstances(organization: Organization, project: Project?, linkType: LinkType, userId: String) {
if (!canCreateLinkInstances(organization, project, linkType, userId)) {
throw NoPermissionException(ResourceType.LINK_TYPE.toString())
}
}
fun canCreateDocuments(organization: Organization, project: Project?, collection: Collection, userId: String): Boolean {
return canReadWorkspace(organization, project, userId) && hasRoleInCollectionWithView(organization, project, collection, RoleType.DataContribute, userId)
}
fun canReadWorkspace(organization: Organization, project: Project?, userId: String): Boolean {
return project != null && hasRole(organization, project, project, RoleType.Read, userId)
}
fun canCreateLinkInstances(organization: Organization, project: Project?, linkType: LinkType, userId: String): Boolean {
return canReadWorkspace(organization, project, userId) && hasRoleInLinkTypeWithView(organization, project, linkType, RoleType.DataContribute, userId)
}
fun checkCanEditDocument(organization: Organization, project: Project?, document: Document?, collection: Collection, userId: String) {
if (!canEditDocument(organization, project, document, collection, userId)) {
throw NoDocumentPermissionException(document)
}
}
fun checkCanEditLinkInstance(organization: Organization, project: Project?, linkInstance: LinkInstance, linkType: LinkType, userId: String) {
if (!canEditLinkInstance(organization, project, linkInstance, linkType, userId)) {
throw NoLinkInstancePermissionException(linkInstance)
}
}
fun canEditDocument(organization: Organization, project: Project?, document: Document?, collection: Collection, userId: String): Boolean {
if (document == null) return false
return (hasRoleInCollectionWithView(organization, project, collection, RoleType.Read, userId) && hasRoleInCollectionWithView(organization, project, collection, RoleType.DataWrite, userId))
|| (canReadWorkspace(organization, project, userId) && isDocumentOwner(organization, project, document, collection, userId))
}
fun canEditLinkInstance(organization: Organization, project: Project?, linkInstance: LinkInstance?, linkType: LinkType, userId: String): Boolean {
if (linkInstance == null) return false
return (hasRoleInLinkTypeWithView(organization, project, linkType, RoleType.Read, userId) && hasRoleInLinkTypeWithView(organization, project, linkType, RoleType.DataWrite, userId))
|| (canReadWorkspace(organization, project, userId) && isLinkOwner(organization, project, linkInstance, linkType, userId))
}
fun checkCanDeleteDocument(organization: Organization, project: Project?, document: Document?, collection: Collection, userId: String) {
if (!canDeleteDocument(organization, project, document, collection, userId)) {
throw NoDocumentPermissionException(document)
}
}
fun checkCanDeleteLinkInstance(organization: Organization, project: Project?, linkInstance: LinkInstance?, linkType: LinkType, userId: String) {
if (!canDeleteLinkInstance(organization, project, linkInstance, linkType, userId)) {
throw NoLinkInstancePermissionException(linkInstance)
}
}
fun canDeleteDocument(organization: Organization, project: Project?, document: Document?, collection: Collection, userId: String): Boolean {
if (document == null) return false
return (hasRoleInCollectionWithView(organization, project, collection, RoleType.Read, userId) && hasRoleInCollectionWithView(organization, project, collection, RoleType.DataDelete, userId))
|| (canReadWorkspace(organization, project, userId) && isDocumentOwner(organization, project, document, collection, userId))
}
fun canDeleteLinkInstance(organization: Organization, project: Project?, linkInstance: LinkInstance?, linkType: LinkType, userId: String): Boolean {
if (linkInstance == null) return false
return (hasRoleInLinkTypeWithView(organization, project, linkType, RoleType.Read, userId) && hasRoleInLinkTypeWithView(organization, project, linkType, RoleType.DataDelete, userId))
|| (canReadWorkspace(organization, project, userId) && isLinkOwner(organization, project, linkInstance, linkType, userId))
}
private fun isDocumentOwner(organization: Organization, project: Project?, document: Document, collection: Collection, userId: String): Boolean {
return isDocumentContributor(organization, project, document, collection, userId) || DocumentUtils.isDocumentOwnerByPurpose(collection, document, getUser(userId), getGroups(organization.id), getUsers(organization.id))
}
private fun isDocumentContributor(organization: Organization, project: Project?, document: Document, collection: Collection, userId: String): Boolean {
return hasRoleInCollectionWithView(organization, project, collection, RoleType.DataContribute, userId) && DocumentUtils.isDocumentOwner(collection, document, userId)
}
private fun isLinkOwner(organization: Organization, project: Project?, linkInstance: LinkInstance, linkType: LinkType, userId: String): Boolean {
return hasRoleInLinkTypeWithView(organization, project, linkType, RoleType.DataContribute, userId) && LinkInstanceUtils.isLinkInstanceOwner(linkType, linkInstance, userId)
}
fun checkRoleInLinkTypeWithView(organization: Organization, project: Project?, linkType: LinkType, role: RoleType, userId: String) {
if (!hasRoleInLinkTypeWithView(organization, project, linkType, role, userId)) {
throw NoPermissionException(ResourceType.LINK_TYPE.toString())
}
}
fun hasRoleInLinkTypeWithView(organization: Organization, project: Project?, linkType: LinkType, role: RoleType, userId: String): Boolean {
val collections = getLinkTypeCollections(linkType)
return hasRole(organization, project, linkType, collections, role, userId) || hasRoleInLinkTypeViaView(organization, project, linkType, collections, role, role, userId, activeView())
}
private fun getLinkTypeCollections(linkType: LinkType) =
// on custom permissions collections are not needed
if (linkType.permissionsType == LinkPermissionsType.Custom) listOf() else linkType.collectionIds.orEmpty().subList(0, 2).map { getCollection(it) }
private fun hasRoleInLinkTypeViaView(organization: Organization, project: Project?, linkType: LinkType, collections: List<Collection>, role: RoleType, viewRole: RoleType, userId: String, view: View?): Boolean {
if (view != null && (hasRole(organization, project, view, viewRole, userId) || hasExtendedPermissionsInLinkTypeViaView(organization, project, linkType, role, userId, view))) { // does user have access to the view?
val authorId = view.authorId.orEmpty()
val linkTypeIds = view.allLinkTypeIds
if (linkTypeIds.contains(linkType.id) && authorId.isNotEmpty()) { // does the view contain the linkType?
if (hasRole(organization, project, linkType, collections, role, authorId)) { // has the view author access to the linkType?
return true // grant access
}
}
}
return false
}
private fun hasExtendedPermissionsInLinkTypeViaView(organization: Organization, project: Project?, linkType: LinkType, role: RoleType, userId: String, view: View?): Boolean {
if (view?.perspective == Perspective.Form) {
val collectionId = FormConfig(view).collectionId.orEmpty()
if (view.additionalLinkTypeIds.contains(linkType.id) && linkType.collectionIds.contains(collectionId)) {
return when (role) {
RoleType.DataContribute -> hasAnyRole(organization, project, view, setOf(RoleType.DataContribute, RoleType.DataWrite), userId)
in listOf(RoleType.DataRead, RoleType.Read) -> hasAnyRole(organization, project, view, setOf(RoleType.DataContribute, RoleType.DataWrite, RoleType.DataRead), userId)
else -> false
}
}
}
return false
}
fun checkRoleInLinkType(organization: Organization, project: Project?, linkType: LinkType, role: RoleType, userId: String) {
if (!hasRoleInLinkType(organization, project, linkType, role, userId)) {
throw NoPermissionException(ResourceType.LINK_TYPE.toString())
}
}
fun checkAnyRoleInLinkType(organization: Organization, project: Project?, linkType: LinkType, roles: Set<RoleType>, userId: String) {
if (!hasAnyRoleInLinkType(organization, project, linkType, roles, userId)) {
throw NoPermissionException(ResourceType.LINK_TYPE.toString())
}
}
fun hasAnyRoleInLinkType(organization: Organization, project: Project?, linkType: LinkType, roles: Set<RoleType>, userId: String): Boolean {
val linkTypeCollections = getLinkTypeCollections(linkType);
return roles.any { hasRoleInLinkType(organization, project, linkType, linkTypeCollections, it, userId) }
}
fun hasRoleInLinkType(organization: Organization, project: Project?, linkType: LinkType, role: RoleType, userId: String): Boolean {
return hasRoleInLinkType(organization, project, linkType, getLinkTypeCollections(linkType), role, userId)
}
fun hasRoleInLinkType(organization: Organization, project: Project?, linkType: LinkType, collections: List<Collection>, role: RoleType, userId: String): Boolean {
return hasRole(organization, project, linkType, collections, role, userId)
}
fun hasRole(organization: Organization?, project: Project?, resource: Resource, role: RoleType, userId: String): Boolean {
return getUserRolesInResource(organization, project, resource, userId).contains(role)
}
fun hasRole(organization: Organization?, project: Project?, resource: Resource, role: RoleType, group: Group): Boolean {
return getUserRolesInResource(organization, project, resource, group).contains(role)
}
fun hasRole(organization: Organization, project: Project?, linkType: LinkType, collection: List<Collection>, role: RoleType, userId: String): Boolean {
return getUserRolesInLinkType(organization, project, linkType, collection, userId).contains(role)
}
fun checkFunctionRuleAccess(organization: Organization, project: Project?, js: String, role: RoleType, userId: String) {
val collections = collections.value.associateBy { it.id }
val collectionIds = collections.keys
val linkTypes = linkTypes.value.associateBy { it.id }
val linkTypeIds = linkTypes.keys
val references = FunctionRuleJsParser.parseRuleFunctionJs(js, collectionIds, linkTypeIds)
references.forEach { reference ->
when (reference.resourceType) {
ResourceType.COLLECTION -> {
checkRole(organization, project, collections[reference.id]!!, role, userId)
}
ResourceType.LINK -> {
checkRoleInLinkType(organization, project, linkTypes[reference.id]!!, role, userId)
}
else -> {
throw NoPermissionException("Rule")
}
}
}
}
fun getUser(userId: String): User {
if (userCache.containsKey(userId)) {
return userCache[userId]!!
}
val user = userDao.getUserById(userId)
if (user != null) userCache[userId] = user
return user ?: User(userId, userId, userId, setOf())
}
fun getUsers(organizationId: String): List<User> {
return usersCache.computeIfAbsent(organizationId) { userDao.getAllUsers(organizationId) }
}
fun getView(viewId: String): View {
return viewCache.computeIfAbsent(viewId) { viewDao.getViewById(viewId) }
}
fun getCollection(collectionId: String): Collection {
return collectionCache.computeIfAbsent(collectionId) { collectionDao.getCollectionById(collectionId) }
}
fun getGroups(organizationId: String): List<Group> {
return groupsCache.computeIfAbsent(organizationId) { groupDao.getAllGroups(organizationId) }
}
}
| gpl-3.0 | 561594a0f072aff774ac8981af38a707 | 54.074 | 223 | 0.734212 | 5.042483 | false | false | false | false |
Magneticraft-Team/Magneticraft | src/main/kotlin/com/cout970/magneticraft/misc/network/SyncVariable.kt | 2 | 1260 | package com.cout970.magneticraft.misc.network
import com.cout970.magneticraft.misc.gui.ValueAverage
/**
* Created by cout970 on 2017/07/01.
*/
abstract class SyncVariable(val id: Int) {
abstract fun read(ibd: IBD)
abstract fun write(ibd: IBD)
}
class FloatSyncVariable(id: Int, val getter: () -> Float, val setter: (Float) -> Unit) : SyncVariable(id) {
override fun read(ibd: IBD) = ibd.getFloat(id, setter)
override fun write(ibd: IBD) {
ibd.setFloat(id, getter())
}
}
class IntSyncVariable(id: Int, val getter: () -> Int, val setter: (Int) -> Unit) : SyncVariable(id) {
override fun read(ibd: IBD) = ibd.getInteger(id, setter)
override fun write(ibd: IBD) {
ibd.setInteger(id, getter())
}
}
class StringSyncVariable(id: Int, val getter: () -> String, val setter: (String) -> Unit) : SyncVariable(id) {
override fun read(ibd: IBD) = ibd.getString(id, setter)
override fun write(ibd: IBD) {
ibd.setString(id, getter())
}
}
class AverageSyncVariable(id: Int, val valueAverage: ValueAverage) : SyncVariable(id) {
override fun read(ibd: IBD) = ibd.getFloat(id) { valueAverage.storage = it }
override fun write(ibd: IBD) {
ibd.setFloat(id, valueAverage.average)
}
} | gpl-2.0 | b188ee7c38b7ded0ff0d5987cdea0307 | 29.02381 | 110 | 0.661111 | 3.433243 | false | false | false | false |
ysl3000/PathfindergoalAPI | Pathfinder_1_14/src/main/java/com/github/ysl3000/bukkit/pathfinding/craftbukkit/v1_14_R1/pathfinding/CraftNavigation.kt | 1 | 1291 | package com.github.ysl3000.bukkit.pathfinding.craftbukkit.v1_14_R1.pathfinding
import com.github.ysl3000.bukkit.pathfinding.AbstractNavigation
import net.minecraft.server.v1_14_R1.NavigationAbstract
import org.bukkit.craftbukkit.v1_14_R1.entity.CraftEntity
class CraftNavigation(private val navigationAbstract: NavigationAbstract, private val defaultSpeed: Double) : AbstractNavigation(
doneNavigating = { navigationAbstract.n() },
pathSearchRange = { navigationAbstract.i() },
moveToPositionU = { x, y, z -> navigationAbstract.a(x, y, z, defaultSpeed) },
moveToPositionB = { x, y, z, speed -> navigationAbstract.a(x, y, z, speed) },
moveToEntityU = { entity -> navigationAbstract.a((entity as CraftEntity).handle, defaultSpeed) },
moveToentityB = { entity, speed -> navigationAbstract.a((entity as CraftEntity).handle, speed) },
speedU = { speed -> navigationAbstract.a(speed) },
clearPathEntityU = navigationAbstract::o,
setCanPassDoors = navigationAbstract.q()::a,
setCanOpenDoors = navigationAbstract.q()::b,
setCanFloat = navigationAbstract.q()::c,
canPassDoors = navigationAbstract.q()::c,
canOpenDoors = navigationAbstract.q()::d,
canFloat = navigationAbstract.q()::e
)
| mit | 0021cba0470e7982545c298d625bf769 | 57.681818 | 129 | 0.707978 | 4.151125 | false | false | false | false |
mrebollob/LoteriadeNavidad | androidApp/src/main/java/com/mrebollob/loteria/android/presentation/settings/manageticket/ui/ManageTicketItemView.kt | 1 | 3424 | package com.mrebollob.loteria.android.presentation.settings.manageticket.ui
import android.content.res.Configuration
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Delete
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.mrebollob.loteria.android.R
import com.mrebollob.loteria.android.presentation.platform.ui.theme.LotteryTheme
import com.mrebollob.loteria.android.presentation.platform.ui.theme.SystemRed
@Composable
fun ManageTicketItemView(
modifier: Modifier = Modifier,
title: String,
subTitle: String = "",
onClick: () -> Unit
) {
Surface(
modifier = modifier
.fillMaxWidth(),
color = MaterialTheme.colors.background
) {
Row(
modifier = Modifier
.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
) {
Row(
verticalAlignment = Alignment.Bottom
) {
Text(
text = title,
style = MaterialTheme.typography.subtitle1,
color = MaterialTheme.colors.onSurface,
)
Text(
modifier = Modifier
.padding(start = 8.dp),
color = MaterialTheme.colors.onSurface.copy(0.7f),
text = subTitle,
style = MaterialTheme.typography.body2
)
}
Spacer(modifier = Modifier.weight(1f))
Icon(
modifier = Modifier
.padding(vertical = 24.dp)
.clickable { onClick() }
.size(24.dp),
imageVector = Icons.Outlined.Delete,
contentDescription = stringResource(id = R.string.manage_tickets_screen_delete_action),
tint = SystemRed
)
}
}
}
@Preview("Manage ticket item")
@Preview("Manage ticket item (dark)", uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
fun PreviewManageTicketItemView() {
LotteryTheme {
Surface(
modifier = Modifier.fillMaxSize()
) {
Column(
modifier = Modifier.padding(16.dp)
) {
ManageTicketItemView(
title = "Familia",
subTitle = "00000 - 20 €",
onClick = {}
)
ManageTicketItemView(
title = "Amigos",
subTitle = "99999 - 200 €",
onClick = {}
)
}
}
}
}
| apache-2.0 | 4731af08a38cf7a19459c8d0d91efe09 | 32.203883 | 103 | 0.602047 | 4.963716 | false | false | false | false |
SUPERCILEX/Robot-Scouter | library/core-ui/src/main/java/com/supercilex/robotscouter/core/ui/StateHolder.kt | 1 | 586 | package com.supercilex.robotscouter.core.ui
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
class StateHolder<T : Any>(state: T) {
private val _liveData = MutableLiveData(state)
val liveData: LiveData<T> get() = _liveData
private var _value: T = state
val value: T get() = _value
fun update(notify: Boolean = true, block: T.() -> T) {
synchronized(LOCK) {
_value = block(value)
if (notify) _liveData.postValue(value)
}
}
private companion object {
val LOCK = Object()
}
}
| gpl-3.0 | a87f15f87218d8547a0d2b24690bcccb | 24.478261 | 58 | 0.629693 | 4.041379 | false | false | false | false |
lehaSVV2009/dnd | api/src/main/kotlin/kadet/dnd/api/service/SceneService.kt | 1 | 3822 | package kadet.dnd.api.service
import kadet.dnd.api.model.Hero
import kadet.dnd.api.model.Scene
import kadet.dnd.api.model.Talent
import kadet.dnd.api.model.Turn
import kadet.dnd.api.repository.DayRepository
import kadet.dnd.api.repository.HeroRepository
import kadet.dnd.api.repository.SceneRepository
import kadet.dnd.api.repository.TalentRepository
import kadet.dnd.api.repository.TurnRepository
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
fun isAvailableTalent(talent: Talent?, usedInScene: Set<String?>, usedInDay: Set<String?>): Boolean {
return talent?.limitType == "Неограниченный"
|| (talent?.limitType == "На сцену" && !usedInScene.contains(talent.id))
|| (talent?.limitType == "На день" && !usedInDay.contains(talent.id))
}
@Service
class SceneService(val sceneRepository: SceneRepository,
val turnRepository: TurnRepository,
val talentRepository: TalentRepository,
val heroRepository: HeroRepository,
val dayRepository: DayRepository) {
/**
* Start scene within a day.
*/
@Transactional
fun startScene(dayId: String): Scene {
val day = dayRepository.findOne(dayId)
val scene = sceneRepository.save(Scene())
day.scenes.add(scene)
dayRepository.save(day)
return scene
}
/**
* Stop scene within a day.
*/
@Transactional
fun stopScene(sceneId: String): Scene {
val scene = sceneRepository.findOne(sceneId)
scene.finished = true
return sceneRepository.save(scene)
}
/**
* Add new turn to scene. (Turn is an action of hero).
*/
@Transactional
fun makeMove(sceneId: String, turn: Turn?): Turn {
val scene = sceneRepository.findOne(sceneId)
val hero = heroRepository.findOne(turn?.owner?.id)
val talent = talentRepository.findOne(turn?.action?.id)
var newTurn = Turn()
newTurn.action = talent
newTurn.owner = hero
newTurn = turnRepository.save(newTurn)
scene.turns.add(newTurn)
sceneRepository.save(scene)
return newTurn
}
/**
* Delete scene from db.
*/
@Transactional
fun delete(sceneId: String) {
sceneRepository.delete(sceneId)
}
/**
* Fetch all talents that are still available in scene.
* All day and scene talents that already used by hero can not be in list.
*/
fun findAvailableTalents(sceneId: String, heroId: String): Set<Talent> {
val scene = sceneRepository.findOne(sceneId)
val hero = heroRepository.findOne(heroId)
return filterAvailableTalents(hero.talents, hero, scene)
}
fun filterAvailableTalents(talents: Set<Talent>, hero: Hero, scene: Scene): Set<Talent> {
// TODO add custom query
val usedInScene = scene.turns
.filter { it.owner?.id == hero.id }
.map { it.action }
.filter { it?.limitType == "На сцену" }
.map { it?.id }
.toSet()
// TODO add custom query
val usedInDay = dayRepository.findAll()
.filter {
it.scenes.map {
it.id
}.contains(scene.id)
}
.flatMap { it.scenes }
.flatMap { it.turns }
.filter { it.owner?.id == hero.id }
.map { it.action }
.filter { it?.limitType == "На день" }
.map { it?.id }
.toSet()
return talents
.filter { isAvailableTalent(it, usedInScene, usedInDay) }
.toSet()
}
}
| mit | 8942db45f1ae54d6d42b0595dd3aedb2 | 32.469027 | 101 | 0.599947 | 4.297727 | false | false | false | false |
AllanWang/Frost-for-Facebook | app/src/main/kotlin/com/pitchedapps/frost/activities/SettingsActivity.kt | 1 | 9100 | /*
* Copyright 2018 Allan Wang
*
* 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.pitchedapps.frost.activities
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.media.RingtoneManager
import android.net.Uri
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import ca.allanwang.kau.kpref.activity.CoreAttributeContract
import ca.allanwang.kau.kpref.activity.KPrefActivity
import ca.allanwang.kau.kpref.activity.KPrefAdapterBuilder
import ca.allanwang.kau.ui.views.RippleCanvas
import ca.allanwang.kau.utils.finishSlideOut
import ca.allanwang.kau.utils.setMenuIcons
import ca.allanwang.kau.utils.startActivityForResult
import ca.allanwang.kau.utils.startLink
import ca.allanwang.kau.utils.tint
import ca.allanwang.kau.utils.withSceneTransitionAnimation
import com.mikepenz.iconics.typeface.library.community.material.CommunityMaterial
import com.mikepenz.iconics.typeface.library.googlematerial.GoogleMaterial
import com.pitchedapps.frost.R
import com.pitchedapps.frost.db.NotificationDao
import com.pitchedapps.frost.facebook.FbCookie
import com.pitchedapps.frost.injectors.ThemeProvider
import com.pitchedapps.frost.prefs.Prefs
import com.pitchedapps.frost.settings.getAppearancePrefs
import com.pitchedapps.frost.settings.getBehaviourPrefs
import com.pitchedapps.frost.settings.getDebugPrefs
import com.pitchedapps.frost.settings.getExperimentalPrefs
import com.pitchedapps.frost.settings.getFeedPrefs
import com.pitchedapps.frost.settings.getNotificationPrefs
import com.pitchedapps.frost.settings.getSecurityPrefs
import com.pitchedapps.frost.settings.sendDebug
import com.pitchedapps.frost.utils.ActivityThemer
import com.pitchedapps.frost.utils.L
import com.pitchedapps.frost.utils.REQUEST_REFRESH
import com.pitchedapps.frost.utils.REQUEST_RESTART
import com.pitchedapps.frost.utils.cookies
import com.pitchedapps.frost.utils.frostChangelog
import com.pitchedapps.frost.utils.frostNavigationBar
import com.pitchedapps.frost.utils.launchNewTask
import com.pitchedapps.frost.utils.loadAssets
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.launch
/** Created by Allan Wang on 2017-06-06. */
@AndroidEntryPoint
class SettingsActivity : KPrefActivity() {
@Inject lateinit var fbCookie: FbCookie
@Inject lateinit var prefs: Prefs
@Inject lateinit var themeProvider: ThemeProvider
@Inject lateinit var notifDao: NotificationDao
@Inject lateinit var activityThemer: ActivityThemer
private var resultFlag = Activity.RESULT_CANCELED
companion object {
private const val REQUEST_RINGTONE = 0b10111 shl 5
const val REQUEST_NOTIFICATION_RINGTONE = REQUEST_RINGTONE or 1
const val REQUEST_MESSAGE_RINGTONE = REQUEST_RINGTONE or 2
const val ACTIVITY_REQUEST_TABS = 29
const val ACTIVITY_REQUEST_DEBUG = 53
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (fetchRingtone(requestCode, resultCode, data)) return
when (requestCode) {
ACTIVITY_REQUEST_TABS -> {
if (resultCode == Activity.RESULT_OK) shouldRestartMain()
return
}
ACTIVITY_REQUEST_DEBUG -> {
val url = data?.extras?.getString(DebugActivity.RESULT_URL)
if (resultCode == Activity.RESULT_OK && url?.isNotBlank() == true)
sendDebug(url, data.getStringExtra(DebugActivity.RESULT_BODY))
return
}
}
reloadList()
}
/** Fetch ringtone and save uri Returns [true] if consumed, [false] otherwise */
private fun fetchRingtone(requestCode: Int, resultCode: Int, data: Intent?): Boolean {
if (requestCode and REQUEST_RINGTONE != REQUEST_RINGTONE || resultCode != Activity.RESULT_OK)
return false
val uri = data?.getParcelableExtra<Uri>(RingtoneManager.EXTRA_RINGTONE_PICKED_URI)
val uriString: String = uri?.toString() ?: ""
if (uri != null) {
try {
grantUriPermission("com.android.systemui", uri, Intent.FLAG_GRANT_READ_URI_PERMISSION)
} catch (e: Exception) {
L.e(e) { "grantUriPermission" }
}
}
when (requestCode) {
REQUEST_NOTIFICATION_RINGTONE -> {
prefs.notificationRingtone = uriString
reloadByTitle(R.string.notification_ringtone)
}
REQUEST_MESSAGE_RINGTONE -> {
prefs.messageRingtone = uriString
reloadByTitle(R.string.message_ringtone)
}
}
return true
}
override fun kPrefCoreAttributes(): CoreAttributeContract.() -> Unit = {
textColor = { themeProvider.textColor }
accentColor = { themeProvider.accentColor }
}
override fun onCreateKPrefs(savedInstanceState: Bundle?): KPrefAdapterBuilder.() -> Unit = {
subItems(R.string.appearance, getAppearancePrefs()) {
descRes = R.string.appearance_desc
iicon = GoogleMaterial.Icon.gmd_palette
}
subItems(R.string.behaviour, getBehaviourPrefs()) {
descRes = R.string.behaviour_desc
iicon = GoogleMaterial.Icon.gmd_trending_up
}
subItems(R.string.newsfeed, getFeedPrefs()) {
descRes = R.string.newsfeed_desc
iicon = CommunityMaterial.Icon3.cmd_newspaper
}
subItems(R.string.notifications, getNotificationPrefs()) {
descRes = R.string.notifications_desc
iicon = GoogleMaterial.Icon.gmd_notifications
}
subItems(R.string.security, getSecurityPrefs()) {
descRes = R.string.security_desc
iicon = GoogleMaterial.Icon.gmd_lock
}
// subItems(R.string.network, getNetworkPrefs()) {
// descRes = R.string.network_desc
// iicon = GoogleMaterial.Icon.gmd_network_cell
// }
// todo add donation?
plainText(R.string.about_frost) {
descRes = R.string.about_frost_desc
iicon = GoogleMaterial.Icon.gmd_info
onClick = {
startActivityForResult<AboutActivity>(
9,
bundleBuilder = { withSceneTransitionAnimation(this@SettingsActivity) }
)
}
}
plainText(R.string.help_translate) {
descRes = R.string.help_translate_desc
iicon = GoogleMaterial.Icon.gmd_translate
onClick = { startLink(R.string.translation_url) }
}
plainText(R.string.replay_intro) {
iicon = GoogleMaterial.Icon.gmd_replay
onClick = { launchNewTask<IntroActivity>(cookies(), true) }
}
subItems(R.string.experimental, getExperimentalPrefs()) {
descRes = R.string.experimental_desc
iicon = CommunityMaterial.Icon2.cmd_flask_outline
}
subItems(R.string.debug_frost, getDebugPrefs()) {
descRes = R.string.debug_frost_desc
iicon = CommunityMaterial.Icon.cmd_bug
visible = { prefs.debugSettings }
}
}
fun setFrostResult(flag: Int) {
resultFlag = resultFlag or flag
}
fun shouldRestartMain() {
setFrostResult(REQUEST_RESTART)
}
fun shouldRefreshMain() {
setFrostResult(REQUEST_REFRESH)
}
@SuppressLint("MissingSuperCall")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
activityThemer.setFrostTheme(forceTransparent = true)
animate = prefs.animate
themeExterior(false)
}
fun themeExterior(animate: Boolean = true) {
if (animate) bgCanvas.fade(themeProvider.bgColor) else bgCanvas.set(themeProvider.bgColor)
if (animate)
toolbarCanvas.ripple(themeProvider.headerColor, RippleCanvas.MIDDLE, RippleCanvas.END)
else toolbarCanvas.set(themeProvider.headerColor)
frostNavigationBar(prefs, themeProvider)
}
override fun onBackPressed() {
if (!super.backPress()) {
setResult(resultFlag)
launch(NonCancellable) {
loadAssets(themeProvider)
finishSlideOut()
}
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_settings, menu)
toolbar.tint(themeProvider.iconColor)
setMenuIcons(
menu,
themeProvider.iconColor,
R.id.action_github to CommunityMaterial.Icon2.cmd_github,
R.id.action_changelog to GoogleMaterial.Icon.gmd_info
)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_github -> startLink(R.string.github_url)
R.id.action_changelog -> frostChangelog()
else -> return super.onOptionsItemSelected(item)
}
return true
}
}
| gpl-3.0 | e8cadef25e91639918ee1a36bd138099 | 33.469697 | 97 | 0.73044 | 4.244403 | false | false | false | false |
davidvavra/next-tram | webhook/src/main/kotlin/me/vavra/nexttram/model/LocationPermissionResponse.kt | 2 | 617 | package me.vavra.nexttram.model
/**
* Response to API.AI which asks for user's location.
*/
class LocationPermissionResponse {
val data = Data()
val speech = "Location"
val contextOut = listOf(Context())
class Data {
val google = Google()
class Google {
val permissions_request = PermissionsRequest()
class PermissionsRequest {
val opt_context = "To find nearby tram stops"
val permissions = listOf("DEVICE_PRECISE_LOCATION")
}
}
}
class Context {
val name = "requesting_permission"
}
} | mit | 72cf48d72eb1d851cf4c72268ea59a3c | 25.869565 | 67 | 0.588331 | 4.50365 | false | false | false | false |
alygin/intellij-rust | src/main/kotlin/org/rust/ide/notifications/MissingToolchainNotificationProvider.kt | 1 | 7105 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.notifications
import com.intellij.ProjectTopics
import com.intellij.ide.util.PropertiesComponent
import com.intellij.notification.NotificationType
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.fileChooser.FileChooser
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleRootEvent
import com.intellij.openapi.roots.ModuleRootListener
import com.intellij.openapi.util.Key
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.EditorNotificationPanel
import com.intellij.ui.EditorNotifications
import org.rust.cargo.project.settings.RustProjectSettingsService
import org.rust.cargo.project.settings.rustSettings
import org.rust.cargo.project.settings.toolchain
import org.rust.cargo.project.workspace.StandardLibrary
import org.rust.cargo.project.workspace.cargoWorkspace
import org.rust.cargo.toolchain.RustToolchain
import org.rust.cargo.util.cargoProjectRoot
import org.rust.lang.core.psi.isNotRustFile
import org.rust.utils.pathAsPath
import java.awt.Component
/**
* Warn user if rust toolchain or standard library is not properly configured.
*
* Try to fix this automatically (toolchain from PATH, standard library from the last project)
* and if not successful show the actual notification to the user.
*/
class MissingToolchainNotificationProvider(
private val project: Project,
private val notifications: EditorNotifications
) : EditorNotifications.Provider<EditorNotificationPanel>() {
init {
project.messageBus.connect(project).apply {
subscribe(RustProjectSettingsService.TOOLCHAIN_TOPIC,
object : RustProjectSettingsService.ToolchainListener {
override fun toolchainChanged() {
notifications.updateAllNotifications()
}
})
subscribe(ProjectTopics.PROJECT_ROOTS, object : ModuleRootListener {
override fun beforeRootsChange(event: ModuleRootEvent?) {
// NOP
}
override fun rootsChanged(event: ModuleRootEvent?) {
notifications.updateAllNotifications()
}
})
}
}
override fun getKey(): Key<EditorNotificationPanel> = PROVIDER_KEY
override fun createNotificationPanel(file: VirtualFile, editor: FileEditor): EditorNotificationPanel? {
if (file.isNotRustFile || isNotificationDisabled()) return null
val toolchain = project.toolchain
if (toolchain == null || !toolchain.looksLikeValidToolchain()) {
return if (trySetupToolchainAutomatically())
null
else
createBadToolchainPanel()
}
val module = ModuleUtilCore.findModuleForFile(file, project) ?: return null
if (module.cargoWorkspace?.hasStandardLibrary == false) {
val rustup = module.cargoProjectRoot?.let { toolchain.rustup(it.pathAsPath) }
// If rustup is not null, the WorkspaceService will use it
// to add stdlib automatically. This happens asynchronously,
// so we can't reliably say here if that succeeded or not.
if (rustup == null) {
createLibraryAttachingPanel(module)
}
}
return null
}
private fun trySetupToolchainAutomatically(): Boolean {
if (alreadyTriedForThisProject(TOOLCHAIN_DISCOVERY_KEY)) return false
val toolchain = RustToolchain.suggest() ?: return false
ApplicationManager.getApplication().invokeLater {
if (project.isDisposed) return@invokeLater
val oldToolchain = project.rustSettings.toolchain
if (oldToolchain != null && oldToolchain.looksLikeValidToolchain()) {
return@invokeLater
}
runWriteAction {
project.rustSettings.data = project.rustSettings.data.copy(toolchain = toolchain)
}
project.showBalloon("Using Cargo at ${toolchain.presentableLocation}", NotificationType.INFORMATION)
notifications.updateAllNotifications()
}
return true
}
private fun createBadToolchainPanel(): EditorNotificationPanel =
EditorNotificationPanel().apply {
setText("No Rust toolchain configured")
createActionLabel("Setup toolchain") {
project.rustSettings.configureToolchain()
}
createActionLabel("Do not show again") {
disableNotification()
notifications.updateAllNotifications()
}
}
private fun createLibraryAttachingPanel(module: Module): EditorNotificationPanel =
EditorNotificationPanel().apply {
setText("Can not attach stdlib sources automatically without rustup.")
createActionLabel("Attach manually") {
val stdlib = chooseStdlibLocation(this) ?: return@createActionLabel
if (StandardLibrary.fromFile(stdlib) != null) {
module.project.rustSettings.explicitPathToStdlib = stdlib.path
} else {
project.showBalloon(
"Invalid Rust standard library source path: `${stdlib.presentableUrl}`",
NotificationType.ERROR
)
}
notifications.updateAllNotifications()
}
createActionLabel("Do not show again") {
disableNotification()
notifications.updateAllNotifications()
}
}
private fun chooseStdlibLocation(parent: Component): VirtualFile? {
val descriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor()
return FileChooser.chooseFile(descriptor, parent, project, null)
}
private fun disableNotification() {
PropertiesComponent.getInstance(project).setValue(NOTIFICATION_STATUS_KEY, true)
}
private fun isNotificationDisabled(): Boolean =
PropertiesComponent.getInstance(project).getBoolean(NOTIFICATION_STATUS_KEY)
private fun alreadyTriedForThisProject(key: String): Boolean {
val properties = PropertiesComponent.getInstance(project)
val result = properties.getBoolean(key)
properties.setValue(key, true)
return result
}
companion object {
private val NOTIFICATION_STATUS_KEY = "org.rust.hideToolchainNotifications"
private val TOOLCHAIN_DISCOVERY_KEY = "org.rust.alreadyTriedToolchainAutoDiscovery"
private val PROVIDER_KEY: Key<EditorNotificationPanel> = Key.create("Setup Rust toolchain")
}
}
| mit | 17c536b5c7eb101f575ad01ac639108b | 38.254144 | 112 | 0.679944 | 5.647854 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.