text:
Q: Unable to reverse a linked list I was trying to reverse a linked list, however whenever I execute the following function, I get only the last element. For example, if the list contained 11,12,13 earlier. After executing the function, it contains only 13. Kindly point out the bug in my code

void reverselist() {
    struct node *a, *b, *c;
    a = NULL;
    b = c = start;

    while (c != NULL) {
        c = b->next;
        b->next = a;
        a = b;
        b = c;
    }
    start = c;
}

A: *

*Doesn't your loop guard insure that start is null?

*If you aren't using start to identify the first element of the list, then the variable you ARE using is still pointing to what WAS the first element, which is now the last.

A: I would have made a prepend function, and done the following:
struct node* prepend(struct node* root, int value)
{
    struct node* new_root = malloc(sizeof(struct node));
    new_root->next = root;
    return new_root;
}

struct node* reverselist(struct node* inlist)
{
    struct node* outlist = NULL;

    while(inlist != NULL) {
        struct node* new_root = prepend(outlist, inlist->value);
        outlist = new_root;
        inlist = inlist->next;
    }

    return outlist;
}

Have not tested this, but guess you grasp the idea of it. Might be just your variable names, which don't describe anything, but I think this approach is cleaner, and easier to understand what actually happens.
EDIT:
Got a question why I don't do it inplace, so I'll answer it here:

*

*Can you do it inplace? Are you sure you don't wish to keep the
original list?

*Do you need to do it inplace? Is the malloc to time consuming/is this a performance critical part of your code? Remember: premature optimization is the root of all evil.

Thing is, this is a first implementation. It should work, and not be optimized. It should also have a test written before this implementation is even thought of, and you should keep this slow, un-optimized implementation until the test passes, and you have proved that it's to slow for your use!
When you have a passing unit test, and proven the implementation to be to slow, you should optimize the code, and make sure it still passes the test, without changing the test.
Also, is it necessary inplace operations which is the answer? What about allocating the memory before reverting it, this way you only have one allocation call, and should hopefully get a nice performance boost.
This way everyone is happy, you have a cleaner code and avoid the risk of having Uncle Bob showing up at your door with a shotgun.

A:

// You should assume that Node has a Node* called next that
// points to the next item in a list
// Returns the head of the reversed list if successful, else NULL / 0
Node *reverse( Node *head )
{
    Node *prev = NULL;

    while( head != NULL )
    {
        // Save next since we will destroy it
        Node *next = head->next;

        // next and previous are now reversed
        head->next = prev;

        // Advance through the list
        prev = head;
        head = next;
    }
    return previous;
}

A: c is a helper pointer.
void reverselist()
{
    struct node *a, *b, *c;
    a=NULL;
    b=start;
    while(b!=NULL)
    {
        c=b->next
        b->next=a;
        a=b
        b=c
    }
    start=a;
}


text:
Q: How to integrate firebase authentication with instagram login for android application I have integrated Facebook login and Twitter login as guided by the firebase tutorials. I am trying to integrate Instagram login for firebase authentication in my android application. I found this firebase article. I have few problems with this guidance.
In Twitter and Facebook integration, firebase provided a callback URL.
Can't we get a custom redirect-uri from Firebase just like for facebook and twitter which will handle the redirection in the same way?
It seems according to this guide, we should have an authentication server endpoint to be redirected after Instagram authentication. In that case how to continue with the authentication process without any kind of interruption in the Android application? To put it another way what is the server side implementation of the redirect-uri endpoint?

A: You can use Firebase Function. You can refer to this sample. This is the fastest way to achieve Instagram login without having any server-side code.
However, you still need to upgrade to the Blaze plan from Firebase.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Count the number of time a certain value appears in javascript I have an api response which I've parsed into Javascript object which looks like this:
teams [{
    0:
    1:
    2:
    3:
    4:
    5:
}]

Inside each of the 100 numbers contains information as follows:
teams [{
    0:
      team_name: "name"
      date: "2018-06-30T16:02:10Z"
      score: 5
      winning_id: 54
    1:
      team_name: "name"
      date: "2018-06-30T16:02:10Z"
      score: 5
      winning_id: 24
    2:
      team_name: "name"
      date: "2018-06-30T16:02:10Z"
      score: 3
      winning_id: 54
    3:
      team_name: "name"
      date: "2018-06-30T16:02:10Z"
      score: 2
      winning_id: 27
    4:
      team_name: "name"
      date: "2018-06-30T16:02:10Z"
      score: 4
      winning_id: 75
    5:
      team_name: "name"
      date: "2018-06-30T16:02:10Z"
      score: 6
      winning_id: 27
}]

I need to find and count how many times each different team won using the winning_id. Can anyone help.
I've tried joining all the winning_ids into one array so I can count but that didn't work, I've also tried turning them into strings to count that way but also didn't work.
The results should be a count for each id for example:
54: 2
24: 1
27: 2
75: 1

A:

const teams = [{
    0: {team_name: "name", date: "2018-06-30T16:02:10Z", score: 5, winning_id: 54,},
    1: {team_name: "name", date: "2018-06-30T16:02:10Z", score: 5, winning_id: 24,},
    2: {team_name: "name", date: "2018-06-30T16:02:10Z", score: 3, winning_id: 54,},
    3: {team_name: "name", date: "2018-06-30T16:02:10Z", score: 2, winning_id: 27,},
    4: {team_name: "name", date: "2018-06-30T16:02:10Z", score: 4, winning_id: 75,},
    5: {team_name: "name", date: "2018-06-30T16:02:10Z", score: 6, winning_id: 27,},
}];

const response = Object.values(teams[0]).reduce(
  (res, {winning_id}) => ({
    ...res,
    [winning_id]: (res[winning_id] || 0) + 1
  }),
{});
console.log(response);

You can try Array.reduce() and accumulate on winning_id occurrence


text:
Q: Is there any way to specify order of alternate questions in QnA pair (QnA Maker)? I am using QnA Maker Service and also active learning feature via explicit feedback which works as follows: query QnA Maker, find ambigous questions/answer pairs, create hero card by choosing first question from each QnA pair (QnAMakerResult) and send it to the user.
Since I am using this logic I want to have the best looking first question in QnA pair. But I have found out that when I click on Save and Train in QnA Maker portal, it will override my order of alternate questions in qna pair which completely breaks active learning experience because some questions in qna pair are not so user friendly such as only specific keywords etc.
Is there any way how to mark some alternate question for this purpose (like mark the most user friendly question) or to disable this automatic sorting in QnA Maker?

A: Since you haven't specified a language, my answer refers to the C# SDK, but the concepts should be transferable to the other SDKs.
I believe you might be able to achieve the functionality that you want in a roundabout and somewhat manual way:

*

*In the QnA Maker Portal add a metadata property to the questions you'd like to disambiguate, it could have the key disambiguation-question and the value would be the question you'd like to use for disambiguation. An example is provided here. e.g. disambiguation-question: My question that I want to use to disambiguate.

*Save, Train, and Publish your Knowledge base.

