text:
Q: Validate date between multiple dates in jQuery.validate and datepicker I'm using jQuery.datepicker and jQuery.validate.
In my form I have multiple date ranges:
2010-02-10 - 2010-02-18
2010-03-01 - 2010-03-12
2010-03-15 - 2010-03-19

etc.
Now I need to validate the datepicker field to check if the date set in the datepicker is between any of those date ranges. For instance, 2010-01-01 would be invalid, as would 2010-02-19.
I've seen many answers but they don't really relate to multiple ranges, as far as I can see.
Does anyone know a solution or at least a pointer to get me in the right direction.
I'm thinking of maybe looping each date range in a .each() and running a validation in there. But there is probably a better way.

A: Your question is something I've been trying to figure out for a while too.  This is what I have so far.
I use this for validating a single date range. It takes input fields as params rather than dates:
jQuery.validator.addMethod("rangeDate", function(value, element, params) {
    try {
        var beforedate=$.datepicker.parseDate($(params[0]).datepicker('option','dateFormat'),$(params[0]).val());
        var afterdate=$.datepicker.parseDate($(params[1]).datepicker('option','dateFormat'),$(params[1]).val());
        var qdate=$.datepicker.parseDate($(element).datepicker('option','dateFormat'),value);
        return this.optional(element) || (qdate >= beforedate && qdate<=afterdate);
    } catch(err){
        return false;
    }
}, function(params){
    return "Date must occur between " + $(params[0]).val() + ' and ' + $(params[1]).val();
}
);

and the rule looks like this:
rules:{
  between_date: { dateCan: true,
         rangeDate:  {
            depends: function(element) { //check that params exist
                return $("input[name='before_date']").valid()
                       && $("input[name='after_date']").valid();
            },
            param:  ["input[name='before_date']", "input[name='after_date']"]
         }
  }
}

After experimenting a bit, I've seen that it's possible to have more than one rangeDate rule for a field. However, the last call appears to overwrite the results of all the previous rangeDate calls for that field. So I think what might work is to add another custom rule that accepts an array of pairs of fields which can be fed to rangeDate. The problem with this approach is that the the depends clause for the rangeDate rule becomes unwieldy as you get more date pairs. This is especially so if you only require at least one pair to be present rather than all pairs.
Of course, if the date ranges aren't dynamic, the problem is easier because no depends clause is necessary. Just rewrite rangeDate to accept dates rather than fields and write a wrapper rule to accept an array of pairs of dates.
If you've found a solution to the problem, I'd love to see it.  Hopefully it will be more elegant than mine.


text:
Q: Having trouble understanding how to test some things Not sure what I need to do here. I have private methods that make database calls to retrive values that are looked at and then return values to a caller. I've looked at Moq but I'm not so sure that's what I need.
An example of one of my methods is this:
    private bool ClientIdMatchesUserId(int userId, Guid clientId, out string message)
    {
        bool idsMatch;

        const string sql = "sql goes here";

        int result = (int)SqlHelper.ExecuteScalar(Connection, CommandType.Text, sql);
        if (result != 1)
        {
            idsMatch = false;
            message = "ClientId does not match.";
        }
        else
        {
            idsMatch = true;
            message = "ClientId matches.";
        }

        return idsMatch;
    }

The thing making this confusing for me is 1) I have a private method and 2) It has out parameters.
Is Moq what I need? Do I need to create a test database with known values?
I should add that I'm new to testing and could use all the advice I can get ;)

A: In order to unit test the class, you'll need to separate the database access from the business logic. At that point you can mock the dependencies and test the class through its public interface.
Here's one example of how that might be done.
public class User
{
    // properties map to columns
    // Consider using NHibernate, Entity Framework, etc.
}

// ALL database access goes through interface implementations.
public interface IUserRepository
{
    // One of several options - TryParse pattern
    bool TryGetById(int userId, out User user);
}

public class SomeBusinessLogic
{
    public SomeBusinessLogic(IUserRepository userRepository)
    {
        _userRepository = userRepository;
    }

    public string ValidateClient(int userId)
    {
        // Probably more logic here.
        string message;
        bool result = ClientIdMatchesUserId(userId, out message);

        if (result)
        {
            return string.Empty;
        }

        return message;
    }

    private bool ClientIdMatchesUserId(int userId, out string message)
    {
        User user;
        bool found = _userRepository.TryGetById(userId, out user);

        message =
            found
            ? "ClientId matches."
            : "ClientId does not match.";

        return found;
    }

    private readonly IUserRepository _userRepository;
}

Your tests would then look something like this:
[Test]
public void ValidateClient_WhenValid_ReturnsEmptyString()
{
    // Arrange
    const int UserId = 1234;
    var mockRepo = new Mock<IUserRepository>();
    var user = new User();
    mockRepo.Setup(x => x.TryGetById(UserId, out user)).Returns(true);
    var sut = new SomeBusinessLogic(mockRepo.Object);

    // Act
    string result = sut.ValidateClient(UserId);

    // Assert
    Assert.That(result, Is.EqualTo(string.Empty));
}

[Test]
public void ValidateClient_WhenInvalid_ReturnsMessage()
{
    // Arrange
    var mockRepo = new Mock<IUserRepository>();
    var sut = new SomeBusinessLogic(mockRepo.Object);

    // Act
    string result = sut.ValidateClient(1234);

    // Assert
    Assert.That(result, Is.EqualTo("ClientId does not match."));
}

I'd recommend reading The Art of Unit Testing with Examples in .NET to get a better understanding of this. It's a complex topic.

A: I'd check out Moles.  http://research.microsoft.com/en-us/projects/pex/downloads.aspx
Moq is used to Mock interface dependencies or dependencies that are public classes with default constructor and virtual methods.  Moles lets you mock basically anything and is specifically designed for mocking external dependencies like databases, files, etc.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python Pandas Error trying to drop the first column I'm trying to drop the first column of a data frame, when I run
X.columns.tolist()

I get this:
['colors', 'num_critic_for_reviews', 'duration', 'director_facebook_likes', 'actor_3_facebook_likes']

so, I want to drop 'colors', but when I run
X = X.drop('colors', index=1) I get:

KeyError: "['colors'] not found in axis"

I tried with the column index and also with the column label, but keep getting the same error. The funny thing is if I tried to access and use the column colors it works, but again if I try to drop it, get the Not found in the axis error.

A: To drop the column you could use
X.drop(columns=['colors'])

If you want to explicitly remove the first one, just replace it inside the array:
X.drop(columns=[X.columns[0]])

A: Use the axis=1 keyword instead of index=1
Check out the documentation

A: Finally, it works if previously I reset the index of X and then use X.drop.


text:
Q: Why I am I getting Error: incompatible types (from S4 to double) in subassignment type fix in my R code? I am trying to do a hypothesis test via bootstrapping for a mixed effects logistic regression. I'm using a data frame with columns for participant, tone, word, correctness, and background, and changing a column called boot_correct with the bootstrapped data of each iteration. In the for loop at the end, I keep getting the error:
  incompatible types (from S4 to double) in subassignment type fix"

The glmr() function works fine with the original data frame before I add the boot_correct column.
Any idea where this error is coming from?
set.seed(1865)
n <- length(ptc_data$correct)
n
B <- 100
variable <- ptc_data$correct

BootstrapSamples <- matrix(sample(c(ptc_data$correct), size=n*B, replace=TRUE),
                                   nrow=n, ncol=B)

Boot.test.stat.word <- rep(0,B)
boot_data <- data
boot_data$boot_correct <- BootstrapSamples[1:304,1]

for (i in 1:B){
  boot_data$boot_correct <- BootstrapSamples[1:304,i]
  boot_data$boot_correct[boot_data$boot_correct  == 1]  <-  0
  boot_data$boot_correct[boot_data$boot_correct  == 2]  <-  1
  Boot.test.stat.word[i] <- glmer(boot_correct ~ background + word +
                                (1 | participant), data = boot_data, family = binomial, control = glmerControl(optimizer = "bobyqa"),
                              nAGQ = 10)
}


text:
Q: can I listen to any cross-domain iframe events? Are there any events that I can listen to on an iframe on a different domain?  For example,  have this page on domain1:
<html>
<body>
  <iframe src="domain2.com"></iframe>
</body>
</html>

What events can I listen to with regard to the contentWindow of the iframe?
Thanks!

A: There are a couple of ways to do this. In newer browsers, you can use window.postMessage to communicate across domains between windows (works for iframes too):
https://developer.mozilla.org/en/DOM/window.postMessage
For older browsers, you can change the URL fragment for the location of the iframe to pass messages back and forth. You can use a separate iframe just to pass messages to avoid polling:
http://ajaxian.com/archives/cross-domain-iframe-communication-without-location-polling

A: I dont see how this should be a problem (having an iframe from another domain in IE) perhaps your issue is that you are opening files straight from your computer... Once these are files are hosted you should not see this problem occur.


text:
Q: How do I get Django rest framework to respect the "required=false" designation in my serializer? I'm using djangorestframework==3.12.2 .  I have this Serializer.  Some fields, like "desc_english" I don't want to be required ...
class ValidateNewCoopSerializer(serializers.Serializer):
    coop_name=serializers.CharField()
    street=serializers.CharField()
    address_public=serializers.CharField()
    city=serializers.CharField()
    state=serializers.CharField()
    zip=serializers.CharField()
    county=serializers.CharField()
    country=serializers.CharField()
    websites=serializers.CharField()
    contact_name=serializers.CharField()
    contact_name_public=serializers.CharField()
    contact_email=serializers.CharField()
    contact_email_public=serializers.CharField()
    contact_phone=serializers.CharField()
    contact_phone_public=serializers.CharField()
    scope=serializers.CharField()
    tags=serializers.CharField(required=False)
    desc_english=serializers.CharField(required=False)
    desc_other=serializers.CharField(required=False)
    req_reason=serializers.CharField()

which is used in my views.py file like so
@api_view(('POST',))
def save_to_sheet_from_form(request):
    """
    This is supposed to write to a Google sheet given a form coming from
    the client.
    """
    valid_ser = ValidateNewCoopSerializer(data=request.data)
    if valid_ser.is_valid():
        post_data = valid_ser.validated_data
        ...
        return Response(post_data, status=status.HTTP_201_CREATED)
    else:
        return Response(valid_ser.errors, status=status.HTTP_400_BAD_REQUEST)

