repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
rei-m/android_hyakuninisshu
feature/examresult/src/main/java/me/rei_m/hyakuninisshu/feature/examresult/ui/ExamFinisherFragment.kt
1
2585
/* * Copyright (c) 2020. Rei Matsushita. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package me.rei_m.hyakuninisshu.feature.examresult.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import me.rei_m.hyakuninisshu.feature.corecomponent.helper.EventObserver import me.rei_m.hyakuninisshu.feature.examresult.databinding.ExamFinisherFragmentBinding import me.rei_m.hyakuninisshu.feature.examresult.di.ExamResultComponent import javax.inject.Inject class ExamFinisherFragment : Fragment() { @Inject lateinit var viewModelFactory: ExamFinisherViewModel.Factory private var _binding: ExamFinisherFragmentBinding? = null private val binding get() = _binding!! private val viewModel by viewModels<ExamFinisherViewModel> { viewModelFactory } override fun onCreate(savedInstanceState: Bundle?) { (requireActivity() as ExamResultComponent.Injector) .examResultComponent() .create() .inject(this) super.onCreate(savedInstanceState) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = ExamFinisherFragmentBinding.inflate(inflater, container, false) binding.lifecycleOwner = viewLifecycleOwner return binding.root } override fun onDestroyView() { _binding = null super.onDestroyView() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.viewModel = viewModel viewModel.onFinishEvent.observe(viewLifecycleOwner, EventObserver { val action = ExamFinisherFragmentDirections.actionExamFinisherToExamResult( examId = it ) findNavController().navigate(action) }) } }
apache-2.0
d410b58bcfb1f1bf0ec833344bf10656
33.466667
88
0.725725
4.822761
false
false
false
false
GlimpseFramework/glimpse-framework
jogl/src/main/kotlin/glimpse/jogl/io/FileChoosers.kt
1
1164
package glimpse.jogl.io import java.io.File import javax.swing.JFileChooser import javax.swing.JFrame /** * Displays a Swing file chooser for opening a file. * @param fileFilter File filter. * @param onOpen Action to be run when the user chooses to open the file. * @param onCancel Action to be run when the user cancels. */ fun JFrame.openFile(fileFilter: PredicateFileFilter, onOpen: (File) -> Unit, onCancel: () -> Unit = {}) { val fileChooser = JFileChooser() fileChooser.addChoosableFileFilter(fileFilter) fileChooser.isAcceptAllFileFilterUsed = false when (fileChooser.showOpenDialog(this)) { JFileChooser.APPROVE_OPTION -> onOpen(fileChooser.selectedFile) else -> onCancel() } } /** * Displays a Swing file chooser for opening an OBJ file. * @param onOpen Action to be run when the user chooses to open the file. */ fun JFrame.openOBJFile(onOpen: (File) -> Unit): Unit = openFile(objFileFilter, onOpen) /** * Displays a Swing file chooser for opening an image file. * @param onOpen Action to be run when the user chooses to open the file. */ fun JFrame.openImageFile(onOpen: (File) -> Unit): Unit = openFile(imageFileFilter, onOpen)
apache-2.0
1015fe1a5296996f108d0a277982865f
34.272727
105
0.743127
3.854305
false
false
false
false
langara/USpek
uspekx-junit5/src/jvmMain/kotlin/USpekXJUnit5.kt
1
1271
package pl.mareklangiewicz.uspek import org.junit.jupiter.api.DynamicContainer import org.junit.jupiter.api.DynamicNode import org.junit.jupiter.api.DynamicTest import java.net.URI fun uspekTestFactory(code: () -> Unit): DynamicNode { uspek(code) return GlobalUSpekContext.root.dynamicNode() } fun suspekTestFactory(ucontext: USpekContext = USpekContext(), code: suspend () -> Unit): DynamicNode = suspekBlocking(ucontext, code).dynamicNode() private fun USpekTree.dynamicNode(): DynamicNode = if (branches.isEmpty()) dynamicTest() else DynamicContainer.dynamicContainer(name, branches.values.map { it.dynamicNode() } + dynamicTest()) private fun USpekTree.dynamicTest(): DynamicTest = DynamicTest.dynamicTest(name) { println(status) end?.cause?.let { throw it } } // TODO: use JUnit5 URIs: https://junit.org/junit5/docs/current/user-guide/#writing-tests-dynamic-tests-uri-test-source // to be able to click (or F4) on the test in the Intellij test tree and to be navigated to exact test line // TODO: check why this doesn't do the trick (or similar for dynamicContainer): // dynamicTest(name, location?.tsource) { end?.cause?.let { throw it } } private fun CodeLocation.testSource() = URI("classpath:/$fileName?line=$lineNumber")
apache-2.0
a741087a684c5a6901fcd4b76e273837
40
119
0.74823
3.67341
false
true
false
false
BrianLusina/MovieReel
app/src/main/kotlin/com/moviereel/ui/settings/SettingsActivity.kt
1
9605
package com.moviereel.ui.settings import android.annotation.TargetApi import android.content.Context import android.content.Intent import android.content.res.Configuration import android.media.Ringtone import android.media.RingtoneManager import android.net.Uri import android.os.Build import android.os.Bundle import android.preference.ListPreference import android.preference.Preference import android.preference.PreferenceActivity import android.preference.PreferenceFragment import android.preference.PreferenceManager import android.preference.RingtonePreference import android.support.v7.app.ActionBar import android.text.TextUtils import android.view.MenuItem import com.moviereel.R /** * A [PreferenceActivity] that presents a set of application settings. On * handset devices, settings are presented as a single list. On tablets, * settings are split by category, with category headers shown to the left of * the list of settings. * * * See [ * Android Design: Settings](http://developer.android.com/design/patterns/settings.html) for design guidelines and the [Settings * API Guide](http://developer.android.com/guide/topics/ui/settings.html) for more information on developing a Settings UI. */ class SettingsActivity : AppCompatPreferenceActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setupActionBar() } /** * Set up the [android.app.ActionBar], if the API is available. */ private fun setupActionBar() { val actionBar = supportActionBar actionBar?.setDisplayHomeAsUpEnabled(true) } /** * {@inheritDoc} */ override fun onIsMultiPane(): Boolean { return isXLargeTablet(this) } /** * {@inheritDoc} */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) override fun onBuildHeaders(target: List<PreferenceActivity.Header>) { loadHeadersFromResource(R.xml.pref_headers, target) } /** * This method stops fragment injection in malicious applications. * Make sure to deny any unknown fragments here. */ override fun isValidFragment(fragmentName: String): Boolean { return PreferenceFragment::class.java.name == fragmentName || GeneralPreferenceFragment::class.java.name == fragmentName || DataSyncPreferenceFragment::class.java.name == fragmentName || NotificationPreferenceFragment::class.java.name == fragmentName } /** * This fragment shows general preferences only. It is used when the * activity is showing a two-pane settings UI. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) class GeneralPreferenceFragment : PreferenceFragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) addPreferencesFromResource(R.xml.pref_general) setHasOptionsMenu(true) // Bind the summaries of EditText/List/Dialog/Ringtone preferences // to their values. When their values change, their summaries are // updated to reflect the new value, per the Android Design // guidelines. bindPreferenceSummaryToValue(findPreference("example_text")) bindPreferenceSummaryToValue(findPreference("example_list")) } override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId if (id == android.R.id.home) { startActivity(Intent(activity, SettingsActivity::class.java)) return true } return super.onOptionsItemSelected(item) } } /** * This fragment shows notification preferences only. It is used when the * activity is showing a two-pane settings UI. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) class NotificationPreferenceFragment : PreferenceFragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) addPreferencesFromResource(R.xml.pref_notification) setHasOptionsMenu(true) // Bind the summaries of EditText/List/Dialog/Ringtone preferences // to their values. When their values change, their summaries are // updated to reflect the new value, per the Android Design // guidelines. bindPreferenceSummaryToValue(findPreference("notifications_new_message_ringtone")) } override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId if (id == android.R.id.home) { startActivity(Intent(activity, SettingsActivity::class.java)) return true } return super.onOptionsItemSelected(item) } } /** * This fragment shows data and sync preferences only. It is used when the * activity is showing a two-pane settings UI. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) class DataSyncPreferenceFragment : PreferenceFragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) addPreferencesFromResource(R.xml.pref_data_sync) setHasOptionsMenu(true) // Bind the summaries of EditText/List/Dialog/Ringtone preferences // to their values. When their values change, their summaries are // updated to reflect the new value, per the Android Design // guidelines. bindPreferenceSummaryToValue(findPreference("sync_frequency")) } override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId if (id == android.R.id.home) { startActivity(Intent(activity, SettingsActivity::class.java)) return true } return super.onOptionsItemSelected(item) } } companion object { /** * A preference value change listener that updates the preference's summary * to reflect its new value. */ private val sBindPreferenceSummaryToValueListener = Preference.OnPreferenceChangeListener { preference, value -> val stringValue = value.toString() if (preference is ListPreference) { // For list preferences, look up the correct display value in // the preference's 'entries' list. val listPreference = preference val index = listPreference.findIndexOfValue(stringValue) // Set the summary to reflect the new value. preference.setSummary( if (index >= 0) listPreference.entries[index] else null) } else if (preference is RingtonePreference) { // For ringtone preferences, look up the correct display value // using RingtoneManager. if (TextUtils.isEmpty(stringValue)) { // Empty values correspond to 'silent' (no ringtone). preference.setSummary(R.string.pref_ringtone_silent) } else { val ringtone = RingtoneManager.getRingtone( preference.getContext(), Uri.parse(stringValue)) if (ringtone == null) { // Clear the summary if there was a lookup error. preference.setSummary(null) } else { // Set the summary to reflect the new ringtone display // name. val name = ringtone.getTitle(preference.getContext()) preference.setSummary(name) } } } else { // For all other preferences, set the summary to the value's // simple string representation. preference.summary = stringValue } true } /** * Helper method to determine if the device has an extra-large screen. For * example, 10" tablets are extra-large. */ private fun isXLargeTablet(context: Context): Boolean { return context.resources.configuration.screenLayout and Configuration.SCREENLAYOUT_SIZE_MASK >= Configuration.SCREENLAYOUT_SIZE_XLARGE } /** * Binds a preference's summary to its value. More specifically, when the * preference's value is changed, its summary (line of text below the * preference title) is updated to reflect the value. The summary is also * immediately updated upon calling this method. The exact display format is * dependent on the type of preference. * @see .sBindPreferenceSummaryToValueListener */ private fun bindPreferenceSummaryToValue(preference: Preference) { // Set the listener to watch for value changes. preference.onPreferenceChangeListener = sBindPreferenceSummaryToValueListener // Trigger the listener immediately with the preference's // current value. sBindPreferenceSummaryToValueListener.onPreferenceChange(preference, PreferenceManager .getDefaultSharedPreferences(preference.context) .getString(preference.key, "")) } } }
mit
60a6388e8f841e4b80f6bc731a87afe5
38.526749
146
0.63113
5.646678
false
false
false
false
tokenbrowser/token-android-client
app/src/main/java/com/toshi/view/activity/SendETHActivity.kt
1
13126
/* * 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.activity import android.app.Activity import android.arch.lifecycle.Observer import android.arch.lifecycle.ViewModelProviders import android.content.ClipboardManager import android.content.Context import android.content.Intent import android.os.Bundle import android.support.v7.app.AppCompatActivity import com.toshi.R import com.toshi.crypto.util.isPaymentAddressValid import com.toshi.extensions.isVisible import com.toshi.extensions.startActivityForResult import com.toshi.extensions.toast import com.toshi.model.network.Balance import com.toshi.model.network.token.EtherToken import com.toshi.util.DialogUtil import com.toshi.util.PaymentType import com.toshi.util.QrCodeHandler import com.toshi.util.ScannerResultType import com.toshi.view.adapter.listeners.TextChangedListener import com.toshi.view.fragment.PaymentConfirmationFragment import com.toshi.viewModel.SendEtherViewModel import kotlinx.android.synthetic.main.activity_send_erc20_token.addressError import kotlinx.android.synthetic.main.activity_send_erc20_token.amountError import kotlinx.android.synthetic.main.activity_send_erc20_token.balance import kotlinx.android.synthetic.main.activity_send_erc20_token.closeButton import kotlinx.android.synthetic.main.activity_send_erc20_token.continueBtn import kotlinx.android.synthetic.main.activity_send_erc20_token.currencySwitcher import kotlinx.android.synthetic.main.activity_send_erc20_token.max import kotlinx.android.synthetic.main.activity_send_erc20_token.networkStatusView import kotlinx.android.synthetic.main.activity_send_erc20_token.paste import kotlinx.android.synthetic.main.activity_send_erc20_token.qrCodeBtn import kotlinx.android.synthetic.main.activity_send_erc20_token.toAddress import kotlinx.android.synthetic.main.activity_send_erc20_token.toAmount import kotlinx.android.synthetic.main.activity_send_erc20_token.toAmountConverted import kotlinx.android.synthetic.main.activity_send_erc20_token.toolbarTitle class SendETHActivity : AppCompatActivity() { companion object { private const val PAYMENT_SCAN_REQUEST_CODE = 200 } private lateinit var viewModel: SendEtherViewModel override fun onCreate(inState: Bundle?) { super.onCreate(inState) setContentView(R.layout.activity_send_erc20_token) init() } private fun init() { initViewModel() initNetworkView() initClickListeners() updateUi() initObservers() initTextListeners() } private fun initViewModel() { viewModel = ViewModelProviders.of(this).get(SendEtherViewModel::class.java) } private fun initNetworkView() { networkStatusView.setNetworkVisibility(viewModel.getNetworks()) } private fun initClickListeners() { max.setOnClickListener { setMaxAmount() } currencySwitcher.setOnClickListener { viewModel.switchCurrencyMode({ switchFromFiatToEthValue() }, { switchFromEthToFiatValue() }) } closeButton.setOnClickListener { finish() } qrCodeBtn.setOnClickListener { startScanQrActivity() } paste.setOnClickListener { pasteToAddress() } continueBtn.setOnClickListener { validateAddressAndShowPaymentConfirmation() } } private fun setMaxAmount() { if (viewModel.isSendingMaxAmount.value == true) { viewModel.isSendingMaxAmount.value = false toAmount.setText("") toAmount.requestFocus() return } showMaxAmountPaymentConfirmation() } private fun showMaxAmountPaymentConfirmation() { DialogUtil.getBaseDialog( this, R.string.send_max_amount_title, R.string.send_max_amount_message, R.string.ok, R.string.cancel, { _, _ -> handleMaxAmountAccepted() }, { _, _ -> handleMaxAmountCanceled() } ).show() } private fun handleMaxAmountAccepted() { viewModel.isSendingMaxAmount.value = true val maxAmount = viewModel.getMaxAmount() toAmount.setText(maxAmount) } private fun handleMaxAmountCanceled() { viewModel.isSendingMaxAmount.value = false } private fun switchFromFiatToEthValue() { val inputValue = toAmount.text.toString() val ethAmount = when { viewModel.isSendingMaxAmount.value == true -> viewModel.getMaxAmount() inputValue.isNotEmpty() -> viewModel.fiatToEth(inputValue) else -> "" } toAmount.setText(ethAmount) toAmount.setSuffix(getString(R.string.eth_currency_code)) toAmount.setPrefix("") toAmount.setSelection(toAmount.text.length) } private fun switchFromEthToFiatValue() { val inputValue = toAmount.text.toString() val fiatAmount = when { viewModel.isSendingMaxAmount.value == true -> viewModel.getMaxAmount() inputValue.isNotEmpty() -> viewModel.ethToFiat(inputValue) else -> "" } toAmount.setText(fiatAmount) toAmount.setSuffix(viewModel.getFiatCurrencyCode()) toAmount.setPrefix(viewModel.getFiatCurrencySymbol()) toAmount.setSelection(toAmount.text.length) } private fun startScanQrActivity() = startActivityForResult<ScannerActivity>(PAYMENT_SCAN_REQUEST_CODE) { putExtra(ScannerActivity.SCANNER_RESULT_TYPE, ScannerResultType.PAYMENT_ADDRESS) } private fun pasteToAddress() { val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager val clipData = clipboard.primaryClip if (clipData == null || clipData.itemCount == 0) return val clipItem = clipData.getItemAt(0) if (clipItem == null || clipItem.text == null) return val textFromClipboard = clipItem.text.toString() toAddress.setText(textFromClipboard) } private fun validateAddressAndShowPaymentConfirmation() { addressError.isVisible(false) val address = toAddress.text.toString() val amount = toAmount.text.toString() val encodedEthAmount = viewModel.getEncodedEthAmount(amount) showPaymentConfirmation(encodedEthAmount, address) } private fun showPaymentConfirmation(value: String, toAddress: String) { val dialog = PaymentConfirmationFragment.newInstanceExternalPayment( paymentAddress = toAddress, value = value, paymentType = PaymentType.TYPE_SEND, currencyMode = viewModel.currencyMode, sendMaxAmount = viewModel.isSendingMaxAmount.value == true ) dialog.show(supportFragmentManager, PaymentConfirmationFragment.TAG) dialog.setOnPaymentConfirmationFinishedListener { finish() } } private fun updateUi() { renderToolbar() setAmountSuffix() showCurrencySwitcher() showConvertedAmount() } private fun showCurrencySwitcher() = currencySwitcher.isVisible(true) private fun showConvertedAmount() { toAmountConverted.isVisible(true) if (toAmountConverted.text.isEmpty()) updateConvertedAmount("0.0") } private fun setAmountSuffix() { val suffix = viewModel.getCurrencyCode() toAmount.setSuffix(suffix) } private fun renderToolbar() { val token = EtherToken.getTokenFromIntent(intent) if (token == null) { toast(R.string.invalid_token) finish() return } toolbarTitle.text = getString(R.string.send_token, token.symbol) } private fun initObservers() { viewModel.ethBalance.observe(this, Observer { if (it != null) renderEthBalance(it) }) viewModel.isSendingMaxAmount.observe(this, Observer { if (it != null) updateMaxButtonState(it) }) } private fun renderEthBalance(currentBalance: Balance) { val totalEthAmount = viewModel.getTotalEthAmount(currentBalance) val ethAmountString = getString(R.string.eth_amount, totalEthAmount) val statusMessage = getString(R.string.your_balance_eth_fiat, ethAmountString, currentBalance.localBalance) balance.text = statusMessage } private fun updateMaxButtonState(isSendingMaxAmount: Boolean) { if (isSendingMaxAmount) enableMaxAmountButtonAndDisableAmountInput() else disableMaxAmountButtonAndEnableAmountInput() } private fun enableMaxAmountButtonAndDisableAmountInput() { max.setBackgroundResource(R.drawable.background_with_round_corners_enabled) max.setTextColor(R.color.textColorContrast) toAmount.updateTextColor(R.color.textColorHint) toAmount.isFocusable = false toAmount.isFocusableInTouchMode = false } private fun disableMaxAmountButtonAndEnableAmountInput() { max.setBackgroundResource(R.drawable.background_with_round_corners_disabled) max.setTextColor(R.color.textColorPrimary) toAmount.updateTextColor(R.color.textColorPrimary) toAmount.isFocusable = true toAmount.isFocusableInTouchMode = true } private fun initTextListeners() { toAmount.addTextChangedListener(object : TextChangedListener() { override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { updateConvertedAmount(s.toString()) validateAmount(s.toString()) enableOrDisableContinueButton() } }) toAddress.addTextChangedListener(object : TextChangedListener() { override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { validateAddress(s.toString()) enableOrDisableContinueButton() } }) } private fun updateConvertedAmount(amountInput: String) { val convertedValue = viewModel.getConvertedValue(amountInput) toAmountConverted.text = convertedValue } private fun validateAmount(amountInput: String) { amountError.isVisible(false) if (amountInput.isEmpty()) return val hasEnoughBalance = viewModel.hasEnoughBalance(amountInput) val isValidAmount = viewModel.isAmountValid(amountInput) if (!isValidAmount) showInvalidAmountError() if (!hasEnoughBalance) showAmountError() } private fun validateAddress(addressInput: String) { addressError.isVisible(false) if (addressInput.isEmpty()) return val isAddressValid = isPaymentAddressValid(addressInput) if (!isAddressValid) showAddressError() } private fun enableOrDisableContinueButton() { val amount = toAmount.text.toString() val address = toAddress.text.toString() val isAmountValid = viewModel.isAmountValid(amount) && viewModel.hasEnoughBalance(amount) val isAddressValid = isPaymentAddressValid(address) if (isAmountValid && isAddressValid) enableContinueButton() else disableContinueButton() } private fun showAmountError() { val ethBalance = getString(R.string.eth_balance, viewModel.getEtherBalance()) amountError.isVisible(true) amountError.text = getString(R.string.insufficient_balance, ethBalance) } private fun showInvalidAmountError() { amountError.isVisible(true) amountError.text = getString(R.string.invalid_format) } private fun showAddressError() { addressError.isVisible(true) addressError.text = getString(R.string.invalid_payment_address) } private fun enableContinueButton() { continueBtn.isEnabled = true continueBtn.setBackgroundResource(R.drawable.background_with_radius_primary_color) } private fun disableContinueButton() { continueBtn.isEnabled = false continueBtn.setBackgroundResource(R.drawable.background_with_radius_disabled) } override fun onActivityResult(requestCode: Int, resultCode: Int, resultIntent: Intent?) { super.onActivityResult(requestCode, resultCode, resultIntent) if (requestCode != PAYMENT_SCAN_REQUEST_CODE || resultCode != Activity.RESULT_OK || resultIntent == null) return val paymentAddress = resultIntent.getStringExtra(QrCodeHandler.ACTIVITY_RESULT) toAddress.setText(paymentAddress) } }
gpl-3.0
56067581b6a5f3ef1b546d11e9b6b0bc
38.539157
140
0.701356
4.59433
false
false
false
false
BasinMC/Basin
faucet/src/main/kotlin/org/basinmc/faucet/util/VersionRange.kt
1
5898
/* * Copyright 2019 Johannes Donath <johannesd@torchmind.com> * and other copyright owners as documented in the project's IP log. * * 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.basinmc.faucet.util import java.util.* /** * * Represents a range which may match one or multiple versions. * * * Each range may consist of one or two versions in the format of `&lt;version&gt;[,&lt;version&gt;]` as well as a prefix and/or suffix which expresses whether a * given version is included or excluded from the range. Where: * * * * `[` and `]` indicate that the start or end of the range is to be included * * `(` and `)` indicate that the start or end of the range is to be excluded * * * * As such: * * * * `1.0.0` includes 1.0.0 * * `[1.0.0` includes all versions newer than or equal to 1.0.0 * * `(1.0.0` includes all versions newer than 1.0.0 * * `1.0.0]` includes all versions older than or equal to 1.0.0 * * `1.0.0)` includes all versions older than 1.0.0 * * `[1.0.0,2.0.0)` includes all versions newer than or equal to 1.0.0 up to (excluding) * 2.0.0 * * * * Note that none or only one prefix may be present when only a single version is specified * (e.g. `1.0.0`, `(1.0.0` and `1.0.0)` are valid while `(1.0.0]` is * considered invalid). When two versions are given, both prefixes must be present at the same time * to specify the bounds. * * @author [Johannes Donath](mailto:johannesd@torchmind.com) * @since 1.0 */ class VersionRange(range: String) { private val start: Version? private val startInclusive: Boolean private val end: Version? private val endInclusive: Boolean companion object { private val prefixCharacters = "([" private val suffixCharacters = "])" } init { var startString = range var endString = range val i = range.indexOf(',') if (i != -1) { startString = range.substring(0, i) endString = range.substring(i + 1) } val prefix = startString[0] val suffix = endString[endString.length - 1] val validPrefix = prefixCharacters.indexOf(prefix) != -1 val validSuffix = suffixCharacters.indexOf(suffix) != -1 if (validPrefix) { startString = startString.substring(1) } if (validSuffix) { endString = endString.substring(0, endString.length - 1) } if (i == -1) { if (validSuffix) { startString = startString.substring(0, startString.length - 1) } if (validPrefix) { endString = endString.substring(1) } } var start: Version? var end: Version? try { start = Version(startString) } catch (ex: IllegalArgumentException) { throw IllegalArgumentException("Illegal range start: $startString", ex) } if (i != -1) { try { end = Version(endString) } catch (ex: IllegalArgumentException) { throw IllegalArgumentException("Illegal range end: $endString", ex) } } else { end = start } if (i == -1) { if (validPrefix && validSuffix) { throw IllegalArgumentException( "Illegal range: \"$range\" specifies upper and lower bound with single version") } if (validPrefix) { end = null } else if (validSuffix) { start = null } } else if (!validPrefix || !validSuffix) { throw IllegalArgumentException( "Illegal range: \"$range\" must specify upper and lower bound") } this.start = start this.end = end this.startInclusive = i == -1 && !validPrefix && !validSuffix || validPrefix && prefix == '[' this.endInclusive = i == -1 && !validPrefix && !validSuffix || validSuffix && suffix == ']' } /** * Evaluates whether a given version is part of this version range. * * @param version a version range. * @return true if within range, false otherwise. */ operator fun contains(version: Version): Boolean { if (this.start != null && (this.start > version || !this.startInclusive && this.start == version)) { return false } return !(this.end != null && (this.end < version || !this.endInclusive && this.end == version)) } override fun toString(): String { if (this.start === this.end) { return this.start!!.toString() } val builder = StringBuilder() if (this.start != null) { if (this.startInclusive) { builder.append('[') } else if (this.end != null) { builder.append('(') } builder.append(this.start) } if (this.end != null) { if (this.start != null) { builder.append(',') } builder.append(this.end) if (this.endInclusive) { builder.append(']') } else if (this.start != null) { builder.append(')') } } return builder.toString() } /** * {@inheritDoc} */ override fun equals(other: Any?): Boolean { if (this === other) { return true } if (other !is VersionRange) { return false } val that = other as VersionRange? return this.startInclusive == that!!.startInclusive && this.endInclusive == that.endInclusive && this.start == that.start && this.end == that.end } /** * {@inheritDoc} */ override fun hashCode(): Int { return Objects.hash(this.start, this.startInclusive, this.end, this.endInclusive) } }
apache-2.0
735adddec1be982b9b4bb4f2aab005b1
27.085714
161
0.620549
3.792926
false
false
false
false
WijayaPrinting/wp-javafx
openpss-client-javafx/src/com/hendraanggrian/openpss/ui/price/EditPlatePriceDialog.kt
1
1543
package com.hendraanggrian.openpss.ui.price import com.hendraanggrian.openpss.FxComponent import com.hendraanggrian.openpss.R2 import com.hendraanggrian.openpss.api.OpenPSSApi import com.hendraanggrian.openpss.schema.PlatePrice import javafx.beans.property.ReadOnlyDoubleWrapper import javafx.beans.value.ObservableValue import kotlinx.coroutines.CoroutineScope import ktfx.cells.textFieldCellFactory import ktfx.coroutines.onEditCommit import ktfx.text.buildStringConverter @Suppress("UNCHECKED_CAST") class EditPlatePriceDialog( component: FxComponent ) : EditPriceDialog<PlatePrice>(component, R2.string.plate_price) { init { getString(R2.string.price)<Double> { minWidth = 128.0 style = "-fx-alignment: center-right;" setCellValueFactory { ReadOnlyDoubleWrapper(it.value.price) as ObservableValue<Double> } textFieldCellFactory(buildStringConverter { fromString { it.toDoubleOrNull() ?: 0.0 } }) onEditCommit { cell -> val plate = cell.rowValue OpenPSSApi.editPlatePrice(plate.apply { price = cell.newValue }) } } } override suspend fun CoroutineScope.refresh(): List<PlatePrice> = OpenPSSApi.getPlatePrices() override suspend fun CoroutineScope.add(name: String): PlatePrice? = OpenPSSApi.addPlatePrice(PlatePrice.new(name)) override suspend fun CoroutineScope.delete(selected: PlatePrice): Boolean = OpenPSSApi.deletePlatePrice(selected.id) }
apache-2.0
a70867fc15b1f177bf10511198be7bd3
36.634146
100
0.720026
4.33427
false
false
false
false
googleapis/gapic-generator-kotlin
generator/src/main/kotlin/com/google/api/kotlin/generator/grpc/Functions.kt
1
20506
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.api.kotlin.generator.grpc import com.google.api.kotlin.GeneratorContext import com.google.api.kotlin.TestableFunSpec import com.google.api.kotlin.asTestable import com.google.api.kotlin.config.FlattenedMethod import com.google.api.kotlin.config.MethodOptions import com.google.api.kotlin.indent import com.google.api.kotlin.types.GrpcTypes import com.google.api.kotlin.types.ProtoTypes import com.google.api.kotlin.types.isNotProtobufEmpty import com.google.api.kotlin.types.isProtobufEmpty import com.google.api.kotlin.util.FieldNamer import com.google.api.kotlin.util.Flattening import com.google.api.kotlin.util.ParameterInfo import com.google.api.kotlin.util.ResponseTypes.getLongRunningResponseType import com.google.api.kotlin.util.ResponseTypes.getResponseListElementType import com.google.api.kotlin.util.isLongRunningOperation import com.google.api.kgax.Page import com.google.protobuf.DescriptorProtos import com.squareup.kotlinpoet.CodeBlock import com.squareup.kotlinpoet.FunSpec import com.squareup.kotlinpoet.KModifier import com.squareup.kotlinpoet.LambdaTypeName import com.squareup.kotlinpoet.ParameterSpec import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import com.squareup.kotlinpoet.UNIT import com.squareup.kotlinpoet.asClassName import com.squareup.kotlinpoet.asTypeName import kotlinx.coroutines.channels.ReceiveChannel import mu.KotlinLogging import java.util.concurrent.TimeUnit private val log = KotlinLogging.logger {} /** Generate the API method functions for the client. */ internal interface Functions { fun generate(context: GeneratorContext): List<TestableFunSpec> companion object { const val FUN_PREPARE = "prepare" const val PARAM_REQUEST = "request" } } internal class FunctionsImpl( private val documentation: Documentation, private val unitTest: UnitTest ) : Functions { override fun generate(context: GeneratorContext): List<TestableFunSpec> { // we'll use this in the example text val firstMethodName = context.service.methodList .firstOrNull()?.name?.decapitalize() // extra methods (not part of the target API) val extras = listOf( FunSpec.builder(Functions.FUN_PREPARE) .addKdoc( """ |Prepare for an API call by setting any desired options. For example: | |``` |%L |val response = client.prepare { | withMetadata("my-custom-header", listOf("some", "thing")) |}.%N(request) |``` | |You may save the client returned by this call and reuse it if you |plan to make multiple requests with the same settings. |""".trimMargin(), documentation.getClientInitializer(context), firstMethodName ?: "method" ) .returns(context.className) .addParameter( ParameterSpec.builder( "init", LambdaTypeName.get( GrpcTypes.Support.ClientCallOptionsBuilder, listOf(), Unit::class.asTypeName() ) ).build() ) .addStatement( "val optionsBuilder = %T(%N)", GrpcTypes.Support.ClientCallOptionsBuilder, Properties.PROP_CALL_OPTS ) .addStatement("optionsBuilder.init()") .addStatement( "return %T(%N, optionsBuilder.build())", context.className, Properties.PROP_CHANNEL ) .build() .asTestable(), FunSpec.builder("shutdownChannel") .addKdoc("Shutdown the [channel] associated with this client.\n") .addParameter( ParameterSpec.builder("waitForSeconds", Long::class.java.asTypeName()) .defaultValue("5") .build() ) .addStatement( "%L.shutdown().awaitTermination(waitForSeconds, %T.SECONDS)", Properties.PROP_CHANNEL, TimeUnit::class.java.asTypeName() ) .build() .asTestable() ) // API methods val apiMethods = context.service.methodList.flatMap { method -> log.debug { "processing proto method: ${method.name}" } val options = context.metadata[context.service].methods .firstOrNull { it.name == method.name } ?: MethodOptions(method.name) when { method.hasClientStreaming() || method.hasServerStreaming() -> createStreamingMethods(context, method, options) else -> createUnaryMethods(context, method, options) } } return extras + apiMethods } private fun createUnaryMethods( context: GeneratorContext, method: DescriptorProtos.MethodDescriptorProto, options: MethodOptions ): List<TestableFunSpec> { val methods = mutableListOf<TestableFunSpec>() // add flattened methods methods.addAll(options.flattenedMethods.map { flattenedMethod -> val (parameters, request) = Flattening.getFlattenedParameters( context, method, flattenedMethod ) createUnaryMethod( context = context, method = method, methodOptions = options, parameters = parameters, requestObject = request, flattenedMethod = flattenedMethod ) }) // add normal method if (options.keepOriginalMethod) { val inputType = context.typeMap.getKotlinType(method.inputType) val parameters = if (inputType.isNotProtobufEmpty()) { listOf( ParameterInfo( ParameterSpec.builder(Functions.PARAM_REQUEST, inputType).build() ) ) } else { listOf() } methods.add( createUnaryMethod( context = context, method = method, methodOptions = options, parameters = parameters, requestObject = if (parameters.isNotEmpty()) { CodeBlock.of(Functions.PARAM_REQUEST) } else { CodeBlock.of("%T.getDefaultInstance()", ProtoTypes.EMPTY) } ) ) } return methods.toList() } private fun createUnaryMethod( context: GeneratorContext, method: DescriptorProtos.MethodDescriptorProto, methodOptions: MethodOptions, parameters: List<ParameterInfo>, requestObject: CodeBlock, flattenedMethod: FlattenedMethod? = null ): TestableFunSpec { val name = methodOptions.name.decapitalize() // init function val m = FunSpec.builder(name) .addParameters(parameters.map { it.spec }) .addModifiers(KModifier.SUSPEND) // add request object to documentation val extraParamDocs = mutableListOf<CodeBlock>() if (flattenedMethod == null) { extraParamDocs.add( CodeBlock.of( "@param %L the request object for the API call", Functions.PARAM_REQUEST ) ) } // build method body when { method.isLongRunningOperation(context.proto) -> { val realResponseType = getLongRunningResponseType(context, method, methodOptions.longRunningResponse) val returnType = GrpcTypes.Support.LongRunningCall(realResponseType) m.returns(returnType) m.addCode( """ |return coroutineScope·{ | %T( | %N.%N, | async·{ | %N.%N.execute(context·=·%S)·{ | it.%L( | %L | ) | } | }, | %T::class.java | ) |} |""".trimMargin(), returnType, Properties.PROP_STUBS, Stubs.PROP_STUBS_OPERATION, Properties.PROP_STUBS, Stubs.PROP_STUBS_API, name, name, requestObject.indent(3), realResponseType ) } methodOptions.pagedResponse != null -> { val outputType = context.typeMap.getKotlinType(method.outputType) val responseListItemType = getResponseListElementType(context, method, methodOptions.pagedResponse) val pageType = Page::class.asClassName().parameterizedBy(responseListItemType) // getters and setters for setting the page sizes, etc. val pageTokenSetter = FieldNamer.getJavaBuilderRawSetterName(methodOptions.pagedResponse.requestPageToken) val nextPageTokenGetter = FieldNamer.getFieldName(methodOptions.pagedResponse.responsePageToken) val responseListGetter = FieldNamer.getJavaBuilderAccessorRepeatedName(methodOptions.pagedResponse.responseList) // build method body using a pager m.returns(ReceiveChannel::class.asClassName().parameterizedBy(pageType)) m.addCode( """ |return pager( | method·=·{·request·-> | %N.%N.execute(context·=·%S)·{ | it.%L(request) | } | }, | initialRequest·=·{ | %L | }, | nextRequest·=·{·request,·token·-> | request.toBuilder().%L(token).build() | }, | nextPage·=·{·response:·%T·-> | %T( | response.%L, | response.%L | ) | } |) |""".trimMargin(), Properties.PROP_STUBS, Stubs.PROP_STUBS_API, name, name, requestObject.indent(2), pageTokenSetter, outputType, pageType, responseListGetter, nextPageTokenGetter ) } else -> { val originalReturnType = context.typeMap.getKotlinType(method.outputType) val returnsNothing = originalReturnType.isProtobufEmpty() m.returns(if (returnsNothing) UNIT else originalReturnType) if (flattenedMethod?.parameters?.size ?: 0 > 1) { m.addCode( """ |${if (returnsNothing) "" else "return "}%N.%N.execute(context·=·%S)·{ | it.%L( | %L | ) |} |""".trimMargin(), Properties.PROP_STUBS, Stubs.PROP_STUBS_API, name, name, requestObject.indent(2) ) } else { m.addCode( """ |${if (returnsNothing) "" else "return "}%N.%N.execute(context·=·%S)·{ | it.%L(%L) |} |""".trimMargin(), Properties.PROP_STUBS, Stubs.PROP_STUBS_API, name, name, requestObject.indent(1) ) } } } // add documentation m.addKdoc( documentation.generateMethodKDoc( context = context, method = method, methodOptions = methodOptions, parameters = parameters, flatteningConfig = flattenedMethod, extras = extraParamDocs ) ) // add unit test val test = unitTest.createUnaryMethodUnitTest( context, method, methodOptions, parameters, flattenedMethod ) return TestableFunSpec(m.build(), test) } private fun createStreamingMethods( context: GeneratorContext, method: DescriptorProtos.MethodDescriptorProto, methodOptions: MethodOptions ): List<TestableFunSpec> { val name = methodOptions.name.decapitalize() val methods = mutableListOf<TestableFunSpec>() // input / output types val normalInputType = context.typeMap.getKotlinType(method.inputType) val normalOutputType = context.typeMap.getKotlinType(method.outputType) // add flattened methods methods.addAll(methodOptions.flattenedMethods.map { flattenedMethod -> val (parameters, request) = Flattening.getFlattenedParameters(context, method, flattenedMethod) val flattened = FunSpec.builder(name) if (method.hasClientStreaming() && method.hasServerStreaming()) { flattened.addKdoc( documentation.generateMethodKDoc( context = context, method = method, methodOptions = methodOptions, flatteningConfig = flattenedMethod, parameters = parameters ) ) flattened.addParameters(parameters.map { it.spec }) flattened.returns( GrpcTypes.Support.StreamingCall( normalInputType, normalOutputType ) ) flattened.addCode( """ |return %N.%N.prepare·{ | withInitialRequest( | %L | ) |}.executeStreaming(context·=·%S)·{ it::%N } |""".trimMargin(), Properties.PROP_STUBS, Stubs.PROP_STUBS_API, request.indent(2), name, name ) } else if (method.hasClientStreaming()) { // client only flattened.addKdoc( documentation.generateMethodKDoc( context = context, method = method, methodOptions = methodOptions, flatteningConfig = flattenedMethod, parameters = parameters ) ) flattened.returns( GrpcTypes.Support.ClientStreamingCall( normalInputType, normalOutputType ) ) flattened.addCode( "return %N.%N.executeClientStreaming(context·=·%S)·{ it::%N }\n", Properties.PROP_STUBS, Stubs.PROP_STUBS_API, name, name ) } else if (method.hasServerStreaming()) { // server only flattened.addKdoc( documentation.generateMethodKDoc( context = context, method = method, methodOptions = methodOptions, flatteningConfig = flattenedMethod, parameters = parameters ) ) flattened.addParameters(parameters.map { it.spec }) flattened.returns(GrpcTypes.Support.ServerStreamingCall(normalOutputType)) flattened.addCode( """ |return %N.%N.executeServerStreaming(context·=·%S)·{·stub,·observer·-> | stub.%N( | %L, | observer | ) |} |""".trimMargin(), Properties.PROP_STUBS, Stubs.PROP_STUBS_API, name, name, request.indent(2) ) } else { throw IllegalArgumentException("Unknown streaming type (not client or server)!") } // generate test val test = unitTest.createStreamingMethodTest( context, method, methodOptions, parameters, flattenedMethod ) TestableFunSpec(flattened.build(), test) }) // unchanged method if (methodOptions.keepOriginalMethod) { val normal = FunSpec.builder(name) .addKdoc(documentation.generateMethodKDoc(context, method, methodOptions)) val parameters = mutableListOf<ParameterInfo>() if (method.hasClientStreaming() && method.hasServerStreaming()) { normal.returns( GrpcTypes.Support.StreamingCall( normalInputType, normalOutputType ) ) normal.addCode( "return %N.%N.executeStreaming(context·=·%S)·{ it::%N }\n", Properties.PROP_STUBS, Stubs.PROP_STUBS_API, name, name ) } else if (method.hasClientStreaming()) { // client only normal.returns( GrpcTypes.Support.ClientStreamingCall( normalInputType, normalOutputType ) ) normal.addCode( "return %N.%N.executeClientStreaming(context·=·%S)·{ it::%N }\n", Properties.PROP_STUBS, Stubs.PROP_STUBS_API, name, name ) } else if (method.hasServerStreaming()) { // server only val param = ParameterSpec.builder(Functions.PARAM_REQUEST, normalInputType).build() parameters.add(ParameterInfo(param)) normal.addParameter(param) normal.returns(GrpcTypes.Support.ServerStreamingCall(normalOutputType)) normal.addCode( """ |return %N.%N.executeServerStreaming(context·=·%S)·{·stub,·observer·-> | stub.%N(%N, observer) |} |""".trimMargin(), Properties.PROP_STUBS, Stubs.PROP_STUBS_API, name, name, Functions.PARAM_REQUEST ) } else { throw IllegalArgumentException("Unknown streaming type (not client or server)!") } // generate test val test = unitTest.createStreamingMethodTest( context, method, methodOptions, parameters.toList(), null ) methods.add(TestableFunSpec(normal.build(), test)) } return methods.toList() } }
apache-2.0
4b690621e0930bd48b405b50c38500c2
39.257874
117
0.509168
5.549796
false
true
false
false
ursjoss/scipamato
public/public-web/src/main/kotlin/ch/difty/scipamato/publ/web/common/BasePage.kt
1
4656
package ch.difty.scipamato.publ.web.common import ch.difty.scipamato.common.logger import ch.difty.scipamato.common.navigator.ItemNavigator import ch.difty.scipamato.common.web.AbstractPage import ch.difty.scipamato.common.web.ScipamatoWebSessionFacade import ch.difty.scipamato.publ.config.ApplicationPublicProperties import ch.difty.scipamato.publ.misc.LocaleExtractor import ch.difty.scipamato.publ.web.CommercialFontResourceProvider import ch.difty.scipamato.publ.web.PublicPageParameters import ch.difty.scipamato.publ.web.pym.PymScripts import ch.difty.scipamato.publ.web.resources.MainCssResourceReference import ch.difty.scipamato.publ.web.resources.PymJavaScriptResourceReference import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5CDNCSSReference import org.apache.wicket.markup.head.CssHeaderItem import org.apache.wicket.markup.head.IHeaderResponse import org.apache.wicket.markup.head.JavaScriptContentHeaderItem import org.apache.wicket.markup.head.JavaScriptHeaderItem import org.apache.wicket.markup.head.OnLoadHeaderItem import org.apache.wicket.model.IModel import org.apache.wicket.request.mapper.parameter.PageParameters import org.apache.wicket.spring.injection.annot.SpringBean private val log = logger() abstract class BasePage<T> : AbstractPage<T> { @SpringBean private lateinit var sessionFacade: ScipamatoWebSessionFacade @SpringBean private lateinit var applicationProperties: ApplicationPublicProperties @SpringBean(name = "parentUrlLocaleExtractor") private lateinit var localeExtractor: LocaleExtractor @SpringBean(name = "metaOTFontResourceProvider") private lateinit var metaOtFontResourceProvider: CommercialFontResourceProvider override val isNavbarVisible: Boolean protected val languageCode: String get() = sessionFacade.languageCode protected val paperIdManager: ItemNavigator<Long> get() = sessionFacade.paperIdManager override val properties: ApplicationPublicProperties get() = applicationProperties protected constructor(parameters: PageParameters) : super(parameters) { val showNavbarValue = parameters[PublicPageParameters.SHOW_NAVBAR.parameterName] isNavbarVisible = showNavbarValue.toBoolean(properties.isNavbarVisibleByDefault) considerSettingLocaleFromParentUrl(parameters) } protected constructor(model: IModel<T>?) : super(model) { isNavbarVisible = properties.isNavbarVisibleByDefault } private fun considerSettingLocaleFromParentUrl(parameters: PageParameters) { val puValue = parameters[PublicPageParameters.PARENT_URL.parameterName] if (!puValue.isNull) { val locale = localeExtractor.extractLocaleFrom(puValue.toString()) log.info("Switching Locale to {}", locale.language) session.locale = locale } } override fun renderHead(response: IHeaderResponse) { super.renderHead(response) response.render(CssHeaderItem.forReference(MainCssResourceReference)) response.render(CssHeaderItem.forReference(FontAwesome5CDNCSSReference.instance())) if (properties.isCommercialFontPresent) renderCommercialFonts(response) if (properties.isResponsiveIframeSupportEnabled) renderPymForResponsiveIframe(response) } private fun renderCommercialFonts(response: IHeaderResponse) = with(response) { render(CssHeaderItem.forReference(metaOtFontResourceProvider.cssResourceReference)) renderAdditionalCommercialFonts(this) } /** * Override to render page specific additional commercial fonts. Note: This code * is only called if the property `commercial-font-present` is set to true. * * @param response the response to render the css header item references on */ open fun renderAdditionalCommercialFonts(response: IHeaderResponse) { // no default implementation } /** * Adds pym.js to the page and instantiates the `pymChild`. * * @param response the response to render the javascript for */ private fun renderPymForResponsiveIframe(response: IHeaderResponse) = with(response) { render(JavaScriptHeaderItem.forReference(PymJavaScriptResourceReference)) render(JavaScriptContentHeaderItem(PymScripts.INSTANTIATE.script, PymScripts.INSTANTIATE.id)) render(OnLoadHeaderItem(PymScripts.RESIZE.script)) } companion object { private const val serialVersionUID = 1L const val SELECT_ALL_RESOURCE_TAG = "multiselect.selectAll" const val DESELECT_ALL_RESOURCE_TAG = "multiselect.deselectAll" } }
bsd-3-clause
b8e573998f8e53f4772110f62343049b
42.514019
101
0.773625
4.609901
false
false
false
false
aucd29/common
library/src/main/java/net/sarangnamu/common/BkView.kt
1
4477
/* * Copyright 2016 Burke Choi All rights reserved. * http://www.sarangnamu.net * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("NOTHING_TO_INLINE", "unused") package net.sarangnamu.common import android.content.Context import android.graphics.Bitmap import android.graphics.drawable.Drawable import android.graphics.drawable.StateListDrawable import android.os.Build import android.support.v4.content.ContextCompat import android.view.* import android.widget.TextView /** * Created by <a href="mailto:aucd29@gmail.com">Burke Choi</a> on 2017. 11. 2.. <p/> */ /** * https://antonioleiva.com/kotlin-ongloballayoutlistener/\ * https://stackoverflow.com/questions/38827186/what-is-the-difference-between-crossinline-and-noinline-in-kotlin */ @Suppress("DEPRECATION") inline fun View.layoutListener(crossinline f: () -> Unit) = with (viewTreeObserver) { addOnGlobalLayoutListener(object: ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) { viewTreeObserver.removeOnGlobalLayoutListener(this) } else { viewTreeObserver.removeGlobalOnLayoutListener(this) } f() } }) } inline fun View.capture(): Bitmap? { clearFocus() isPressed = false val cacheDrawing = willNotCacheDrawing() setWillNotCacheDrawing(false) invalidate() buildDrawingCache() val color = drawingCacheBackgroundColor drawingCacheBackgroundColor = 0 if (color != 0) { destroyDrawingCache() } val cache = drawingCache if (cache == null) { return null } val bmp = Bitmap.createBitmap(cache) destroyDrawingCache() setWillNotCacheDrawing(cacheDrawing) drawingCacheBackgroundColor = color return bmp } inline fun TextView.gravityCenter() { gravity = Gravity.CENTER } inline fun Context.drawable(name: String): Drawable? { val id = resources.getIdentifier(name, "drawable", packageName) return ContextCompat.getDrawable(this, id) } inline fun StateListDrawable.normalState(drawable: Drawable) { addState(intArrayOf(), drawable) } inline fun StateListDrawable.pressedState(drawable: Drawable) { addState(intArrayOf(android.R.attr.state_pressed), drawable) } inline fun StateListDrawable.disabledState(drawable: Drawable) { addState(intArrayOf(-android.R.attr.state_enabled), drawable) } class DrawableSelector(context: Context): SelectorBase(context) { override fun drawable(name: String): Drawable { return context.drawable(name)!! } } abstract class SelectorBase(var context: Context) { companion object { val MASK: Int = 0X1 val TP_DISABLED: Int = 0x1 val TP_PRESSED: Int = 0x2 val TP_NORMAL: Int = 0x3 val TP_DEFAULT: Int = TP_NORMAL or TP_PRESSED val TP_ALL: Int = TP_DISABLED or TP_PRESSED or TP_NORMAL } var disableSuffix = "_disabled" var pressedSuffix = "_pressed" var normalSuffix = "_normal" fun select(name: String, type: Int): StateListDrawable { val drawable = StateListDrawable() (0..3).forEach { i -> when (type and (MASK shl i)) { TP_NORMAL -> drawable.normalState(drawable(name + normalSuffix)) TP_PRESSED -> drawable.pressedState(drawable(name + pressedSuffix)) TP_DISABLED -> drawable.disabledState(drawable(name + disableSuffix)) } } return drawable } abstract fun drawable(name : String): Drawable } inline fun Window.statusBar(color: Int) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) setStatusBarColor(color) } }
apache-2.0
ccc2b86f76274053da96675aa82ffc4f
29.25
113
0.687291
4.203756
false
false
false
false
PaulWoitaschek/Voice
data/src/main/kotlin/voice/data/legacy/LegacyBookMetaData.kt
1
680
package voice.data.legacy import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import java.util.UUID @Entity(tableName = "bookMetaData") data class LegacyBookMetaData( @ColumnInfo(name = "id") @PrimaryKey val id: UUID, @ColumnInfo(name = "type") val type: LegacyBookType, @ColumnInfo(name = "author") val author: String?, @ColumnInfo(name = "name") val name: String, @ColumnInfo(name = "root") val root: String, @ColumnInfo(name = "addedAtMillis") val addedAtMillis: Long, ) { init { require(name.isNotEmpty()) { "name must not be empty" } require(root.isNotEmpty()) { "root must not be empty" } } }
gpl-3.0
b30bccdfa07864e62b96ab3cf3c3fbec
22.448276
59
0.697059
3.523316
false
false
false
false
DSolyom/ViolinDS
ViolinDS/app/src/main/java/ds/violin/v1/widget/adapter/SectionedAdapter.kt
1
5753
/* Copyright 2016 Dániel Sólyom 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 ds.violin.v1.widget.adapter import android.support.v7.widget.RecyclerView import ds.violin.v1.app.violin.PlayingViolin import ds.violin.v1.model.modeling.ListModeling import ds.violin.v1.model.modeling.Modeling import ds.violin.v1.model.modeling.SerializableMapModel import ds.violin.v1.util.common.Debug import ds.violin.v1.viewmodel.AbsModelRecyclerViewItemBinder import ds.violin.v1.viewmodel.AbsModelSectionBinder import ds.violin.v1.viewmodel.binding.ModelViewBinding import java.util.* /** * */ open class SectionInfo() : SerializableMapModel() interface SectionedAdapter { /** = ArrayList(), section information */ var sectionInfos: ArrayList<SectionInfo> /** = ArrayList(), sections' position */ var sectionPositions: ArrayList<Int> /** * return section number for [position] */ fun sectionFor(position: Int): Int? { if (sectionPositions.isEmpty()) { return null } val sectionCount = sectionPositions.size var prox = (sectionCount - 1) / 2 while(true) { val slp = sectionPositions[prox] if (slp <= position) { if (prox == sectionCount - 1 || sectionPositions[prox + 1] > position) { return prox } prox = (sectionCount + prox + 1) / 2 } else if (slp > position) { if (prox == 0) { return null } if (sectionPositions[prox - 1] <= position) { return prox - 1 } prox /= 2 } } } /** * return real item view type for given !data! position and section * * !note: meaning of the dataPosition may differ in implementation */ fun getItemViewType(dataPosition: Int, section: Int): Int { return AbsHeaderedAdapter.VIEWTYPE_DEFAULT } /** * return section view type for given section position */ fun getSectionViewType(section: Int): Int { return AbsHeaderedAdapter.VIEWTYPE_SECTION_HEADER } } /** * an adapter with headers and with data separated by sections * * [AbsMultiDataAdapter] handles it's data separated in sections */ abstract class AbsMultiDataAdapter(on: PlayingViolin, sectionData: Array<ListModeling<*, *>>, sectionInfos: ArrayList<SectionInfo>) : AbsHeaderedAdapter(on), SectionedAdapter { val values: Array<ListModeling<*, *>> = sectionData override var sectionInfos = sectionInfos override var sectionPositions = ArrayList<Int>() override fun getRealItemViewType(position: Int): Int { val section = sectionFor(position) ?: -1 // it's never -1 if (sectionPositions.contains(position)) { /** section header requires section header view type */ return getSectionViewType(section!!) } else { /** normal item - [getItemViewType]s position is the position in the item's section */ var dataPosition = position - sectionPositions[section] - 1 return getItemViewType(dataPosition, section) } } override fun onBindViewHolder(binder: AbsModelRecyclerViewItemBinder, position: Int) { try { val section = sectionFor(position) ?: -1 // it's never -1 if (sectionPositions.contains(position)) { /** section header */ when (binder) { is AbsModelSectionBinder -> binder.bind(sectionInfos[section], section) is AbsModelRecyclerViewItemBinder -> binder.bind(sectionInfos[section], position, section) else -> (binder as ModelViewBinding<Modeling<*, *>>).bind(sectionInfos[section]!!) } } else { /** normal data - [getItemDataModel]'s and [binder]'s position is the position in the item's section */ val dataPosition = position - sectionPositions[section] - 1 val rowDataModel = getItemDataModel(dataPosition, section) if (binder is AbsModelRecyclerViewItemBinder) { binder.bind(rowDataModel, dataPosition, section) } else { (binder as ModelViewBinding<Modeling<*, *>>).bind(rowDataModel) } } } catch(e: Throwable) { Debug.logException(e) } } override fun getRealCount(): Int { sectionPositions.clear() var count = 0 val max = values.size - 1 for (i in 0..max) { sectionPositions.add(count + sectionPositions.size) count += values[i].size } return count } override fun getItemCount(): Int { var count = getRealCount() + sectionPositions.size return count + when (headerView) { null -> 0 else -> 1 } + when (footerView) { null -> 0 else -> 1 } } }
apache-2.0
2ae65bf2c9dbe06cfc92c513f7722aef
33.238095
119
0.59294
4.698529
false
false
false
false
andrei-heidelbacher/metanalysis
chronolens-test/src/main/kotlin/org/chronolens/test/core/model/EditBuilders.kt
1
4345
/* * Copyright 2018 Andrei Heidelbacher <andrei.heidelbacher@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.chronolens.test.core.model import org.chronolens.core.model.EditFunction import org.chronolens.core.model.EditType import org.chronolens.core.model.EditVariable import org.chronolens.core.model.ListEdit import org.chronolens.core.model.SetEdit import org.chronolens.test.core.BuilderMarker import org.chronolens.test.core.Init import org.chronolens.test.core.apply public class SetEditsBuilder<T> { private val setEdits = mutableListOf<SetEdit<T>>() public fun add(value: T): SetEditsBuilder<T> { setEdits += SetEdit.Add(value) return this } public operator fun T.unaryPlus() { setEdits += SetEdit.Add(this) } public fun remove(value: T): SetEditsBuilder<T> { setEdits += SetEdit.Remove(value) return this } public operator fun T.unaryMinus() { setEdits += SetEdit.Remove(this) } public fun build(): List<SetEdit<T>> = setEdits } @BuilderMarker public class ListEditsBuilder<T> { private val listEdits = mutableListOf<ListEdit<T>>() public fun add(index: Int, value: T): ListEditsBuilder<T> { listEdits += ListEdit.Add(index, value) return this } public fun remove(index: Int): ListEditsBuilder<T> { listEdits += ListEdit.Remove(index) return this } public fun build(): List<ListEdit<T>> = listEdits } @BuilderMarker public class EditTypeBuilder(private val id: String) { private val supertypeEdits = mutableListOf<SetEdit<String>>() private val modifierEdits = mutableListOf<SetEdit<String>>() public fun supertypes( init: Init<SetEditsBuilder<String>>, ): EditTypeBuilder { supertypeEdits += SetEditsBuilder<String>().apply(init).build() return this } public fun modifiers(init: Init<SetEditsBuilder<String>>): EditTypeBuilder { modifierEdits += SetEditsBuilder<String>().apply(init).build() return this } public fun build(): EditType = EditType(id, supertypeEdits, modifierEdits) } @BuilderMarker public class EditFunctionBuilder(private val id: String) { private val modifierEdits = mutableListOf<SetEdit<String>>() private val parameterEdits = mutableListOf<ListEdit<String>>() private val bodyEdits = mutableListOf<ListEdit<String>>() public fun parameters( init: Init<ListEditsBuilder<String>>, ): EditFunctionBuilder { parameterEdits += ListEditsBuilder<String>().apply(init).build() return this } public fun modifiers( init: Init<SetEditsBuilder<String>>, ): EditFunctionBuilder { modifierEdits += SetEditsBuilder<String>().apply(init).build() return this } public fun body( init: Init<ListEditsBuilder<String>>, ): EditFunctionBuilder { bodyEdits += ListEditsBuilder<String>().apply(init).build() return this } public fun build(): EditFunction = EditFunction(id, parameterEdits, modifierEdits, bodyEdits) } @BuilderMarker public class EditVariableBuilder(private val id: String) { private val modifierEdits = mutableListOf<SetEdit<String>>() private val initializerEdits = mutableListOf<ListEdit<String>>() public fun modifiers( init: Init<SetEditsBuilder<String>>, ): EditVariableBuilder { modifierEdits += SetEditsBuilder<String>().apply(init).build() return this } public fun initializer( init: Init<ListEditsBuilder<String>>, ): EditVariableBuilder { initializerEdits += ListEditsBuilder<String>().apply(init).build() return this } public fun build(): EditVariable = EditVariable(id, modifierEdits, initializerEdits) }
apache-2.0
2b39748918f468de286d6801efeeab4d
29.815603
80
0.693441
4.214355
false
false
false
false
NextFaze/dev-fun
devfun/src/main/java/com/nextfaze/devfun/invoke/InvokeUi.kt
1
9180
package com.nextfaze.devfun.invoke import android.app.Dialog import android.os.Bundle import android.os.Handler import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.Window import android.widget.Button import android.widget.ProgressBar import android.widget.Spinner import android.widget.Switch import android.widget.TextView import android.widget.Toast import android.widget.Toast.LENGTH_LONG import androidx.fragment.app.FragmentActivity import com.google.android.material.textfield.TextInputLayout import com.nextfaze.devfun.DebugException import com.nextfaze.devfun.core.R import com.nextfaze.devfun.error.ErrorHandler import com.nextfaze.devfun.internal.android.* import com.nextfaze.devfun.internal.log.* import com.nextfaze.devfun.internal.splitCamelCase import com.nextfaze.devfun.invoke.view.From import com.nextfaze.devfun.invoke.view.InvokeParameterView import com.nextfaze.devfun.invoke.view.WithValue import com.nextfaze.devfun.invoke.view.simple.ErrorParameterView import com.nextfaze.devfun.invoke.view.simple.InjectedParameterView import com.nextfaze.devfun.invoke.view.types.getTypeOrNull import kotlinx.android.synthetic.main.df_devfun_invoker_dialog_fragment.* internal class InvokingDialogFragment : BaseDialogFragment() { companion object { fun show(activity: FragmentActivity, function: UiFunction) = showNow(activity) { InvokingDialogFragment().apply { this.function = function } } } private val log = logger() private lateinit var function: UiFunction private val devFun = com.nextfaze.devfun.core.devFun private val errorHandler by lazy { devFun.get<ErrorHandler>() } private var canExecute = true override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (savedInstanceState != null) { Toast.makeText(context, "Invocation dialog does not support recreation from a saved state at this time.", LENGTH_LONG).show() dismissAllowingStateLoss() } setStyle(STYLE_NO_TITLE, 0) } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog = super.onCreateDialog(savedInstanceState).apply { requestWindowFeature(Window.FEATURE_NO_TITLE) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.df_devfun_invoker_dialog_fragment, container, false) private val Parameter.displayName: CharSequence get() = name.let { name -> when (name) { is String -> name.capitalize().splitCamelCase() else -> name ?: "Unknown" } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { try { canExecute = true performOnViewCreated() } catch (t: Throwable) { errorHandler.onError( t, "View Creation Failure", "Something when wrong when trying to create the invocation dialog view for $function." ) Handler().post { dismissAllowingStateLoss() } } } override fun onResume() { super.onResume() dialog?.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) } private fun performOnViewCreated() { titleText.text = function.title subtitleText.text = function.subtitle subtitleText.visibility = if (function.subtitle == null) View.GONE else View.VISIBLE functionSignatureText.text = function.signature functionSignatureText.visibility = if (function.signature == null) View.GONE else View.VISIBLE function.parameters.forEach { buildParameterView(it) } fun Button.setUiButton(uiButton: UiButton) { visibility = View.VISIBLE uiButton.text?.also { text = it } uiButton.textId?.also { text = getText(it) } setOnClickListener { val invoke = uiButton.invoke when { invoke != null -> onInvokeButtonClick(invoke) else -> uiButton.onClick?.invoke() } dialog.dismiss() } if (!canExecute && uiButton.invoke != null) { isEnabled = false } } (function.negativeButton ?: uiButton()).also { negativeButton.setUiButton(it) } function.neutralButton?.also { neutralButton.setUiButton(it) } (function.positiveButton ?: uiButton()).also { positiveButton.setUiButton(it) } if (!canExecute) { (0 until inputsList.childCount).forEach { inputsList.getChildAt(it).also { view -> view as InvokeParameterView val paramView = view.view // we want to leave these enabled so we can click to show error details if (paramView !is ErrorParameterView) { view.isEnabled = false } } } errorMessageText.visibility = View.VISIBLE } } private fun onInvokeButtonClick(simpleInvoke: SimpleInvoke) { try { fun View?.getValue(): Any? { return when (this) { is InvokeParameterView -> if (isNull) null else view.getValue() is InjectedParameterView -> devFun.instanceOf(value) is WithValue<*> -> value is TextInputLayout -> editText!!.text is Switch -> isChecked is Spinner -> selectedItem is ProgressBar -> progress is TextView -> text else -> throw RuntimeException("Unexpected view type $this. If this is a custom view, add the WithValue interface. If this is a standard platform view, create an issue to have it handled.") } } val params = (0 until inputsList.childCount).map { inputsList.getChildAt(it).getValue() } log.d { "Invoke $function\nwith params: $params" } simpleInvoke(params) } catch (de: DebugException) { throw de } catch (t: Throwable) { errorHandler.onError(t, "Invocation Failure", "Something went wrong when trying to execute requested method for $function.") } } @Suppress("UNCHECKED_CAST") private fun buildParameterView(parameter: Parameter) { val paramView = layoutInflater.inflate(R.layout.df_devfun_parameter, inputsList, false) as ViewGroup paramView as InvokeParameterView paramView.label = parameter.displayName paramView.nullable = if (parameter is WithNullability) parameter.isNullable else false val injectException = try { devFun.instanceOf(parameter.type).let { null } } catch (t: Throwable) { t } if (injectException == null) { paramView.view = devFun.viewFactories[InjectedParameterView::class]?.inflate(layoutInflater, inputsList)?.apply { if (this is InjectedParameterView) { value = parameter.type paramView.attributes = getText(R.string.df_devfun_injected) } } } else { val inputViewFactory = devFun.parameterViewFactories[parameter] if (inputViewFactory != null) { paramView.view = inputViewFactory.inflate(layoutInflater, inputsList).apply { if (this is WithValue<*>) { if (parameter is WithInitialValue<*>) { val value = parameter.value when (value) { null -> paramView.isNull = paramView.nullable else -> (this as WithValue<Any>).value = value } } else { parameter.annotations.getTypeOrNull<From> { (this as WithValue<Any>).value = devFun.instanceOf(it.source).value } } } } } else { canExecute = false devFun.viewFactories[ErrorParameterView::class]?.inflate(layoutInflater, inputsList)?.apply { this as ErrorParameterView value = parameter.type paramView.attributes = getText(R.string.df_devfun_missing) paramView.view = this paramView.setOnClickListener { devFun.get<ErrorHandler>() .onError(injectException, "Instance Not Found", getString(R.string.df_devfun_cannot_execute)) } } } } inputsList.addView(paramView) } }
apache-2.0
4f9c2d2f3f1c427100ed54108d53b318
39.619469
209
0.596732
5.111359
false
false
false
false
jospint/Architecture-Components-DroidDevs
ArchitectureComponents/app/src/main/java/com/jospint/droiddevs/architecturecomponents/view/start/PlacesAdapter.kt
1
1367
package com.jospint.droiddevs.architecturecomponents.view.start import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.jospint.droiddevs.architecturecomponents.R import com.jospint.droiddevs.architecturecomponents.data.googlemaps.model.PlaceResult import com.jospint.droiddevs.architecturecomponents.util.extension.singleClick import kotlinx.android.synthetic.main.view_locality.view.* import kotlin.properties.Delegates class PlacesAdapter : RecyclerView.Adapter<PlacesAdapter.LocalityVH>() { var listener: (PlaceResult) -> Unit = {} var places: List<PlaceResult> by Delegates.observable(emptyList()) { _, _, _ -> notifyDataSetChanged() } override fun onBindViewHolder(holder: LocalityVH, position: Int) { val place = places[position] holder.itemView.apply { singleClick { listener(place) } locality_name.text = place.name locality_address.text = place.formattedAddress } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LocalityVH = LocalityVH(LayoutInflater.from(parent.context).inflate(R.layout.view_locality, parent, false)) override fun getItemCount(): Int = places.size class LocalityVH(itemView: View) : RecyclerView.ViewHolder(itemView) }
apache-2.0
7e1b1a6112bfee0af1d76d9bd4f8877a
39.235294
108
0.754206
4.423948
false
false
false
false
nickthecoder/paratask
paratask-core/src/main/kotlin/uk/co/nickthecoder/paratask/parameters/FloatParameter.kt
1
3112
/* ParaTask 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.paratask.parameters import javafx.util.StringConverter import uk.co.nickthecoder.paratask.ParameterException import uk.co.nickthecoder.paratask.parameters.fields.FloatField import uk.co.nickthecoder.paratask.util.uncamel import java.text.DecimalFormat private val doubleFormat = DecimalFormat("0.#######") open class FloatParameter( name: String, label: String = name.uncamel(), description: String = "", hint: String = "", value: Float? = null, required: Boolean = true, val columnCount: Int = 8, val minValue: Float = -Float.MAX_VALUE, val maxValue: Float = Float.MAX_VALUE) : AbstractValueParameter<Float?>( name = name, label = label, description = description, hint = hint, value = value, required = required) { override val converter = object : StringConverter<Float?>() { override fun fromString(str: String): Float? { val trimmed = str.trim() if (trimmed.isEmpty()) { return null } try { return trimmed.toFloat() } catch (e: Exception) { throw ParameterException(this@FloatParameter, "Not a number") } } override fun toString(obj: Float?): String { if (obj == null) { return "" } val l = obj.toLong() if (obj == l.toFloat()) { return l.toString() } else { return doubleFormat.format(obj) } } } override fun errorMessage(v: Float?): String? { if (isProgrammingMode()) return null if (v == null) { return super.errorMessage(v) } if (v < minValue) { return "Cannot be less than $minValue" } else if (v > maxValue) { return "Cannot be more than $maxValue" } return null } override fun isStretchy() = false override fun createField(): FloatField = FloatField(this).build() as FloatField override fun toString(): String = "Double" + super.toString() override fun copy() = FloatParameter(name = name, label = label, description = description, hint = hint, value = value, required = required, minValue = minValue, maxValue = maxValue, columnCount = columnCount) }
gpl-3.0
fdadf24c637a9441f9511aa2afde83ad
30.755102
116
0.612468
4.60355
false
false
false
false
wiltonlazary/kotlin-native
build-tools/src/main/kotlin/org/jetbrains/kotlin/benchmark/SwiftBenchmarkingPlugin.kt
1
4537
package org.jetbrains.kotlin.benchmark import org.gradle.api.NamedDomainObjectContainer import org.gradle.api.Project import org.gradle.api.Task import org.jetbrains.kotlin.* import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet import org.jetbrains.kotlin.gradle.plugin.mpp.Framework import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget import org.jetbrains.kotlin.gradle.plugin.mpp.AbstractKotlinNativeTargetPreset import org.jetbrains.kotlin.gradle.plugin.mpp.NativeBuildType import java.io.File import javax.inject.Inject import java.nio.file.Paths import kotlin.reflect.KClass enum class CodeSizeEntity { FRAMEWORK, EXECUTABLE } open class SwiftBenchmarkExtension @Inject constructor(project: Project) : BenchmarkExtension(project) { var swiftSources: List<String> = emptyList() var useCodeSize: CodeSizeEntity = CodeSizeEntity.FRAMEWORK // use as code size metric framework size or executable } /** * A plugin configuring a benchmark Kotlin/Native project. */ open class SwiftBenchmarkingPlugin : BenchmarkingPlugin() { override fun Project.configureJvmJsonTask(jvmRun: Task): Task { return tasks.create("jvmJsonReport") { logger.info("JVM run is unsupported") jvmRun.finalizedBy(it) } } override fun Project.configureJvmTask(): Task { return tasks.create("jvmRun") { task -> task.doLast { logger.info("JVM run is unsupported") } } } override val benchmarkExtensionClass: KClass<*> get() = SwiftBenchmarkExtension::class override val Project.benchmark: SwiftBenchmarkExtension get() = extensions.getByName(benchmarkExtensionName) as SwiftBenchmarkExtension override val benchmarkExtensionName: String = "swiftBenchmark" override val Project.nativeExecutable: String get() = Paths.get(buildDir.absolutePath, benchmark.applicationName).toString() override val Project.nativeLinkTask: Task get() = tasks.getByName("buildSwift") private lateinit var framework: Framework val nativeFrameworkName = "benchmark" override fun NamedDomainObjectContainer<KotlinSourceSet>.configureSources(project: Project) { project.benchmark.let { commonMain.kotlin.srcDirs(*it.commonSrcDirs.toTypedArray()) nativeMain.kotlin.srcDirs(*(it.nativeSrcDirs).toTypedArray()) } } override fun Project.determinePreset(): AbstractKotlinNativeTargetPreset<*> = kotlin.presets.macosX64 as AbstractKotlinNativeTargetPreset<*> override fun KotlinNativeTarget.configureNativeOutput(project: Project) { binaries.framework(nativeFrameworkName, listOf(project.benchmark.buildType)) { // Specify settings configured by a user in the benchmark extension. project.afterEvaluate { linkerOpts.addAll(project.benchmark.linkerOpts) } } } override fun Project.configureExtraTasks() { val nativeTarget = kotlin.targets.getByName(NATIVE_TARGET_NAME) as KotlinNativeTarget // Build executable from swift code. framework = nativeTarget.binaries.getFramework(nativeFrameworkName, benchmark.buildType) val buildSwift = tasks.create("buildSwift") { task -> task.dependsOn(framework.linkTaskName) task.doLast { val frameworkParentDirPath = framework.outputDirectory.absolutePath val options = listOf("-O", "-wmo", "-Xlinker", "-rpath", "-Xlinker", frameworkParentDirPath, "-F", frameworkParentDirPath) compileSwift(project, nativeTarget.konanTarget, benchmark.swiftSources, options, Paths.get(buildDir.absolutePath, benchmark.applicationName), false) } } } override fun Project.collectCodeSize(applicationName: String) = getCodeSizeBenchmark(applicationName, if (benchmark.useCodeSize == CodeSizeEntity.FRAMEWORK) File("${framework.outputFile.absolutePath}/$nativeFrameworkName").canonicalPath else nativeExecutable ) override fun getCompilerFlags(project: Project, nativeTarget: KotlinNativeTarget) = if (project.benchmark.useCodeSize == CodeSizeEntity.FRAMEWORK) { super.getCompilerFlags(project, nativeTarget) + framework.freeCompilerArgs.map { "\"$it\"" } } else { listOf("-O", "-wmo") } }
apache-2.0
de7e8b3a1af18966380c203efed7331d
41.411215
144
0.694071
4.878495
false
true
false
false
ashdavies/data-binding
mobile/src/main/kotlin/io/ashdavies/playground/conferences/ConferencesFragment.kt
1
1660
package io.ashdavies.playground.conferences import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.Observer import androidx.lifecycle.lifecycleScope import io.ashdavies.playground.R import io.ashdavies.playground.binding import io.ashdavies.playground.common.MainViewModel import io.ashdavies.playground.databinding.ConferencesFragmentBinding import io.ashdavies.playground.extensions.navigate import kotlinx.coroutines.launch internal class ConferencesFragment : Fragment() { private val model: ConferencesViewModel by viewModels { ConferencesViewModel.Factory(requireContext()) } private val parent: MainViewModel by viewModels() private val adapter = ConferencesAdapter(R.layout.list_item) private lateinit var binding: ConferencesFragmentBinding override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = inflater.binding(R.layout.conferences_fragment, container, false) binding.lifecycleOwner = viewLifecycleOwner binding.model = model return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewLifecycleOwner .lifecycleScope .launch { navigate(model) } binding .recycler .adapter = adapter with(model) { items.observe(viewLifecycleOwner, Observer(adapter::submitList)) errors.observe(viewLifecycleOwner, Observer(parent::onError)) } } }
apache-2.0
ae1179ff6d02b57d675dea2b71c9515d
32.2
114
0.787952
4.729345
false
false
false
false
antoniolg/Bandhook-Kotlin
app/src/main/java/com/antonioleiva/bandhookkotlin/ui/screens/detail/BiographyFragment.kt
1
2197
/* * Copyright (C) 2016 Alexey Verein * * 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.antonioleiva.bandhookkotlin.ui.screens.detail import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.antonioleiva.bandhookkotlin.R import com.antonioleiva.bandhookkotlin.ui.activity.ViewAnkoComponent import com.antonioleiva.bandhookkotlin.ui.util.fromHtml import com.antonioleiva.bandhookkotlin.ui.util.setTextAppearanceC import org.jetbrains.anko.* import org.jetbrains.anko.support.v4.nestedScrollView class BiographyFragment : Fragment() { private var component: Component? = null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { component = container?.let { Component(container) } return component?.inflate() } fun setBiographyText(biographyText: String?) { component?.textView?.text = biographyText?.fromHtml() } fun getBiographyText(): String? { return component?.textView?.text?.toString() } private class Component(override val view: ViewGroup) : ViewAnkoComponent<ViewGroup> { lateinit var textView: TextView override fun createView(ui: AnkoContext<ViewGroup>): View = with(ui) { nestedScrollView { textView = textView { backgroundResource = android.R.color.white padding = dip(16) setTextAppearanceC(R.style.TextAppearance_AppCompat_Body1) } } } } }
apache-2.0
8cccc5a98ef5752b2227964fce0e16e3
33.888889
116
0.71188
4.548654
false
false
false
false
LarsKrogJensen/graphql-kotlin
src/main/kotlin/graphql/validation/rules/LoneAnonymousOperation.kt
1
1412
package graphql.validation.rules import graphql.language.Document import graphql.language.OperationDefinition import graphql.validation.IValidationContext import graphql.validation.ValidationErrorType import graphql.validation.* class LoneAnonymousOperation(validationContext: IValidationContext, validationErrorCollector: ValidationErrorCollector) : AbstractRule(validationContext, validationErrorCollector) { private var _hasAnonymousOp = false private var _count = 0 override fun checkOperationDefinition(operationDefinition: OperationDefinition) { super.checkOperationDefinition(operationDefinition) val name = operationDefinition.name var message: String? = null if (name == null) { _hasAnonymousOp = true if (_count > 0) { message = "Anonymous operation with other operations." } } else { if (_hasAnonymousOp) { message = "Operation $name is following anonymous operation." } } _count++ if (message != null) { addError(ValidationError(ValidationErrorType.LoneAnonymousOperationViolation, operationDefinition.sourceLocation, message)) } } override fun documentFinished(document: Document) { super.documentFinished(document) _hasAnonymousOp = false } }
mit
24cf79b679fd05d10c0ac063c0fea5d8
33.439024
135
0.675637
5.308271
false
false
false
false
nickbutcher/plaid
core/src/main/java/io/plaidapp/core/dribbble/data/api/model/Shot.kt
1
1564
/* * Copyright 2018 Google LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.plaidapp.core.dribbble.data.api.model import com.google.gson.annotations.SerializedName import io.plaidapp.core.data.PlaidItem import java.util.Date /** * Models a dibbble shot */ data class Shot( @SerializedName("id") override val id: Long, @SerializedName("title") override val title: String, @SerializedName("page") override val page: Int, @SerializedName("description") val description: String, @SerializedName("images") val images: Images, @SerializedName("views_count") val viewsCount: Int = 0, @SerializedName("likes_count") val likesCount: Int = 0, @SerializedName("created_at") val createdAt: Date? = null, @SerializedName("html_url") val htmlUrl: String = "https://dribbble.com/shots/$id", @SerializedName("animated") val animated: Boolean = false, @SerializedName("user") val user: User ) : PlaidItem(id, title, htmlUrl, page) { // todo move this into a decorator var hasFadedIn = false }
apache-2.0
1d081bb45f799a449de92eef2b1010bc
36.238095
87
0.719309
3.989796
false
false
false
false
hummatli/MAHAds
app-cross-promoter/src/main/java/com/mobapphome/appcrosspromoter/ProgramItmAdpt.kt
2
3755
package com.mobapphome.appcrosspromoter import android.support.v7.widget.RecyclerView import android.util.Log import android.util.TypedValue import android.view.View import android.view.ViewGroup import com.bumptech.glide.Glide import com.mobapphome.appcrosspromoter.commons.* import com.mobapphome.appcrosspromoter.tools.Constants import com.mobapphome.appcrosspromoter.tools.Program import com.mobapphome.appcrosspromoter.tools.checkPackageIfExists import com.mobapphome.appcrosspromoter.tools.getUrlOfImage import kotlinx.android.synthetic.main.program_item_programs.view.* /** * Created by settar on 6/30/17. */ class ProgramItmAdpt(val items: List<Any>, val urlRootOnServer: String?, val fontName: String?, val listenerOnClick: (Any) -> Unit, val listenerOnMoreClick: (Any, View) -> Unit) : RecyclerView.Adapter<ProgramItmAdpt.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder = ViewHolder(parent.inflate(R.layout.program_item_programs)!!) override fun onBindViewHolder(holder: ViewHolder, position: Int) = holder.bind(items[position], listenerOnClick, listenerOnMoreClick)!! override fun getItemCount(): Int = items.size inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bind(item: Any, listenerOnClick: (Any) -> Unit, listenerOnMoreClick: (Any, View) -> Unit) = with(itemView) { if (item is Program) { val pckgName = item.uri.trim { it <= ' ' } tvProgramNewText.makeGone() val freshnestStr = item.getFreshnestStr(context) if (freshnestStr != null) { tvProgramNewText.setTextSize(TypedValue.COMPLEX_UNIT_SP, item.getFreshnestStrTextSizeInSP(context).toFloat()) tvProgramNewText.text = freshnestStr tvProgramNewText.startAnimationFillAfter(R.anim.tv_rotate, true) tvProgramNewText.makeVisible() } else { tvProgramNewText.makeGone() } if (checkPackageIfExists(context, pckgName)) { tvOpenInstall.text = context.resources.getString(R.string.cmnd_verb_acp_open_program) } else { tvOpenInstall.text = context.resources.getString(R.string.cmnd_verb_acp_install_program) } tvProgramName.text = item.name tvProgramDesc.text = item.desc Log.i(Constants.LOG_TAG_MAH_ADS, getUrlOfImage(urlRootOnServer!!, item.img)) Glide.with(context) .load(getUrlOfImage(urlRootOnServer, item.img)) //.diskCacheStrategy(DiskCacheStrategy.ALL) .centerCrop() .placeholder(R.drawable.img_place_holder_normal) .crossFade() .error(context.getDrawableWithColorFilter(R.drawable.img_not_found, R.color.acp_no_image_color)) .into(ivProgramImg) imgBtnMore.setColorFilterCompat(R.color.acp_all_and_btn_text_color) imgBtnMore.setImageResource(R.drawable.ic_more_vert_grey600_24dp) tvProgramNewText.setFontTextView(fontName) tvProgramName.setFontTextView(fontName) tvProgramDesc.setFontTextView(fontName) tvOpenInstall.setFontTextView(fontName) setOnClickListener { listenerOnClick(item) } imgBtnMore.setOnClickListener { v -> listenerOnMoreClick(item, v) } } } } }
apache-2.0
57489b3b41ebd8844f9ecff138ba47c3
41.681818
144
0.626897
4.45433
false
false
false
false
equeim/tremotesf-android
app/src/main/kotlin/org/equeim/tremotesf/ui/AboutFragment.kt
1
5312
/* * Copyright (C) 2017-2022 Alexey Rochev <equeim@gmail.com> * * This file is part of Tremotesf. * * Tremotesf 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. * * Tremotesf 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 org.equeim.tremotesf.ui import android.os.Bundle import androidx.annotation.LayoutRes import androidx.annotation.StringRes import androidx.core.text.HtmlCompat import androidx.fragment.app.Fragment import androidx.viewpager2.adapter.FragmentStateAdapter import com.google.android.material.tabs.TabLayoutMediator import org.equeim.tremotesf.BuildConfig import org.equeim.tremotesf.R import org.equeim.tremotesf.databinding.AboutFragmentBaseTabFragmentBinding import org.equeim.tremotesf.databinding.AboutFragmentBinding import org.equeim.tremotesf.databinding.AboutFragmentLicenseTabFragmentBinding class AboutFragment : NavigationFragment(R.layout.about_fragment) { private var pagerAdapter: PagerAdapter? = null override fun onViewStateRestored(savedInstanceState: Bundle?) { super.onViewStateRestored(savedInstanceState) toolbar.title = "%s %s".format(getString(R.string.app_name), BuildConfig.VERSION_NAME) pagerAdapter = PagerAdapter(this) with(AboutFragmentBinding.bind(requireView())) { pager.adapter = pagerAdapter TabLayoutMediator(tabLayout, pager) { tab, position -> tab.setText(PagerAdapter.getTitle(position)) }.attach() } } private class PagerAdapter(fragment: Fragment) : FragmentStateAdapter(fragment) { companion object { private val tabs = Tab.values().toList() @StringRes fun getTitle(position: Int): Int { return when (tabs[position]) { Tab.Main -> R.string.about Tab.Authors -> R.string.authors Tab.Translators -> R.string.translators Tab.License -> R.string.license } } } private enum class Tab { Main, Authors, Translators, License } override fun getItemCount() = tabs.size override fun createFragment(position: Int): Fragment { return when (tabs[position]) { Tab.Main -> MainTabFragment() Tab.Authors -> AuthorsTabFragment() Tab.Translators -> TranslatorsTabFragment() Tab.License -> LicenseTabFragment() } } } open class PagerFragment(@LayoutRes contentLayoutId: Int) : Fragment(contentLayoutId) { override fun onViewStateRestored(savedInstanceState: Bundle?) { super.onViewStateRestored(savedInstanceState) applyNavigationBarBottomInset() } } class MainTabFragment : PagerFragment(R.layout.about_fragment_base_tab_fragment) { override fun onViewStateRestored(savedInstanceState: Bundle?) { super.onViewStateRestored(savedInstanceState) resources.openRawResource(R.raw.about).use { inputStream -> with(AboutFragmentBaseTabFragmentBinding.bind(requireView())) { textView.text = HtmlCompat.fromHtml(inputStream.reader().readText(), 0) } } } } class AuthorsTabFragment : PagerFragment(R.layout.about_fragment_base_tab_fragment) { override fun onViewStateRestored(savedInstanceState: Bundle?) { super.onViewStateRestored(savedInstanceState) resources.openRawResource(R.raw.authors).use { inputStream -> with(AboutFragmentBaseTabFragmentBinding.bind(requireView())) { textView.text = HtmlCompat.fromHtml(inputStream.reader().readText(), 0) } } } } class TranslatorsTabFragment : PagerFragment(R.layout.about_fragment_base_tab_fragment) { override fun onViewStateRestored(savedInstanceState: Bundle?) { super.onViewStateRestored(savedInstanceState) resources.openRawResource(R.raw.translators).use { AboutFragmentBaseTabFragmentBinding.bind(requireView()).textView.text = it.reader().readText() } } } class LicenseTabFragment : PagerFragment(R.layout.about_fragment_license_tab_fragment) { override fun onViewStateRestored(savedInstanceState: Bundle?) { super.onViewStateRestored(savedInstanceState) resources.openRawResource(R.raw.license).use { AboutFragmentLicenseTabFragmentBinding.bind(requireView()).webView.loadData( it.reader().readText(), "text/html", null ) } } } }
gpl-3.0
a7acf3810545f30e453d838d1e72dcf0
37.773723
94
0.656438
5.088123
false
false
false
false
MimiReader/mimi-reader
mimi-app/src/main/java/com/emogoth/android/phone/mimi/activity/SlidingPanelActivity.kt
1
12646
package com.emogoth.android.phone.mimi.activity import android.content.Intent import android.graphics.Color import android.os.Bundle import android.text.TextUtils import android.view.Menu import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.appcompat.widget.Toolbar import androidx.core.content.res.ResourcesCompat import androidx.slidingpanelayout.widget.SlidingPaneLayout import androidx.slidingpanelayout.widget.SlidingPaneLayout.PanelSlideListener import com.emogoth.android.phone.mimi.R import com.emogoth.android.phone.mimi.activity.GalleryActivity2.Companion.start import com.emogoth.android.phone.mimi.db.HistoryTableConnection import com.emogoth.android.phone.mimi.fragment.* import com.emogoth.android.phone.mimi.interfaces.* import com.emogoth.android.phone.mimi.util.* import com.google.android.material.floatingactionbutton.FloatingActionButton import com.mimireader.chanlib.models.ChanBoard import com.mimireader.chanlib.models.ChanPost import com.novoda.simplechromecustomtabs.SimpleChromeCustomTabs class SlidingPanelActivity : MimiActivity(), BoardItemClickListener, View.OnClickListener, ThumbnailClickListener, GalleryMenuItemClickListener, IToolbarContainer { private var listType = BOARD_LIST_ID private var boardName: String? = null private var boardTitle: String? = null private var listFragment: MimiFragmentBase? = null private var detailFragment: MimiFragmentBase? = null private var boardsFragment: MimiFragmentBase? = null private var openPage = Pages.NONE private var addContentFab: FloatingActionButton? = null private var panelLayout: SlidingPaneLayout? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_sliding_panel) var sliderFadeColor = if (MimiUtil.getInstance().theme == MimiUtil.THEME_LIGHT) { ResourcesCompat.getColor(resources, R.color.background_light, theme) } else { ResourcesCompat.getColor(resources, R.color.background_dark, theme) } val coverFadeColor = sliderFadeColor sliderFadeColor = Color.argb(0xAA, Color.red(sliderFadeColor), Color.green(sliderFadeColor), Color.blue(sliderFadeColor)) panelLayout = findViewById<View>(R.id.panel_layout) as SlidingPaneLayout panelLayout?.sliderFadeColor = sliderFadeColor panelLayout?.coveredFadeColor = coverFadeColor panelLayout?.setPanelSlideListener(object : PanelSlideListener { override fun onPanelSlide(panel: View, slideOffset: Float) {} override fun onPanelOpened(panel: View) { if (listFragment != null) { listFragment?.initMenu() } } override fun onPanelClosed(panel: View) { if (detailFragment != null) { detailFragment?.initMenu() } } }) panelLayout?.openPane() addContentFab = findViewById<View>(R.id.fab_add_content) as FloatingActionButton addContentFab?.setOnClickListener { val fragment = if (panelLayout?.isOpen == true) { listFragment } else { detailFragment } if (fragment is ContentInterface) { (fragment as ContentInterface).addContent() } } val toolbar: Toolbar? = findViewById<View>(R.id.mimi_toolbar) as Toolbar if (toolbar != null) { toolbar.setNavigationOnClickListener(this) this.toolbar = toolbar } extractExtras(intent.extras) initDrawers(R.id.nav_drawer, R.id.nav_drawer_container, true) createDrawers(R.id.nav_drawer) initFragments() if (openPage == Pages.BOOKMARKS) { openHistoryPage(true) } } private fun initFragments() { val ft = supportFragmentManager.beginTransaction() when (listType) { BOARD_LIST_ID -> { val fragment = BoardItemListFragment() val extras = Bundle() extras.putBoolean(Extras.EXTRAS_OPTIONS_MENU_ENABLED, false) fragment.arguments = extras ft.add(R.id.postitem_list, fragment, TAG_BOARD_LIST) ft.commit() fragment.setActivateOnItemClick(true) detailFragment = fragment listFragment = fragment boardsFragment = fragment } BOOKMARKS_ID -> { val fragment = HistoryFragment() val args = Bundle() args.putInt(Extras.EXTRAS_HISTORY_QUERY_TYPE, HistoryTableConnection.BOOKMARKS) args.putInt(Extras.EXTRAS_VIEWING_HISTORY, VIEWING_BOOKMARKS) args.putBoolean(Extras.EXTRAS_OPTIONS_MENU_ENABLED, false) fragment.arguments = args ft.add(R.id.postitem_list, fragment, TAG_BOARD_LIST) ft.commit() detailFragment = fragment listFragment = fragment } HISTORY_ID -> { val fragment = HistoryFragment() val args = Bundle() args.putInt(Extras.EXTRAS_HISTORY_QUERY_TYPE, HistoryTableConnection.HISTORY) args.putInt(Extras.EXTRAS_VIEWING_HISTORY, VIEWING_HISTORY) args.putBoolean(Extras.EXTRAS_OPTIONS_MENU_ENABLED, false) fragment.arguments = args ft.add(R.id.postitem_list, fragment, TAG_BOARD_LIST) ft.commit() detailFragment = fragment listFragment = fragment } } } private fun extractExtras(extras: Bundle?) { if (extras != null) { boardName = extras.getString(Extras.EXTRAS_BOARD_NAME) if (extras.containsKey(Extras.EXTRAS_LIST_TYPE)) { listType = extras.getInt(Extras.EXTRAS_LIST_TYPE) } if (extras.containsKey(Extras.OPEN_PAGE)) { val page = extras.getString(Extras.OPEN_PAGE) if (!TextUtils.isEmpty(page)) { openPage = Pages.valueOf(page!!) } } } } private fun setFabVisibility(visible: Boolean) { if (addContentFab?.isShown == true && !visible) { addContentFab?.hide() } else if (addContentFab?.isShown == false && visible) { addContentFab?.show() } } override fun onPause() { SimpleChromeCustomTabs.getInstance().disconnectFrom(this) super.onPause() } override fun onResume() { SimpleChromeCustomTabs.getInstance().connectTo(this) super.onResume() } override fun onCreateOptionsMenu(menu: Menu): Boolean { val inflater = menuInflater if (panelLayout?.isOpen == true) { listFragment?.onCreateOptionsMenu(menu, inflater) } else { detailFragment?.onCreateOptionsMenu(menu, inflater) } return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { toggleNavDrawer() return true } return if (panelLayout?.isOpen == true) { listFragment?.onOptionsItemSelected(item) == true } else { detailFragment?.onOptionsItemSelected(item) == true } } override val pageName: String get() = "sliding_drawer_activity" override fun onClick(v: View) { if (listType == BOARD_LIST_ID) { toggleNavDrawer() } else { finish() } } override fun onBoardItemClick(board: ChanBoard, saveBackStack: Boolean) { val arguments = Bundle() arguments.putString(Extras.EXTRAS_BOARD_NAME, board.name) arguments.putString(Extras.EXTRAS_BOARD_TITLE, board.title) arguments.putBoolean(Extras.EXTRAS_OPTIONS_MENU_ENABLED, false) val fragment = PostItemsListFragment() fragment.arguments = arguments val fm = supportFragmentManager val ft = fm.beginTransaction() val catalogItemsFragment = fm.findFragmentByTag(TAG_POST_LIST) if (catalogItemsFragment != null) { ft.remove(catalogItemsFragment) } ft.replace(R.id.postitem_list, fragment, TAG_POST_LIST) if (saveBackStack) { ft.addToBackStack(null) } ft.commit() listFragment = fragment setFabVisibility(fragment.showFab()) } override fun onGalleryMenuItemClick(boardPath: String, threadId: Long) { start(this, GalleryActivity2.GALLERY_TYPE_GRID, 0, boardPath, threadId, LongArray(0)) } override fun setExpandedToolbar(expanded: Boolean, animate: Boolean) { // no op } override fun onPostItemClick(v: View?, posts: List<ChanPost>, position: Int, boardTitle: String, boardName: String, threadId: Long) { openThread(posts, position, boardName, boardTitle, threadId) } private fun openThread(posts: List<ChanPost>, position: Int, boardName: String, boardTitle: String, threadId: Long) { this.boardName = boardName this.boardTitle = boardTitle val threadDetailFragment = if (posts.size > position) { ThreadDetailFragment.newInstance(posts[position].no, boardName, boardTitle, posts[position], true, false) } else { ThreadDetailFragment.newInstance(threadId, boardName, boardTitle, null, true, false) } val fm = supportFragmentManager val ft = fm.beginTransaction() ft.replace(R.id.postitem_detail, threadDetailFragment, TAG_THREAD_DETAIL) ft.commit() panelLayout?.closePane() detailFragment = threadDetailFragment } override fun onBackPressed() { if (panelLayout?.isOpen == true) { if (listFragment is HistoryFragment) { val fm = supportFragmentManager val ft = fm.beginTransaction() ft.remove(listFragment as HistoryFragment).commit() } listFragment = boardsFragment super.onBackPressed() listFragment?.initMenu() } else { panelLayout?.openPane() } } override fun onHistoryItemClicked(boardName: String, threadId: Long, boardTitle: String, position: Int, watched: Boolean) { this.boardName = boardName this.boardTitle = boardTitle val fm = supportFragmentManager val ft = fm.beginTransaction() val threadDetailFragment = ThreadDetailFragment.newInstance(threadId, boardName, boardTitle, null, false, false) ft.replace(R.id.postitem_detail, threadDetailFragment, TAG_THREAD_DETAIL) ft.commit() if (panelLayout?.isOpen == true) { panelLayout?.closePane() } detailFragment = threadDetailFragment } override fun openHistoryPage(watched: Boolean) { val fm = supportFragmentManager val ft = fm.beginTransaction() val saveBackStack = listFragment === boardsFragment val fragment = HistoryFragment.newInstance(watched) ft.replace(R.id.postitem_list, fragment, TAG_POST_LIST) if (saveBackStack) { ft.addToBackStack(null) } ft.commit() listFragment = fragment panelLayout?.openPane() } override fun onReplyClicked(boardName: String, threadId: Long, id: Long, replies: List<String>) { if (detailFragment is ReplyClickListener) { val frag = detailFragment as ReplyClickListener frag.onReplyClicked(boardName, threadId, id, replies) } } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) val page = intent.getStringExtra(Extras.OPEN_PAGE) if (!TextUtils.isEmpty(page)) { try { val pageEnum = Pages.valueOf(page!!) val watched: Boolean watched = pageEnum == Pages.BOOKMARKS openHistoryPage(watched) } catch (e: Exception) { } } } companion object { const val BOARD_LIST_ID = 0 const val BOOKMARKS_ID = 1 const val HISTORY_ID = 2 private const val TAG_BOARD_LIST = "board_list_fragment" private const val TAG_POST_LIST = "post_list_fragment" private const val TAG_THREAD_DETAIL = "thread_detail_fragment" } }
apache-2.0
112e2fc160599bd423209b6d8ab3af7d
38.398754
164
0.628815
4.764883
false
false
false
false
ffc-nectec/FFC
ffc/src/main/kotlin/ffc/app/health/service/HealthCareServiceAdapter.kt
1
5968
package ffc.app.health.service import android.support.annotation.DrawableRes import android.support.annotation.StringRes import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageButton import android.widget.ImageView import android.widget.TextView import com.felipecsl.asymmetricgridview.AsymmetricRecyclerView import ffc.android.drawable import ffc.android.getString import ffc.android.gone import ffc.android.onClick import ffc.android.visible import ffc.app.R import ffc.app.photo.asymmetric.bind import ffc.app.util.AdapterClickListener import ffc.app.util.datetime.toBuddistString import ffc.app.util.takeIfNotEmpty import ffc.app.util.takeIfNotNullOrBlank import ffc.app.util.timeago.toTimeAgo import ffc.app.util.value.Value import ffc.app.util.value.ValueAdapter import ffc.entity.Lang import ffc.entity.Lookup import ffc.entity.healthcare.CommunityService import ffc.entity.healthcare.Diagnosis import ffc.entity.healthcare.HealthCareService import ffc.entity.healthcare.HomeVisit import ffc.entity.healthcare.SpecialPP import org.jetbrains.anko.find import org.joda.time.LocalDate class HealthCareServiceAdapter( val services: List<HealthCareService>, val limit: Int = 10, onClickDsl: AdapterClickListener<HealthCareService>.() -> Unit ) : RecyclerView.Adapter<HealthCareServiceViewHolder>() { private val listener = AdapterClickListener<HealthCareService>().apply(onClickDsl) override fun onCreateViewHolder(parent: ViewGroup, type: Int): HealthCareServiceViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.hs_service_item, parent, false) return HealthCareServiceViewHolder(view) } override fun getItemCount() = if (services.size > limit) limit else services.size override fun onBindViewHolder(holder: HealthCareServiceViewHolder, position: Int) { holder.bind(services[position]) holder.itemView.onClick { listener.onItemClick!!.invoke(holder.itemView, services[position]) } listener.bindOnViewClick(holder.itemView, services[position], holder.editButton) } } class HealthCareServiceViewHolder(view: View) : RecyclerView.ViewHolder(view) { private val icon = view.find<ImageView>(R.id.serviceIconView) private val title = view.find<TextView>(R.id.serviceTitleView) private val date = view.find<TextView>(R.id.serviceDateView) private val detailView = view.find<RecyclerView>(R.id.detailView) private val photos = view.find<AsymmetricRecyclerView>(R.id.photos) val editButton = view.find<ImageButton>(R.id.editButton) init { detailView.layoutManager = LinearLayoutManager(itemView.context) } private val HealthCareService.isEditable: Boolean get() = time.toLocalDate().isEqual(LocalDate.now()) fun bind(services: HealthCareService) { with(services) { date.text = services.time.toTimeAgo() val type = typeOf(services) title.text = getString(type.titleRes) icon.setImageDrawable(itemView.context.drawable(type.iconRes)) photos.bind(photosUrl) detailView.adapter = ValueAdapter(toValue(), ValueAdapter.Style.SMALL, true) if (type == ServiceType.HOME_VISIT && isEditable) { editButton.visible() } else { editButton.gone() } } } private fun typeOf(services: HealthCareService): ServiceType { return when { services.specialPPs.isNotEmpty() -> ServiceType.SPECIAL_PP services.communityServices.isNotEmpty() -> { if (services.communityServices.firstOrNull { it is HomeVisit } != null) ServiceType.HOME_VISIT else ServiceType.COMMUNITY_SERVICE } services.ncdScreen != null -> ServiceType.NCD_SCREENING else -> ServiceType.SERVICE } } enum class ServiceType( @DrawableRes val iconRes: Int = R.drawable.ic_stethoscope_color_24dp, @StringRes val titleRes: Int = R.string.general_service ) { SERVICE, NCD_SCREENING(R.drawable.ic_loupe_color_24dp, R.string.ncd_screen), HOME_VISIT(R.drawable.ic_home_visit_color_24dp, R.string.home_visit), COMMUNITY_SERVICE(R.drawable.ic_home_visit_color_24dp, R.string.community_service), SPECIAL_PP(R.drawable.ic_shield_color_24dp, R.string.special_pp) } } private fun HealthCareService.toValue(): List<Value> { val values = mutableListOf<Value>() syntom.takeIfNotNullOrBlank()?.let { values.add(Value("อาการเบื้องต้น", it)) } nextAppoint?.let { values.add(Value("นัดครั้งต่อไป", it.toBuddistString())) } diagnosises.toValue().takeIfNotEmpty()?.let { values.addAll(it) } specialPPs.toSpecialPpValues().takeIfNotEmpty()?.let { values.addAll(it) } communityServices.toCommunityServiceValues().takeIfNotEmpty()?.let { values.addAll(it) } suggestion.takeIfNotNullOrBlank()?.let { values.add(Value("คำแนะนำ", it)) } note.takeIfNotNullOrBlank()?.let { values.add(Value("บันทึก", it)) } return values } private fun List<SpecialPP>.toSpecialPpValues(): List<Value> { return map { Value("ส่งเสริมป้องกัน", "· ${it.ppType.nameTh}") } } private fun List<CommunityService>.toCommunityServiceValues(): List<Value> { return map { Value("บริการชุมชน", "· ${it.serviceType.nameTh}") } } private fun List<Diagnosis>.toValue(): List<Value> { return sortedBy { it.dxType }.map { Value("วินิจฉัย", "· ${it.disease.nameTh}") } } val Lookup.nameTh: String get() = translation[Lang.th].takeIfNotNullOrBlank() ?: name
apache-2.0
1039da83ead762ad2981a6656d622306
39.117241
103
0.71291
3.745654
false
false
false
false
sugnakys/UsbSerialConsole
UsbSerialConsole/app/src/main/java/jp/sugnakys/usbserialconsole/presentation/home/HomeFragment.kt
1
7815
package jp.sugnakys.usbserialconsole.presentation.home import android.graphics.Color import android.graphics.drawable.ColorDrawable 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 android.widget.Toast import androidx.core.net.toUri import androidx.core.widget.addTextChangedListener import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.OnScrollListener import androidx.recyclerview.widget.RecyclerView.SCROLL_STATE_DRAGGING import com.google.android.material.snackbar.Snackbar import dagger.hilt.android.AndroidEntryPoint import java.io.File import java.util.Date import javax.inject.Inject import jp.sugnakys.usbserialconsole.R import jp.sugnakys.usbserialconsole.databinding.FragmentHomeBinding import jp.sugnakys.usbserialconsole.preference.DefaultPreference import jp.sugnakys.usbserialconsole.presentation.log.LogViewFragmentArgs @AndroidEntryPoint class HomeFragment : Fragment() { @Inject lateinit var preference: DefaultPreference private val viewModel by viewModels<HomeViewModel>() private lateinit var binding: FragmentHomeBinding private var isAutoScroll = true override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentHomeBinding.inflate(inflater, container, false) return binding.root } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.menu_main, menu) } override fun onPrepareOptionsMenu(menu: Menu) { val item = menu.findItem(R.id.action_connect) item.isEnabled = viewModel.isUSBReady item.title = if (viewModel.isConnect.value == true) { getString(R.string.action_disconnect) } else { getString(R.string.action_connect) } super.onPrepareOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.action_connect -> { if (viewModel.isConnect.value == true) { viewModel.changeConnection(false) Toast.makeText( requireContext(), getString(R.string.stop_connection), Toast.LENGTH_SHORT ).show() } else { viewModel.changeConnection(true) Toast.makeText( requireContext(), getString(R.string.start_connection), Toast.LENGTH_SHORT ).show() } true } R.id.action_clear_log -> { viewModel.clearReceivedMessage() true } R.id.action_save_log -> { val fileName = viewModel.getFileName(Date(System.currentTimeMillis())) val dirName = viewModel.getLogDir() val targetFile = File(dirName, fileName) if (viewModel.writeToFile( file = targetFile, isTimestamp = preference.timestampVisibility ) ) { val snackBar = Snackbar.make( requireContext(), binding.mainLayout, "${requireContext().getString(R.string.action_save_log)} : $fileName", Snackbar.LENGTH_LONG ) snackBar.setAction(R.string.open) { val args = LogViewFragmentArgs(targetFile.toUri().toString()).toBundle() findNavController() .navigate( R.id.action_homeFragment_to_logViewFragment, args ) } snackBar.show() } true } R.id.action_settings -> { findNavController().navigate(R.id.action_homeFragment_to_settingsFragment) true } R.id.action_log_list -> { findNavController().navigate(R.id.action_homeFragment_to_logListFragment) true } else -> false } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.lifecycleOwner = viewLifecycleOwner binding.viewmodel = viewModel setDefaultColor() val adapter = LogViewListAdapter(preference) binding.receivedMsgView.adapter = adapter binding.receivedMsgView.itemAnimator = null binding.receivedMsgView.addOnScrollListener(object : OnScrollListener() { override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { super.onScrollStateChanged(recyclerView, newState) if (newState == SCROLL_STATE_DRAGGING) { isAutoScroll = false } } override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) if (!recyclerView.canScrollVertically(1)) { isAutoScroll = true } } }) binding.sendMsgView.addTextChangedListener { text -> binding.sendBtn.isEnabled = text?.isNotEmpty() ?: false } binding.sendBtn.setOnClickListener { viewModel.sendMessage(binding.sendMsgView.text.toString()) binding.sendMsgView.text.clear() } viewModel.receivedMessage.observe(viewLifecycleOwner, { adapter.submitList(it) if (isAutoScroll) { binding.receivedMsgView.scrollToPosition(adapter.itemCount - 1) } }) binding.sendViewLayout.visibility = if (preference.sendFormVisibility) { View.VISIBLE } else { View.GONE } preference.colorConsoleBackground?.let { binding.mainLayout.setBackgroundColor(it) } preference.colorConsoleText?.let { binding.sendMsgView.setTextColor(it) } } private fun setDefaultColor() { if (preference.colorConsoleBackgroundDefault == null) { var defaultBackgroundColor = Color.TRANSPARENT val background = binding.mainLayout.background if (background is ColorDrawable) { defaultBackgroundColor = background.color } preference.colorConsoleBackgroundDefault = defaultBackgroundColor if (preference.colorConsoleBackground == null) { preference.colorConsoleBackground = preference.colorConsoleBackgroundDefault } } if (preference.colorConsoleTextDefault == null) { val defaultTextColor = binding.sendMsgView.textColors.defaultColor preference.colorConsoleTextDefault = defaultTextColor if (preference.colorConsoleText == null) { preference.colorConsoleText = preference.colorConsoleTextDefault } } } }
mit
a7b7ddffd91304567d128ce3e3f99e52
35.353488
96
0.601536
5.442201
false
false
false
false
panpf/sketch
sketch/src/androidTest/java/com/github/panpf/sketch/test/http/HttpHeadersTest.kt
1
11263
/* * Copyright (C) 2022 panpf <panpfpanpf@outlook.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.panpf.sketch.test.http import androidx.test.ext.junit.runners.AndroidJUnit4 import com.github.panpf.sketch.http.HttpHeaders import com.github.panpf.sketch.http.isNotEmpty import com.github.panpf.sketch.http.merged import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class HttpHeadersTest { @Test fun testNewBuilder() { val httpHeaders = HttpHeaders.Builder().apply { set("key1", "value1") set("key2", "value2") add("key3", "value3") add("key3", "value31") }.build() Assert.assertEquals(httpHeaders, httpHeaders.newBuilder().build()) Assert.assertNotEquals(httpHeaders, httpHeaders.newBuilder { add("key3", "value32") }.build()) Assert.assertEquals(httpHeaders, httpHeaders.newHttpHeaders()) Assert.assertNotEquals(httpHeaders, httpHeaders.newHttpHeaders() { add("key3", "value32") }) } @Test fun testSizeAndCount() { HttpHeaders.Builder().build().apply { Assert.assertEquals(0, size) Assert.assertEquals(0, addSize) Assert.assertEquals(0, setSize) } HttpHeaders.Builder().apply { set("key1", "value1") }.build().apply { Assert.assertEquals(1, size) Assert.assertEquals(0, addSize) Assert.assertEquals(1, setSize) } HttpHeaders.Builder().apply { set("key1", "value1") set("key2", "value2") set("key1", "value11") add("key3", "value3") add("key3", "value31") }.build().apply { Assert.assertEquals(4, size) Assert.assertEquals(2, addSize) Assert.assertEquals(2, setSize) } } @Test fun testIsEmptyAndIsNotEmpty() { HttpHeaders.Builder().build().apply { Assert.assertTrue(isEmpty()) Assert.assertFalse(isNotEmpty()) } HttpHeaders.Builder().apply { set("key1", "value1") }.build().apply { Assert.assertFalse(isEmpty()) Assert.assertTrue(isNotEmpty()) } HttpHeaders.Builder().apply { add("key1", "value1") }.build().apply { Assert.assertFalse(isEmpty()) Assert.assertTrue(isNotEmpty()) } HttpHeaders.Builder().apply { set("key1", "value1") add("key2", "value2") }.build().apply { Assert.assertFalse(isEmpty()) Assert.assertTrue(isNotEmpty()) } } @Test fun testAddSetGetRemove() { HttpHeaders.Builder().build().apply { Assert.assertNull(getSet("key1")) Assert.assertNull(getAdd("key2")) } HttpHeaders.Builder().apply { set("key1", "value1") }.build().apply { Assert.assertEquals("value1", getSet("key1")) Assert.assertNull(getAdd("key2")) } HttpHeaders.Builder().apply { add("key2", "value2") }.build().apply { Assert.assertNull(getSet("key1")) Assert.assertEquals(listOf("value2"), getAdd("key2")) } HttpHeaders.Builder().apply { set("key1", "value1") add("key2", "value2") }.build().apply { Assert.assertEquals("value1", getSet("key1")) Assert.assertEquals(listOf("value2"), getAdd("key2")) } // key conflict HttpHeaders.Builder().apply { set("key1", "value1") set("key1", "value11") add("key2", "value2") add("key2", "value21") }.build().apply { Assert.assertEquals("value11", getSet("key1")) Assert.assertEquals(listOf("value2", "value21"), getAdd("key2")) } // key conflict on add set HttpHeaders.Builder().apply { set("key1", "value1") add("key1", "value11") }.build().apply { Assert.assertNull(getSet("key1")) Assert.assertEquals(listOf("value11"), getAdd("key1")) } HttpHeaders.Builder().apply { add("key1", "value11") set("key1", "value1") }.build().apply { Assert.assertEquals("value1", getSet("key1")) Assert.assertNull(getAdd("key1")) } // remove HttpHeaders.Builder().apply { set("key1", "value1") add("key2", "value2") }.build().apply { Assert.assertEquals("value1", getSet("key1")) Assert.assertEquals(listOf("value2"), getAdd("key2")) }.newHttpHeaders { removeAll("key1") }.apply { Assert.assertNull(getSet("key1")) Assert.assertEquals(listOf("value2"), getAdd("key2")) } HttpHeaders.Builder().apply { set("key1", "value1") add("key2", "value2") }.build().apply { Assert.assertEquals("value1", getSet("key1")) Assert.assertEquals(listOf("value2"), getAdd("key2")) }.newHttpHeaders { removeAll("key2") }.apply { Assert.assertEquals("value1", getSet("key1")) Assert.assertNull(getAdd("key2")) } } @Test fun testEqualsAndHashCode() { val element1 = HttpHeaders.Builder().apply { set("key1", "value1") add("key2", "value2") }.build() val element11 = HttpHeaders.Builder().apply { set("key1", "value1") add("key2", "value2") }.build() val element2 = HttpHeaders.Builder().apply { set("key1", "value1") add("key3", "value3") }.build() val element3 = HttpHeaders.Builder().apply { set("key3", "value3") add("key2", "value2") }.build() Assert.assertNotSame(element1, element11) Assert.assertNotSame(element1, element2) Assert.assertNotSame(element1, element3) Assert.assertNotSame(element2, element11) Assert.assertNotSame(element2, element3) Assert.assertEquals(element1, element1) Assert.assertEquals(element1, element11) Assert.assertNotEquals(element1, element2) Assert.assertNotEquals(element1, element3) Assert.assertNotEquals(element2, element11) Assert.assertNotEquals(element2, element3) Assert.assertNotEquals(element1, null) Assert.assertNotEquals(element1, Any()) Assert.assertEquals(element1.hashCode(), element1.hashCode()) Assert.assertEquals(element1.hashCode(), element11.hashCode()) Assert.assertNotEquals(element1.hashCode(), element2.hashCode()) Assert.assertNotEquals(element1.hashCode(), element3.hashCode()) Assert.assertNotEquals(element2.hashCode(), element11.hashCode()) Assert.assertNotEquals(element2.hashCode(), element3.hashCode()) } @Test fun testToString() { HttpHeaders.Builder().build().apply { Assert.assertEquals("HttpHeaders(sets=[],adds=[])", toString()) } HttpHeaders.Builder().apply { set("key1", "value1") add("key2", "value2") }.build().apply { Assert.assertEquals("HttpHeaders(sets=[key1:value1],adds=[key2:value2])", toString()) } HttpHeaders.Builder().apply { set("key1", "value1") add("key2", "value2") add("key2", "value21") }.build().apply { Assert.assertEquals( "HttpHeaders(sets=[key1:value1],adds=[key2:value2,key2:value21])", toString() ) } } @Test fun testMerged() { val httpHeaders0 = HttpHeaders.Builder().build().apply { Assert.assertEquals("HttpHeaders(sets=[],adds=[])", toString()) } val httpHeaders1 = HttpHeaders.Builder().apply { set("set1", "setValue1") add("add1", "addValue1") }.build().apply { Assert.assertEquals( "HttpHeaders(sets=[set1:setValue1],adds=[add1:addValue1])", toString() ) } val httpHeaders11 = HttpHeaders.Builder().apply { set("set1", "setValue11") add("add1", "addValue11") }.build().apply { Assert.assertEquals( "HttpHeaders(sets=[set1:setValue11],adds=[add1:addValue11])", toString() ) } val httpHeaders2 = HttpHeaders.Builder().apply { set("set21", "setValue21") set("set22", "setValue22") add("add21", "addValue21") add("add22", "addValue22") }.build().apply { Assert.assertEquals( "HttpHeaders(sets=[set21:setValue21,set22:setValue22],adds=[add21:addValue21,add22:addValue22])", toString() ) } httpHeaders0.merged(httpHeaders0).apply { Assert.assertEquals("HttpHeaders(sets=[],adds=[])", toString()) } httpHeaders0.merged(httpHeaders1).apply { Assert.assertEquals( "HttpHeaders(sets=[set1:setValue1],adds=[add1:addValue1])", toString() ) } httpHeaders0.merged(httpHeaders2).apply { Assert.assertEquals( "HttpHeaders(sets=[set21:setValue21,set22:setValue22],adds=[add21:addValue21,add22:addValue22])", toString() ) } httpHeaders1.merged(httpHeaders2).apply { Assert.assertEquals( "HttpHeaders(sets=[set1:setValue1,set21:setValue21,set22:setValue22],adds=[add1:addValue1,add21:addValue21,add22:addValue22])", toString() ) } httpHeaders1.merged(httpHeaders11).apply { Assert.assertEquals( "HttpHeaders(sets=[set1:setValue1],adds=[add1:addValue1,add1:addValue11])", toString() ) } httpHeaders11.merged(httpHeaders1).apply { Assert.assertEquals( "HttpHeaders(sets=[set1:setValue11],adds=[add1:addValue11,add1:addValue1])", toString() ) } httpHeaders1.merged(null).apply { Assert.assertSame(httpHeaders1, this) } null.merged(httpHeaders1).apply { Assert.assertSame(httpHeaders1, this) } } }
apache-2.0
ef1b135eea97c70a60b004b445baaded
32.227139
143
0.554559
4.399609
false
true
false
false
lare96/luna
plugins/api/predef/EventPredef.kt
1
4009
package api.predef import api.event.InterceptBy import api.event.InterceptUseItem import api.event.Matcher import io.luna.game.event.Event import io.luna.game.event.EventListener import io.luna.game.event.impl.ButtonClickEvent import io.luna.game.event.impl.CommandEvent import io.luna.game.event.impl.ItemClickEvent.* import io.luna.game.event.impl.ItemOnItemEvent import io.luna.game.event.impl.ItemOnObjectEvent import io.luna.game.event.impl.NpcClickEvent.* import io.luna.game.event.impl.ObjectClickEvent.* import io.luna.game.model.mob.PlayerRights import java.util.* import kotlin.reflect.KClass /** * The player dedicated event listener consumer alias. */ private typealias EventAction<E> = E.() -> Unit /** * The command key, used to match [CommandEvent]s. */ class CommandKey(val name: String, val rights: PlayerRights) { override fun hashCode() = Objects.hash(name) override fun equals(other: Any?) = when (other) { is CommandKey -> name == other.name else -> false } } /** * The main event interception function. Forwards to [InterceptBy]. */ fun <E : Event> on(eventClass: KClass<E>) = InterceptBy(eventClass) /** * The main event interception function. Runs the action without any forwarding. */ fun <E : Event> on(eventClass: KClass<E>, action: EventAction<E>) { scriptListeners += EventListener(eventClass.java, action) } /** * The [ItemOnItemEvent] and [ItemOnObjectEvent] matcher function. Forwards to [InterceptUseItem]. */ fun useItem(id: Int) = InterceptUseItem(id) /** * The [ButtonClickEvent] matcher function. */ fun button(id: Int, action: EventAction<ButtonClickEvent>) = Matcher.get<ButtonClickEvent, Int>().set(id, action) /** The [NpcFirstClickEvent] matcher function.*/ fun npc1(id: Int, action: EventAction<NpcFirstClickEvent>) = Matcher.get<NpcFirstClickEvent, Int>().set(id, action) /** The [NpcSecondClickEvent] matcher function.*/ fun npc2(id: Int, action: EventAction<NpcSecondClickEvent>) = Matcher.get<NpcSecondClickEvent, Int>().set(id, action) /** The [NpcThirdClickEvent] matcher function.*/ fun npc3(id: Int, action: EventAction<NpcThirdClickEvent>) = Matcher.get<NpcThirdClickEvent, Int>().set(id, action) /** The [NpcFourthClickEvent] matcher function.*/ fun npc4(id: Int, action: EventAction<NpcFourthClickEvent>) = Matcher.get<NpcFourthClickEvent, Int>().set(id, action) /** The [NpcFifthClickEvent] matcher function.*/ fun npc5(id: Int, action: EventAction<NpcFifthClickEvent>) = Matcher.get<NpcFifthClickEvent, Int>().set(id, action) /** The [ItemFirstClickEvent] matcher function.*/ fun item1(id: Int, action: EventAction<ItemFirstClickEvent>) = Matcher.get<ItemFirstClickEvent, Int>().set(id, action) /** The [ItemSecondClickEvent] matcher function.*/ fun item2(id: Int, action: EventAction<ItemSecondClickEvent>) = Matcher.get<ItemSecondClickEvent, Int>().set(id, action) /** The [ItemThirdClickEvent] matcher function.*/ fun item3(id: Int, action: EventAction<ItemThirdClickEvent>) = Matcher.get<ItemThirdClickEvent, Int>().set(id, action) /** The [ItemFourthClickEvent] matcher function.*/ fun item4(id: Int, action: EventAction<ItemFourthClickEvent>) = Matcher.get<ItemFourthClickEvent, Int>().set(id, action) /** The [ItemFifthClickEvent] matcher function.*/ fun item5(id: Int, action: EventAction<ItemFifthClickEvent>) = Matcher.get<ItemFifthClickEvent, Int>().set(id, action) /** The [ObjectFirstClickEvent] matcher function.*/ fun object1(id: Int, action: EventAction<ObjectFirstClickEvent>) = Matcher.get<ObjectFirstClickEvent, Int>().set(id, action) /** The [ObjectSecondClickEvent] matcher function.*/ fun object2(id: Int, action: EventAction<ObjectSecondClickEvent>) = Matcher.get<ObjectSecondClickEvent, Int>().set(id, action) /** The [ObjectThirdClickEvent] matcher function.*/ fun object3(id: Int, action: EventAction<ObjectThirdClickEvent>) = Matcher.get<ObjectThirdClickEvent, Int>().set(id, action)
mit
81824c326fcdd3acbd0cd9e6cbea7111
34.803571
98
0.738339
3.618231
false
false
false
false
vondear/RxTools
RxKit/src/main/java/com/tamsiree/rxkit/RxConstants.kt
1
5506
package com.tamsiree.rxkit import java.io.File import java.text.DecimalFormat import java.util.* /** * @author tamsiree * @date 2017/1/13 */ object RxConstants { const val FAST_CLICK_TIME = 100 const val VIBRATE_TIME = 100 //----------------------------------------------------常用链接- start ------------------------------------------------------------ /** * RxTool的Github地址 */ const val URL_RXTOOL = "https://github.com/tamsiree/RxTool" /** * 百度文字搜索 */ const val URL_BAIDU_SEARCH = "http://www.baidu.com/s?wd=" /** * ACFUN */ const val URL_ACFUN = "http://www.acfun.tv/" const val URL_JPG_TO_FONT = "http://ku.cndesign.com/pic/" //===================================================常用链接== end ============================================================== const val URL_BORING_PICTURE = "http://jandan.net/?oxwlxojflwblxbsapi=jandan.get_pic_comments&page=" const val URL_PERI_PICTURE = "http://jandan.net/?oxwlxojflwblxbsapi=jandan.get_ooxx_comments&page=" const val URL_JOKE_MUSIC = "http://route.showapi.com/255-1?type=31&showapi_appid=20569&showapi_sign=0707a6bfb3e842fb8c8aa450012d9756&page=" const val SP_MADE_CODE = "MADE_CODE" //==========================================煎蛋 API end========================================= const val SP_SCAN_CODE = "SCAN_CODE" //微信统一下单接口 const val WX_TOTAL_ORDER = "https://api.mch.weixin.qq.com/pay/unifiedorder" //------------------------------------------煎蛋 API start-------------------------------------- var URL_JOKE = "http://ic.snssdk.com/neihan/stream/mix/v1/?" + "mpic=1&essence=1" + "&content_type=-102" + "&message_cursor=-1" + "&bd_Stringitude=113.369569" + "&bd_latitude=23.149678" + "&bd_city=%E5%B9%BF%E5%B7%9E%E5%B8%82" + "&am_Stringitude=113.367846" + "&am_latitude=23.149878" + "&am_city=%E5%B9%BF%E5%B7%9E%E5%B8%82" + "&am_loc_time=1465213692154&count=30" + "&min_time=1465213700&screen_width=720&iid=4512422578" + "&device_id=17215021497" + "&ac=wifi" + "&channel=NHSQH5AN" + "&aid=7" + "&app_name=joke_essay" + "&version_code=431" + "&device_platform=android" + "&ssmix=a" + "&device_type=6s+Plus" + "&os_api=19" + "&os_version=4.4.2" + "&uuid=864394108025091" + "&openudid=80FA5B208E050000" + "&manifest_version_code=431" //高德地图APP 包名 const val GAODE_PACKAGE_NAME = "com.autonavi.minimap" //百度地图APP 包名 const val BAIDU_PACKAGE_NAME = "com.baidu.BaiduMap" /** * 速度格式化 */ val FORMAT_ONE = DecimalFormat("#.#") /** * 距离格式化 */ @JvmField val FORMAT_TWO = DecimalFormat("#.##") /** * 速度格式化 */ val FORMAT_THREE = DecimalFormat("#.###") //默认保存下载文件目录 val DOWNLOAD_DIR = RxFileTool.rootPath.toString() + File.separator + "Download" + File.separator + RxDeviceTool.appPackageName + File.separator //图片缓存路径 @JvmField val PICTURE_CACHE_PATH = RxFileTool.getCacheFolder(RxTool.getContext()).toString() + File.separator + "Picture" + File.separator + "Cache" + File.separator //图片原始路径 val PICTURE_ORIGIN_PATH = RxFileTool.rootPath.toString() + File.separator + RxDeviceTool.appPackageName + File.separator + "Picture" + File.separator + "Origin" + File.separator //图片压缩路径 val PICTURE_COMPRESS_PATH = RxFileTool.rootPath.toString() + File.separator + RxDeviceTool.appPackageName + File.separator + "Picture" + File.separator + "Compress" + File.separator //默认导出文件目录 val EXPORT_FILE_PATH = RxFileTool.rootPath.toString() + File.separator + RxDeviceTool.appPackageName + File.separator + "ExportFile" + File.separator //图片名称 val pictureName: String get() = RxTimeTool.getCurrentDateTime(DATE_FORMAT_LINK) + "_" + Random().nextInt(1000) + ".jpg" //Date格式 const val DATE_FORMAT_LINK = "yyyyMMddHHmmssSSS" //Date格式 常用 const val DATE_FORMAT_DETACH = "yyyy-MM-dd HH:mm:ss" const val DATE_FORMAT_DETACH_CN = "yyyy年MM月dd日 HH:mm:ss" const val DATE_FORMAT_DETACH_CN_SSS = "yyyy年MM月dd日 HH:mm:ss SSS" //Date格式 带毫秒 const val DATE_FORMAT_DETACH_SSS = "yyyy-MM-dd HH:mm:ss SSS" //时间格式 分钟:秒钟 一般用于视频时间显示 const val DATE_FORMAT_MM_SS = "mm:ss" // Performance testing notes (JDK 1.4, Jul03, scolebourne) // Whitespace: // Character.isWhitespace() is faster than WHITESPACE.indexOf() // where WHITESPACE is a string of all whitespace characters // // Character access: // String.charAt(n) versus toCharArray(), then array[n] // String.charAt(n) is about 15% worse for a 10K string // They are about equal for a length 50 string // String.charAt(n) is about 4 times better for a length 3 string // String.charAt(n) is best bet overall // // Append: // String.concat about twice as fast as StringBuffer.append // (not sure who tested this) /** * A String for a space character. * * @since 3.2 */ const val SPACE = " " }
apache-2.0
02fe767c1588910d9a1202a78074e17f
34.187919
185
0.567531
3.349521
false
false
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/talk/NotificationDirectReplyHelper.kt
1
4823
package org.wikipedia.talk import android.app.NotificationManager import android.content.Context import android.os.Build import android.widget.Toast import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.core.content.getSystemService import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.schedulers.Schedulers import org.wikipedia.Constants import org.wikipedia.R import org.wikipedia.auth.AccountUtil import org.wikipedia.csrf.CsrfTokenClient import org.wikipedia.dataclient.ServiceFactory import org.wikipedia.dataclient.WikiSite import org.wikipedia.dataclient.okhttp.HttpStatusException import org.wikipedia.edit.Edit import org.wikipedia.page.PageTitle import org.wikipedia.util.StringUtil import org.wikipedia.util.log.L import java.util.concurrent.TimeUnit object NotificationDirectReplyHelper { const val DIRECT_REPLY_EDIT_COMMENT = "#directreply-1.0" // TODO: update this to use DiscussionTools API, and enable. fun handleReply(context: Context, wiki: WikiSite, title: PageTitle, replyText: String, replyTo: String, notificationId: Int) { Toast.makeText(context, context.getString(R.string.notifications_direct_reply_progress, replyTo), Toast.LENGTH_SHORT).show() Observable.zip(CsrfTokenClient.getToken(wiki).subscribeOn(Schedulers.io()), ServiceFactory.getRest(wiki).getTalkPage(title.prefixedText).subscribeOn(Schedulers.io())) { token, response -> Pair(token, response) }.subscribeOn(Schedulers.io()) .flatMap { pair -> val topic = pair.second.topics!!.find { it.id > 0 && it.html?.trim().orEmpty() == StringUtil.removeUnderscores(title.fragment) } if (topic == null || title.fragment.isNullOrEmpty()) { Observable.just(Edit()) } else { ServiceFactory.get(wiki).postEditSubmit( title.prefixedText, topic.id.toString(), null, DIRECT_REPLY_EDIT_COMMENT, if (AccountUtil.isLoggedIn) "user" else null, null, replyText, pair.second.revision, pair.first, null, null ) } } .subscribe({ if (it.edit?.editSucceeded == true) { waitForUpdatedRevision(context, wiki, title, it.edit.newRevId, notificationId) } else { fallBackToTalkPage(context, title) } }, { L.e(it) fallBackToTalkPage(context, title) }) } private fun waitForUpdatedRevision(context: Context, wiki: WikiSite, title: PageTitle, newRevision: Long, notificationId: Int) { ServiceFactory.getRest(wiki).getTalkPage(title.prefixedText) .delay(2, TimeUnit.SECONDS) .subscribeOn(Schedulers.io()) .map { if (it.revision < newRevision) { throw IllegalStateException() } it.revision } .retry(20) { (it is IllegalStateException) || (it is HttpStatusException && it.code == 404) } .observeOn(AndroidSchedulers.mainThread()) .doOnTerminate { cancelNotification(context, notificationId) } .subscribe({ // revisionForUndo = it Toast.makeText(context, R.string.notifications_direct_reply_success, Toast.LENGTH_LONG).show() }, { L.e(it) fallBackToTalkPage(context, title) }) } private fun fallBackToTalkPage(context: Context, title: PageTitle) { Toast.makeText(context, R.string.notifications_direct_reply_error, Toast.LENGTH_LONG).show() context.startActivity(TalkTopicsActivity.newIntent(context, title, Constants.InvokeSource.NOTIFICATION)) } private fun cancelNotification(context: Context, notificationId: Int) { if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.O) { return } context.getSystemService<NotificationManager>()?.activeNotifications?.find { it.id == notificationId }?.run { val n = NotificationCompat.Builder(context, this.notification) .setRemoteInputHistory(null) .setPriority(NotificationCompat.PRIORITY_MIN) .setVibrate(null) .setTimeoutAfter(1) .build() NotificationManagerCompat.from(context).notify(notificationId, n) } } }
apache-2.0
5060f4450340be79203b7b14328a527a
42.0625
132
0.618495
4.866801
false
false
false
false
slartus/4pdaClient-plus
app/src/main/java/org/softeg/slartus/forpdaplus/fragments/search/ForumsTreeDialogFragment.kt
1
9017
package org.softeg.slartus.forpdaplus.fragments.search import android.app.Dialog import android.content.Context import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.* import android.widget.AdapterView.OnItemClickListener import android.widget.AdapterView.OnItemSelectedListener import androidx.fragment.app.DialogFragment import com.afollestad.materialdialogs.MaterialDialog import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers import org.softeg.slartus.forpdaplus.MainActivity import org.softeg.slartus.forpdaplus.R import org.softeg.slartus.forpdaplus.classes.ForumsAdapter import org.softeg.slartus.forpdaplus.common.AppLog import org.softeg.slartus.forpdaplus.repositories.ForumsRepository import java.util.* /* * Created by slinkin on 24.04.2014. */ class ForumsTreeDialogFragment : DialogFragment() { private var m_ListView: ListView? = null private var m_Spinner: Spinner? = null private var m_ListViewAdapter: ForumsAdapter? = null private var m_SpinnerAdapter: SpinnerAdapter? = null private var m_Progress: View? = null private val m_Forums = ArrayList<CheckableForumItem>() override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val inflater = activity!!.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater val view = inflater.inflate(R.layout.forums_tree_dialog_fragment, null as ViewGroup?)!! m_ListView = view.findViewById(android.R.id.list) initListView() m_Spinner = view.findViewById(R.id.selected_spinner) initSpinner() m_Progress = view.findViewById(R.id.progress) //dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); return MaterialDialog.Builder(activity!!) .customView(view, false) .title(R.string.forum) .positiveText(R.string.accept) .negativeText(R.string.cancel) .onPositive { _, _ -> val intent = Intent() intent.putExtra( FORUM_IDS_KEY, m_ListViewAdapter!!.checkedIds.toTypedArray() ) targetFragment!!.onActivityResult( SearchSettingsDialogFragment.FORUMS_DIALOG_REQUEST, OK_RESULT, intent ) } .onNegative { _, _ -> targetFragment!!.onActivityResult( SearchSettingsDialogFragment.FORUMS_DIALOG_REQUEST, CANCEL_RESULT, null ) } .build() } private fun initListView() { m_ListView!!.isFastScrollEnabled = true m_ListViewAdapter = ForumsAdapter( activity, m_Forums ) m_ListView!!.adapter = m_ListViewAdapter m_ListView!!.onItemClickListener = OnItemClickListener { _, _, position, _ -> m_ListViewAdapter!!.toggleChecked(position) m_SpinnerAdapter!!.notifyDataSetChanged() } } private fun initSpinner() { m_SpinnerAdapter = SpinnerAdapter( activity, m_Forums ) m_Spinner!!.adapter = m_SpinnerAdapter m_Spinner!!.onItemSelectedListener = object : OnItemSelectedListener { override fun onItemSelected(adapterView: AdapterView<*>?, view: View, i: Int, l: Long) { if (l == 0L) return val item = m_SpinnerAdapter!!.getItem(l.toInt()) m_ListView!!.setSelection(m_ListViewAdapter!!.getPosition(item)) m_Spinner!!.setSelection(0) } override fun onNothingSelected(adapterView: AdapterView<*>?) {} } } private var dataSubscriber: Disposable? = null private fun subscribesData() { dataSubscriber?.dispose() setLoading(true) dataSubscriber = ForumsRepository.instance .forumsSubject .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnSubscribe { setLoading(true) } .doAfterTerminate { setLoading(false) } .subscribe( { items -> deliveryResult(items) setLoading(false) }, { setLoading(false) AppLog.e(activity, it) } ) } override fun onPause() { super.onPause() dataSubscriber?.dispose() MainActivity.searchSettings = SearchSettingsDialogFragment.createDefaultSearchSettings() } override fun onResume() { super.onResume() subscribesData() } private fun deliveryResult(result: List<org.softeg.slartus.forpdaapi.Forum>) { m_Forums.clear() addForumCaptions( m_Forums, result, null, 0, Arrays.asList( *arguments!!.getStringArray( FORUM_IDS_KEY ) ) ) m_ListViewAdapter!!.notifyDataSetChanged() m_SpinnerAdapter!!.notifyDataSetChanged() } private fun setLoading(b: Boolean) { m_Progress!!.visibility = if (b) View.VISIBLE else View.GONE } private fun addForumCaptions( forums: ArrayList<CheckableForumItem>, forum: List<org.softeg.slartus.forpdaapi.Forum>, parentForum: org.softeg.slartus.forpdaapi.Forum?, level: Int, checkIds: Collection<String?> ) { if (parentForum == null) { forums.add(CheckableForumItem("all", ">> " + getString(R.string.all_forums)).apply { this.level = level IsChecked = checkIds.contains(this.Id) }) addForumCaptions( forums, forum, org.softeg.slartus.forpdaapi.Forum(null, ""), level + 1, checkIds ) } else { forum .filter { it.parentId == parentForum.id } .forEach { forums.add(CheckableForumItem(it.id, it.title).apply { this.level = level IsChecked = checkIds.contains(this.Id) }) addForumCaptions(forums, forum, it, level + 1, checkIds) } } } inner class SpinnerAdapter( context: Context?, private val mForums: ArrayList<CheckableForumItem> ) : BaseAdapter() { private val m_Inflater: LayoutInflater = LayoutInflater.from(context) override fun getCount(): Int { var c = 1 for (f in mForums) { if (f.IsChecked) c++ } return c } override fun getItem(i: Int): CheckableForumItem? { if (i == 0) { return CheckableForumItem("", getString(R.string.total) + ": " + (count - 1)) } var c = 1 for (f in mForums) { if (f.IsChecked && c == i) return f if (f.IsChecked) c++ } return null } override fun getItemId(i: Int): Long { return i.toLong() } override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View? { val holder: ViewHolder var rowView = convertView if (rowView == null) { rowView = m_Inflater.inflate(android.R.layout.simple_spinner_dropdown_item, null) holder = ViewHolder() assert(rowView != null) holder.text = rowView .findViewById(android.R.id.text1) rowView.tag = holder } else { holder = rowView.tag as ViewHolder } val item = getItem(position) holder.text!!.text = item?.Title return rowView } inner class ViewHolder { var text: TextView? = null } } companion object { const val IS_DIALOG_KEY = "IS_DIALOG_KEY" const val FORUM_IDS_KEY = "FORUM_IDS_KEY" const val OK_RESULT = 0 const val CANCEL_RESULT = 1 @JvmStatic fun newInstance( dialog: Boolean?, checkedForumIds: Collection<String?> ): ForumsTreeDialogFragment { val args = Bundle() args.putBoolean(IS_DIALOG_KEY, dialog!!) args.putStringArray(FORUM_IDS_KEY, checkedForumIds.toTypedArray()) val fragment = ForumsTreeDialogFragment() fragment.arguments = args return fragment } } }
apache-2.0
ac4a0121a3d928894c472e8f1ce8b4d7
33.551724
100
0.566929
5.001109
false
false
false
false
hannesa2/owncloud-android
owncloudDomain/src/main/java/com/owncloud/android/domain/sharing/shares/model/OCShare.kt
2
1932
/** * ownCloud Android client application * * @author David González Verdugo * Copyright (C) 2020 ownCloud GmbH. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.owncloud.android.domain.sharing.shares.model import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class OCShare( val id: Int? = null, val shareType: ShareType, val shareWith: String?, val path: String, val permissions: Int, val sharedDate: Long, val expirationDate: Long, val token: String?, val sharedWithDisplayName: String?, val sharedWithAdditionalInfo: String?, val isFolder: Boolean, val remoteId: String, var accountOwner: String = "", val name: String?, val shareLink: String? ) : Parcelable { val isPasswordProtected: Boolean get() = shareType == ShareType.PUBLIC_LINK && !shareWith.isNullOrEmpty() } /** * Enum for Share Type, with values: * -1 - Unknown * 0 - Shared by user * 1 - Shared by group * 3 - Shared by public link * 4 - Shared by e-mail * 5 - Shared by contact * 6 - Federated * * @author masensio */ enum class ShareType constructor(val value: Int) { UNKNOWN(-1), USER(0), GROUP(1), PUBLIC_LINK(3), EMAIL(4), CONTACT(5), FEDERATED(6); companion object { fun fromValue(value: Int) = values().firstOrNull { it.value == value } } }
gpl-2.0
5e68178a922ad6e006c47b514831c639
25.452055
80
0.683584
3.956967
false
false
false
false
AndroidX/androidx
compose/ui/ui-text/src/androidMain/kotlin/androidx/compose/ui/text/platform/AndroidTextPaint.android.kt
3
5267
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.text.platform import android.text.TextPaint import androidx.annotation.VisibleForTesting import androidx.compose.ui.geometry.Size import androidx.compose.ui.geometry.isSpecified import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Paint import androidx.compose.ui.graphics.PaintingStyle import androidx.compose.ui.graphics.ShaderBrush import androidx.compose.ui.graphics.Shadow import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.drawscope.DrawStyle import androidx.compose.ui.graphics.drawscope.Fill import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.graphics.isSpecified import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.graphics.toComposePaint import androidx.compose.ui.text.platform.extensions.correctBlurRadius import androidx.compose.ui.text.style.TextDecoration import kotlin.math.roundToInt internal class AndroidTextPaint(flags: Int, density: Float) : TextPaint(flags) { init { this.density = density } // A wrapper to use Compose Paint APIs on this TextPaint private val composePaint: Paint = this.toComposePaint() private var textDecoration: TextDecoration = TextDecoration.None @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) internal var shadow: Shadow = Shadow.None private var drawStyle: DrawStyle? = null fun setTextDecoration(textDecoration: TextDecoration?) { if (textDecoration == null) return if (this.textDecoration != textDecoration) { this.textDecoration = textDecoration isUnderlineText = TextDecoration.Underline in this.textDecoration isStrikeThruText = TextDecoration.LineThrough in this.textDecoration } } fun setShadow(shadow: Shadow?) { if (shadow == null) return if (this.shadow != shadow) { this.shadow = shadow if (this.shadow == Shadow.None) { clearShadowLayer() } else { setShadowLayer( correctBlurRadius(this.shadow.blurRadius), this.shadow.offset.x, this.shadow.offset.y, this.shadow.color.toArgb() ) } } } fun setColor(color: Color) { color.toArgb() if (color.isSpecified) { composePaint.color = color composePaint.shader = null } } fun setBrush(brush: Brush?, size: Size, alpha: Float = Float.NaN) { // if size is unspecified and brush is not null, nothing should be done. // it basically means brush is given but size is not yet calculated at this time. if ((brush is SolidColor && brush.value.isSpecified) || (brush is ShaderBrush && size.isSpecified)) { // alpha is always applied even if Float.NaN is passed to applyTo function. // if it's actually Float.NaN, we simply send the current value brush.applyTo( size, composePaint, if (alpha.isNaN()) composePaint.alpha else alpha.coerceIn(0f, 1f) ) } else if (brush == null) { composePaint.shader = null } } fun setDrawStyle(drawStyle: DrawStyle?) { if (drawStyle == null) return if (this.drawStyle != drawStyle) { this.drawStyle = drawStyle when (drawStyle) { Fill -> { // Stroke properties such as strokeWidth, strokeMiter are not re-set because // Fill style should make those properties no-op. Next time the style is set // as Stroke, stroke properties get re-set as well. composePaint.style = PaintingStyle.Fill } is Stroke -> { composePaint.style = PaintingStyle.Stroke composePaint.strokeWidth = drawStyle.width composePaint.strokeMiterLimit = drawStyle.miter composePaint.strokeJoin = drawStyle.join composePaint.strokeCap = drawStyle.cap composePaint.pathEffect = drawStyle.pathEffect } } } } } /** * Accepts an alpha value in the range [0f, 1f] then maps to an integer value * in [0, 255] range. */ internal fun TextPaint.setAlpha(alpha: Float) { if (!alpha.isNaN()) { val alphaInt = alpha.coerceIn(0f, 1f).times(255).roundToInt() setAlpha(alphaInt) } }
apache-2.0
0a1fd01162ee987d924d22cb82436e3a
36.899281
96
0.647238
4.604021
false
false
false
false

IVA Kotlin GitHub Code Dataset - Curated - Validation

Dataset Description

This is the curated valid split of IVA Kotlin dataset extracted from GitHub. It contains curated Kotlin files gathered with the purpose to train & validate a code generation model.

The dataset only contains a valid split.

For validation and unspliced versions, please check the following links:

Information about dataset structure, data involved, licenses and standard Dataset Card information is available that applies to this dataset also.

Considerations for Using the Data

The dataset comprises source code from various repositories, potentially containing harmful or biased code, along with sensitive information such as passwords or usernames.

Downloads last month
0

Models trained or fine-tuned on mvasiliniuc/iva-kotlin-codeint-clean-valid