*Update your code to filter on the Metadataproperty of the QueryResult class, which contains an array of Metadata objects. TheGetAnswersAsyncmethod which is how you query your QnA Maker endpoint, will return an array ofQueryResult` objects.

*Use the Value from the Metadata object to display in your card for disambiguation. There is an example of how to do this here.

There is also an overview of how the QnA Maker ranking system for answers works available here, currently it works as follows:
| Step  | Purpose |
| --- | --- |
| 1 | The client application sends the user query to the GenerateAnswer API |
| 2 | QnA Maker preprocesses the user query with language detection, spellers, and word breakers. |
| 3 | This preprocessing is taken to alter the user query for the best search results. |
| 4 | This altered query is sent to an Azure Cognitive Search Index, which receives the top number of results. If the correct answer isn't in these results, increase the value of top slightly. Generally, a value of 10 for top works in 90% of queries. |
| 5 | QnA Maker uses syntactic and semantic based featurization to determine the similarity between the user query and the fetched QnA results. |
| 6 | The machine-learned ranker model uses the different features, from step 5, to determine the confidence scores and the new ranking order. |
| 7 | The new results are returned to the client application in ranked order. |

Features used include but aren't limited to word-level semantics, term-level importance in a corpus, and deep learned semantic models to determine similarity and relevance between two text strings.

I hope this helps.


text:
Q: From Password Protected Excel File to Python Object I am using Windows 7, Python 2.7 and Microsoft Excel 2013.
I know from here that I can open and access a password protected Excel sheet using the below sample code:
import sys
import win32com.client
xlApp = win32com.client.Dispatch("Excel.Application")
print "Excel library version:", xlApp.Version
filename, password = sys.argv[1:3]
xlwb = xlApp.Workbooks.Open(filename, Password=password)
# xlwb = xlApp.Workbooks.Open(filename)
xlws = xlwb.Sheets(1) # counts from 1, not from 0
print xlws.Name
print xlws.Cells(1, 1) # that's A1

I would like to save an Excel worksheet from a password protected file as a Python object. Ideally it would be saved as a pandas dataframe but I would be OK to have it as a dictionary or any other object type.
I have the password. Is this possible?
Thanks!

A: Add the following lines to your existing code (where xlwb already exists):
import os
import pandas as pd
from tempfile import NamedTemporaryFile

# Create an accessible temporary file, and then delete it. We only need a valid path.
f = NamedTemporaryFile(delete=False, suffix='.csv')
f.close()
os.unlink(f.name)  # Not deleting will result in a "File already exists" warning

xlCSVWindows = 0x17  # CSV file format, from enum XlFileFormat
xlwb.SaveAs(Filename=f.name, FileFormat=xlCSVWindows)  # Save the workbook as CSV
df = pd.read_csv(f.name)  # Read that CSV from Pandas
print df

Bear in mind that for me your code didn't fully work, and I got prompted for a password. But assuming you do manage to read a password protected file, the code above works.
Excel SaveAs reference: https://msdn.microsoft.com/en-us/library/bb214129(v=office.12).aspx


text:
Q: A visual indication that a text field is editable I'm developing an iPhone app. One of the screens contains several text fields, and an "edit" button. The text is static, but when the user taps the "edit" button, all the fields become editable. How do I communicate to the user via UI that they are now free to edit the text? I've played with changing the text/background color, but nothing seems right. I'll appreciate any references to apps that handle this issue nicely.

A: One way you could do it would be to change the textFieldDidBeginEditing: method to put some placeholder text in place in each of the text fields as follows:
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    textField.placeholder = @"Tap to edit!";
}

A: Have you tried maybe using the placeholder option for fields?
Example:  <input type="text" name="fname" placeholder="First name" />
Ok check out this link then. It uses jQuery (not sure if your doing web or native) But the effect is making the text field "Flash", drawing attention to it.
jQuery Flash

A: How about set the textfield become first responder and show up the keyboard when user press the button.
[textField becomeFirstResponder];


text:
Q: Is there any function called after the OnInitDialog function in MFC? I want to create a thread after the creation of a dialog box in MFC. Is there any function that Windows has provided and is automatically called after OnInitDialog so that I can create my thread inside it?

A: You can simply create your thread in the OnInitDialog function. There's no reason to overcomplicate things by going and searching for a different function, or splitting your initialization code up in two pieces. (There also isn't any such function, because there's no corresponding Windows message that is sent.)
If you want to get your dialog box on the screen before you create the thread, you can just show it manually using the ShowWindow function. For example:
ShowWindow(SW_SHOW);
RedrawWindow();

Also see this post by Raymond Chen: Waiting until the dialog box is displayed before doing something

A: OnInitDialog() is the main function called upon initialization (in reaction to WM_CREATE).
Why can't you create your thread in there?

A: I have changed the thread priority to below normal and when the thread executes for the first time I set the thread to normal priory. This works fine. Thanks for your response.

A: After many years of feeling unsatisifed with the OnTimer solution to draw first view graphics in an MFC dialog app (a favorite playground), this seemed like a nice simple solution:-

*

*Add a WM_HSCROLL handler with class wizard.

*At the end of OnInitDialog post a hscroll message with a NULL LPARAM

*In handler detect the NULL, draw graphics.

a timer meant that the app was alive for some time before graphics happened, and apparently hscroll is prioritized to happen just after the WM_PAINT message which would erase a picture element to its blank state, deleting anything that was drawn during initdialog.
BOOL CSpecDlg::OnInitDialog()
{
    ...

    PostMessage(WM_HSCROLL,0, (LPARAM)NULL);
    return TRUE;  // return TRUE  unless you set the focus to a control
}

void CSpecDlg::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)
{
    // TODO: Add your message handler code here and/or call default
    if (pScrollBar==NULL)
    {
        plot();
    }
    CDialogEx::OnHScroll(nSBCode, nPos, pScrollBar);
}


text:
Q: Magento 2.3.1 UI Component Dynamic Rows, "Is Default" is not getting saved I have created a dynamic form using Dynamic Rows in UI component form as shown in following screenshot:

Following is my code samples for your reference:

Namespace\ModuleName\view\adminhtml\ui_component\form.xml

<fieldset name="fee_options_container" component="Magento_Catalog/js/components/visible-on-option/fieldset"
          sortOrder="15">
    <argument name="data" xsi:type="array">
        <item name="config" xsi:type="array">
            <item name="valuesForOptions" xsi:type="array">
                <item name="select" xsi:type="string">select</item>
            </item>
        </item>
    </argument>
    <settings>
        <collapsible>true</collapsible>
        Manage Options
    </settings>
    <dynamicRows name="fee_options">
        <settings>
            <addButtonLabel translate="true">Add Option</addButtonLabel>
            <additionalClasses>
                <class name="admin__field-wide">true</class>
            </additionalClasses>
            <componentType>dynamicRows</componentType>
        </settings>
        <container name="record" component="Magento_Ui/js/dynamic-rows/record">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="isTemplate" xsi:type="boolean">true</item>
                    <item name="is_collection" xsi:type="boolean">true</item>
                    <item name="componentType" xsi:type="string">container</item>
                </item>
            </argument>
            <field name="is_default" component="Magento_Catalog/js/form/element/checkbox" sortOrder="0"
                   formElement="checkbox">
                <argument name="data" xsi:type="array">
                    <item name="config" xsi:type="array">
                        <item name="prefixElementName" xsi:type="string">option_</item>
                        <item name="inputCheckBoxName" xsi:type="string">default</item>
                        <item name="columnsHeaderClasses" xsi:type="string">control-table-options-th</item>
                        <item name="modules" xsi:type="array">
                            <item name="rows" xsi:type="string">ns = ${ $.ns }, index = fee_options</item>
                        </item>
                    </item>
                </argument>
                <settings>
                    <additionalClasses>
                        <class name="control-table-options-cell">true</class>
                    </additionalClasses>
                    <dataType>boolean</dataType>
                    Is Default
                </settings>
                <formElements>
                    <checkbox>
                        <settings>
                            <prefer>radio</prefer>
                        </settings>
                    </checkbox>
                </formElements>
            </field>
            <field name="fee_price" component="Magento_Catalog/js/form/element/input"
                   template="Magento_Catalog/form/element/input" formElement="input">
                <argument name="data" xsi:type="array">
                    <item name="config" xsi:type="array">
                        <item name="prefixName" xsi:type="string">fee_price.value</item>
                        <item name="prefixElementName" xsi:type="string">option_</item>
                        <item name="suffixName" xsi:type="string">0</item>
                        <item name="sortOrder" xsi:type="number">20</item>
                        <item name="validation" xsi:type="array">
                            <item name="required-entry" xsi:type="boolean">true</item>
                            <item name="validate-digits" xsi:type="boolean">true</item>
                        </item>
                    </item>
                </argument>
                <settings>
                    <dataType>text</dataType>
                    Price
                </settings>
            </field>
            <field name="fee_type" formElement="select">
                <argument name="data" xsi:type="array">
                    <item name="config" xsi:type="array">
                        <item name="prefixName" xsi:type="string">fee_type.value</item>
                        <item name="prefixElementName" xsi:type="string">option_</item>
                        <item name="sortOrder" xsi:type="number">30</item>
                    </item>
                </argument>
                <settings>
                    <dataType>text</dataType>
                    Apply As
                    <dataScope>fee_type</dataScope>
                </settings>
                <formElements>
                    <select>
                        <settings>
                            <options class="Magedelight\AdditionalFee\Model\Rule\Action\ActionProvider"/>
                        </settings>
                    </select>
                </formElements>
            </field>
            <field name="store_0" component="Magento_Catalog/js/form/element/input"
                   template="Magento_Catalog/form/element/input" formElement="input">
                <argument name="data" xsi:type="array">
                    <item name="config" xsi:type="array">
                        <item name="prefixElementName" xsi:type="string">option_</item>
                        <item name="sortOrder" xsi:type="number">40</item>
                        <item name="validation" xsi:type="array">
                            <item name="required-entry" xsi:type="boolean">true</item>
                        </item>
                    </item>
                </argument>
                <settings>
                    <dataType>text</dataType>
                    Admin
                </settings>
            </field>
            <field name="position" component="Magento_Catalog/js/form/element/input" formElement="input">
                <argument name="data" xsi:type="array">
                    <item name="config" xsi:type="array">
                        <item name="prefixName" xsi:type="string">position.order</item>
                        <item name="prefixElementName" xsi:type="string">option_</item>
                    </item>
                </argument>
                <settings>
                    <visible>false</visible>
                </settings>
            </field>
            <actionDelete name="action_delete">
                <argument name="data" xsi:type="array">
                    <item name="config" xsi:type="array">
                        <item name="fit" xsi:type="boolean">true</item>
                        <item name="prefixElementName" xsi:type="string">option_</item>
                        <item name="prefixName" xsi:type="string">fee.delete</item>
                        <item name="sortOrder" xsi:type="number">80</item>
                    </item>
                </argument>
                <settings>
                    <elementTmpl>Magento_Catalog/form/element/action-delete</elementTmpl>
                    <dataType>text</dataType>
                    <componentType>actionDelete</componentType>
                </settings>
            </actionDelete>
        </container>
    </dynamicRows>
</fieldset>

Namespace\Modulename\Controller\Adminhtml\Index\Save.php

public function execute() {
   $dynamicRowData = $this->getRequest()->getParams();
}

Response of $dynamicRowData:

Array
(
    [fee_id] => 4
    [fee_name] => test
    [display_type] => checkbox
    [fee_options] => Array
        (
            [0] => Array
                (
                    [store_1] => test 1
                    [store_2] => test 1
                    [fee_type] => F
                    [record_id] => 0
                    [fee_price] => 10
                    [store_0] => test 1
                    [position] => 1
                    [initialize] => true
                    [is_default] => 1
                )

            [1] => Array
                (
                    [record_id] => 1
                    [store_1] => test 2
                    [store_2] => test 2
                    [fee_price] => 20
                    [fee_type] => F
                    [store_0] => test 2
                    [position] => 2
                    [initialize] => true
                    [is_default] => 0
                )

        )

    [default] => Array
        (
            [0] => option_0
        )

    [fee_price] => Array
        (
            [value] => Array
                (
                    [option_0] => Array
                        (
                            [0] => 10
                        )

                    [option_1] => Array
                        (
                            [0] => 20
                        )

                )

        )

    [option_0] => test 1
    [option_1] => test 2
    [position] => Array
        (
            [order] => Array
                (
                    [option_0] => 1
                    [option_1] => 2
                )

        )

    [form_key] => 4Nj0oUjsJRfKgtWo

I'm saving is_default value like follows:
if (isset($data['is_default'])) {
    foreach ($dynamicRowData as $recId => $record) {
        if ($recId == $data['is_default']) {
            $dynamicRowData[$recId]['is_default'] = 1;
        }
        else {
            $dynamicRowData[$recId]['is_default'] = 0;
        }
    }
}

On edit page if I print Dataprovider's data, I'm getting following array for fee_options:
[fee_options] => Array
(
    [0] => Array
        (
            [store_1] => test 1
            [store_2] => test 1
            [fee_type] => F
            [record_id] => 0
            [fee_price] => 10
            [store_0] => test 1
            [position] => 1
            [initialize] => true
            [is_default] => 1
        )

    [1] => Array
        (
            [record_id] => 1
            [store_1] => test 2
            [store_2] => test 2
            [fee_price] => 20
            [fee_type] => F
            [store_0] => test 2
            [position] => 2
            [initialize] => true
            [is_default] => 0
        )
)

I can't save "is_default" field value, how can I make it selected at the time of Edit form. Can anyone please let me know if I'm missing anything? Thanks in anticipation.

A: Try This :-
 $dynamicRowData = $this->getRequest()->getParam('fee_options');

 foreach($dynamicRowData as $data)
 {
    if($data['is_default'] == 0)
    {
            //save is_default value
    }
 }


text:
Q: Missing Devel::Peek module My Perl has a missing Devel::Peek nodule.

# cpanm B::COW
--> Working on B::COW
Fetching http://www.cpan.org/authors/id/A/AT/ATOOMIC/B-COW-0.004.tar.gz ... OK
Configuring B-COW-0.004 ... OK
==> Found dependencies: Devel::Peek
skipping X/XS/XSAWYERX/perl-5.32.0.tar.gz
! Installing the dependencies failed: Module 'Devel::Peek' is not installed
! Bailing out the installation for B-COW-0.004.

# cpanm Devel::Peek
skipping X/XS/XSAWYERX/perl-5.32.0.tar.gz

I assume it supposed to be included in my Perl installation by default, but it is not.
# perl -v

This is perl 5, version 26, subversion 3 (v5.26.3) built for x86_64-linux-thread-multi
(with 51 registered patches, see perl -V for more detail)

Copyright 1987-2018, Larry Wall

Perl may be copied only under the terms of either the Artistic License or the
GNU General Public License, which may be found in the Perl 5 source kit.

Complete documentation for Perl, including FAQ lists, should be found on
this system using "man perl" or "perldoc perl".  If you have access to the
Internet, point your browser at http://www.perl.org/, the Perl Home Page.

How can I fix this? What workaround should I do?

A: Fixed by installing the Perl package
yum perl-Devel-Peek


text:
Q: Convert a CSV to JSON and change specific key values into Boolean or string using PHP Is there a way I can change specific key values into boolean or string. The conversion changes all the Data into string. For example the Key value "Date" should be an integer instead of a string.
<?php

    function csvToJson($fname) {
        if (!($fp = fopen($fname, 'r') )) {
            die("Can't open file");
        }

        $key = fgetcsv($fp, "1024", ",");

        $json = array();
            while ($row = fgetcsv($fp, "1024", ",")) {
                $json[] = array_combine($key, $row);
        }

        fclose($fp);

        foreach ( $json as $k=>$v ) {

            $json[$k]['dateRequested']     = $json[$k]['DATE'];
            $json[$k]['assignedAgent']     = $json[$k]['AGENT'];
            $json[$k]['finalCompanyName']  = $json[$k]['COMPANY NAME'];

            unset($json[$k]['DATE']);
            unset($json[$k]['AGENT']);
            unset($json[$k]['COMPANY NAME']);

        }

        return json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);

    }

 ?>

<?php
$json_data = csvToJson("lms.csv");
?>

A: Try this:
while ($row = fgetcsv($fp, "1024", ",")) {
// here $row contains all the columns in it in a numeric array
// Means 0 => first column of csv, 2 => second column of csv and so on

// you can convert any specific column value like
$json[] = array($row[0], setype($row[0], "string"), and so on);

}

A: You can do like this:
$json[$k]['dateRequested']     = (int)($json[$k]['DATE']);
$json[$k]['assignedAgent']     = $json[$k]['AGENT'];
$json[$k]['finalCompanyName']  = $json[$k]['COMPANY NAME'];

Sample usage :
$int = (int)(123);
$bool = (bool)(1);
$string = (string)(1234);

var_dump($int);
var_dump($bool);
var_dump($string);


text:
Q: Merge two plots into one with label Having a code like this:
Having this commands:
library(stm)
gadarian <- gadarian
K<-c(5,10,15)
temp<-textProcessor(documents=gadarian$open.ended.response,metadata=gadarian)
out <- prepDocuments(temp$documents, temp$vocab, temp$meta)
documents <- out$documents
vocab <- out$vocab
meta <- out$meta
set.seed(02138)
K<-c(5,10,15)
df1 <- searchK(documents, vocab, K, prevalence=~treatment + s(pid_rep), data=meta)
df2 <- searchK(documents, vocab, K, prevalence=~treatment + s(pid_rep), data=meta)

We can plot the results of df1:
plot(df1$results$K, df1$results$heldout, type = "p", main = "Held-Out Likelihood",
    xlab = "Number of Topics (K)", ylab = "Held-Out Likelihood", ask = TRUE)
lines(df1$results$K, df1$results$heldout, lty = 1, col = 1)

and for df2 using this:
plot(df2$results$K, df2$results$heldout, type = "p", main = "Held-Out Likelihood",
    xlab = "Number of Topics (K)", ylab = "Held-Out Likelihood", ask = TRUE)
lines(df2$results$K, df2$results$heldout, lty = 1, col = 1)

How is it possible to merge this two plot into one having different colors for every line and add a box in the right up corner of the graph which will have the color line and next to it the label likehood_score_df1 and likehood_score_df2?

A: You can use the following code
plot(df1$results$K,df1$results$heldout,
     ylim=range(c(df1$results$heldout,df2$results$heldout)),
     xlim=range(c(df1$results$K,df2$results$K)), type="b",col="red",
     xlab = "Number of Topics (K)", ylab = "Held-out Likelihood",
     main="Held-out Likelihood")

lines(df2$results$K,df2$results$heldout,col="green", type="b")

# Add a legend
legend(5, -5.52, legend=c("Likelihood score 1", "Likelihood score 2"),
   col=c("red", "green"), lty=1, cex=0.8, pch = 1)

Here you have to provide your x and y corodinates where you want to add your legend. A much better solution is dynamic positioning of the legend using
legend(locator(1), legend=c("Likelihood score 1", "Likelihood score 2"),
       col=c("red", "green"), lty=1, cex=0.8, pch = 1)

After running this click where you want to have the legend within the plot.

The code is bit messy but works.

A: Here is a possible solution using ggplot2. If you want to add points or adjust the layout its quite easy to do so. I hope the example gets you started :)
For future questions it would be helpful, if you could provide a minimal working example (i.e. if you could just have provided df1$result and df2$result it would have been fine)
df1$results %>%
  dplyr::mutate(group="likehood_score_df1") %>%
  dplyr::bind_rows(df2$results %>%
                     dplyr::mutate(group="likehood_score_df2")) %>%
  ggplot2::ggplot(ggplot2::aes(x=K, y=heldout, color=group)) +
  ggplot2::geom_line() +
  ggplot2::labs(x="Number of Topics (K)",
                y="Held-Out Likelihood",
                title="Held-Out Likelihood") +
  ggplot2::theme_minimal() +
  ggplot2::theme(legend.position=c(0.9,0.9),
                 legend.direction="vertical")


text:
Q: The representation of a group Do all the homomorphisms $\phi: SL(2,\mathbb{Z})\ltimes \mathbb{Z}^2 \to GL(2,\mathbb{R})$ always have that $\phi_{|\mathbb{Z}^2}$ is trivial, i.e. $\phi(\mathbb{Z}^2)=I_2$?

A: Yes. Consider $\mathbb R^2$ as a representation of the semidirect product, hence as a representation of $\mathbb Z^2$, and write it as an extension of irreducible characters $\chi_1$, $\chi_2$. If any nontrivial character $\chi$ appears, then all conjugates of that character by automorphisms of $\mathbb Z^2$ in $SL_2(\mathbb Z)$ must appear as well. But each nontrivial character has at least three distinct conjugates (with the minimum achieved by the three nontrivial quadratic characters), so none can appear. Hence the representation of $\mathbb Z^2$ is unipotent, but this just gives a character $\mathbb Z^2 \to \mathbb R^{+}$. Again all conjugates must appear, but there is just one conjugate, so it must be trivial.
So $\mathbb Z^2$ acts trivially.


text:
Q: Do a union or struct permit assignment from an uninitialised instance? This question is about the definedness or otherwise of assigning an uninitalised automatic variable to another one of the same type.
Consider
typedef struct
{
    int s1;
    int s2;
} Foo;

typedef union
{
    int u1;
    Foo u2;
} Bar;

int main()
{
    {
        int a;
        int b = a; // (1)
    }
    {
        Foo a;
        Foo b = a; // (2)
    }
    {
        Bar a;
        a.u1 = 0;
        Bar b = a; // (3)
    }
}

Referring to the comments in main:
(1) is undefined since a is uninitialised. That much I know.
But what about (2)? The struct members s1 and s2 are uninitialised.
Furthermore, what about (3)? The memory u2.s2 is uninitialised, so reading it is undefined behaviour no?

A: The behavior is undefined in (1) and (2).
Per the C standard, the value of an object with automatic storage duration that is not initialized is indeterminate (C 2011 [N1570] 6.7.9 10). Nominally, this means it has some value, but we do not know what it is while writing the program.
However, the standard also says "If the lvalue designates an object of automatic storage duration that could have been declared with the register storage class (never had its address taken), and that object is uninitialized (not declared with an initializer and no assignment to it has been performed prior to use), the behavior is undefined" (6.3.2.1 2). In your sample code, the address of a is never taken, and it is not initialized, and using it in an expression is an lvalue. Therefore, the behavior is undefined.
(This passage, 6.3.2.1 2, was designed to accommodate processors that can detect use of an uninitialized register. Nonetheless, the rule in the C standard applies to all implementations.)
(3) is not clearly addressed by the C standard. Although a member of the union has been assigned a value, and hence is not uninitialized for purposes of 6.3.2.1 2, the object being used in b = a is the union, not its member. Obviously, our intuitive notion is that, if a member of a union is assigned a value, the union has a value. However, I do not see this specified in the C standard.
We can infer 6.3.2.1 2 is not intended to consider a union or structure to be uninitialized, at least if part of it has been assigned a value, because:

*

*Structures can have unnamed members, such as unnamed bit fields.

*Per C 6.7.9 9, unnamed members of structures have indeterminate value, even after initialization (of the structures).

*If 6.3.2.1 2 applied to structures in which not every member had been assigned a value, then b = a would always be undefined if a were a structure with an unnamed member and had automatic storage duration.

*That seems unreasonable and not what the standard intended.
However, there is some wiggle room here. The standard could have specified that a structure is not uninitialized only if it were initialized or all of its named members have been assigned values. In that case (3) would be undefined if a were a structure in which only one member had been assigned a value. I do not think this wiggle room exists with a union; if a member of the union has been assigned a value, it is only reasonable to consider the union not to be uninitialized.

A: In general, assigning from an uninitialized object isn't undefined behavior, it only makes the result unspecified.
But the code you show indeed has undefined behavior -- for a different reason than you assume. Citing N1570 (latest C11 draft), §6.3.2.1 p2 here:

[...] If
  the lvalue designates an object of automatic storage duration that could have been
  declared with the register storage class (never had its address taken), and that object
  is uninitialized (not declared with an initializer and no assignment to it has been
  performed prior to use), the behavior is undefined.

Explaining this a bit: The C standard is prepared to handle values that aren't stored in an addressable location. This is typically the case when they are held in one of the CPU's registers. Explicitly giving an object the register storage class is only a hint to the compiler that it should, if sensible, hold that object in a register. The other way around, a compiler is free to hold any object with automatic storage duration in a register as long as the code doesn't need to address it (by taking a pointer).
In your code, you have uninitialized objects with automatic storage duration that never have their address taken, so the compiler would be free to place them in registers. This means there is no value for the object (not even an unspecified one) before it is initialized. Therefore, using this potentially non-existent value to initialize another object (or, for other purposes) is undefined behavior.
If your code would take a pointer to the respective a in all these examples, the result of the assignment would be unspecified (of course), but the behavior would be defined.

It's worth to add that structs and unions have nothing to do with the answer to your question. The rules are the same for all kind of objects with automatic storage duration. That said, in your third example, a isn't uninitialized any more, after you assign one member of the union. So for your third example, the behavior is well-defined. It doesn't matter what's in the other member of the union, a union can only hold a value for one of its members at a time.


text:
Q: Extracting batches from image list in Tensorflow I have a list of images(try to train CNN model with custom images), defined and reshaped by:
reader.images = tf.reshape(self.images, [-1, 256, 256, 3])

Which prints:
reader.Images :
[[[[ 127.  255.  127.]
   [ 140.  255.  114.]
   [ 217.  255.   38.]
  ...,
  [[ 255.  240.    0.]
   [ 255.  241.    0.]
   [ 249.  246.    6.]
   ...,
   [ 203.  237.   52.]
   [ 152.  251.  102.]
   [ 143.  253.  111.]]

  [[ 255.  184.    0.]
   [ 248.  192.    7.]
   [ 205.  242.   50.]
   ...,
   [ 255.  139.    0.]
   [ 255.  171.    0.]
   [ 255.  177.    0.]]

  [[ 255.  178.    0.]
   [ 237.  187.   18.]
   [ 131.  240.  124.]
   ...,
   [ 255.  123.    0.]
   [ 255.  156.    0.]
   [ 255.  162.    0.]]]]

I want to train my model, by extracting one batch per iteration. But when i use:
image_batch = tf.train.batch(
        [reader.images], batch_size=batch_size, dynamic_pad=True)

with batch_size =1
I get the whole image as output(same as printed above for whole list images).
I am new in Tensorflow so any tips are welcome.

A: Short answer:
For what you are asking for, you should add enqueue_many=True.
Long answer:
tf.train.batch is usually used to create a batch from single item tensors that would come from for example a queue.
So you would might feed it with an image tensor ([256, 256, 3]) and get a batched tensor out ([batch_size, 256, 256, 3]).
It is not generally used to slice batches out of a list tensor. You'd have to load all of the images into memory if you used it that way, which wouldn't be very scalable.
That is at least the default, enqueue_many=False:

If enqueue_many is False, tensors is assumed to represent a single
  example. An input tensor with shape [x, y, z] will be output as a
  tensor with shape [batch_size, x, y, z].

If you really want to load all images into memory you could add enqueue_many=True to the tf.train.batch call.

If enqueue_many is True, tensors is assumed to represent a batch of
  examples, where the first dimension is indexed by example, and all
  members of tensors should have the same size in the first dimension.
  If an input tensor has shape [*, x, y, z], the output will have shape
  [batch_size, x, y, z]. The capacity argument controls the how long the
  prefetching is allowed to grow the queues.

I would recommend reading https://www.tensorflow.org/programmers_guide/datasets for further guidance (now documenting the new recommended way of using datasets instead of the previously recommended queues - you can create the batch directly from the dataset rather than calling tf.train.batch).


text:
Q: how to disable preveious date in a date picker? i am using Gregorian calendar and i need to disable a previous date to till current date in android. i already checked setMinDate method but its not working.. can anyone help me? here is my code..
 public void SelectDateTime() {
        final View dialogView = View.inflate(getApplicationContext(), R.layout.date_picker_activate, null);
        DateTimeDialog = new AlertDialog.Builder(getApplicationContext()).create();
        dialogView.findViewById(R.id.cancelBtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DateTimeDialog.dismiss();
            }
        });
        dialogView.findViewById(R.id.date_time_set).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DatePicker datePicker = (DatePicker) dialogView.findViewById(R.id.datePicker1);
                TimePicker timePicker = (TimePicker) dialogView.findViewById(R.id.timePicker);
                Calendar calendar = new GregorianCalendar(datePicker.getYear(),
                        datePicker.getMonth(),
                        datePicker.getDayOfMonth(),
                        timePicker.getCurrentHour(),
                        timePicker.getCurrentMinute());

                datePicker.getMinDate();

                final long today1 = System.currentTimeMillis() - 1000;

                calendar.after(System.currentTimeMillis());

               // datePicker.setMinDate(calendar.getTimeInMillis());

A: Use this code
    public static class DatePickerFragment extends DialogFragment
        implements DatePickerDialog.OnDateSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);
        DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, year, month, day);
        // dialog.getDatePicker().setMaxDate(c.getTimeInMillis());
        dialog.getDatePicker().setMinDate(c.getTimeInMillis());
        return dialog;
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
        txt_date.setText(String.format(Locale.ENGLISH, "%02d/%02d/%d", day, month + 1, year));
    }
}

Call this method in side button click like
DialogFragment newFragment = new DatePickerFragment();
            newFragment.show(getActivity().getSupportFragmentManager(), "datePicker");

This line set min date -  dialog.getDatePicker().setMinDate(c.getTimeInMillis());

and use this to set max date

dialog.getDatePicker().setMaxDate(c.getTimeInMillis());

A: This will disable previouis dates
public void showDateToSelect() {
        // Get Current Date
        final Calendar c = Calendar.getInstance();
        int mYear = c.get(Calendar.YEAR);
        int mMonth = c.get(Calendar.MONTH);
        int mDay = c.get(Calendar.DAY_OF_MONTH);
        /*DatePicker dialog to select date*/
        DatePickerDialog datePickerDialog = new DatePickerDialog(mContext,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        textView.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year);
                    }
                }, mYear, mMonth, mDay);
        /*To show only dates from today to future*/
        datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
        datePickerDialog.show();
    }

A: User this library
implementation 'com.github.florent37:singledateandtimepicker:1.2.1'

And initiate with following code
 startSingleDateAndTimePickerDialog = new SingleDateAndTimePickerDialog.Builder(context);
            startSingleDateAndTimePickerDialog
                    .bottomSheet()
                    .curved()
                    .displayHours(true)
                    .displayMinutes(true)
                    .minDateRange(new Date(minDate))
                    .defaultDate(new Date(defaultDate))
                    .mustBeOnFuture()
.displayListener(new SingleDateAndTimePickerDialog.DisplayListener() {
                    @Override
                    public void onDisplayed(SingleDateAndTimePicker picker) {
                        //retrieve the SingleDateAndTimePicker
                    }
                })

                .title("Date & Time")
                .listener(new SingleDateAndTimePickerDialog.Listener() {
                    @Override
                    public void onDateSelected(Date date) {

                        Date currentDate = new Date(System.currentTimeMillis());

     String dateTime = getDate(date.getTime() / 1000);
textview.settext(dateTime);

                    }
                }).display();

 public static String getDate(long timeStamp) {
        Date time = new Date(timeStamp*1000);
        SimpleDateFormat df2 = new SimpleDateFormat("MMM dd,yyy h:mm a");
        return df2.format(time);
    }


text:
Q: Contact Picker fails from URL in WebView but work in same URL in android chrome browser I used the chrome contact Picker from glitch to view my phone contacts from my website in android chrome.
A WebView app using the same website as URL opens the contact Picker stage alright but fails to show phone contacts. Do I need certain permissions before using the API in android WebView?
Your help will be appreciated.


text:
Q: Is it possible to perform one query linking to tables on 2 databases with Dapper? I have 2 databases, a master and a company. Both databases are on the same server currently but will eventually be on different servers. Is it possible to perform a query that joins tables across databases in dapper? My application is Asp.NET Core and the databases are MariaDB (so basically MySQL).
Here is an example of a query I'm trying to perform:
select a.username, b.name from company.user a join master.lookup_user_type b on a.user_type_id = b.id

Maybe I'm confused what my actual question is, maybe I just need to figure out how to have one conncetion string that references multiple databases.

A: Yes, it is possible to perform a query across two different databases on the same server, as long as the user you're logging in as has permission to access both databases.. Assuming your databases are named company and master, then your query looks correct.
If your databases are on two different servers, you will need to use federated tables.


text:
Q: how do you 'connect' this source code with my tkinter python hi am new to python and i have created a very simple encryption code and a simple gui with tkinter
but i cant seem to 'connect' them together i tried so hard but i need help right now
def machine():
    global newMessage
    keys = "abcdefghijklmnopqrstuvwxyz !"
    values = keys[-1] + keys[0:-1]

    encryptDict = dict(zip(keys, values))
    decryptdict = dict(zip(values, keys))

    message = input("Enter your message so i can encrypt or decrypt it :) ")
    mode = input("encrypt(E) OR decrypt(D) ")
    if mode.upper() == "E":
        newMessage = ''.join([encryptDict[letter] for letter in message.lower()])
    elif mode.upper() == "D":
        newMessage = ''.join([decryptdict[letter] for letter in message.lower()])
    else:
        print("use either E or D ")

    return newMessage

print(machine())

that is the encryption method
import tkinter as tk

HIGHT = 240
WIDTH = 720

root = tk.Tk()

canvas = tk.Canvas(root, height=HIGHT, width=WIDTH)
canvas.pack()

label = tk.Label(root, text="Enter your message so i can encrypt or decrypt it :)")
label.place(relx=0.25, rely=0.1, relwidth=0.5, relheight=0.125)

entry = tk.Entry(root)
entry.place(relx=0.1, rely=0.3, relwidth=0.8, relheight=0.125)

entry = tk.Entry(root)
entry.place(relx=0.1, rely=0.7, relwidth=0.8, relheight=0.125)

button = tk.Button(root, text="Incrypt")
button.place(relx=0.68, rely=0.5, relwidth=0.125, relheight=0.125)

button = tk.Button(root, text="Decrypt")
button.place(relx=0.18, rely=0.5, relwidth=0.125, relheight=0.125)

root.mainloop()

and that is the gui

A: You need to use the message = entry.config().
config() takes what you have typed into the entry label and assigns it into the message variable.
Also you should assign to a button your functions,
button_incrypt = tk.Button(root, text="Incrypt", command=incrypt)
button_decrypt = tk.Button(root, text="Decrypt", command=decrypt)
In general i suggest, make two different functions, one each for every button,
as well two entries, by which those functions will absorb the encrypted/decrypted text.

A: use the 'command' parameter in the Button widget to set it to an event handler which in your case is machine. Since you are encrypting and decrypting under the same function send a signal when calling this function as shown below using lambda function. Also, replace  message = input("Enter your message so i can encrypt or decrypt it :) ") with message=entry.get(). You have assigned entry=Entry() twice I assume that's a mistake so remove it. Finally instead of return use the existing label widget to display output
using config or you can also create a new label and use that for displaying the output.
Here is the complete code, which you may further improvise:
import tkinter as tk

HIGHT = 240
WIDTH = 720

def machine(mode):
    global newMessage
    keys = "abcdefghijklmnopqrstuvwxyz !"
    values = keys[-1] + keys[0:-1]

    encryptDict = dict(zip(keys, values))
    decryptdict = dict(zip(values, keys))

    message = entry.get()

    if mode == 0:
        newMessage = ''.join([encryptDict[letter] for letter in message.lower()])

    elif mode == 1:
        newMessage = ''.join([decryptdict[letter] for letter in message.lower()])

    label.config(text='Message: '+ newMessage)

root = tk.Tk()

canvas = tk.Canvas(root, height=HIGHT, width=WIDTH)
canvas.pack()

label = tk.Label(root, text="Enter your message so i can encrypt or decrypt it :)")
label.place(relx=0.25, rely=0.1, relwidth=0.5, relheight=0.125)

entry = tk.Entry(root)
entry.place(relx=0.1, rely=0.3, relwidth=0.8, relheight=0.125)

button = tk.Button(root, text="Encrypt", command=lambda :machine(0))
button.place(relx=0.68, rely=0.5, relwidth=0.125, relheight=0.125)

button2 = tk.Button(root, text="Decrypt", command=lambda :machine(1))
button2.place(relx=0.18, rely=0.5, relwidth=0.125, relheight=0.125)

root.mainloop()

Update:
To insert the text into the Entry widget use Entry.insert(index, string). Also, don't forget to clear the existing text in the Entry by using Entry.delete(0, END), the 'END' specifier will make sure that it deletes all the text starting from 0th index.
import tkinter as tk

HIGHT = 240
WIDTH = 720

def machine(mode):
    global newMessage
    keys = "abcdefghijklmnopqrstuvwxyz !"
    values = keys[-1] + keys[0:-1]

    encryptDict = dict(zip(keys, values))
    decryptdict = dict(zip(values, keys))

    message = entry.get()

    if mode == 0:
        newMessage = ''.join([encryptDict[letter] for letter in message.lower()])

    elif mode == 1:
        newMessage = ''.join([decryptdict[letter] for letter in message.lower()])

    entry2.delete(0, tk.END)
    entry2.insert(0,'Message: '+ newMessage)

root = tk.Tk()

canvas = tk.Canvas(root, height=HIGHT, width=WIDTH)
canvas.pack()

label = tk.Label(root, text="Enter your message so i can encrypt or decrypt it :)")
label.place(relx=0.25, rely=0.1, relwidth=0.5, relheight=0.125)

entry = tk.Entry(root)
entry.place(relx=0.1, rely=0.3, relwidth=0.8, relheight=0.125)

entry2 = tk.Entry(root)
entry2.place(relx=0.1, rely=0.7, relwidth=0.8, relheight=0.125)

button = tk.Button(root, text="Encrypt", command=lambda :machine(0))
button.place(relx=0.68, rely=0.5, relwidth=0.125, relheight=0.125)

button2 = tk.Button(root, text="Decrypt", command=lambda :machine(1))
button2.place(relx=0.18, rely=0.5, relwidth=0.125, relheight=0.125)

root.mainloop()

A: You can pass the mode and message to machine() function instead of using input() to get them:
ENCRYPT = "E"
DECRYPT = "D"

def machine(mode, message):
    keys = "abcdefghijklmnopqrstuvwxyz !"
    values = keys[-1] + keys[:-1]

    mydict = dict(zip(keys, values)) if mode == ENCRYPT else dict(zip(values, keys))
    return "".join(mydict[letter] for letter in message.lower())

Then you can use command option to call machine() with required arguments:
entry_message = tk.Entry(root)
entry_message.place(relx=0.1, rely=0.3, relwidth=0.8, relheight=0.125)

result = tk.StringVar()  # use it for easier update of the result entry box
entry_result = tk.Entry(root, textvariable=result)
entry_result.place(relx=0.1, rely=0.7, relwidth=0.8, relheight=0.125)

button = tk.Button(root, text="Encrypt", command=lambda: result.set(machine(ENCRYPT, entry_message.get())))
button.place(relx=0.68, rely=0.5, relwidth=0.125, relheight=0.125)

button = tk.Button(root, text="Decrypt", command=lambda: result.set(machine(DECRYPT, entry_message.get())))
button.place(relx=0.18, rely=0.5, relwidth=0.125, relheight=0.125)


text:
Q: What is the acceptable level of concurvity? I got the following concurvity values as a result of a GAM model.

Are they considered high or low? I don't know what is the acceptable value.

A: This is a late bump to a relatively old question, but may be of help to future visitors.
In Noam Ross' course on GAMs, GAMs in R, Chapter 2, section 10 "checking concurvity" says that observing a value over 0.8 for the worst case requires closer inspection of the model. So in the image you pasted there's only one variable over 0.8 (VV_PROM_S60), but there are many very close to that threshold, so you may want to check those too. The suggested way to have a closer look at the model is by using concurvity(model, full = FALSE) and carefully analyzing the pairwise concurvities.

A: I would like to get more clarity on this as well, but I did find one paper (Tree traits influence response to fire severity in the western Oregon Cascades, USA; 2019) that used the mgcv package where the authors used a cutoff of 0.3.  It sounded like they applied that cutoff to all three measures of concurvity.  Of course, even they said it was an arbitrary cutoff.

A: Another source, from a doctoral dissertation Multi-city time series analyses of air pollution and mortality data using generalized geoadditive mixed models
by Lung-Chang Chien. Free online access.

So far, there is no strict criterion to identify the level of concurvity which can
severely affect model fitting. Ramsay et al. (2003a) suggested using 0.5 to be the cutoff
point. If the level of concurvity in nonparametric or semiparametric models is greater than
0.5, it is necessary to seek in order to eliminate or reduce this problem.


text:
Q: $\mathbb{R}[x,y]/(y^2+x)$ is not a noetherian $\mathbb{R}$-module I've been given the task to find whether or not $R=\mathbb{R}[x,y]/(y^2+x)$ is noetherian as a  $\mathbb{R}$-module. I've been thinking of using the usual submodule of powers of $x$ to prove that it isn't noetherian. Considering the $\mathbb{R}$-submodule generated by powers of the residue classes of $x$.
$$ S = \langle \overline{x}, \overline{x}^2,\dots,\overline{x}^n,\dots\rangle$$
$S$ can't then be finitely generated on $\mathbb{R}$ because any finite generator set won't generate $\overline{x}^n$ for some sufficiently large $n$.
I feel a bit uncomfortable working with submodules of quotient modules and it looks like the quotient is irrelevant for this question. Can I use such an argument to prove that $R$ isn't noetherian?


text:
Q: javascript dynamic Select from php sql query There are so many questions around embedding php in javascript that I hate to even ask this, but I'm stuck.
I have two things working independently and I'm essentially trying to combine them:

*

*dynamically filling in select options through php

*dynamically creating a select element through javascript

My PHP code (works fine for my first select):
<select id="select_employee" name="employee">
  <option disabled selected value>-- Select an employee --</option>
  <?php
    while( $row = sqlsrv_fetch_array( $d_Employees, SQLSRV_FETCH_ASSOC))
    {
      echo "<option class='o_employee " . $row['dept'] . "' value='" . $row['employee'] . "'>" . $row['employee'] . "</option>";
    }
  ?>
</select>

javascript code to add additional selects
const t_select = document.createElement("select")
  t_select.setAttribute('id', 'select_employee'+cols)
  t_select.setAttribute('name', 'employee'+cols)

  //create default option for select
  var option = document.createElement("option")
  option.setAttribute('disabled', 'disabled')
  option.setAttribute('selected', 'selected')
  option.setAttribute('value', 'value')
  option.innerHTML = '-- Select an employee --'
  t_select.appendChild(option)

  //create dropdown via php - this is where I'm stuck
  var option = document.createElement("option")
  option.????? = <?php
    while( $row = sqlsrv_fetch_array( $d_Employees, SQLSRV_FETCH_ASSOC))
    {
      echo "<option class='o_employee " . $row['dept'] . "' value='" . $row['employee'] . "'>" . $row['employee'] . "</option>";
    }
  ?>

Bonus points if the consecutive selects pare down the options based on prior selections.  :)
Thanks for any suggestions!

A: The easy answer was:  cloneNode
var t_select = document.createElement("select")
var source = document.getElementById('select_employee0')
t_select = source.cloneNode(true)
t_select.setAttribute('id', 'select_employee'+cols)
t_select.setAttribute('name', 'employee'+cols)


text:
Q: How to use Yelp API v2 C# example in Umbraco site I'm new to .net and Umbraco in general. I have a basic site setup and want to use the Yelp API to display some content on the site. I've played with the code sample from git:
https://github.com/Yelp/yelp-api/tree/master/v2/csharp
And have successfully built that, which produces an executable command line program. My question is, how do I convert the code from the sample for use directly on the website, specifically Umbraco v7?
Any help much appreciated, thanks.

A: Your code should not differ a lot from the example combined with normal ASP.NET.
If you are in a Partial view or Template in Umbraco your Razor code could look something like:
@{
  // todo: add other relevant code or link to other classes encapsulating your calls
  JObject response = client.Search(term, location);
  JArray businesses = (JArray)response.GetValue("businesses");
}

  @foreach(var item in businesses) {

id: @item["id"]

  }


text:
Q: Probability Question (Equally likely sample points) An airport bus deposits 25 passengers at 7 stops. Each passenger is as likely to get off at any stop as at any other, and the passengers act independently of one another. The bus makes a stop only if someone wants to get off. What is the probability that nobody gets off at the third stop?
I know the total possibilities are $7^{25}$, but I am not sure about the numerator.
Since no one is getting off at the third stop, that would assume they are getting off on the other 6 stops. So would the answer be $\frac{6^{25}}{7^{25}}$?

A: You are correct.
If you understand the reason of $7^{25}$, you should understand the value of $6^{25}$.


text:
Q: replace Multiple patterns within a list_file with One in target_file with awk I'm facing a problem
1) I got a list_file intended to be used for inlace replacement like this
Replacement pattern ; Matching patterns

EXTRACT ___________________
toto ; tutu | tata | tonton  | titi
bobo ; bibi | baba | bubu | bebe
etc. 14000 lines !!!
_____________________________

2) I got a target file in witch I want to replace thoses paterns
EXTRACT INPUT _______________
hello my name is bob and I am a Titi and I like bubu
_____________________________

I want it to become
EXTRACT OUTPUT ______________
hello my name is bob and I am a toto and I like bobo
_____________________________

for example with one replacement :
echo 'toto; tutu | tata | tonton | titi ' | awk '{gsub(/ tutu | tata | tonton | titi /," toto ")}1'
gives
toto; toto | toto | toto | toto

with
awk -F';' 'NR==FNR{A[$1]=$2; next} IGNORECASE = 1 {for(i in A) gsub(/A[i]/,i)}1'

I expect to :

*

*register an array A with $2 as content and $1 as key
so in the fist line
$2 =' tutu | tata | tonton | titi '
$1 = ' toto '

*replace with gsub(/$2/,$1)}1
so in the fist line
awk 'IGNORECASE = 1 {gsub(/ tutu | tata | tonton | titi /," toto ")}1

Sadly awk doesn't seems to understand the pipe « | » character as a OR indicator … I have also tried to achieve this with sed but this option goes very slowly aven if it works :(
does anyone have a better idea ?
Thanks
M

A: By putting the array reference inside regexp delimiters you're turning A[i] into literal characters in the regexp instead of an array that contains a regexp indexed by a string. Just don't do that. Also your placement of setting IGNORECASE makes no sense. Try this:
awk -F';' 'BEGIN{IGNORECASE = 1} NR==FNR{A[$1]=$2; next} {for(i in A) gsub(A[i],i)}1'

I'm not saying it's a good idea but it might give you the output you're looking for. Stop using the word "pattern" btw as patterns are for quilts and sweaters - in text matching and replacing use either regexp or string, whichever one you mean in every context. You'll find it much easier to write and understand code if you understand where regexps vs strings occur.


text:
Q: More robust way of extracting date field from string in shell script I have a string which described the active directory expiration date of my account. I want to use/parse this string and do something when expiration date is coming soon. Now I have a problem extracting the date-part of the complete string. The string is:
Password expires             1-4-2015 15:41:05

I want to extract 1-4-2014 from it, but when the date is 20-12-2015, the mechanism should also work. Unfortunately I'm unable to config the source system so that it outputs leading zero's. I have tried piping the string to cut -c30-39, but obviously this does not work with strings which are in total longer (like 20-12-2015).
So I'm looking for a more robust solution, something like extracting extracting until the last 4 digits AFTER the 2nd --character.

A: You could use grep,
$ echo 'Password expires             1-4-2015 15:41:05' | grep -o '\b[0-9]\{1,2\}-[0-9]\{1,2\}-[0-9]\{4\}\b'
1-4-2015
$ echo 'Password expires             20-12-2015 15:41:05' | grep -o '\b[0-9]\{1,2\}-[0-9]\{1,2\}-[0-9]\{4\}\b'
20-12-2015

To grep only the year.
$ echo 'Password expires             20-12-2015 15:41:05' | grep -oP '^(?:[^-]*-){2}\K\d{4}\b'
2015

To get only the day
$ echo 'Password expires             1-4-2015 15:41:05' | grep -oP '\b[0-9]{1,2}(?=-[0-9]{1,2}-[0-9]{4}\b)'
1

To get only the month
$ echo 'Password expires             1-4-2015 15:41:05' | grep -oP '\b[0-9]{1,2}-\K[0-9]{1,2}(?=-[0-9]{4}\b)'
4

A: Either:
awk "{print $3}"

Or
tr -s ' ' | cut -d ' ' -f 3

That's assuming you are after "third thing" on the line. Then use date to parse, and verify. Unfortunately, because it's ambiguous, your date string won't parse.
You'd need to reverse it - some versions of date have -f input format specifier, but not all. (I'm fairly sure if you used Perl, Time::Piece and strptime, you'd be able to do this too, but suspect that's out of scope)
date -d "2015-1-4 15:41:05" +"%s"
#1420386065

Which you can then numerically compare against date +"%s" to check how soon it's coming. You can use cut or awk to extract your date fields.
NEWDATE=`echo $MYDATE | awk -F- '{print $3"-"$2"-"$1}'`
date -d "$NEWDATE $TIME" +"%s"

Stringing together might end up something like this:
STRING="Password expires             1-4-2015 15:41:05"

DATE=`echo $STRING | awk '{print $3}'`
TIME=`echo $STRING | awk '{print $4}'`

NEWDATE=`echo $DATE | awk -F- '{print $3"-"$2"-"$1}'`

EPOCH_EXP=`date -d "$NEWDATE $TIME" +"%s"`
EPOCH_TIME=`date +"%s"`

EXPIRES_S=$(($EPOCH_TIME - $EPOCH_EXP))
echo "Password expires in $EXPIRES_S seconds"

(I'm sure this could be done better, but this is mostly aimed as an illustration)

A: Without regex for the two samples:
$ echo "Password expires             1-4-2015 15:41:05"  | tr -s " " | cut -d' ' -f3
1-4-2015

$ echo "Password expires             20-4-2015 15:41:05"  | tr -s " " | cut -d' ' -f3
20-4-2015


text:
Q: R: How do I create k subsets subject to a condition applied to k columns? Example:
fdistr[ which(fdistm[,4]<=5),]
        zip      long      lat 1   2     3  4   5
32403 72756 -94.07141 36.34224 3 122 19401 51 704
32404 72757 -94.11565 36.37198 2 141 19546 45 740
32405 72758 -94.14622 36.30662 1 149 19578 30 724

fdistr[ which(fdistm[,5]<=5),]
        zip      long      lat   1 2     3   4   5
32312 72601 -93.09345 36.23698 181 1 16548 328 354

fdistr[ which(fdistm[,6]<=5),]
        zip      long      lat     1     2 3     4     5
13271 30529 -83.46842 34.21042 16867 15514 1 17241 12593

How do I loop over k columns to create k subsets?
Thanks!

A: Use lapply as follows:
k <- 5
subsets <- lapply(3 + 1:k, function(x, i, m) x[x[, i] <= m, ], x = fdistm, m = 5)

It will return a list of k subsets.

A: Use apply and assuming your dataframe is fdistm(Not tested)
fdistm[apply(fdistm[, -1], MARGIN = 1, function(x) all(x <=5)), ]
Note:applies to all except the first


text:
Q: Installation fails with "error: No such disk"  I installed ubuntu 11.04 with the CD. My computer already has windows 7, and I want to install Ubuntu, the installation process takes place normally, I used to be ubuntu, but when my windows 7 to escape and use it on ubuntu then an error occurs is:
error: No such device 00000000 0000000000000 -------- ----- --------- 000,000 000,000
error: No such disk
error: you need to load the kernel first

Press any key to continue ....
I had to reinstall ubuntu again, but the results remain like that.
Who can show me how to fix on it?

A: Please reinstall grub booting from the live install cd ... select try Ubuntu without install and follow this page:

*

*https://help.ubuntu.com/community/Grub2?action=show&redirect=GRUB2#Reinstalling_GRUB2

*https://help.ubuntu.com/community/RecoveringUbuntuAfterInstallingWindows


text:
Q: ejabberd - max number of participants in MUCs vs. PubSub I am building a mobile chat platform with support for both private and public rooms. For private rooms, I have already successfully implemented the MUC functionality using ejabberd on the server and XMPPFramework for my iOS client. However, for public rooms, I would like to evaluate whether PubSub makes more sense or not?
To define the use case in detail, all public room members should be able to post / send messages, as well as have offline messages delivered to them when they login. The rooms should be persistent as well. Also, I would expect the max number of participants in a public room to be many thousands (eventual state if I were to plan for high scalability right now). This would differ from the private rooms where I intend to set the max number of participants' limit to be 200 or so. For the private rooms, I am exchanging presence, but for the public ones, presence exchange is not mandatory if that overloads the server.
Can folks advise please what should be the approach recommended here? Also, are there any pointers as to how I can go about capacity-testing these approaches...
Many thanks!

A: For benchmarking ejabberd and comparing performance, you can use Tsung: https://github.com/processone/tsung
It should help measuring yourself the difference of behaviour for your user case.


text:
Q: sql server full index search partial word and full word I have a table like this:

Key     SearchTexts
KZ78    Aberdeen American Equity A Acc, KZ78, GB00B0XWN143, ,

My sql query is:

select * from dbunits.dbo.fxUnitSearch where CONTAINS(searchText, '"Aberdeen American Equity A Acc*"')

However, it returns no data. If I do this:

select * from dbunits.dbo.fxUnitSearch where CONTAINS(searchText, '"Aberdeen American Equity A Acc"')

Then it returns. I thought 'xxx*' will partial search, which should work for exact match as well?
What am I doing wrong here?
Many Thanks

A: You can use FREETEXT instead of CONTAINS
select * from dbunits.dbo.fxUnitSearch where FREETEXT (searchText, '"Aberdeen American Equity A Acc*"')


text:
Q: JMSMessage content looped in Glassfish 4 I've recently written some test code for the Java EE JMS API and have stumbled upon something that seems to be a bug to me.
The test is fairly simple: A CDI bean is connected to a JSF page and sends a predefinied JMSMessage to a Queue. There is an message-driven bean listening for messages on that Queue and it answers incoming messages in it's onMessage method.
Through another call from the JSF page the CDI bean tries to receive new messages synchronously and displays them to the frontend.
Here is the source:
MDB
@JMSDestinationDefinition(
    name = "java:app/jms/SomeQueue",
    interfaceName = "javax.jms.Queue",
    destinationName = "SomeQueue")
@MessageDriven(activationConfig = {
    @ActivationConfigProperty(propertyName = "destinationLookup", propertyValue = "java:app/jms/SomeQueue"),
    @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")
})
public class MyBean implements MessageListener {

@Inject
private JMSContext context;
@Resource
private MessageDrivenContext mdc;

@Resource(lookup = "java:app/jms/SomeQueue")
private Queue queue;

@Override
public void onMessage(Message message) {
    TextMessage tMessage = (TextMessage) message;
    try {
        context.createProducer().send(queue, tMessage.getText()+", Answer");
    } catch (JMSException e) {
        mdc.setRollbackOnly();
        e.printStackTrace();
    }
}
}

The CDI bean
@RequestScoped
@Named("jmssender")
public class JMSSender {

@Inject
private JMSContext context;

@Resource(lookup = "java:app/jms/SomeQueue")
private Queue queue;

@Inject
private UserTransaction utx;

private String answer;

private TextMessage message;

private int num;

public void sendMessage() {
    try {
        utx.begin();
        message = context.createTextMessage();
        String message = "This is message Nr. " + num;
        try {
            this.message.setText(message);
        } catch (JMSException e) {
            e.printStackTrace();
            message = "An error occurred";
        }
        context.createProducer().send(queue, message);
        utx.commit();
    } catch (HeuristicRollbackException e) {
        e.printStackTrace();
    } catch (RollbackException e) {
        e.printStackTrace();
    } catch (SystemException e) {
        e.printStackTrace();
    } catch (HeuristicMixedException e) {
        e.printStackTrace();
    } catch (NotSupportedException e) {
        e.printStackTrace();
    }
}

public void receive() {
    try {
        utx.begin();
        answer = context.createConsumer(queue).receiveBody(String.class);
        utx.commit();
    } catch (NotSupportedException |
            SystemException |
            HeuristicRollbackException |
            RollbackException |
            HeuristicMixedException e) {
        answer = "Error receiving message";
        e.printStackTrace();
    }
}
       ------getters and setters-----

The num property is used to identify each message send. I've used the message property to check whether my JMSMessages were send correctly.
The Problem
After having send a message, I try to receive the answer and see it in my frontend, it looks like this:
This is message Nr. 8 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0 Version 2.0
Apparently it loops the part of the string I enclosed to the original message, though when changing where exaclty in the code the additional String ", Answer" is added to the message, the message itself "this is message NR. X" is looped. Also it seems that how long the looped snippet is depends on how big the interval between pressing the "send" and the "receive" button is.
If I only specify a string like "Hello" or just send the message back with tMessage.getText(), it works fine and doesn't loop any particular part
Am I making the mistake or is it actually a bug?

UPDATE
-Deleted all uses of the UserTransaction interface (thought it might be needed to acknowledge messages in a CDI Bean) - didn't help


text:
Q: How to display outcoming and incoming SOAP message for ZSI.ServiceProxy in Python (version 2.1)? Couple months ago I have asked the same question but in the context of older version of ZSI (How to display outcoming and incoming SOAP message for ZSI.ServiceProxy in Python?). Now, in the new version of ZSI 2.1 there is no tacefile parameter). I tried to find a documentation for the new version but I faild. Does anyone know how to display the SOAP messages generated and received by ZSI 2.1? Thank you in advance :-)

A: For debugging I have found less interfering solution using wireshark to trace the TCP packages. It looks like that:

A: I had this same problem. My workaround was to modify the dispatch.py file that comes with ZSI.
I created a logging function (logmessage) for my app that would store SOAP messages into a database and then added that function where necessary. I do not recall the ZSI version I was using however. You should be able to find these functions pretty easily in the code though. I ave approximate L numbers since i made other edits
in Dispatch.py file in your site-packages directory
L156 - logs SOAP responses
def _Dispatch(tons-of-args, **kw):
     #several lines of code edited here#
     #several lines of code edited here#
     #several lines of code edited here#

     sw = SoapWriter(nsdict=nsdict)
     sw.serialize(result, tc)
     logmessage( str(sw), 1, kw['request'].get_remote_host() ) #LOGGING HERE

L168 - logs SOAP errors
def _ModPythonSendFault(f, **kw):
    logmessage( str(f.AsSOAP()), 1, kw['request'].get_remote_host() )  #LOGGING ADDED HERE
    _ModPythonSendXML(f.AsSOAP(), 500, **kw)

L277 - logs requests
def AsHandler(request=None, modules=None, **kw):
    '''Dispatch from within ModPython.'''
    a = request.read(-1)
    logmessage( a, 0, request.get_remote_host() ) #LOGGING ADDED HERE
    ps = ParsedSoap(a)
    kw['request'] = request
    _Dispatch(ps, modules, _ModPythonSendXML, _ModPythonSendFault, **kw)


text:
Q: Prevent Full Postback from __doPostBack I have a content page that contains the following...

*

*UpdatePanel1 - containing Error Display Divs
    contains update triggers for both buttons

*UpdatePanel2 - containing process 1 with an asp:button

*updatePanel3 - containing process 2 with an asp:button

*JavaScript that presents the user with a Popup confirm Jquery Messagebox based on the process they are executing.

UpdatePanel 2 or 3 becomes visible based on the users selection from the menu options.

When I click a button the messagebox pops and the page is processed correctly using __doPostback from the messagebox response and the page does a full postback.
I would rather the page do a partial postback and the content it had and display the Error Display Divs if there was an error. Any assistance would be appreciated.
nothing special about the button
<asp:Button ID="ResetSomething" runat="server" Text="ResetSomething" Width="275px" />

here is the content page script block
    <script type="text/javascript" language="javascript">
<!--
    function pageLoad() {
        setform();

    };

    function setform() {
        var reset1_button = $('input[id*=ResetSomething]');
        var reset2_button = $('input[id*=ResetSomethingElse]');

        reset1_button.click(function() {
            var element = $(this);
            $.prompt('Message1', { show: 'slideDown', buttons: { Ok: true, Cancel: false },
                submit: function(v, m, f) { submit_reset_callback(v, m, element); }
            });
            return (false);
        });

        var submit_reset_callback = function(result, messages, element) {
            if (result) { __doPostBack("ResetSomething");}
            return (false);
        };

        reset2_button.click(function() {
            var element = $(this);
            $.prompt('Message2', { show: 'slideDown', buttons: { Ok: true, Cancel: false },
                submit: function(v, m, f) { submit_update_callback(v, m, element); }
            });
            return (false);
        });

        var submit_update_callback = function(result, messages, element) {
            if (result) { __doPostBack("ResetSomethingElse"); }
            return (false);
        };
    };
-->
</script>

this is the code behind for the OnInit:
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        this.PreLoad += (sender, args) =>
                            {

                                this.ClientScript.GetPostBackEventReference(this, "arg");

                                if (!IsPostBack) { return; }

                                string __targetaction = this.Request["__EVENTTARGET"];
                                string __args = this.Request["__EVENTARGUMENT"];

                                if (string.IsNullOrEmpty(__args)) return;

                                if (__targetaction == "ResetSomething")
                                {
                                    ResetSomething();
                                }
                                if (__targetaction == "ResetSomethingElse")
                                {
                                    ResetSomethingElse();
                                }
                                this.upnlNotifications.Update();
                            };
    }

A: Define the function below and replace your __doPostBack calls with doPostBackAsync(controlId, null).
function doPostBackAsync(eventName, eventArgs) {
    var prm = Sys.WebForms.PageRequestManager.getInstance();

    if (!Array.contains(prm._asyncPostBackControlIDs, eventName)) {
        prm._asyncPostBackControlIDs.push(eventName);
    }

    if (!Array.contains(prm._asyncPostBackControlClientIDs, eventName)) {
        prm._asyncPostBackControlClientIDs.push(eventName);
    }

    __doPostBack(eventName, eventArgs);
}

A: The controlId should be the id of the button to generate async postback else full postback occurs in the page.
For that you can use the clientidmode as static e.g
<asp:Button ID="button1" runat="server"  ClientIDMode="Static"/>

   //then you can use below code
   _doPostBack('button1', '');//clientidmode forces buttonid = id given by us

Check its correct?
If so then you can get the async postback instead of a  full page postback.
This helped me.
Thanks @Tim for his comment.


text:
Q: Docker compose and Fargate rollbacks I'm trying to improve my service by setting a rollback strategy in case my changes crash the container and keep the tasks exiting.
Context:
I have a simple service that I update changing the tag.
services
  web:
    image: AWS-Account-Id.dkr.ecr.us-east-1.amazonaws.com/my-service:1
    environment:
      - ENV=dev
    ports: ["80:80"]

I make some change in the docker image, build, tag, and push it to ECR. Then update the tag to 2 (for example) and run docker compose up.
Let's say that I introduce an error and the container starts but then stops (due to the error) it will keep constantly trying to start and stop the container with error: Essential container in task exited
Is there a way in docker-compose to set a condition where if it tries to start the container web 2 times and the tasks fail to reach and maintain the status of running, rollback changes or do a cloudformation cancel update operation?
There is a load balancer that listens to port 80 and I also added a health check to the
    healthcheck:
      test: ["CMD", "curl", "-f", "/status"]
      interval: 1m
      timeout: 10s
      retries: 2
      start_period: 40s

But I cannot make it work. Tasks keep exiting and the cloudformation deployment keeps going.

A: This is no direct way for this, but you can consider this approach:

*

*Create a Wait Condition and a WaitCondition Handle Resource.

*Calibrate how long it usually takes for the Task / Container to start and set the timeout accordingly.

*Configure the application to post a success signal to the endpoint URL on successful setup.

*Ensure that the Service and the waitcondition handle start updating / creating in parallel.

If the time exceeds the timeout period, the wait condition handle will rollback.
Thing to consider: On every operation the waitcondition handle and the waitcondition resources will need to be re-created. Easy way to do that is to modify the logical id of the resources. There can be a parameters / template hash calculator that will add the hash as suffix to the wait condition resources. Thus, if there's a change in the parameters / template, the wait condition resources will be recreated automatically.


text:
Q: html5lib/lxml examples for BeautifulSoup users? I'm trying to wean myself from BeautifulSoup, which I love but seems to be (aggressively) unsupported.  I'm trying to work with html5lib and lxml, but I can't seem to figure out how to use the "find" and "findall" operators.
By looking at the docs for html5lib, I came up with this for a test program:
import cStringIO

f = cStringIO.StringIO()
f.write("""

          one
          1

          two
          2</td

  """)
f.seek(0)

import html5lib
from html5lib import treebuilders
from lxml import etree  # why?

parser = html5lib.HTMLParser(tree=treebuilders.getTreeBuilder("lxml"))
etree_document = parser.parse(f)

root = etree_document.getroot()

root.find(".//tr")

But this returns None.  I noticed that if I do a etree.tostring(root) I get all my data back, but all my tags are prefaced by html (e.g. ).  But root.find(".//html:tr") throws a KeyError.
Can someone put me back on the right track?

A: You can turn off namespaces with this command:
etree_document = html5lib.parse(t, treebuilder="lxml", namespaceHTMLElements=False)

A: In general, use lxml.html for HTML. Then you don't need to worry about generating your own parser & worrying about namespaces.
>>> import lxml.html as l
>>> doc = """
...
...

...

...        one
...        1
...

...

...        two
...        2</td
...

...

...    """
>>> doc = l.document_fromstring(doc)
>>> doc.finall('.//tr')
[<Element tr at ...>, <Element tr at ...>] #doctest: +ELLIPSIS

FYI, lxml.html also allows you to use CSS selectors, which I find is an easier syntax.
>>> doc.cssselect('tr')
[<Element tr at ...>, <Element tr at ...>] #doctest: +ELLIPSIS

A: It appears that using the "lxml" html5lib TreeBuilder causes html5lib to build the tree in the XHTML namespace -- which makes sense, as lxml is an XML library, and XHTML is how one represents HTML as XML.  You can use lxml's qname syntax with the find() method to do something like:
root.find('.//{http://www.w3.org/1999/xhtml}tr')

Or you can use lxml's full XPath functions to do something like:
root.xpath('.//html:tr', namespaces={'html': 'http://www.w3.org/1999/xhtml'})

The lxml documentation has more information on how it uses XML namespaces.

A: I realize that this is an old question, but I came here in a quest for information I didn't find in any other one place.  I was trying to scrape something with BeautifulSoup but it was choking on some chunky html.  The default html parser is apparently less loose than some others that are available.  One often preferred parser is lxml, which I believe produces the same parsing as expected for browsers.  BeautifulSoup allows you to specify lxml as the source parser, but using it requires a little bit of work.
First, you need html5lib AND you must also install lxml.  While html5lib is prepared to use lxml (and some other libraries), the two do not come packaged together.  [for Windows users, even though I don't like fussing with Win dependencies to the extent that I usually get libraries by making a copy in the same directory as my project, I strongly recommend using pip for this; pretty painless; I think you need administrator access.]
Then you need to write something like this:
import urllib2
from bs4 import BeautifulSoup
import html5lib
from html5lib import sanitizer
from html5lib import treebuilders
from lxml import etree

url = 'http://...'

content = urllib2.urlopen(url)
parser = html5lib.HTMLParser(tokenizer=sanitizer.HTMLSanitizer,
                             tree=treebuilders.getTreeBuilder("lxml"),
                             namespaceHTMLElements=False)
htmlData = parser.parse(content)
htmlStr = etree.tostring(htmlData)

soup = BeautifulSoup(htmlStr, "lxml")

Then enjoy your beautiful soup!
Note the namespaceHTMLElements=false option on the parser.  This is important because lxml is intended for XML as opposed to just HTML.  Because of that, it will label all the tags it provides as belonging to the HTML namespace.  The tags will look like (for example)

and BeautifulSoup will not work well.

A: Try:
root.find('.//{http://www.w3.org/1999/xhtml}tr')

You have to specify the namespace rather than the namespace prefix (html:tr).  For more information, see the lxml docs, particularly the section:

*

*Tutorial - Namespaces


text:
Q: Just-in-time invocation of Facebook login window from UIWebView I have an app that presents a UIWebView pointing to my own server.  I have a Facebook Like button on some pages inside the UIWebView.
I have it working now, but the login screen is way too big for the phone screen.  I would like to present a nicer login dialog such as the one in the Facebook iPhone API, and then continue back to the web view.
The Facebook iPhone SDK has support for a login button and iPhone-friendly login screen, but it assumes that a user will click a login button before doing anything Facebook related.  I would like the Like button to just appear, and to bring up the iPhone login screen only when necessary.
I have monitored HTTP requests from my web view, and it looks like I could intercept the login request there, and present the login dialog.  However, it seems that this would be fragile, because if Facebook changes those calls then my app will no longer work.  Is there a more elegant way to do this?


text:
Q: Why doesn't work I18n.locale and redirect_back? I'm trying to make an eternal fixed locale in the site URL. That is, the locale parameter should always be in the site URL.
In ApplicationController I added this code:
def default_url_options
  { locale: I18n.locale }
end

In theory, I should now always have the locale parameter in all URLs. Right? But why is this not happening? The first thing I need is to have the locale parameter absolutely always in the URL inside the specific namespace.
Next I have this controller:
class Public::BaseController < ApplicationController
  layout 'public'

  around_action :prepare_locale

  private

  def prepare_locale(&action)
    received_locale = params[:locale].presence || I18n.default_locale

    if I18n.available_locales.include?(received_locale.to_sym)
      I18n.with_locale(received_locale, &action)
    else
      I18n.with_locale(I18n.default_locale, &action)
    end
  end
end

And this code, which is responsible for changing the locale parameter:
class Service::LanguagesController < Service::BaseController
  def change
    received_locale = params[:new_locale].presence || I18n.default_locale

    redirect_back(
      fallback_location: root_path,
      allow_other_host: false,
      params: {  # this is to make sure
        locale: received_locale
      },
      locale: received_locale
    )
  end
end

As a result, params[:new_locale] has a new locale. But redirect_back doesn't change anything. Why?
This code works:
redirect_to root_path(locale: received_locale)

But this option doesn't fit, as it is inconvenient.
In total, I don't understand how I can do what I intended.

A: I looked at rails internals and saw that redirect_back is a redirect_to passing referrer as first argument. See here
But in that case the params passed to redirect_to are ignored because it's just an String.
I suggest you to use redirect_to instead and pass locale explicit.


text:
Q: After Upgrading from 2.3.5 to 2.4.3-p1 composer.json file is slightly changed, baler is not working Upgrading from 2.3.5-p1 to 2.4.3-p1 install issue
Yes, I agree with @WebHostigAce
It requires to upgrade to 2.4.2 as it is mentioned here https://devdocs.magento.com/guides/v2.4/comp-mgr/cli/cli-upgrade.html

The following instructions show you how to upgrade Magento using Composer. Magento 2.4.2 introduced support for Composer 2. If you are attempting to upgrade from Magento <2.4.1, you must first upgrade to a version of Magento that is compatible with Composer 2 (for example, 2.4.2) using Composer 1 before upgrading to Composer 2 for Magento >2.4.2 upgrades. In addition, you must be running a supported version of PHP.

I tried below steps to upgrade from 2.3.5 to 2.4.3-p1
I first switched to PHP 7.3 sudo update-alternatives --set php /usr/bin/php7.3 and used composer 1 with PHP 7.3 and then below commands
composer require magento/composer-root-update-plugin ~2.0 --no-update
composer update

composer require-commerce magento/product-community-edition 2.4.2 --no-update --force-root-updates
composer update

Then I switched PHP version to 7.4 sudo update-alternatives --set php /usr/bin/php7.4; and downloaded composer.phar file of version 2 https://getcomposer.org/download/ as I didn't want to update composer 1 in my system
Now, below commands with PHP 7.4 and composer 2
php -dmemory_limit=5G composer.phar require magento/composer-root-update-plugin ~2.0 --no-update
php -dmemory_limit=5G composer.phar update

php -dmemory_limit=5G composer.phar require-commerce magento/product-community-edition 2.4.3-p1 --no-update --force-root-updates
php -dmemory_limit=5G composer.phar update

It upgrades to 2.4.3-p1 successfully, but I am having doubt when I compared upgraded composer.json file with the file provided by magento as zip archive
I downloaded the zip archive of 2.4.3-p1 from https://magento.com/tech-resources/download
Noticed few things:
composer.json file is not same: the one which I upgraded and the one which they provide in zip format
composer.json file Provided by Magento in zip format
"require": {
    "magento/product-community-edition": "2.4.3-p1",
    "magento/composer-root-update-plugin": "~1.1",
    "magento/composer-dependency-version-audit-plugin": "~0.1"
}

"require-dev": {
    "allure-framework/allure-phpunit": "~1.4",
    "dealerdirect/phpcodesniffer-composer-installer": "^0.7.0",
    "friendsofphp/php-cs-fixer": "~2.18.1",
    "lusitanian/oauth": "~0.8.10",
    "magento/magento-coding-standard": "*",
    "magento/magento2-functional-testing-framework": "^3.0",
    "pdepend/pdepend": "~2.7.1",
    "phpcompatibility/php-compatibility": "^9.3",
    "phpmd/phpmd": "^2.8.0",
    "phpstan/phpstan": "^0.12.77",
    "phpunit/phpunit": "^9",
    "sebastian/phpcpd": "^6.0.3",
    "squizlabs/php_codesniffer": "~3.5.4",
    "symfony/finder": "^5.2"
},
"conflict": {
    "gene/bluefoot": "*"
}

composer.json file after upgrading:
"require": {
    "magento/product-community-edition": "2.4.3-p1",
    "magento/composer-dependency-version-audit-plugin": "~0.1",
    "composer/composer": "@alpha",
    "magento/composer-root-update-plugin": "~2.0"
}

"require-dev": {
    "allure-framework/allure-phpunit": "~1.4",
    "dealerdirect/phpcodesniffer-composer-installer": "^0.7.0",
    "friendsofphp/php-cs-fixer": "~2.18.1",
    "lusitanian/oauth": "~0.8.10",
    "magento/magento-coding-standard": "~3.0.0",
    "magento/magento2-functional-testing-framework": "^3.0",
    "pdepend/pdepend": "~2.7.1",
    "phpmd/phpmd": "^2.8.0",
    "phpstan/phpstan": "^0.12.77",
    "phpunit/phpunit": "^9",
    "sebastian/phpcpd": "^6.0.3",
    "squizlabs/php_codesniffer": "~3.5.4",
    "symfony/finder": "^5.2"
},

*

*Missing phpcompatibility/php-compatibility, gene/bluefoot in upgraded file

*Version of magento/composer-root-update-plugin is 1.1 in original file

*I can not run upgraded version of Magento 2.4.3-p1 using PHP 7.3

*The same version of Magento 2.4.3-p1 which I downloaded works with PHP 7.3 where it should not work with PHP 7.3 as per system requirements. It can create confusion, as in devdocs it is mentioned only PHP 7.4 with 2.4.3 in system requirements

*Will the steps I followed create any future issues when upgrading to 2.4.4 for example?

*Why downloaded version of Magento works with PHP 7.3?

*I use baler baler-devtools in version 2.3.5 previously but now Baler doesn't work with upgraded version of magento in 2.4.3-p1 as upgraded magento only works in PHP 7.4 and baler requires < 7.4 (not sure exactly but when I tried to install baler, it shows PHP compatibility error regarding 7.4) And I think Baler will work in downloaded zip format of Magento 2.4.3-p1 as that version of magento works in PHP 7.3 as well (I need to test baler installation with it)

Can anyone clear above doubts I raised and share opinion on the steps I followed please?


text:
Q: mysql master-slave-master-slave replication I have two phisical servers.
I copied some databases from server1 to server2 using command:
server1$ mysqldump -u root -q -p --delete-master-logs --flush-logs --extended-insert --master-data=1 --single-transaction --databases db1 db2 db3 db4>to_server2.sql

and then imported them as usual
server2$ mysql -u root -p <to_server2.sql

my.cnf on server2 includes:
server-id               = 2
log_bin
binlog_format           = mixed
replicate_do_db         = db1,db2
transaction-isolation=READ-COMMITTED

my.cnf on server1 includes:
server-id               = 1
log_bin
binlog_format           = mixed
replicate_do_db         = db3,db4
transaction-isolation=READ-COMMITTED

then I issue change master on both servers to point to each other;
SHOW SLAVE STATUS already includes Read_Master_Log_Pos on server2 but anyway no data changes have been made during this operations.
Then started slave on both servers. SHOW SLAVE STATUS looks good on both server1 and server2.
The problem:
Whenever data is changed on any server1 or server2 data appears in server's binlog and in other server's mysqld-relay-bin log fies BUT not appears in slave database.
Read_Master_Log_Pos changes but not data in slave database.
Any idea why?

A: The answer is: it is really because of coma in replicate_do_db betwin database names. The solution was to make replicate_do_db statement in my.cnf for each database to be replicated