I notice, though, that when I submit requests, the fields are mark as not required are coming back with errors ...
curl 'http://localhost:8000/save_to_sheet_from_form/' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:88.0) Gecko/20100101 Firefox/88.0' -H 'Accept: */*' -H 'Accept-Language: en-US,en;q=0.5' --compressed -H 'Referer: http://localhost:3001/' -H 'Content-Type: application/json' -H 'Origin: http://localhost:3001' -H 'Connection: keep-alive' -H 'Pragma: no-cache' -H 'Cache-Control: no-cache' --data-raw '{"coop_name":"","street":"","address_public":"no","city":"","state":"IL","zip":"","county":"","country":"US","websites":"","contact_name":"","contact_name_public":"no","contact_email":"","contact_email_public":"no","contact_phone":"","contact_phone_public":"no","scope":"local","tags":"","desc_english":"","desc_other":"","req_reason":"add"}'

results in
{"coop_name":["This field may not be blank."],"street":["This field may not be blank."],"city":["This field may not be blank."],"zip":["This field may not be blank."],"county":["This field may not be blank."],"websites":["This field may not be blank."],"contact_name":["This field may not be blank."],"contact_email":["This field may not be blank."],"contact_phone":["This field may not be blank."],"tags":["This field may not be blank."],"desc_english":["This field may not be blank."],"desc_other":["This field may not be blank."]}

How do I configure my serializer so that these fields are actually not required?

A: You have set required=False on the serializer fields. This means that if you don't supply the key for them in the request it will work, but if you do supply the key then they would be validated. Looking at your request you pass "desc_english":"", i.e. you do supply the key with an empty string, hence that error is correct. You can set allow_blank=True [DRF docs] on the field if you want to allow empty strings:
desc_english=serializers.CharField(required=False, allow_blank=True)

If you may want to pass null values (None in python) to the field you can also set allow_null [DRF docs] to True:
desc_english=serializers.CharField(required=False, allow_blank=True, allow_null=True)


text:
Q: Determine HTTPS status and set Header in a single line I wish to set a response header in .htaccess but only when the site is loaded over HTTPS:
Header set MyHeader "%D %t" "%{HTTPS:on}"
# Error: Unknown parameter: %{HTTPS:on}

Header set MyHeader "%D %t" "expr=%{HTTPS:on}"
# Error: syntax error, unexpected $end: Function 'HTTPS' does not exist

Header set MyHeader "%D %t" "expr=%{HTTPS}==on"
# Error: syntax error, unexpected $end, expecting '('

HTTPS is listed as a variable here
PS: I'm having a really hard time understanding how Apache expressions work so if anyone has come across a simple introduction with good examples, please share.

A: Use an <If> clause, it should work in .htaccess:
<If "%{HTTPS} == 'on'">
    Header set MyHeader "%D %t"
</If>

Reference:
http://httpd.apache.org/docs/2.4/mod/core.html#if


text:
Q: HtmlUnit not finding form and not handling postback I'm trying to use HtmlUnit (2.35) in Java on this url https://www.pharmacy.ohio.gov/Licensing/RosterRequests.aspx to select options from the radio buttons and then click the download button and receive the file.
I'm fairly certain I am setting the radio buttons correctly but I'm not sure if I am pressing the button or, if I am, how to detect the start of the download which is accomplished by a postback (I think).
I've tried waiting for Javascript, turning off Javascript, looping for 60 seconds while checking the contentType and creating a listener.
I also thought to load the form from the page as perhaps the HtmlUnit click() action was just firing off the Javascript and not doing the post action but HtmlUnit can't seem to find a form on the page even though there is one there.
public static void main( String[] args ) throws IOException, InterruptedException {
        WebClient webClient;
        webClient = new WebClient( BrowserVersion.FIREFOX_60 );

        webClient.getOptions().setJavaScriptEnabled(false);
        webClient.getOptions().setUseInsecureSSL(true);
        webClient.getOptions().setThrowExceptionOnScriptError(false);
        webClient.getOptions().setSSLClientProtocols(new String[]{"TLSv1.2","TLSv1.1","TLSv1"});
        webClient.setAjaxController(new NicelyResynchronizingAjaxController());

        HtmlPage MainPage = (HtmlPage) webClient.getPage("https://www.pharmacy.ohio.gov/Licensing/RosterRequests.aspx");
        HtmlElement body = MainPage.getBody();
        if (dbg) System.out.println("MainPage = " + MainPage);

\\ All of the below are empty:

        System.out.println( "MainPageForm = " + MainPage.getFirstByXPath( "//*[@id=\"form1\"]"));
        System.out.println( "Form List = " + MainPage.getElementsByIdAndOrName( "form#form1"));
        System.out.println( "Form List = " + MainPage.getForms());
        System.out.println( "Form? = " + MainPage.querySelector("#form1"));
        System.out.println( "Form? = " + MainPage.getFirstByXPath( "//form[@action=\"RosterRequests.aspx\"]" ));
        System.out.println( "Form? = " + MainPage.getElementById( "#form1"));
        System.out.println( "MainPageButton = " + MainPage.getFirstByXPath( "//*[@id=\"phBody_rblLicenseType_5\"]") );

\\ Code to click buttons:

HtmlRadioButtonInput rad_status = (HtmlRadioButtonInput)MainPage.getHtmlElementById("phBody_rblLicenseStatus_1");
rad_status.setChecked( true );
HtmlRadioButtonInput rad_tddd = MainPage.getHtmlElementById( "phBody_rblLicenseType_1");
rad_tddd.setChecked( true );
HtmlInput btn_download = (HtmlInput)MainPage.getHtmlElementById( "phBody_btnSubmit" );
WebResponse response = btn_download.click().getWebResponse();

\\ ContentType never changes

        int tries = 30;

        while ( tries > 0 ) {
            //System.out.println( response.getWebRequest().toString());
            System.out.println( response.getContentType());
            synchronized (response) { response.wait(1000);}

        tries--;
        }

        webClient.close();

    }

Nothing is ever downloaded and the ContentType never changes. In a browser, the dev tools show the aspx page is reloaded with a different ContentType which triggers the download dialog.

A: This works with HtmlUnit 2.36.0 (or at least with the latest 2.35.0-SNAPSHOT.
final String url = "https://www.pharmacy.ohio.gov/Licensing/RosterRequests.aspx";

try (final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_60)) {
    HtmlPage page = webClient.getPage(url);

    HtmlRadioButtonInput rad_status = (HtmlRadioButtonInput)page.getHtmlElementById("phBody_rblLicenseStatus_1");
    rad_status.setChecked( true );
    HtmlRadioButtonInput rad_tddd = page.getHtmlElementById( "phBody_rblLicenseType_1");
    rad_tddd.setChecked( true );

    HtmlInput btn_download = (HtmlInput)page.getHtmlElementById( "phBody_btnSubmit" );
    WebResponse response = btn_download.click().getWebResponse();

    try (InputStream in = response.getContentAsStream();
         FileOutputStream out = new FileOutputStream("c:/tmp/test.xlsx")) {
        byte[] buffer = new byte[8 * 1024];
        int bytesRead;
        while ((bytesRead = in.read(buffer)) != -1) {
            out.write(buffer, 0, bytesRead);
        }
    }
}


text:
Q: sapui5: sap.m.SelectList with context menu I'm using sap.m.SelectList in the XML-View to give a possibility to choose key/value pairs and need to extend it with context menu which is available in sap.m.List. I have problems with it, because ContextMenu is defined in sap.m.ListBase, sap.m.List inherits it, but sap.m.SelectList does not.
What is the simplest or recommended approach? My restriction is, I've to use XML-View (but can extend it in JS).
Regards,
Annie


text:
Q: Executing a stored procedure over ODBC I have an application that allows the user to enter an SQL string with a placeholder for certain values my application produces. The application will the replace the placeholders with values and execute the SQL string through various database backends.
For the ODBC backend, I call SQLExecDirect() on the SQL strin which works nicely on regular queries, but fails for stored procedures with parameters.
Is there a simple way to extend this mechanism to support stored procedures ? A certain way how the SQL must be written ?
The only thing I can think of right now is to start parsing the SQL string and call SQLBindParameter() n times if it conatains a "call". But parsing SQL is tricky.
Any ideas ?
Working SQL example: SELECT columnA from foo where columnB = '%placeholder'
Non-working SQL: CALL StoredFoo('%placeholder')

A: How to call stored procedures (ODBC):

To run a procedure as an RPC

*

*Construct a SQL statement that uses the ODBC CALL escape sequence.
  The statement uses parameter markers
  for each input, input/output, and
  output parameter, and for the
  procedure return value (if any):
{? = CALL procname (?,?)}

*Call SQLBindParameter for each input, input/output, and output
  parameter, and for the procedure
  return value (if any).

*Execute the statement with SQLExecDirect.

Otherwise you need to execute the procedure as an ordinary batch (not an RPC call), ie. you need to run the batch:
EXEC procname @param1, @param2, @param3...;


text:
Q: Null response for spring-amqp Request/Reply Messaging I'm following the instructions for the Stock Trading sample, which outlines how to use request/reply messaging in spring-amqp: http://static.springsource.org/spring-amqp/docs/1.2.x/reference/html/sample-apps.html#d4e742
I've tweaked the sample instructions to create a client which should wait for the reply by using convertSendAndReceive instead of convertAndSend: https://gist.github.com/pulkitsinghal/5774487
Now even though the reply is put on the responseQueue and I've updated the timeout rabbitTemplate.setReplyTimeout(60000); to be longer than the 5 second default ... in my client I receive null back as the reply.
Does anyone know what's going on?

Update#1
I was advised to add a <reply-listener/> to the <rabbit:template/> but I'm not sure how to do that programatically:
@Bean
public RabbitTemplate rabbitTemplate() {
    RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory());
    rabbitTemplate.setMessageConverter(jsonMessageConverter());
    rabbitTemplate.setReplyQueue(responseQueue());
    rabbitTemplate.setReplyTimeout(60000);
    // following is private
    //rabbitTemplate.addListener
    return rabbitTemplate;
}

A: I assume the fact you are not getting an error on the convertsendAndReceive means that you have configured the RabbitTemplate with a fixed reply queue; if you do that, you need a listener container to receive the messages with the template as the 'listener'.
The easiest way to configure this is with xml
<rabbit:template ... reply-queue="foo">
    <reply-listener/>
</rabbit:template>

I suggest you get it working first without a fixed reply queue - let the template create its own reply queue.
You should also remove the MessagePostProcessor in the convertSendAndReceive because the template will take care of its own reply queue and correlation configuration. This is not allowed when there's not a fixed reply queue.
When you switch to using a fixed reply-queue I suggest you use 1.2.0.M1 (or snapshot) because the template used a non-standard correlation technique.
Update: To use @Bean configuration instead of XML simply create a SimpleMessageListenerContainer bean and make its listener the RabbitTemplate. Just be sure to use the same queue in both places (the parser takes care of that when using the namespace).


text:
Q: Login using the Lynx browser How do you login to the sites if you are using a text-browser such as Lynx? I get the error

Because JavaScript is disabled, you can only log in by entering your openID URL manually

When JavaScript is enabled, I click on the Google icon and it logs me in. But I do not know what an openID URL is. Could you please tell me what this means and how to log in?

A: An OpenID identifier is a URL that represents an identity on the Internet. OpenID was invented by LiveJournal as a way for users to prove their control over a particular blog. It has since come to be used by Google, AOL, Yahoo!, Stack Exchange, and other web sites as a decentralized authentication platform to let someone with an account on one site (the "provider") log in to other sites ("relying parties"). Sometimes the identifier is specific to a user, such as a user's profile page or blog, and sometimes it's a generic identifier that the provider redirects to a user's identifier. For more information about OpenID, check FAQ for Stack Exchange sites.
As Bart pointed out in a comment to the question, Google is an OpenID provider. This generic identifier will trigger the Google Account login flow on Stack Exchange or any other relying party:
https://www.google.com/accounts/o8/id

In any case, there are good reasons to access Stack Exchange sites with Lynx or another user agent that does not require a running GUI, such as doing things that the Stack Exchange sites support but which currently do not have a corresponding API function. Posting questions and answers used to be one of them back in the first quarter of 2011 when the API was read-only. As of the fourth quarter of 2014, one thing that the API still does not support is suggesting edits.


text:
Q: C++ - Gettings size from vector in FOR loop I have a loop that asks for user input, and adds it too a vector, then when if they type "EXIT" it will stop and display the list. What I am trying to do now is determine the number of elements with size()
This is what I have:
#include <iostream>
#include <string>
#include <unistd.h>
#include <iterator>
#include <vector>
using namespace std;

int main()
{
    write(1,"\E[H\E[2J",7);
    vector<string> list;
    cout << "Enter UIDs: \n\n";
    for(string uid ; cin >> uid && uid != "EXIT"; list.push_back(uid))
        cout << " \n";
    copy(list.begin(), list.end(), ostream_iterator<string>(cout, "\n\n"));
    cout << "Vector size: " << uid.size() << endl;
    return 0;
}

When attempting to compile that I get the error:
g++ sof.cpp -o sof

sof.cpp: In function 'int main()':
  sof.cpp:16:32: error: name lookup of 'uid' changed for ISO 'for' scoping
  sof.cpp:13:16: error:   cannot use obsolete binding at 'uid' because it has a destructor

A: You're querying uid.size() instead of list.size()


text:
Q: How would you formulate this graph problem? I am having a really hard time explaining a problem to some fellow coders and specially to computer scientists, could you please help me formalizing the following problem:
Lets assume that we have a non weighted, undirected Graph with Vertices A,B,C,D,E
A --- B
|   / | \
|  /  |  C
| /   | /
D --- E

Which means its adjacency matrix like this one:
  A  B  C  D  E
A -  1  0  1  0
B 1  -  1  1  1
C 0  1  -  0  1
D 1  1  0  -  1
E 0  1  1  1  -

Assuming all edges are undirected, we have the following edges:
(a,b) (a,d) (b,d) (b,e) (b,c) (e,d) (e,c)

What I want is that through AI, I can take that graph and generate two groups of edges of roughly the same size. (In this particular case, since we have 7 edges, we would get a group of 3 edges and another one of 4 edges.
Group 1: (a,b) (a,d) (b,d) (e,d)
A --- B
|   /
|  /
| /
D --- E

Group 2: (b,e) (b,c) (e,c)
B
| \
|  C
| /
E

Notice that all edges in each group are connected by at least one node, that is a requirement.
Another valid solution could be, for example:
Group 1: (d,a) (a,b) (b,c) (c,e)
A --- B
|       \
|       C
|       /
D     E
Group 2: (d,b) (b,e) (e,d)
      B
    / |
   /  |
  /   |
D --- E

And so on, as you see there are many valid solutions but I will accept the first one found.
I'm sure that theres a formal way to state this problem, and I will very much appreciate your help in doing that.
(I apologize in advance, I'm self taught so I have some major knowledge gaps)

A: You want to find a cut that divides the connected graph into two connected graphs with (nearly) the same number of edges.
Look for algorithms and results on graph cuts. Related is the minimal cut problem.

A: After a lot of help here, Stack Overflow and Computer Science Exchange and a lot of reading, I finally understood that what I'm actually trying to do is:
Given a Graph G, obtain two disjointed trails of approximately the same size so that every edge is visited by one of those trails.
Thanks to everyone!


text:
Q: Reading claims from another application using jquery I have a static method in static class in MVC application that returns User Claims, when I access directly the url of this application,I am getting those values but when I access application url from another application using Javascript,it is not returning anything.I am not getting any error.It is returning empty result.I am also not getting CORS issue.i suspect it is something related to authentication & passing user credentials,both site is under same ADFS configuration
public static UserDetails GetUserDetails()
        {
            var userdetails = new UserDetails();

            var objClaims = ((ClaimsIdentity)Thread.CurrentPrincipal.Identity).Claims;

            foreach(var c in objClaims)
            {

                else if (c.Type == ConstantsHelper.emailAddress)
                {
                    userdetails.Email = c.Value;
                }
                else if (c.Type == ConstantsHelper.userName)
                {
                    userdetails.UserName = c.Value;
                }
                else if (c.Type == ConstantsHelper.shortName)
                {
                    userdetails.ShortName = c.Value;
                }
            }
            return userdetails;
        }

Code to access it from another application.
function GetLoggedInUsermethod() {
        var url = GetLoggedInUser;
        $.ajax({
            type: "GET",
            url: url,
            crossDomain: true,
            success: function (json) {

            },
            error: function (e) {

            }

        });
    }

A: If the calling application is hosted in different domain (different ports will qualify for different domains), then you may need to add the Access-Control-Allow-Origin header to the response with the value set to the calling application's domain for the call to succeed.
More details here.


text:
Q: Overloading a method just to report a nicer error in C++. Is there a better way? I ran into this issue quite a few times. Let's say I have a method:
template <typename T>
bool Foo(T* param)
{
  //...
}

If I pass a non-pointer, Visual Studio gives me the error: could not deduce template argument for 'const T *' but since the code is heavily templated, there is a ton of garbage attached to it (I say garbage because it is not related to the error... i.e. namespaces and template types etc.). Yes, I can tell what is wrong by looking at the message, but it takes that much longer and I think people can relate how that wastes time in the long run.
So I thought I will provide a overload and give a static assertion:
template <typename T>
bool Foo(T param)
{
  STATIC_ASSERT_FORCE(Function_does_not_take_a_non_pointer_argument);
}

This works nicely and I get a nice, clear error message. This function is placed just before the definition of the 'correct' function and it becomes immediately clear what I (or whoever is using my code) did wrong and what to do to correct it (that is, call the correct overload).
But that obviously pollutes the method list. Is there any other way to output a better error message?

A: Instead of only accepting pointers, you could modify your function to accept any type:
template <typename T>
bool Foo(T param)
{
  //...
}

In the body, just assume that param is a pointer. If it isn't, the compiler will complain about operator-> or operator* being undefined for type T, and hopefully it'll also tell you what T's concrete type is.
I'm not sure if this really helps the clarity of your error messages. But it comes with a bonus: your function can suddenly be applied to other pointer-like types as well!

Edit: there might be some SFINAE static-assertion trickery to actually verify that the operators you want are implemented for T and give a clear error if they're not. Maybe someone else will chime in with a solution for that.


text:
Q: when i import arcpy in python idle i get an error when i type import arcpy i get this error
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    from arcpy import da
  File "C:\Program Files (x86)\ArcGIS\Desktop10.1\arcpy\arcpy\__init__.py", line 21, in <module>
    from arcpy.geoprocessing import gp
  File "C:\Program Files (x86)\ArcGIS\Desktop10.1\arcpy\arcpy\geoprocessing\__init__.py", line 14, in <module>
    from _base import *
  File "C:\Program Files (x86)\ArcGIS\Desktop10.1\arcpy\arcpy\geoprocessing\_base.py", line 578, in <module>
    env = GPEnvironments(gp)
  File "C:\Program Files (x86)\ArcGIS\Desktop10.1\arcpy\arcpy\geoprocessing\_base.py", line 575, in GPEnvironments
    return GPEnvironment(geoprocessor)
  File "C:\Program Files (x86)\ArcGIS\Desktop10.1\arcpy\arcpy\geoprocessing\_base.py", line 531, in __init__
    self._refresh()
  File "C:\Program Files (x86)\ArcGIS\Desktop10.1\arcpy\arcpy\geoprocessing\_base.py", line 533, in _refresh
    envset = (set(env for env in self._gp.listEnvironments()))
RuntimeError: NotInitialized

what should i do ?
i need to use arcpy in eclipse also and i can't!

A: This sometimes happens when there are not enough licenses to go around, or if your organization has disabled automated library downloading as part of their software suite.
Check what version of Python you're using in Eclipse, I know friends who've had to download condas in order to import arcpy without fail.


text:
Q: Playing sounds from an array of strings in Objective-C I'm trying to create an array of strings that can be used to initiate the urls for sounds to play. This works if I explicitly type in the file name as shown below, but how can I insert one of the array strings at a specific object index into the 'fileURLWithPath?
soundsArray = [[NSMutableArray alloc] initWithObjects:@"test", @"test2",@"test3", nil];

NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/test.mp3", [[NSBundle mainBundle] resourcePath]]];

Thanks for any insight!

A: You have an array, so you should probably loop over the array, pulling out the next string on each iteration. You already know how to use stringWithFormat: to create a new string composed of other strings, as you're doing it with the resource path. Just do it again with the name of the file. (hint: [NSString stringWithFormat:@"%@/%@.mp3", [[NSBundle mainBundle] resourcePath], nextFileName].)


text:
Q: How do I set conditions from multiple tables in my LINQ query? In the query below, I want to return people that meet multiple conditions. Some of the conditions apply to fields in the table containing the people to be returned. The other condition is applied to a different table (EmailAddresses) linked to the main table (People) via PersonId.
var t = People.Where(x =>
            x.Type == 102 &&
            x.FirstName == "Bob" &&
            x.LastName == "Williams" &&
                 x.EmailAddresses.Where (ea=> ea.EmailAddress
                                                 == "bob.williams@acme.org")
            )
            .Select(x => x.PersonId)

How do I do this?

A: Do understand this right, at least one of them should have that adress? If yes, use the Any method:
var t = People.Where(x =>
            x.Type == 102 &&
            x.FirstName == "Bob" &&
            x.LastName == "Williams" &&
                 x.EmailAddresses.Any(ea=> ea.EmailAddress
                                                 == "bob.williams@acme.org")
            )
            .Select(x => x.PersonId)

Any returns true if at least one of the elements of the IQueryable<T> fulfills the predicate.

A: I think you could do it with a join, something like this...
var t = from p in People
        join e in EmailAddress on p.PersonId equals e.PersonId into pe
        from a in pe.DefaultIfEmpty
        where p.Type == 102 &&
           p.FirstName == "Bob" &&
           p.LastName == "Williams" &&
           a.EmailAddress == "bob.williams@acme.org"
        select p.PersonId


text:
Q: Regex for string like 7h AM/ 17h PM I want to validator string like input form like    7h AM/ 17h PM ,I try to many pattern but not corect

A: I assume the string input is based on 12h format.

let regex = /^(([0]*[1-9]{1}|[1]+[0]|[1]*[1-2]{1})[h]\s(AM|PM))$/;

function testPattern(value) {
  console.log(value + ' ==> ' + regex.test(value));
}

testPattern('7h AM');
testPattern('07h AM');
testPattern('17h AM');
testPattern('25h AM');
testPattern('12h AM');
testPattern('12h PM');

I hope this solution works for you.


text:
Q: AWS CQL editor showing incorrect data when queried I have inserted the order with all the necessary fields into Cassandra using python (cassandra-driver==3.21.0).
Table schema looks like this:
Columns datatype
-----------------------
name         text
phone        text
date         text
inserteddate text

Name = 'Bob'
Phone = '48562'
Date = '2023-02-24'
Inserteddate = '2023-02-15 05:30:00.0',
orderId = 'test'
Data = [Name,Phone,Date,Inserteddate,orderId]
query = "INSERT INTO  dev.orders (name,phone,date,inserteddate,orderid) VALUES (%s,%s,%s,%s,%s)"
session.execute(query,Data)

After completing the insertion I am checking aws cql editor to check if it was inserted properly with below command.
SELECT * FROM dev.orders where date ='2023-02-24' ALLOW FILTERING;

It is fetching the record with which I have inserted but the date column is showing as null.
Expected result in console:
Results:
name   phone   date         inserteddate             orderid
bob    48562   2023-02-24   2023-02-15 05:30:00.0    test

What I got from aws cql editor
Results:
name   phone   date         inserteddate             orderid
bob    48562   null         2023-02-15 05:30:00.0    test

But when checked using putty to fetch the record, I could see the original value for the date field. What could be the reason for it showing incorrect data when using cql editor? How to overcome this?


text:
Q: Cheap 1MHz oscilloscope I'm learning electronics (and basic electricity) and I wondered if a 1MHz oscilloscope like the DSO Nano is enough for (very) basic electrical and/or electronic circuits. I'm almost broke and I need a cheap portable oscilloscope to try various circuits (wherever I am, hence the required portable property) with resistors, capacitors, transistors, and microcontrollers (if I study hard enough). I don't thing I need a more powerful oscilloscope because I'm learning and I'm just following the exercises in various books right now. This would be my first oscilloscope and I would eventually buy a 20MHz portable oscilloscope later.
Thank you!

A: I have put together an oscilloscope comparison table where you can filter and sort devices to find the one best for your needs:  Digital oscilloscopes for hobbyists

A: A good rule of thumb is you need a minimum of 4x the speed of the signal you are watching, and higher (up to 10x) is better. So if you want to watch a signal that's running at 1MHz, you need a 4-10MHz scope.

A: Depends on what you're designing.  If you only need 1 MHz bandwidth it should work fine.  You can get a cheap analog scope on eBay though, and it will have a higher bandwidth.  Just bulkier and harder to carry around.  The shipping on my old 20 MHz analog scope was more than the scope itself.  :)
I also have a Bitscope BS50U, which I carry around with me, but I almost never use it and don't recommend it.  The software is the weakest link.  It's hard to navigate, unintuitive, hard to get a good trigger, etc.  A software-based oscilloscope should be more powerful than a hardware scope, not less.

A: No, I wouldn't advise it.
Main reasons:

*

*While it has a 1 MHz bandwidth, its sample rate is only 1 MS/s. Practically this means you can only measure up to 100 KHz square waves. It is only suitable for audio signals in my opinion.

*You spend $90 on the DSO Nano but you could spend $200 on a second hand oscilloscope with at least 60 MHz. I spend £150 (around $200 at the time) on my HP 54501A which was a pretty good deal. It has everything a hobbyist should need: 100 MHz bandwidth (will measure up to 300 MHz clock signals), excellent trigger facilities, including video, pattern and state (very useful for what I'm doing), it's digitising and it has HP-IB. If you can find a similar deal, go for it.

*Trigger: it only mentions auto and single. Out of luck for complex triggers like I mentioned. You don't think you need them, but you often will.

*Input protection: or lack of it. Most good scopes can take at least 100V on the inputs. This one only goes to 80Vp-p (so 40V amplitude maximum.) Don't worry, I've done this one or two times to be thankful that my scope has 250V maximum inputs.

*It's not earthed. Don't even touch equipment plugged into the mains or you won't be protected like a normal scope is.

A: The best scope for beginners is hands down Rigol 50Mhz scope, I used it for professional and hobby projects. You can buy below 350$, it has math function, two channels, can be hacked to support 100Mhz, digital filter, a decent size memory, USB capture etc. etc. Cannot say enough about it, it is really good. It has an antialiasing problem at 1msec but you can work around it.

A: The DSO Nano is a poor choice for a hobbyist's oscilloscope.
Capabilities
It's really only good for audio bandwidth signals - anything above 100kHz is going to be visible, but unmeasurable.  By most standards you want the sampling rate to be 10x the bandwidth of the signal in order to get close to measuring significant parameters of the signal (peaks, rise time, frequency, duty cycle, etc).  While you can see signals with as poor as a 5x sampling rate, you can't reliably measure such signals and expect to get good results.
Competition, New Oscilloscopes
Keep in mind that a very low end entry oscilloscope NEW is only about $400 - so if you can spend more then a 2 channel 50MHz Rigol would be a fine choice as a beginner:
http://www.dealextreme.com/details.dx/sku.30573
Note that the 50MHz rating is the fastest signal it can measure.  It measures at 1 billion samples per second for one channel, or 500 million samples per second for both channels, which means you'll be able to see signals much faster than the rated 50MHz.
Compared to the single channel, 1 million samples per second Nano this is worlds better.
Competition, Used Oscilloscopes
But even if that's too much, you can get a $50-$100 used oscilloscope on ebay that is significantly better than the nano.  For the same price you can easily find a 2 channel 20MHz scope (which can be used to measure the clock of a 40MHz micro, just not precisely) and there are many scopes in the 50-60MHz range for under $100.
What is it good for?
The nano is NOT an oscilloscope replacement.  The major reasons to get one are

*

*You want one (it's open source, and could be fun to hack)

*You need a portable device that can function as a simple oscilloscope for audio bandwidth applications

*You are only interested in high-level overview of the signals you measure, and won't really be doing significant work with it (ie, beginning hobbyist) so don't want something bulky that you might only use a few times a year.

That being said, despite its severe limitations, I can see it as an additional tool for the workbench after you've invested in a good oscilloscope and other gear.  Keep in mind that many tasks, such as SPI, can be slowed down to within the range of the oscilloscope, and even though it's only good up to 100kHz analog signals, one could reasonably measure up to 500kHz digital signals (if they wrote software for the Nano that synchronized the ADC clock to the input signal).
Conclusion
The price to performance of the device is just so low that I can't see it being worth the cost except to tinkerers that might want to hack it.  Your money is better spent on a used oscilloscope.

A: Your typical hobbyist microcontroller can range anywhere from KHz up to 40MHz or more. So if you are wanting to have a microcontroller running at lets say 40MHz and be able to see what a PWM looks like, you may be out of luck.
However, if you are just wanting to see a general idea of what is happening on your analog circuits or simple digital circuits then the DSO Nano will work just fine for you.
Another option to consider is an OScope on a computer. You can use the sound card on your computer to interface with a program (Here is an example). The down side to this is that computer sound cards tend to be very noisy and many times only have a sample rate of about 96KHz or lower in some cases.

A: IMHO for its low price, the DSO Nano is actually a good first-time scope. As others have mentioned, you will have problems with showing anything faster than 100-250KHz coherently, but this is pretty high for quite a lot of uses. Yes, you won't be able to see system clocks or PWMs with it, but in my experience a scope is more useful for analog signals, and as long as they don't rise and fall too quickly, you'll be fine with the DSO Nano.
Once you get more money and become more serious about the projects, you should invest in a 2nd hand scope, something real with at least 100MHz bandwidth.

A: The first great step in oscilloscopes functionality was triggered sweep.  Ignoring ones which are not triggerable, A lot of old scopes SUITABLE FOR BEGINNERS can be set to trigger at a voltage level within the range displayed, selectable for rising or falling slope.  More complicated triggering than line-frequency-synchronized and adjustable per the signal as described above is suitable for paying attention to once you figure out how to use these.  I used to sell used test equipment, and the combination of adjustable trigger and delayed sweep in the old tektronix 530 and 540 series oscilloscopes is the reason Jim Williams kept on restoring them until he died, FYI he is a recently deceased master analog circuitry designer.  I can't speak well enough about the simplicity of these scopes as a first scope for a beginner.  And they keep the room warm while you use them.

A: Just to throw this out there, if you're trying to learn from a book and tight on money, another option is to use a circuit simulator.  I've had sucess with SPICE (free versions), but I'm sure there are other options.
I'm not trying to say that hands on practice with circuits is not needed.  At some point you do have to try things with actual hardware.  But if you're just trying to learn and money is a constraint, circuit simulators can be very helpful.


text:
Q: REST API for setting multi select field type in Azure Devops I have installed following plugin to support multi-value type field in Azure DevOps
https://marketplace.visualstudio.com/items?itemName=ms-devlabs.vsts-extensions-multivalue-control#:~:text=Azure%20Devops%20Services,used%20to%20back%20the%20extension.
I am able to set the option for this field by separating using "semicolon". like "A; B; C"
I can also see this field in my work item and able to set the values.
I need help with how can I update this multivalue type field through REST API.
I want to change the value of the work item which has this multi-value type field through REST API. I have already tried updating them using the following approaches

*

*"A; B"

*"A, B"

*"[A, B]"

*"A;B"

*"A,B"

It sets up the value which I am sending using option 4, but it adds those as an extra option though the option already exists with that value. I can see extra spaces on the option which I am sending through REST AP{I, but I have checked my JSON there is no extra space (using option 4).

A: I add a new work item field Multivalue control Test and configure Multivalue control
We could get the work item details via the REST API Work Items - Get Work Item:
GET https://dev.azure.com/{organization}/{project}/_apis/wit/workitems/{id}?api-version=6.0

And we could check the value of field Custom.MultivaluecontrolTest
Result:

Then we could update the value via the REST API Work Items - Update to update the value.
PATCH https://dev.azure.com/{organization}/{project}/_apis/wit/workitems/{id}?api-version=6.0

Sample request body:
[
  {
    "op": "test",
    "path": "/rev",
    "value": 7
  },
  {
    "op": "add",
    "path": "/fields/Custom.MultivaluecontrolTest",
    "value": "A;B;C"
  }
]

Result:

The filed value format is A;B;C, same as UI


text:
Q: How to use MemoryRouter and BrowserRouter in the same time at react-router-dom? I would like to have url changings for certain routes and for other routes have a memory based routing.
Is there a smooth way to combine MemoryRouter with BrowserRouter?


text:
Q: Как заставить двигаться спрайт Как вырезать конкретную картинку из спарйта и заставить двигаться динозаврика? В данный момент dino.png это обычный png файл(не спрайт), имеется спрайт со всеми анимациями, но как вырезать конкретный участок из него для начала игры(когда он просто стоит) и для анимации ходьбы? Как работать со спрайтами в js, или я не так начал изначально разработку полагаясь на анимации из css?
script.js
const dino = document.getElementById("dino");
const cactus = document.getElementById("cactus");

document.addEventListener("keydown", function(event) {
    jump();
});

function jump() {
    if (dino.classList != "jump") {
        dino.classList.add("jump");
    }
    setTimeout(function () {
        dino.classList.remove("jump");
    }, 500)
}

let isAlive = setInterval(function () {
  let dinoTop = parseInt(window.getComputedStyle(dino).getPropertyValue("top"));
  let cactusLeft = parseInt(window.getComputedStyle(cactus).getPropertyValue("left"));

    if (cactusLeft < 50 && cactusLeft > 0 && dinoTop >= 140) {
        alert("Game Over");
        }
}, 10)

css
#dino {
    width: 50px;
    height: 50px;
    background-image: url("image/dino.png");
    background-size: 50px 50px;
    position: relative;
    top: 150px;
}
#cactus {
    width: 45px;
    height: 45px;
    background-image: url("image/cactus.png");
    background-size: 40px 50px;
    position: relative;
    top: 105px;
    left: 575px;
    animation: cactusMove 1.5s infinite linear;
}

@keyframes cactusMove {
    0% {
        left: 575px;
    }
    100% {
        left: -25px;
    }
}

.jump {
    animation: jumpDino 0.5s linear;
}

@keyframes jumpDino {
    0% {
        top: 150px;
    }
    5%{
        top: 143px;
    }
    10%{
        top: 136px;


text:
Q: How do I track a branch of another repository on the same machine? I have two private repositories on one machine.  Let's call them repo-A and repo-B, which are the directories ~/repo-A and ~/repo-B, respectively.  repo-A has two relevant branches: master and live.  I'd like to set up repo-B to track repo-A's live branch, so that git pull will pull any updates from repo-A's live branch into repo-B's master branch.  Right now, I have the following in repo-B's .git/config:
[remote "origin"]
        url = /home/stutzbach/repo-A/
        fetch = +refs/heads/live:refs/remotes/origin/live
[branch "master"]
        remote = origin
        merge = refs/heads/master

However, when I run git pull, it seems to pull from repo-A's master branch.  Obviously, I don't have it set up right.  What's the right way?

A: You've pasted exactly the bit of the config that's causing that:
[branch "master"]
        remote = origin
        merge = refs/heads/master

That's telling it to merge (which is part of pull) from the master branch of origin. Change it to refs/heads/live and you'll have what you want.


text:
Q: How many key-sets should be in use to encrypt/decrypt data in several instances of the same web application? We host several instances of our web application on four different servers.  Two of the servers host the IIS/web portion of the application, the other two host the MSSQL databases.  Each of our clients has an individual virtual directory in IIS and an individual database.  Each database shares exactly the same schema.
Assume we're using asymmetric encryption.  Should there be one master key-set used by all instances for encryption/decryption?  One key-set per server?  One per instance?  One per field encrypted?
It seems that the most fine-grained approach would be the best security-wise (one per record?) but that seems a bit difficult to manage.  What is the best practice here, or am I off the mark entirely?
I'll need to figure out how to store these keys as well, but I figure that's a separate question and may depend on the answer here.

A: It depends on your particular balance of security versus usability. Storing and managing keys is at least as big a problem as deciding where and when to use keys. Managing keys can be difficult and cumbersome depending on how keys need to be protected and how many people will have access to them. And it will depend on how many records you are managing, now and in the future. Having too many keys is generally a bad idea. Try to match the number of keys to some partitioning of protection. If each instance of the server is serving the same clients, then use the same key for all of them. Unless you server different clients from different servers there's no reason to segregate them, and it will inhibit distributed processing and fail over. Again with the data, try to match usage partitioning. If a user has access to read all data in a table, secure the table instead of the records with a key. Also, consult your legal team. The US has regulations regarding the protection of customer data, especially medical and financial.


text:
Q: Swift UIView pointing by rotating at another UIView
I have a small app that I am working on and it contains this piece of UI.
The user can touch and move the speaker, which is now located in the center. Based on that some other values in the rest of the UI changes, it ranges from -10 to 10 and has 2 angels, a X and a Y.
Based on where the speaker is I need to point the soundwaves to the speakers (in all the corners). How do I do that? Can I manipulate X and Y so I can do it with:
extension UIView{
    func rotate(angle: CGFloat) {
        let radians = angle / 180.0 * CGFloat(Double.pi)
        self.transform = CGAffineTransform.init(rotationAngle: radians)
    }
}

or is there any other simpler method to di this? I got the touchesMoved already fixed and it doesn't move out of the image so that is working ok. The X and Y coordinates are also done.
I now only need to move these soundwaves which are simple UIImages. It would be ideal if they would stretch and shrink too based on how far the speaker is.


text:
Q: Determine the nature of a critical point (Lagrange multipliers)
Let $F \colon \mathbb R^2 \to \mathbb R$ be the function
  $$
F(x,y):=xye^x + ye^y - e^x+1
$$
  and denote with $C$ the set of zeroes of $F$, i.e. $C:=\{(x,y) \in \mathbb R^2 : F(x,y)=0\}$. Let also $f \colon \mathbb R^2 \to \mathbb R$ be a function which is $C^2$ in a neighbourhood of $(0,0)$ and such that
  $$
\nabla f(0,0) = (-2,2), \qquad \qquad H_f(0,0) = \begin{pmatrix} 2 & 1 \\ 1 & 0  \end{pmatrix}.
$$
  Question: is $(0,0)$ a minimum for $f$ on $C$?

Well, I show you what I have done so far. First of all, some routine calculations yield
$$
\nabla F(0,0) = (-1,1) \qquad \qquad H_F(0,0) = \begin{pmatrix} -1 & 1 \\ 1 & 2  \end{pmatrix}
$$
Indeed, the fact that
$$
\nabla f(0,0) = 2\nabla F(0,0)
$$
does agree with the theory of Lagrange multipliers: the gradients are parellel, so I think that $(0,0)$ is an extremum for $f$ on $C$. The problem is how to classify it without any information on $f$: we have only its hessian matrix, which is - I suppose - the key to solve this. Both $H_f(0,0)$ and $H_F(0,0)$ are indefinite.
How can we establish the nature of the critical point $(0,0)$?
Thanks in advance for your help.

A: Suppose you have a parametrization $x=X(t), y=Y(t)$ of the curve $C$ near $(0,0)$, with $X(0)=0$ and $Y(0)=0$.  Thus if $V$ and $A$ are the corresponding velocity and acceleration vectors,
$$\dfrac{d}{dt} f(X(t),Y(t))  = X' f_x(X,Y) + Y' f_y(X,Y) = (\nabla f)\cdot V$$
$$\dfrac{d^2}{dt^2} f(X(t),Y(t)) = X'' f_x(X,Y) + Y'' f_y(X,Y) + (X')^2 f_{xx}(X,Y) + 2 X' Y' f_{xy}(X,Y) + (Y')^2 f_{yy}(X,Y) = (\nabla f)\cdot A + V^T H(f) V $$
Similarly for $f$ replaced by $F$, but in this case $\dfrac{d}{dt} F(X(t),Y(t)) =
\dfrac{d^2}{dt^2} F(X(t),Y(t)) = 0$.
Now since $\nabla f(0,0) = 2 \nabla F(0,0)$, $(\nabla F(0,0)) \cdot V(0) = 0$ implies
$\dfrac{d}{dt} f(X(t),Y(t))|_{t=0} = (\nabla f(0,0)) \cdot V(0) = 0$.  And
$$\dfrac{d^2}{dt^2} f(X(t),Y(t))|_{t=0} = \dfrac{d^2}{dt^2} f(X(t),Y(t))|_{t=0} - 2 \dfrac{d^2}{dt^2} F(X(t),Y(t))|_{t=0} = V(0)^T (H(f) - 2 H(F)) V(0)$$
Now $V(0)$ is orthogonal to $\nabla F(0,0) = (-1,1)$, so it is a multiple of $(1,1)$, and
$$ (1,1) \left( \pmatrix{2 & 1\cr 1 & 0\cr} - 2 \pmatrix{-1 & 1\cr 1 & 2\cr}\right) \pmatrix{1\cr 1\cr} = -2$$
so the second derivative is negative, and you have a local maximum.

A: In order to find the Hessian, we need to know the change in $f$ to second order in the deviation from $(0,0)$.
Expanding $F(x,y)$ around this point, we have up to second order
$$ F(x,y) = \nabla F(0,0)\begin{pmatrix} x \\y\end{pmatrix}
+ \tfrac12 \begin{pmatrix} x & y\end{pmatrix} H_F \begin{pmatrix} x \\y\end{pmatrix}.$$
Similarly, expanding $f(x,y)$ we obtain
$$ f(x,y) = \nabla f(0,0)\begin{pmatrix} x \\y\end{pmatrix}
+ \tfrac12 \begin{pmatrix} x & y\end{pmatrix} H_f \begin{pmatrix} x \\y\end{pmatrix}.$$
In the last step, we need to implement the constraint $F(x,y)=0$. To first order, we have $\nabla F(0,0) \begin{pmatrix} x \\y\end{pmatrix}=0$ and because $\nabla f \parallel \nabla F$, we have that $f(0,0)$ is an extremum. In particular, we have $y=x$ to first order.
To second order, we have
$$\tfrac12 \begin{pmatrix} x & y\end{pmatrix} H_F \begin{pmatrix} x \\y\end{pmatrix} = \tfrac12 \begin{pmatrix} x & x\end{pmatrix} H_F \begin{pmatrix} x \\x\end{pmatrix} = \frac{3}{2} x^2. $$
In order that $F(x,y)=0$ to second order, we need to compensate this via the first term, so we have $y= x - \frac{3}{2} x^2$.
Plugging this into the expansion of $f(x,y)$, we obtain a term from the gradiant and a term from the Hessian (Tunococ just considered the term from the Hessian). In total, we have
$$f(x,y) = -3 x^2 + 2 x^2 =-x^2.$$
So it is a local maximum.

A: Edit: I did not take into account the non-linearity of the constraint so it was wrong. This is the wrong version:
The complementary space of $\nabla F(0, 0)$ is spanned by $(1, 1)$. The (unscaled) reduced Hessian of $f$ is a $1$-by-$1$ matrix: $\begin{pmatrix}1 & 1\end{pmatrix}\begin{pmatrix}2 & 1 \\ 1 & 0\end{pmatrix}\begin{pmatrix}1 \\ 1\end{pmatrix} = 4 > 0$, so it is a minimum.
For correct answer, see Robert's answer above.


text:
Q: Is there a way to extract function parameters from a dictionary? I am trying to create some more functional code in Python and I want to know if it is possible to transform dictionary (key,values) to pass as a function parameter.
I am currently doing this in a more imperative way, where I filter and then manually extract each key depending on the result of the filter. My current code:
def a(i: int, config: dict):
    function_array = [function1, function2, function3]
    selected = function_array[i]
    if (i == "0"):
        result = selected(x = config['x'])
    elif (i == "1"):
        result = selected(y = config['y'])
    elif (i == "2"):
        result = selected(z = config['z'])
    return result

The current result is correct, but when I have many cases, I need to hardcode each parameter for the specified function. So, that is why I want to know if it is possible to pass the config object as I want (with an x when i is 0, for example) and then just do something like this:
def a(i: int, config: dict):
    function_array = [function1, function2, function3]
    result = function_array[i](config)
    return result

A: The syntax for passing items from a dictionary as function parameters is simply selected(**config)
So for your example, it would look something like this:
def function1(x=0):
    return x + 1

def function2(y=42):
    return y * 2

def function3(z=100):
    return z

def a(i, config):
    function_array = [function1, function2, function3]
    selected = function_array[i]
    return selected(**config)

config = {x: 10}
a(0, config) # calls function1(x=10)

config = {y: 20}
a(1, config) # calls function2(y=20)

config = {}
a(2, config) # calls function3()

A: Every python function can be instructed to take a dictionary of keywords.  See e.g. https://www.pythoncheatsheet.org/blog/python-easy-args-kwargs .  (Official source at https://docs.python.org/3/reference/compound_stmts.html#function-definitions, but it's harder to read.)
You could do:
def a(i: int, keyword: str, **kwargs: dict):
    if keyword in kwargs:
        result = kwargs[keyword](i)

and you would run it with something like:
a(5, "func3", func1=print, func2=sum, func3=all)

Or, you could just pass a dictionary itself into the function:
def a(i: int, keyword: str, config: dict)
    if keyword in config:
        result = config[keyword](i)

This would be run with something like:
a(5, "func3", {"func1": print, "func2": sum, "func3": all})

The only difference is that the ** in the function declaration tells python to automatically make a dictionary out of explicit keywords.  In the second example, you make the dictionary by yourself.
There's an important thing happening behind the scenes here.  Functions are being passed around just like anything else.  In python, functions are still objects.  You can pass a function just as easily as you can pass an int.  So if you wanted to have a list of lists, where each inner list is a function with some arguments, you easily could:
things_to_do = [[sum, 5, 7, 9], [any, 1, 0], [all, 1, 0]]
for thing_list in things_to_do:
    function = thing_list[0]
    args = thing_list[1:]
    print(function(args))

And you'll get the following results:
21
True
False

(Note also that all of those functions take an iterable, such as a list.  If you want to pass each argument separately, you would use *args instead of args.)
You can do it with defined functions, too.  If you have
def foo1(arg1):
    pass
def foo2(arg1, arg2):
    pass

you can just as easily have
things_to_do = [[sum, 5, 7, 9], [foo1, 'a'], [foo2, 0, None]]


text:
Q: Group by the same ID with diferent diseases I have a table

each different disease create a new row with the same ID, i want to group this rows to transform the ID into a primary key. I already tried a bunch of queryes without success.

A: With group by you can group by data with a column. Here you want to group by your ID and keep the maximum of every ID. So you can use GROUP BY and display the maximum value with MAX().
SELECT ID, MAX(DISEASE1), MAX(DISEASE2), MAX(DISEASE3)
FROM table
GROUP BY ID


text:
Q: How to iterate over two byte slices Each byte slice represents a key,
I want to iterate from the lower key to the Upper Key
pkg
https://golang.org/pkg/bytes/
Suppose there are two byte slices
lower :=[]byte
upper :=[]byte
how do I do this?
   for i:=lower;i<upper;i++ {

    }

Example
 lower:= []byte{0,0,0,0,0,0}  // can be thought as 0 in decimal
 upper:= []byte{0,0,0,0,0,255} // can be thought as 255 in decimal
 //iterate over all numbers in between lower and upper
// {0,0,0,0,0,0} {0,0,0,0,0,1} ... {0,0,0,0,0,2} ..{0,0,0,0,0,255}
 for i:=0; i<=255;i++{

 }
//instead of converting to decimal iterate using byte arrays

Alternatively,
How can I divide the range of the byte array (upper-lower) into smaller ranges
\\eg
   l := []byte{0,1}
   r := []byte{1,255}

break this into smaller ranges
   l := []byte{0 , 1}
   l2:= []byte{x1,y1}
...
   r:= []byte{1,255}

A: The easiest way to do this is to simply interpret the bytes as a big-endian integer. Since there is no int48 type in Go (i.e. a six bytes large integer), you have to first extend the byte slices with leading zeros until it fits into the next largest type, int64 or uint64. Then interate with a standard for loop and reverse the decoding for each iteration:
package main

import (
        "encoding/binary"
        "fmt"
)

func main() {
        lower := []byte{0, 0, 0, 0, 0, 0}
        lowerInt := binary.BigEndian.Uint64(append([]byte{0, 0}, lower...))

        upper := []byte{0, 0, 0, 0, 0, 255}
        upperInt := binary.BigEndian.Uint64(append([]byte{0, 0}, upper...))

        buf := make([]byte, 8)
        for i := lowerInt; i <= upperInt; i++ {
                binary.BigEndian.PutUint64(buf, i)
                fmt.Println(buf[2:])
        }
}
// Output:
// [0 0 0 0 0 0]
// [0 0 0 0 0 1]
// ...
// [0 0 0 0 0 254]
// [0 0 0 0 0 255]

Try it on the Playground: https://play.golang.org/p/86iN0V47nZi


text:
Q: Is it possible to combine columns on a table with max width? I have a table

Here be some 	#	#

1	2	3

Is it possible to expand the text Here be some across all columns?  I do not care if #	 is removed, but removing the columns does not appear to help.
The problem is that the table has enough row width to fit the content, but only if the first column fills the entire row's width.
Essentially, is it possible to emulate what we can do with Excel's merge cell ability?

A: colspan

Here be some

1	2	3

A:

Here be some

1	2	3

A: You want colspan

Here be some

1	2	3


text:
Q: What is the probability that the first defective item occurs in the the fifth item inspected Q In a production line, the probability of finding a defective item is 0.3 . What is the probability that the first defective item occurs in the the fifth item inspected.
f(x)=(1−p)^(x−1)P
How to apply this formula here?

A: Congratulations, you got the right formula for the problem in the first place. This is the hardest part most of the time. Now, let's use it.
[Side note: I don't know why you wrote the "p" uppercase one time and lowercase another time. It should be the same.]
[Side note 2: I assume you know how to evaluate this formula with an electronic calculator. Just to make sure: The notation x^y means "take x to the y-th power", or: "multiply x with itself y times".]
So your formula has two variables (p and x) and you got two numbers (0.3 and 5). What is left is to figure out which is which. I'd say 50% chance to get it right by guessing. Let's increase this chance by understanding the formula.
f(x) is the overall probability that an event with probability (1-p) occurs (x-1) times in a row, followed by one event with probability p.
In your example, we want to find the overall probability that the event "item is ok" occurs 4 times in a row, followed by one event of type "item is defective".
See the correspondences?


text:
Q: How to create button scaling effect in CSS? I need a button whose after selector expands and gets disappeared when clicked. I need this effect via CSS.

When i click this button it's after selector expands.
Like
#button::after{
  transform: scale(2);
}

But this is not happening for me. Please help me. When clicked the after selector button should expand then should disappear. In a nutshell, i need button scaling effect.

A: Do you mean something like this?
As far as I know you can't get an onclick event with CSS only and without using JavaScript. You can use :active, but this will only apply the style when the mouse button is held down. See Bojangles answer on "Can I have an Onclick effect in CSS".

#button {
  display: block;
  border: none;
  position: relative;
  color: red;
  background-color: white;
  font-size: 30px;
  padding: 15px 30px;
}

#button:after {
  content: '';
  position: absolute;
  display: block;
  height: 100%;
  width: 100%;
  top: 0;
  left: 0;
  border: 4px solid red;
  color: black;
  font-size: 8px;
  opacity: 1;
  transition: transform .3s ease, opacity .5s ease;
}
#button:active:after {
  transform: scale(5);
  opacity: 0;
}
<button id="button">BUTTON</button>

A: **The code snippet is built upon on benedikt's answer.
#button:after's border color is set to transparent, adds border-color during the animation. this creates the illusion that it disappears. I hope this helps.

#button {
  display: block;
  border: 4px solid red;
  position: relative;
  color: red;
  background-color: white;
  font-size: 30px;
  padding: 15px 30px;
}

#button:after {
  content: '';
  position: absolute;
  display: block;
  width:100%;
  height:100%;
  top:0;
  left:0;
  border: 4px solid transparent;
  color: black;
  font-size: 8px;
  opacity: 1;
  transition: transform 0.3s ease, opacity 0.5s ease, border-color 0.1s ease;
}
#button:active:after {
  transform: scale(2);
  border-color:red;
  opacity: 0;

}
<button id="button">BUTTON</button>


text:
Q: Strict string matching locate file batch - Case sensitive I have a piece of code which runs through each line in a find.txt file and tries locate it. If it does not exist it will populate a output.txt file. Thing is, if a file is called "Egg.mp3" and in my find.txt has "egg.mp3" it counts that as if it found it? Now correct.. It did but i need something thats strict! Case sensitive even so that "Egg.mp3" is not the same as "egg.mp3" therefore to drop "egg.mp3" into my output.txt.
Does anyone have a solution to this? I searched around and found nothing that may help.
Batch code:
for /f "usebackq delims=" %%i in ("E:\find.txt") do IF EXIST "C:\Users\PC\Desktop\Lib\%%i" (echo "File Exists") ELSE (echo "C:\Users\PC\Desktop\Lib\%%i">> "C:\Users\PC\Desktop\output.txt")
pause

A: Windows does not differentiate case when dealing with file or folder names. So "egg.mp3" and "Egg.mp3" really are equivalent.
But if you still want to include file names that differ only in case, then you can do the following:
@echo off
set "folder=C:\Users\PC\Desktop\Lib"
set "output=C:\Users\PC\Desktop\output.txt"

pushd "%folder%"
>"%output%" (
  for /f "usebackq delims=" %%F in ("e:\find.txt") do dir /b /a-d "%%F" 2>nul | findstr /xc:"%%F" >&2 || echo %folder%\%%F
)
popd

The following would be a lot faster (assuming you don't really need the path info in the output), but this nasty FINDSTR bug prevents the following from working properly - DO NOT USE!
@echo off
dir /b /a-d "C:\Users\PC\Desktop\Lib" >"e:\temp.txt"
findstr /LXVG:"e:\temp.txt" "e:\find.txt" >"C:\Users\PC\Desktop\output.txt"
del "e:\temp.txt"

If you have JREPL.BAT, then you can do the following instead:
@echo off
dir /b /a-d "C:\Users\PC\Desktop\Lib" >"e:\temp.txt"
call jrepl "e:\temp.txt" "" /b /e /r 0:FILE /f "e:\find.txt" /o "C:\Users\PC\Desktop\output.txt"
del "e:\temp.txt"

If you really need the path info in your output, then you can do the following:
@echo off
dir /b /a-d "C:\Users\PC\Desktop\Lib" >"e:\temp.txt"
jrepl "e:\temp.txt" "" /b /e /r 0:FILE /f "e:\find.txt" | jrepl "^" "C:\Users\PC\Desktop\Lib\" /o "C:\Users\PC\Desktop\output.txt"
del "e:\temp.txt"

A: Based off of a comment in this solution, this should do what you want:
@echo off
for /f "usebackq delims=" %%i in ("find.txt") do (
    echo Checking for %%i...
    dir /b /a-d "%%i"|find "%%i" >nul
    if %errorlevel% == 0 (
        echo "File Exists"
    ) ELSE (
        echo "Not found"
    )
)

Example of the base command in action:
D:\batch>dir /b /a-d "egg.mp3"|find "egg.mp3"

D:\batch>dir /b /a-d "Egg.mp3"|find "Egg.mp3"
Egg.mp3


text:
Q: Question regarding probability notation of splitting a Poisson process with Binomial conditionals Suppose I know that events occur according to a splitting Poisson process of rate $\lambda = 10$ per hour. Suppose further that events is categorized as type $1$ with probability $\frac{1}{4}$ and as type $2$ with probability $\frac{3}{4}$. Assume that a total of $200$ events arrived in the first $10$ hours. Conditional on this, I would like to find the probability that $n$ events are categorized as type $1$ in  the first $4$ hours.
I know that $P(X(4) = N|X(10)=200) = \dbinom{200}{N}\left(\frac4{10}\right)^N\left(\frac6{10}\right)^{200-N}$. Hence, given $200$ events arrived in $10$ hours, the number of events occurring in $4$ hours is distributed $Bin\left(N,\frac{4}{10}\right)$. Now, conditional on $N$ events occurring in $4$ hours, the number of events categorized as being of category $1$ is binomially distributed. If I let $N_1(4)$ denote the number of events being categorized as category $1$ in $4$ hours, then $N_1(4)$ conditional on $X(4) = N$ is $Bin\left(N, \frac{1}{4}\right)$.
I understand that conditional binomial events are conditional as well, and so conditional on $200$ events arriving in $10$ hours, the number of events arriving as category $1$ in $4$ hours from these $10$ hours is distributed $Bin\left(N, \frac{1}{4}\frac{4}{10}\right)$.
I am wondering how to express these in terms of probability notation. Does the following equations express what is going on correctly?
$$
P(N_1(4) = n_1|X(4) = N, X(10) = 200) = P(N_1(4)= n_1|X(4) = N) \cdot P(X(4) = N|X(10)=200)
$$
where $P(N_1(4)= n_1|X(4) = N) \sim Bin\left(N, \frac{1}{4}\right)$
and $P(X(4) = N|X(10)=200) \sim Bin\left(N,\frac{4}{10}\right)$
and $P(N_1(4) = n_1|X(4) = N, X(10) = 200) \sim Bin\left(N, \frac{1}{4}\frac{4}{10}\right)$?


text:
Q: Удалить поля в MySQL с условием Добрый день. Необходимо удалить поля (заменить их значения на NULL), размер которых меньше 10 символов).
Структура таблицы следующая:
-----------------------------------------
Name | City | Phone1 | Phone 2 | Phone 3
-----------------------------------------

Знаю, что нужно использовать условие where CHAR_LENGTH (phone1)<11 ..., но как составить запрос не могу понять.
Заранее спасибо за совет!

A: UPDATE table SET phone1 = NULL WHERE CHAR_LENGTH(phone1) < 11?


text:
Q: Stripes does not see my ActionBean I'm having again some little problems with Stripes, this time with the link tag
Basically i am calling an action bean from a jsp like so:
<s:link beanclass="users.action.UserFormActionBean">...</s:link>

The exception i receive is:
The value supplied for the 'beanclass' attribute does not represent a valid ActionBean.

Which is not true because that class implements ActionBean (via a class helper called BaseActionBean) and it contains a @DefaultHandler.
I really cant figure out why it does not work, below i will post the two classes
public class UserFormActionBean extends BaseActionBean{

private User user;

private static final String FORM="/WEB-INF/jsp/form.jsp";

private static final String LIST="/WEB-INF/jsp/list.jsp";

@DefaultHandler
public Resolution goToForm(){

    return new ForwardResolution(FORM);
}

/**
 * A getter for the user
 * @return
 */
public User getUser(){

    return this.user;
}

/**
 *save the new user into db
 */
public Resolution save(User user){

    DaoUtil.save(user);

    return new ForwardResolution(LIST);
}

}
the helper:
public class BaseActionBean implements ActionBean{

private ActionBeanContext ctx;

public void setContext(ActionBeanContext ctx){

    this.ctx=ctx;
}

public ActionBeanContext getContext(){

    return this.ctx;
}

}

A: Check your package declaration for UserFormActionBean it should be:
package users.action;

(Although I would recommend using another package name as this name does not conform to the general Java naming convention that describes that a package name should start with one of the top-level domain names of your organization).


text:
Q: sudo-apt get update fails because of spotify repository I've been trying to run sudo apt-get update and it keeps spitting out an error that it failed to fetch http://repository.spotify.com/dists/stable/InRelease. The output is as follows:
Hit:1 http://repo.steampowered.com/steam precise InRelease
Hit:2 http://packages.microsoft.com/repos/vscode stable InRelease
Hit:3 http://archive.ubuntu.com/ubuntu xenial InRelease
Get:4 http://repository.spotify.com stable InRelease [3,302 B]
Hit:5 http://archive.ubuntu.com/ubuntu xenial-updates InRelease
Hit:6 https://dl.winehq.org/wine-builds/ubuntu xenial InRelease
Hit:7 http://archive.ubuntu.com/ubuntu xenial-security InRelease
Err:4 http://repository.spotify.com stable InRelease
  The following signatures couldn't be verified because the public key
is not available: NO_PUBKEY A87FF9DF48BF1C90
Fetched 3,302 B in 1s (2,125 B/s)
Reading package lists...Done
W: An error occured during the signature verification. The repository
is not updated and the previous index files will be used. GPG error:
http://repository.spotify.com stable InRelease: The following
signatures couldn't be verified because the public key is not
availiable: NO_PUBKEY A87FF9DF48BF1C90
W:Failed to fetch http://repository.spotify.com/dists/stable/InRelease
The following signatures couldn't be verified because the pupblic key
is not available: NO_PUBKEY A87FF9DF48BF1C90
W: Some index files failed to download. They have been ignored, or old
ones used instead. `

Now is there some way to completely get rid of the spotify repostitory? or update it maybe? I cant figure it out.

A: In the output identify the following value, the one you see right now is for reference
NO_PUBKEY 11111111111

Then you add it to the following command, in this case it is 11111111111
$ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 11111111111

Finally
$ sudo apt update

It worked for me, here is the source that helped me, I hope it will serve you.
https://linuxconfig.org/ubuntu-20-04-gpg-error-the-following-signatures-couldn-t-be-verified

A: As the root cause of this is unknown at the moment I workarounded it by downloading the key with wget and adding it to apt trusted keys manually.
$ wget -q "https://keyserver.ubuntu.com/pks/lookup?op=get&search=0xA87FF9DF48BF1C90" -O-  | gpg --dearmor > spotify-A87FF9DF48BF1C90.gpg

$ sudo mv spotify-A87FF9DF48BF1C90.gpg /etc/apt/trusted.gpg.d/

Apt updated spotify repository correctly.
Above data has been taken and tested from blog https://linuxer.eu/apt-key-gpg-keyserver-receive-failed/


text:
Q: How to write a reverse loop for 2 conditions using openpyxl I have written the following function, which uses openpyxl and test values in management_style list vs. a column in a .xlsx called 'Management Style' (denoted by min_col=3, max_col=3). If the cell value =! of the 'Management Style' column cell of any value in management_style, the row is dropped using a sort of reverse loop and the indexes
import openpyxl
from openpyxl import load_workbook

management_style = [
    'Advisory',
    'Advisory - No Fee',
    'Holding',
    'JPAS',
    'Liquidity Management',
    'Trading'
]

model_type = [
    'Client',
    'Holding Account',
    'Holding Company',
    'Trust'
]

def row_cleansing(excel_file_path):

    workbook = load_workbook(excel_file_path)
    data_sheet = workbook.active

    delete_indexes = []
    for row in data_sheet.iter_rows(min_col=3, max_col=3, min_row=2, max_row=None):
        for cell in row:
            if cell.value not in management_style:
                    print(cell.row, cell.value)
                    delete_indexes.append(cell.row)

    delete_indexes.reverse()
    for i in delete_indexes:
        data_sheet.delete_rows(i, amount=1)
    workbook.save(excel_file_path)

row_cleansing('data_to_be_split_test.xlsx')

You will note that the model_type list is not utilized in the code, which is where I need help -  how would I expand/refactor this function so that it tests values in both management_style (denoted by min_col=3, max_col=3) and model_type (will be min_col=11, max_col=11)?
In other words, I only want to remove rows if there is no match in the Management Style column vs. management_style AND in the Model Type Column vs. model_type list.

A: You can loop over the row indices and get just the cells you need directly:
    for r in range(2, data_sheet.max_row + 1):
        management_value = data_sheet.cell(row=r, column=3).value
        model_value = data_sheet.cell(row=r, column=11).value
        if management_value not in management_style and model_value not in model_type:
            print(r, management_value, model_value)
            delete_indexes.append(r)


text:
Q: Issue style Angular Material mat-menu in IE11 So we are using Angular 7.2 with Materials 7.2.1, and we are trying to fix a css-related issue where we add fxLayout to the mat-menu.
This adds horizonal and vertical scrollbars, which makes it unusable (see screenshots).
My question is main around how I can modify the flexbox styles in scss to handle this ie11 issue :
i.e. perhaps using a media query:
 @media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
    // IE10+ CSS here
}

Here's a snippet from our menubar html template :

<button mat-button [matMenuTriggerFor]="adminMenu" *ngIf="userRoles.admin.CanView">Admin
    <mat-icon svgIcon="down" style ="vertical-align: top;height: 20px; width: 20px;"class="caret">arrow_drop_down</mat-icon>
</button>

<mat-menu #adminMenu="matMenu" [overlapTrigger]="false" class="mega-menu app-dropdown">

            Management
            Monitoring
            Configuration
            Activation

</mat-menu>

and an example of the generated html for the management menu item (copied from Chrome inspector):

Management

My question is main around what I can do in our scss file to handle some of these special ie1 related css issues:
i.e. perhaps using a media query:
 @media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
    // IE10+ CSS here
}

A: We just removed fxLayout and fxFlex from the div and it works fine in IE:

<mat-menu #adminMenu="matMenu" [overlapTrigger]="false" class="mega-menu app-dropdown">

            Management
            Monitoring
            Configuration
            Activation

</mat-menu>


text:
Q: R - How to store custom objects in a matrix (or similar structure)? I'm trying to fill a matrix with objects of a custom class. But it seems like this wouldn't work. Here's my attempt:
setClass('Person', representation(name = 'character', age = 'numeric'))

m = matrix(nrow = 10, ncol = 10)

m[1, 1] = 42 #works

john = new('Person', name = 'John Smith', age = 42)

m[1, 1] = john #Error in m[1, 1] = john : number of items to replace is not a multiple of replacement length

Am I missing something or is matrix just the wrong tool for this? If  so, what should I use instead?

A: Using a data frame, you can store the object as a list (column is coerced to a list variable):
setClass('Person', representation(name = 'character', age = 'numeric'))

m = as.data.frame(matrix(nrow = 10, ncol = 10))

m[1, 1] = 42 #works

john = new('Person', name = 'John Smith', age = 42)

m[1, 1] = list(list(john))

A: It probably isn't the right tool. You can however force things into matrices if you have a list() for each cell, but it's often not ideal. Consider:
m <- matrix(list(), nrow=10, ncol=10)
m[1, 1] = list(john)
m[1, 1]
#[[1]]
#An object of class "Person"
#Slot "name":
#[1] "John Smith"
#
#Slot "age":
#[1] 42


text:
Q: Virtual installation: where to find the ISO I'm running windows 7 on my computer (64-bit) and I need to install Ubuntu 12.10 (kernel: 3.5.0-17-generic) virtually.
I've installed VirtualBox from Oracle but I can't find the iso image for this Ubuntu version. Plus, I've read that there are certain procedures in order to install and write C/C++ programs (some people said that installing eclipse was a problem and others said that the GCC compiler was a problem) and that it's not as simple as windows.
So would anyone please tell me where to find the iso image and what steps should I do to successfully start writing parallel programs on Ubuntu.

A: First set up the virtual machine (VM), and download a suitable ISO file from the Ubuntu download page. Personally, I would recommend sticking with a LTS release, in this case Ubuntu 12.04. Mount the ISO file as the VM's optical disk and install from there.
Boot the new VM, login, open a terminal and type:
sudo apt-get install build-essential

That will set up the basic things you need in order to compile and build packages on Ubuntu.
Next, install Eclipse from a downloaded archive or (even easier) from the package.
You asked about Eclipse, but you might also want to give the Netbeans IDE a try, which also offers a similar cross-platform IDE experience.


text:
Q: looking for a multiplicity one prime in a finite sum So I'm trying to compute the Galois group of family of polynomials (indexed by their degree) using the technique of the Newton polygon. In order to apply this technique I need to find some good prime number $p$.
So this is the motivation behind my question that might seem a little bit unmotivated:
Let $N$ be a large integer. Then it is not too difficult to show the following statement:
Theorem: For every prime $p$ such that $N/2< p< 2N/3$ one has that $p$ divides the following sum
$$
S_N:=\sum_{k=0}^N \binom{N+k}{k}2^{N-k}(-1)^k
$$
After many numerical examples, it always happens that most of the primes in the interval
$N/2 < p < 2N/3$ divide $S_N$ with multiplicity one. So here is my question:
Q: How would you show that there exists at least one prime $p$ in the interval $N/2 < p < 2N/3$ that divides exactly $S_N$, i.e., $p|S_N$ but $p^2\nmid S_N$ ,?
Note that the square of the product of all primes in the interval $(\frac{N}{2},\frac{2N}{3})$ is less that $\binom{2N}{N}$, so a naive counting argument does not seem to work here.
If you think that this problem is intractable then let me know, I'll try a different strategy.

A: No answer, just some data. Up to $n=825$ there are 41 pairs $[p,n]$ such that $S_n \equiv 0 \mod p^2$ and $\frac n2 \lt p \lt \frac{2n}{3}$. Here they are: $ \small [7, 12], [11, 21], [29, 55], [41, 68], [43, 72], [47, 80], [61, 100], [73, 136], [\mathbf{89}, 138], [\mathbf{89}, 150], [79, 156], [89, 167]$ $ \small [109, 183] [\mathbf{127}, 206], [\mathbf{127}, 230], [131, 231], [157, 276], [181, 301], [199, 306], [197, 364], [227, 386], [257, 445] $ $\small [\mathbf{277}, 450], [\mathbf{277}, 475] [313, 482], [251, 492], [353, 538], [307, 542], [421, 654], [439, 670], [367, 701], [431, 702]$ $\small [\mathbf{359}, 703], [\mathbf{359}, 710], [373, 731] [401, 737], [467, 737], [409, 755], [431, 757], [491, 798], [419, 822] $
Over the same range the (naively ) expected number of repeat divisors of that type is about $43$ so the result seems almost certainly true, but perhaps for no special reason.
It is notable that several times one gets the same $p$ twice in a row. I don't know if it is significant however.


text:
Q: Using autoReleased objects without an NSAutoReleasePool? I'm writing my very first steps in Objective-C.
I followed some examples and the official documentation, and am using autoreleased objects* without explicitly declaring an NSAutoReleasePool.
* By autoreleased objects I mean: SomeClass *obj = [SomeClass someClass];
Is it ok to do it this way?
Will it cause a memory problem?
Is declaring a NSAutoReleasePool more efficient?
edit: I made a mistake in the code example, what I meant was getting an object by it's class factory method instead of allocing an instance of it. This factory methods [often|always] return autoreleased objects, right? for example: [NSString stringWithCString:x]

A: You don't need to create an autorelease pool explicitly usually. When you do normal Mac programming using the AppKit framework, there will be an implicit autorelease pool which is handled by the event loop. You need to concern yourself with autorelease pools mainly on two occasions:

*

*Your code runs in a background thread: If you have a background thread there is no autorelease pool created for you and you will have to do this manually.

*You have a tight loop where you create and destroy a lot of objects. If in this loop any objects are autoreleased they will not actually be released until the autorelease pool is drained. This means that your memory consumption will rise, even though you don't reference those objects anymore. In this situation having a local autorelease pool can help with performance, although switching from autoreleasing to explicit retain/release is probably more efficient.

A: In answer to your question: that's a no-no. You will leak memory if you autorelease an object (or use an autoreleased object) in a scope that has no autorelease pool.
perhaps ignore the following:
With regard to your example, it might be rather confusing the way you've written it, since Class is a typedef of struct objc_class*. So, you're really declaring a pointer-to-a-pointer to a class, and then assigning a pointer to a class to it. Which won't work. Moreover, since Class is not an Objective-C "class-type" per se, you can't send messages to it.
But all this is neither here nor there, since ±class does not return an autoreleased object.


text:
Q: Using Return to end the app. Correct? I have very simple application just in the body of Main method. I have tried to find out different ways of ending the app except for Environment.Exit() but I entirely forgot I can just call return. Is it correct to use it for ending the app if it just run in Main method? I cannot see any problem but I want to learn as much as I can. Thanks

A: Right, sounds like you're on the right track. It's not clear if you're running a console application, and this code should help highlight.
static void Main(string[] args)
{
    bool keepRunning = true;
    int x = 0;
    while (keepRunning)
    {
        //at some point, flip keepRunning to fall out of the while loop
        if (moon.Color == Blue)
           keepRunning = false;

        if (x > 0) //or some other condition
            return;
    }
   //naturally will fall out of the Main() and terminate the program
}

A: If you're exiting out due to an error, you really should use Environment.Exit with a non-zero argument... documenting what type of error returns which exit code is a good idea, too.
Otherwise, it should be OK to just return... but it's really a stylistic choice.

A: Yes, it is OK to return from the Main method.


text:
Q: graphics not showing on resized subpanel? I am having issues with a small project im working on. I am trying to create a Moveable message panel when holding down the mouse button but i am stuck on one part.
I want to place the A small panel with a size of 50x30 pixels that contains the message "java" in it and have this small panel in a larger panel and place that panel into my JFrame.
However, when i do so the message "java" disappears and only the the small panel in the larger panel appears. I added borders to my panels to make sure that my panels were actually visible. Please help  and here is my code:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;

public class MovingPanel extends JFrame {
    private String message;
    private int x = 100;
    private int y = 100;

    public MovingPanel() {
        JPanel panel = new JPanel();
        MessagePanel p1 = new MessagePanel("Java");
        panel.setBorder(new LineBorder(Color.RED, 2));
        panel.setLayout(null);
        p1.setLocation(x, y);
        p1.setSize(50, 30);
        p1.setBorder(new LineBorder(Color.BLACK, 2));
        p1.setLayout(new BorderLayout());
        panel.add(p1);
        add(panel);

     }

public static void main(String[] args) {

    MovingPanel frame = new MovingPanel();

    frame.setSize(500, 500);

    frame.setLocationRelativeTo(null);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.setTitle("Test Message Panel");

    frame.setVisible(true);

}

class MessagePanel extends JPanel {

    public MessagePanel(String s) {

        message = s;

    }

    protected void paintComponent(Graphics g) {

        super.paintComponent(g);

        g.drawString(message, x + 20, y + 10);

    }
}

}

A: Maybe you can try to use a simple JLabel component instead of your "MessagePanel".

A: First thing you need to understand is this.

*

*The second and third arguments of this g.drawString(message, x + 20, y + 10); method are the x and y location of the panel.

*With the above being said, you have to remember that it is the x and y location of the containing panel, which is MessagePanel.

*You have the size of your MessagePanel object set at 50, 30, yet you are trying to access a point 120 (x + 20) and 110 (100 + 10), which does not exist since you size the size of the panel.

*So now that's understood, let's say you want to paint the message at the very left corner of the MessagePanel, so you try and do this g.drawString(message, 0, 0);. This still would show anything as the point starts from the bottom left corner of the message, so the message would actually be riding just above the visible area.

*When drawing strings, you need to consider the FontMetrics, which allows you to get the size of the string you are trying to draw, so you can position the message exactly on the screen where you want it.

*A simple fix would be just set an x and y a little above 0, 0, like 15, 15. Though this might get your message to draw, it wouldn't be centered. You can keep on changing and getting different numbers to check if it is aligned in the middle, but the proper way is to use FontMetrics

As a said a simple (but maybe not desired) fix is to just change this
g.drawString(message, x + 20, y + 10);

To
g.drawString(message, 15, 15);

And you will see the message.

Instead of what you are doing though, this is how I would do it.

*

*Instead of using two panels, I would just use one - the one that's doing the painting.

*Don't set the size of it, instead override getPrefferedSize inside that class, to whatever size you want the main panel to me.

*When you draw, just draw a rectangle the size you want at the specified coordinates.

*Also draw the message in the same paintComponent method.

*call pack() on the JFrame.

*If you do the above, there's no need to try and move the location of the MessagePanel. Instead move the x and y coordinates when you call repaint, You can have offsets for the message. Like
int boxX = 100;
int boxY = 100;
int messageOffset = 15;

*Then you can paint like this
protected void paintComponent(Graphics g){
    super.paintComponent(g);
    g.drawRect(boxX, boxY, 50, 30);
    g.drawString(message, boxX + messageOffset, boxY + messageOffset);
}

*Now in your action methods, just alter the boxX and/or boxY and call repaint.

*Also, if you want a thicker line, look into Graphics2D API, you can setStroke.


text:
Q: No type named 'nullptr_t' in namespace 'std' Someone is compiling my Qt program that is using the C++11 standard and they got this error (Mac OS X / gcc). I know I can declare it, but shouldn't it be already in <cstddef>?
./collectable_smartptr.hpp:54:33: error: no type named 'nullptr_t' in namespace 'std'
void operator=(std::nullptr_t &null)

This code works just fine on Windows and Linux, I see it just on Mac.
Mac is i386-apple-darwin11.3.0, compiler is:
$ g++ --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn)
Target: x86_64-apple-darwin13.2.0
Thread model: posix

g++ options (some) are -c -pipe -std=c++11 -O2 -arch x86_64 -Xarch_x86_64 -mmacosx-version-min=10.5 -Wall -W -DQT_USE_QSTRINGBUILDER -DQT_NO_DEBUG -DQT_WEBKIT_LIB -DQT_XML_LIB -DQT_GUI_LIB -DQT_NETWORK_LIB -DQT_CORE_LIB -DQT_SHARED
Is this normal? Or is there something extra what needs to be done on Mac for C++11 to work?

A: It is always better to include things explicitly and so, I would add this to the code:
#include <cstddef>

If that does not work that means you have a fundamental issue with your system, namely:

*

*You do not use a recent enough standard library implementation (e.g. try libc++).

*You do not have the C++11 and on compilation enabled.

As a quick and nasty workaround, you could do the typedef yourself of course, as follows:
namespace std {
    typedef decltype(nullptr) nullptr_t;
}

or without std, but this really ought to be the last resort, and usually it means you are doing something wrong.

A: Using #include <cstddef> didn't resolve the problem, but inserting
namespace std
{
    typedef decltype(nullptr) nullptr_t;
}

did apparently help get through this problem, despite I still don't understand why it was really needed.
PS: Given that I am not owner of computer where this happens I can't do any further investigation, see https://github.com/huggle/huggle3-qt-lx/issues/101 for details

A: I had the same issue when I included sstream in the namespace std:
namespace std {
// Some #ifdefs and so on
// quite hidden
#include <sstream>
}

Moving the include out of the namespace resolved the issue:
#include <sstream>
namespace std {
}

Compiler: Apple LLVM version 8.0.0 (clang-800.0.38) without C++11.


text:
Q: Nuxt generate - The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received undefined UPDATE: Link to Gitlab repo https://gitlab.com/daaf730/730-prismic
I'm totally lost on this one and the stacktrace is pointing me nowhere.
The error i'm getting is the one in the title saying:
The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received undefined. In the picture below you'll find the complete stacktrace, as it is very hard to put into text over here.

All my data is gathered async, just like in the example here.
Has anyone experienced something like this before and knows how to solve it?
If you need to see more code, I would gladly share it, but I just don't know which code to share .
Would love to hear from you!
~ Dave


text:
Q: Switch view with same object in winUI3 Example I have 4 images, I want to make a button to switch view for displaying those images:
view1(view1.xaml) as uniform grid(2x2), view2(view2.xaml) as listview(1x4), and 2 views use the same datatemplate (Image).
What is the best way to do it?
I will re-create object (images) and view or I can keep the same object, view instanse when switch view?
Should I put the datatemplate in resourceDictionary and 2 views will refer it?
I very appreciate if have any code example for it. Thanks

A: You can do something like this.
<Pivot>
    <PivotItem Header="2x2">
        <Grid ColumnDefinitions="*,*" RowDefinitions="*,*">
            <Image
                Grid.Row="0"
                Grid.Column="0"
                Source="/Assets/LockScreenLogo.scale-200.png" />
            <Image
                Grid.Row="0"
                Grid.Column="1"
                Source="/Assets/LockScreenLogo.scale-200.png" />
            <Image
                Grid.Row="1"
                Grid.Column="0"
                Source="/Assets/LockScreenLogo.scale-200.png" />
            <Image
                Grid.Row="1"
                Grid.Column="1"
                Source="/Assets/LockScreenLogo.scale-200.png" />
        </Grid>
    </PivotItem>
    <PivotItem Header="1x4">
        <Grid ColumnDefinitions="*,*,*,*">
            <Image Grid.Column="0" Source="/Assets/LockScreenLogo.scale-200.png" />
            <Image Grid.Column="1" Source="/Assets/LockScreenLogo.scale-200.png" />
            <Image Grid.Column="2" Source="/Assets/LockScreenLogo.scale-200.png" />
            <Image Grid.Column="3" Source="/Assets/LockScreenLogo.scale-200.png" />
        </Grid>
    </PivotItem>
</Pivot>