Delete multiple Core Data objects: Issue with NSFetchedResultsController

Question: I have found a fix for this, but I'm not really liking the fix. My issue goes like this. I am using a NSFetchedResultsController to populate a UICollectionView-- which displays a collection of images. Each image is described by a Core Data object (e.g., its file name is in the Core Data object).
I have UI controls that allow a user to delete multiple images at the same time, and was having a problem when the user would delete more than one object. The code to do the deletion was:
    for image in images {
       CoreData.sessionNamed(CoreDataExtras.sessionName).remove(image)
    }

    CoreData.sessionNamed(CoreDataExtras.sessionName).saveContext()

(Some of this is my library code).
With the deletion of two objects, I get a crash and the following log message:

CoreData: error: Serious application error. Exception was caught
  during Core Data change processing. This is usually a bug within an
  observer of NSManagedObjectContextObjectsDidChangeNotification.
  Invalid update: invalid number of items in section 0. The number of
  items contained in an existing section after the update (99) must be
  equal to the number of items contained in that section before the
  update (101), plus or minus the number of items inserted or deleted
  from that section (0 inserted, 1 deleted) and plus or minus the number
  of items moved into or out of that section (0 moved in, 0 moved out).
  with userInfo (null)

What fixes the problem is if I change the deletion code to:
    for image in images {
        CoreData.sessionNamed(CoreDataExtras.sessionName).remove(image)
        CoreData.sessionNamed(CoreDataExtras.sessionName).saveContext()
    }

I guess the problem is that in the delegate callback method:
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
       atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
      newIndexPath:(NSIndexPath *)newIndexPath {

I do:
collectionView.deleteItems(at: [indexPath])

Apparently, you can either do a reloadItems in the didChangeObject method, or you can do a saveContext after each object deletion.
Answer: If you delete several images, and then save the context, the FRC processes all the deletions - so its sections, fetchedObjects, etc, reflect all those changes.  But it then calls the didChangeObject: delegate method separately for each change.  In that method, you call the collectionView update methods (eg. deleteItems); the collectionView then calls its dataSource methods and does a quick tally up: there were X items, Y items were deleted, there are now Z items and throws an error because Z != X-Y.
When a FRC is used with a tableView, this problem is overcome by using the tableView beginUpdates and endUpdates calls in the FRC controllerWillChangeContent: and controllerDidChangeContent: delegate methods.  This causes the tableView to defer doing the tally up until ALL the individual changes have been processed - at which point the numbers do add up.
Your solution - to call saveContext after each deletion - causes the FRC to process each deletion in turn: updating its sections, fetchedObjects, etc, to reflect only one deletion at a time.  This keeps the FRC's data in sync with the collectionView.  One possible refinement would be to call processPendingChanges on the context after each deletion, instead of saving the context.  This avoids saving data when you might not want to, but nonetheless causes each deletion to be processed separately.
The alternative is to mimic the tableView's beginUpdates/endUpdates mechanism for holding all the collectionView updates until all the FRC updates have been processed.  This works broadly as follows:

Create arrays to keep track of the changes (inserts, deletes).
Each time didChangeObject: is called, add the corresponding indexPath to the relevant array.
When controllerDidChangeContent: is called, iterate through the arrays (deletions first, when inserts) calling the corresponding collectionView update methods. (Then empty the arrays ready for the next batch of updates).

Some good explanations and potential implementations are included in this question and its answers.
Comment: Thank you! -- I'll likely make use of your `processPendingChanges` idea.
Comment: It turns out that I had to move to the kind of solution you talked about with arrays-- to accumulate the pending deletions and do them all at once-- in terms of the collection view. Neither my original "fix" to the problem nor the `processPendingChanges` change completely solved my problem.
Comment: Well, life went on and my crashes didn't go away. Even with these changes. It turned there was something else, the same but different, going on-- I had a second view controller also using a `NSFetchedResultsController` with the same Core Data objects. However, there was a memory leak and this view controller was being retained. When I deleted images in my main view controller, this other, retained view controller was causing the crash-- for basically the same reasons as discussed above by @pbasdf.


Passing a dictionary to a new function in python?

Question: If I create a dictionary that I need to access in multiple functions what would be the best way to pass it?
What I currently am doing keeps reseting the dictionary to empty. If I print in the addDictionary() I get the result I want. However, when I go to look up a element using the key in lookUpEntry(), I can't find it. When I print I get an empty dictionary. I also have to eventually pickle and unpickle so if anyone has any feedback on that, that would also help.
import pickle

def dictionary():
addressBook = {}

return addressBook

def addPerson():
personLastName = input("Enter the last name of "
                   "the person you want to add: ").lower()
personFirstName = input("Please enter the first name of "
                        "the person you want to add: ")

localPart = input("Please enter the local part of the email address")
while not localPart.isalnum():
    localPart = input("Please enter a valid input, a-z and numbers 0-9: ")

domain = input("Please enter the domain of the email addres: ")
while not domain.isalnum():
    domain = input("Please enter a valid input, a-z and numbers 0-9: ")

topLevelDomain = input("Please enter the top level domain, examples: com, net, org: ")
while not topLevelDomain.isalnum() or len(topLevelDomain) > 3:
     topLevelDomain = input("Please enter only letters, a-z and not more then 3 characters: ")

personEmail = localPart + "@" + domain + "." + topLevelDomain

personStreetAddress = input("Please enter house number and street of the person you want to add: ")
personCityState = input("Please enter the city, state abbreviation and zipcode of the person you want to add: ")

personPhone = input("Please enter the phone number of the person you want to add: ")

personPhoneStr = personPhone.strip("-")

while not personPhoneStr.isdigit() and not len(personPhoneStr) == 10:
    personPhone = input("Error. That is not a valid phone number. Try again: ")

    personPhoneStr = personPhone.strip("-")

return personLastName, personFirstName, personEmail, personStreetAddress, personCityState, personPhone

def addDictionary():
addressBook = dictionary()

personLastName, personFirstName, personEmail, personStreetAddress, personCityState, personPhone = addPerson()

addressBook[personLastName] = personFirstName, personEmail, personStreetAddress, personCityState, personPhone

print(personFirstName,personLastName, "has been added to the address book!")

print(addressBook)

return addressBook

def lookUpEntry():
addressBook = dictionary()

keyName = input("Enter the last name of the person you are trying to find.")

while not keyName in addressBook:
    keyName = input("That name is not in the address book. Please try again.").lower()

x = input("Enter '1' if you want to look up a email. Enter '2' if you want to look "
          "up a persons address. Enter '3' to look up a persons phone number: ")
if x == "1":
    print("The email of", addressBook[keyName[0]], keyName, "is:", addressBook[keyName[1]])
elif x == "2":
    print("The address of", addressBook[keyName[0]], keyName, "is:", addressBook[keyName[2]], addressBook[keyName[3]])
elif x == "3":
    print("The phone number of", addressBook[keyName[0]], keyName, "is:", addressBook[keyName[4]])
else:
    print("Sorry that item is not stored in this address book.")

def main():
addDictionary()
lookUpEntry()

main()
Comment: Please indent your code correctly
Answer: Currently you define dictionary as
def dictionary():
    addressBook = {}
    return addressBook

Here you create a new dictionary every time it is called.  Try replacing this with
# a global dictionary
_addressBook = {}
def dictionary():
    return _addressBook

Comment: as your current code stands, where you don't pass a `dict` to either `addDictionary` or `lookupEntry`, it will pretty much require a global
Comment: Okay what would be the best method to pass the dict ? Sorry I had mono and missed the class on passing values to functions. Not my strong suit.


MFMessageComposeViewController not working

Question: I have a simple method that gets one argument and then sends a message. It is not working.
Code:
<code>- (void)sendSMS:(NSString *)text {
    MFMessageComposeViewController *viewController = [[MFMessageComposeViewController alloc] init];
    viewController.body = text;
    viewControllerM.mailComposeDelegate = self;
    [self presentViewController:viewController animated:YES completion:nil];
}
</code>
What's wrong?
Answer: You need to set the delegate:
<code>MFMessageComposeViewController *controller = [[[MFMessageComposeViewController alloc] init] autorelease];
    if([MFMessageComposeViewController canSendText])
    {
        controller.body = @"YO";
        controller.recipients = [NSArray arrayWithObjects:@"5625555555", nil];
        controller.messageComposeDelegate = self;

        [self presentViewController:controller animated:YES completion:nil];
    }
</code>


android:cacheColorHint="#00000000" don't work for <ExpandableListView

Question: I'm using an ExpandableListView, when is expanded and scrolling, it turns  black for a second when the scroll finishes. I used "android:cacheColorHint="#00000000" but It seems not work for expandable listview. The code is:
    <ExpandableListView android:id="@+id/android:list"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:layout_marginBottom="55dp" android:divider="@color/color_negro"
        android:listSelector="@android:color/transparent"
        android:cacheColorHint="#00000000" android:childDivider="@color/color_negro"
        android:descendantFocusability="afterDescendants" android:background="@null">
    </ExpandableListView>

and for to draw each child:
            public View newChildView(boolean isLastChild, ViewGroup parent) {
                if(layoutInflater == null){
                    layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                }
                return layoutInflater.inflate(R.layout.row_personas, null, false);
            }

Code for row_personas.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="vertical" >

<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content" android:orientation="horizontal"
android:background="@layout/custom_text_view_apellido"
android:layout_marginLeft="20dp" android:layout_marginRight="15dp"
>

<TextView android:id="@+id/rowApellido" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:textColor="@color/color_negro"
android:textSize="14sp" android:paddingLeft="10dp"
android:paddingTop="0dp" android:paddingRight="4dp"
android:paddingBottom="5dp" android:typeface="sans"
android:maxLength="20" >
</TextView>

<TextView android:id="@+id/rowNombres" android:layout_height="wrap_content"
android:layout_width="fill_parent" android:textSize="14sp"
android:textColor="@color/color_negro" android:paddingBottom="5dp"
android:layout_marginRight="5dp" android:maxLength="20"
android:singleLine="true" android:typeface="sans" android:paddingTop="0dp" >
</TextView>

</LinearLayout>

<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content" android:orientation="horizontal"
android:layout_marginLeft="20dp" android:layout_marginRight="15dp">

<ImageView android:id="@+id/photo" android:layout_height="34dp"
android:layout_width="41dp" android:layout_marginTop="2dp"
android:layout_marginRight="2dp" />

<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content" android:orientation="vertical">

<TextView android:id="@+id/rowDatoRelevante"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:textStyle="bold" android:textColor="@color/color_gris_oscuro"
android:textSize="12sp" android:paddingLeft="15dp"
android:paddingTop="1dp" android:paddingBottom="1dp"
android:background="@layout/custom_text_view_categoria"
android:gravity="left" android:layout_marginRight="25dp"
android:singleLine="true">
</TextView>

<TextView android:id="@+id/rowDatoRelevante2"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:textStyle="italic" android:textColor="@color/color_gris_oscuro"
android:textSize="12sp" android:paddingLeft="15dp"
android:background="@layout/custom_text_view_categoria_desc"
android:gravity="left" android:layout_marginRight="55dp"
android:singleLine="true">
</TextView>
</LinearLayout>
</LinearLayout>

</LinearLayout>

If someone can help me...Thanks!!!!!
Answer: I resolved my problem!!! I changed the declaration of ExpandableListView in this way:
<ExpandableListView android:id="@+id/android:list"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:layout_marginBottom="55dp"
android:scrollbarAlwaysDrawVerticalTrack="true" android:divider="@android:color/black"
android:childDivider="@android:color/transparent"
android:listSelector="@android:color/transparent"
android:cacheColorHint="@android:color/transparent"
android:background="@android:color/transparent">
</ExpandableListView>

I think that the problem was assign black color to "android:childDivider". I hope to help someone with this!
Answer: I was able to fix a similar bug by drawing a 9 patch png and setting it as the childDivider. My 9 patch png is two pixels high: the first row is set to the desired divider color, the second - stretchable one - to transparent.


can't find favicon.ico issue in play scala

Question: I have tested a play 2.3.4 app, and in the console it complains the following:
! @6jg7imio5 - Internal server error, for (GET) [/favicon.ico] ->

play.api.Application$$anon$1: Execution exception[[NoSuchElementException: key not found: favicon.ico]]
    at play.api.Application$class.handleError(Application.scala:296) ~[play_2.10-2.3.0.jar:2.3.0]
    at play.api.DefaultApplication.handleError(Application.scala:402) [play_2.10-2.3.0.jar:2.3.0]
    at play.core.server.netty.PlayDefaultUpstreamHandler$$anonfun$14$$anonfun$apply$1.applyOrElse(PlayDefaultUpstreamHandler.scala:205) [play_2.10-2.3.0.jar:2.3.0]
    at play.core.server.netty.PlayDefaultUpstreamHandler$$anonfun$14$$anonfun$apply$1.applyOrElse(PlayDefaultUpstreamHandler.scala:202) [play_2.10-2.3.0.jar:2.3.0]
    at scala.runtime.AbstractPartialFunction.apply(AbstractPartialFunction.scala:33) [scala-library.jar:na]
Caused by: java.util.NoSuchElementException: key not found: favicon.ico
    at scala.collection.MapLike$class.default(MapLike.scala:228) ~[scala-library.jar:na]
    at scala.collection.AbstractMap.default(Map.scala:58) ~[scala-library.jar:na]
    at scala.collection.MapLike$class.apply(MapLike.scala:141) ~[scala-library.jar:na]
    at scala.collection.AbstractMap.apply(Map.scala:58) ~[scala-library.jar:na]
    at controllers.Application$$anonfun$list$1$$anonfun$apply$7$$anonfun$apply$8.apply(Application.scala:68) ~[classes/:2.3.0]

Then I searched all the source code and can't find anywhere used favicon.ico. Is it used in some library?
The library I used in slick. The library configuration is as below:
libraryDependencies ++= Seq(
    "com.typesafe.play" %% "play-slick" % "0.7.0",
    "org.slf4j" % "slf4j-nop" % "1.6.4",
    "joda-time" % "joda-time" % "2.3",
    "org.joda" % "joda-convert" % "1.5",
    "com.github.tototoshi" %% "slick-joda-mapper" % "1.1.0",
    jdbc,
    anorm
)

UPDATE:
oracle@SomeHost ~/activator-1.2.10/abb_web_1/public $ tree
.
├── images
│   └── favicon.ico
├── javascripts
│   ├── forms.js
│   └── jquery.js
└── stylesheets
    ├── bootstrap.min.css
    └── main.css

In the route file, I added the following per biesior's reply. But it still complain the same error.Did I put the favicon.ico on the wrong place?
GET     /favicon.ico                controllers.Assets.at(path="/public", file="favicon.ico")

Comment: if you put it in subfolder, your route should be `...at(path="/public", file="images/favicon.ico")`
Comment: I changed, but still have the problem. and i checked the default router created by play template, there is no such router for favicon.ico, so why that works for other app?
Comment: I have no idea, push this project i.e. to github so we can see it whole
Answer: Every browser looks for favicon.ico when visiting the address. Just add that file to your public folder and add a route:
GET  /favicon.ico   controllers.Assets.at(path="/public", file="favicon.ico")

TIP: it can be also png file - in default new PlayJava or PlayScala project it can be found in public/images/favicon.png
Comment: I changed accordingly, but still failed, I updated my original message, please help review.
Answer: you should denote the path as controllers.Assets.at(path="/public/images", file="favicon.ico")


Algorithm for randomly choosing learning cards

Question: I'm programming a learning software. It works with question-/answercards. I´m searching for a algorithm that gives me a higher probability for cards that the user has answered wrong.
My actual idea (edit: Inverse transform sampling) is that each card has an integer which indicates how often the user has answerd the question wrong. Count all integer-values, creating a random integer between 0 and the counted integer-values and use this integer to go through my cards and count their integers until I reached the random integer. Then I reach the integer I choose this card :-)
But there must be a better solution ;-)
Edit: Rejection Sampling
<code>N = number of cards
M = score of the highest card
c = random (1 - N)
x = random (1 - M)

if (x <= (score of card-nr: c)) accept card!
else create new c & x and goto if-querry
</code>
That means that cards with a higher score will choosen more often.
Comment: By the way, what you are doing is essentially [inverse transform sampling](http://en.wikipedia.org/wiki/Inverse_transform_sampling).
Comment: @Rahul Narain: good to know, thx
Answer: You solution seems ok if you don't mind sorting the cards each time. Here is a different method: choose a card at random and a number at random from 0 to the max card score. Accept the chosen card if the number is at most the card score. Otherwise, repeat. This method is rejection sampling on the graph of card scores.
Comment: The algorithm in the question requires no sorting.
Comment: It does require a linear traverse through the list of cards; this method is also prone to this behavior if there are a few cards with much higher score than the others.
Comment: I have looked at the artical but don´t understand it :-( Can you try to explain the algorithm to me?
Comment: @myName: I did it in the answer. I'll try again: If there are $N$ cards, choose a random number $c$ between $1$ and $N$. Now choose a random number $x$ between $1$ and $M$, where $M$ is the max score of all cards. If $x \le \mbox{score}(c)$ then accept card $c$. Otherwise, start again. If you think about the score graph, you're choosing a point $(c,x)$ that lies below the graph.
Comment: I think i have anderstood you :-) Can you please have a look at the example above and confirm or correct it.
Comment: @myName: it's almost what I said, except that $M$ is the max score of all cards (that is, the score of the card with highest score), not the total score.
Comment: @lhf: thx, i have correct the example and i will give it a try :-)
Answer: Here's a more efficient algorithm, requiring some space. You keep a lookup table containing the card to pick for each value of your random integer. The table is init by letting cell $i$ point at card $i$. When you increase the prominence of card $j$, just add a new cell pointing to $j$.
If you are memory-savvy, then you can use the following algorithm. Put all your cards in a balanced binary tree. Each card maintains both its own prominence and the sum of prominence of it and all its descendants. To select a card, use binary search. When you increase the prominence of a card, you need to update only its ancestors. So both operations take logarithmic time.
Answer: No, that's pretty much the best way of producing that distribution. You might want to add something that slowly decreases the weight of correctly-answered flashcards or your total counts just keep inflating, which becomes a problem after a while.
Comment: i thought i multiply the score with 0,X if the answer was right and with 1,X if the answer was wrong ;-)
Comment: You're right that for that application, the slow running time doesn't matter. In some applications it might, and then you can be smarter and use a more efficient algorithm.
Answer: You probably don't want to make the initial numbers 0, or you'll never see a new card once you've had a wrong answer to something else.


tcl Uplevel set command fails when value has multiple words

Question: All,
 What i am trying to do: Proc A calls Proc B, Using uplevel command from B i am trying to set variable in proc A scope. Error occurs when the value has spaces.
proc B { } {
    set string1 "Test"
    set string2 "Test with space"
    uplevel 1 set key1 $string1
    uplevel 1 set key2 $string2
    return 0
}

proc A { } {
    set res [B]
    puts "key1 is $key1"
    puts "key2 is $key2"
}

If i comment out key2, it works fine. When add key2, it fails with following error.
wrong # args: should be "set varName ?newValue?"
    while executing
"set key2 Test with space"

Any suggestions on how to overcome this error. Appreciate your help.
Answer: uplevel 1 set key2 $string2 becomes set key1 test with space, which is why you are getting your error.
The best practice is to build up the command you want to run using [list]:
uplevel 1 [list set key2 $string2]

This will guarantee a well-formed set statement.
Comment: For the specific case of setting a variable, it's better to use `upvar`. For everything else, `list` is _great_ for constructing substitution-free commands.


Java IOException

Question: I am executing a below program which call the shell through java and I am getting the excepton please help me.
program:
import java.io.*;
import java.util.*;

public class ProcessExample {

/**
 * @param args
 */
 public static void main(String args[]) throws IOException {

       File file=new File("/opt/nilesh/fazal");

       ProcessBuilder processBuilder = new ProcessBuilder("./LicenseGen.sh --batchfile commands.txt");
       processBuilder.directory(file);
       processBuilder.redirectErrorStream(true);
       System.out.println("nilesh");
        Process process=processBuilder.start();

       InputStream is = process.getInputStream();
       InputStreamReader isr = new InputStreamReader(is);
       BufferedReader br = new BufferedReader(isr);

       String line;

       System.out.printf("Output of running %s is:",
          Arrays.toString(args));

       while ((line = br.readLine()) != null) {
         System.out.println(line);
       }

       OutputStream os=process.getOutputStream();
       OutputStreamWriter osw=new OutputStreamWriter(os);
       BufferedWriter bw=new BufferedWriter(osw);
       bw.write("create licensekey -x license-input.xml");

       while ((line = br.readLine()) != null) {
         System.out.println(line);
       }

     }

}
and the exception
Excepton:Exception in thread "main" java.io.IOException: Cannot run program "./LicenseGen.sh --batchfile commands.tx": java.io.IOException: error=2, No such file or directory
at java.lang.ProcessBuilder.start(ProcessBuilder.java:459)
at ProcessExample.main(ProcessExample.java:23)
Caused by: java.io.IOException: java.io.IOException: error=2, No such file or directory
at java.lang.UNIXProcess.<init>(UNIXProcess.java:148)
at java.lang.ProcessImpl.start(ProcessImpl.java:65)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:452)
... 1 more

Comment: Don't write new questions. Just discuss your topic on same question: http://stackoverflow.com/questions/5855768/to-run-shell-script-through-java
Answer: ProcessBuilder processBuilder =
    new ProcessBuilder("./LicenseGen.sh","--batchfile","commands.txt");

You need to pass in the command and args as separate strings or a list.
http://download.oracle.com/javase/6/docs/api/java/lang/ProcessBuilder.html

Java IOException


UIScrollView draws unused part of view

Question: I have a UIScrollView with a custom content view that uses drawRect to display its contents.
In my drawRect method I respect the passed CGRect parameter and only draw what's needed.
However, each time the drawRect is called it is passed the entire bounds of the view, even if it is several thousand pixels, and I'm worried about performance and memory use. Is there any way to make a UIScrollView limit this, or am I worrying too much over nothing?
Also, I've tried using CATiledLayer as the layer, and while this corrects the passed rect, it feels like I'm misusing the class. Also, the view still keeps all the pixels backed as far as I can tell. (Even if it doesn't draw some of them right away)
Answer: using CATiledLayer is probably the best option. I'm familiar with CATiledLayer as a concept, but never used it myself, so I'm not going to say anything about that. What I can say, is that if you subclass the UIScrollView and implement
layoutSubviews

you should be able to redraw the subviews toll-free with good performance, as long as you implement a construction using
CGRectIntersectsRect()

In which you can see if the current visible rect, in the case of a subclass
[self bounds]

intersects with the rect of the object you want to draw. if it doesn't, you can choose to ignore the object or even (if it is already on the scrollview) remove it from superview. if it does, you can place the object on superview.
again, CATiledLayer is a way better solution, but if you feel like you are misusing it, try the approach I described.
Comment: I think I can make this work. I need to break the large view up into smaller views, then have some method of reusing them (like UITableView does). The reason I didn't want to use CATiledLayer is that it automatically includes drawing in a background thread, which wasn't what I wanted.
Answer: 1.content view large than scrollview is true..
2.may be you should realize UiScrollViewDelegate's
      scrollViewDidScroll

caculate content view 's rect that should be redrawed ,not the entire bounds .

UIScrollView draws unused part of view


REST API, knowing the format for adding an element to an empty list

Question: How do you know the format to post data to a rest based api if there's no documentation?
Should the get for the collection return an example element?
I guess I'm thinking here of HATEOAS, the GET call returns links to POST to but how do you know the format for the POST?
https://martinfowler.com/articles/richardsonMaturityModel.html
Comment: Ideally, the server should return [415](https://tools.ietf.org/html/rfc7231#section-6.5.13) if the `Content-Type` of your request isn't supported. Although it's not explicitly stated in the RFC, I guess it's allowed (as not explicitly disallowed either) to have the server return the available content types, just like it states for [406](https://tools.ietf.org/html/rfc7231#section-6.5.6).

But yeah, without a proper API documentation, not sure you can guess exactly which representation of the resource you're supposed to send...
Comment: Is this question intended to be about working with existing REST-like APIs without any documentation, or about best practices on how to build such an API and properly supply that information?
Comment: The latter, building a new API where we can easily find the POST representation without resorting to documentation.
Answer:
How do you know the format to post data to a rest based api if there's no documentation?

The server should teach the client how a request should look like. In HTML, i.e., this is done via a Web form that includes all of the elements the server supports. In case of an update the fields may be automatically filled with the current values which can be modified by the user/application. As the form also contains the URI to send the data to, a client simply can trigger a request by invoking the submit button of the form.
For REST APIs a similar approach can and should be taken. Here the server might give the client a hint on the supported media-types (depending whether the media-type received by the client supports such a feature), which could also be looked up via the OPTIONS operation that informs the client about the capabilities of the endpoint such as the supported media-types or operations that can be invoked on the endpoint.

Should the get for the collection return an example element?

If the client is served with a form that explains how a request has to look like, no out-of-band information is actually required here, so this is rather unnecessary.

As you've linked the Richardsen Maturity Model (RMM): IMO this model doesn't make much sense in terms of REST. First, there is no REST adherence before level 3 anyway and even with level 3 in place you have no guarantee that you are actually conform to the REST architecture design.
This probably needs some further explanation, I guess. REST is an interaction model and not a protocol. It makes use of the properties that made the Web so successful, such as easy scaling through stateless communication, and reduction of workload due to caching of responses at intermediary servers or distribution of request among load-balanced servers. One of its aims is the decoupling of clients and servers, allowing the latter one to evolve freely without having to fear breaking the former ones. As such, a server should teach a client anything it needs to make educated choices on which "actions" to perform next.
I.e., a server will provide all of the links a client might need including some accompanying link relation names, where the relation names give the URI a named context the client can use to decide whether to invoke it or not. Such names are either standardized by IANA or need to be absolute URIs as defined in RFC 8288 - Web Linking, i.e. as Dublin Core extensions. This concept allows the server to change URIs of resources at any time. Clients respecting this concept will still be able to process their task while clients parsing and analyzing such URIs might break as a consequence.
According to Fielding

A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types. Any effort spent describing what methods to use on what URIs of interest should be entirely defined within the scope of the processing rules for a media type (and, in most cases, already defined by existing media types) (Source)

In addition to that, Fielding mentioned that clients should not regard resources to have a certain type but instead negotiate with the server about the supported representation formats understood by both applications via content-type negotiation. A client that is expecting a http://acmee.com/api/users endpoint to return a JSON representation with predefined fields may have certain issues if the response either ships with other field names or with other value types or in general with an other structure than expected. This also couples the client directly to the return value of a certain API and thus requires certain out-of-band knowledge. This is i.e. a thing completely missing in the RMM. Therefore, even if you reached level 3 in the RMM you might still fail to respect every constraint Fielding puts in place in order to adhere to the REST architecture style.
Answer: OpenAPI standard
A good way to provide standartized, discoverable information and examples about all the input/output formats of your APIs is the OpenAPI standard. It's essentially a standard for YAML specification of REST-like API formats with a supporting infrastructure (Swagger) that allows easy transformation of that specification to both human-readable documentation, valid examples of input and output data, and also to boilerplate code in many programming languages and frameworks that will send data to/from the documented API.
To get started, the Swagger page or the editor hands-on demo may be interesting.


Is there a function to know when a function was released?

Question: When developing a package, it's useful to know when a function that we want to use was introduced in R or in a dependency, so that we know whether including it will change the dependencies of our package. Is there a function that takes a function name as input and outputs the R version or the package version in which it was released?
Example:
implemented_in("list2DF()")
#> '4.0.0'

Even better if this function could work for every package and not just for base R, for example:
implemented_in("dplyr::relocate()")
#> '1.0.0'

Comment: Agreed. However, you can use it for some packages, e.g. `news(package = "dplyr")`
Comment: For current package installation only: `"relocate" %in% ls("package:dplyr")`, you might test if needed functions exist.
Comment: You might be able to construct something based on: https://stackoverflow.com/questions/10111420/figure-out-what-version-of-r-a-function-was-introduced-in
Comment: @Clemsang yes but if I want to know if a function exists, I can easily know it with the docs or Rstudio autocomplete. I wish there's something as fast to know in which version a particular function was implemented
Comment: @harre Thanks! It's not perfect because it shows every time a function was mentioned in the news (+ it won't work for packages), but I'll dig more
Comment: It would not be fast or convenient **at all** but you could scrape your way through the CRAN archives for a package, construct lists of functions, etc etc etc etc.. Not "existing function" though
Comment: @BenBolker Thanks for the info, I'm working on a package to easily display all the info on a particular function that are put in the changelog. Not what I wanted first but it'll make it easier to find when a function appears and when it changes. I'll put a link here when it's done
Answer: I made a small package for this. It doesn't extract the version in which a function was introduced but it gets all mentions of a function in the NEWS. Therefore, you can find when a function was added, but also when it was modified:
library(getnews)

getnews("paste0")
#> VERSION 2.15.0
#>  ===========
#>
#>  New function paste0(), an efficient version of paste(*,
#> sep=""), to be used in many places for more concise (and
#> slightly more efficient) code.
#>
#>
#> VERSION 4.0.1
#>  ===========
#>
#>  paste() and paste0() gain a new optional argument recycle0.
#> When set to true, zero-length arguments are recycled leading to
#> character(0) after the sep-concatenation, i.e., to the empty
#> string "" if collapse is a string and to the zero-length value
#> character(0) when collapse = NULL.
#>
#> A package whose code uses this should depend on R (>= 4.0.1).

getnews("adist")
#> VERSION 2.14.0
#>  ===========
#>
#>  New function adist() in package utils for computing 'edit'
#> (generalized Levenshtein) distances between strings.

getnews("relocate", "dplyr")
#> VERSION 1.0.0
#>  ===========
#>  New relocate() verb makes it easy to move columns around within a
#>     data frame (#4598).
#>
#>
#>
#> VERSION 1.0.3
#>  ===========
#>  relocate() can rename columns it relocates (#5569).
#>
#>

Created on 2022-07-09 by the reprex package (v2.0.1)
Link to the package
Answer: You could search through the NAMESPACE files of package versions to find
the first time a function has been exported. Two packages help with this:
pkgsearch can be used to find all CRAN versions of a contributed
package, and pacs can retrieve and read NAMESPACE files.
A simple version (without handling any edge cases) of such a search function
could look like this:
implemented_in <- function(fn, pkg) {
  history <- pkgsearch::cran_package_history(pkg)

  # Always search at least one version
  last_without <- 0
  first_with <- nrow(history) + 1

  # Binary search to avoid reading all NAMESPACE files
  while (first_with - last_without > 1) {
    next_index <- floor((last_without + first_with) / 2)

    version <- history[next_index, ]$Version
    ns <- pacs::pac_namespace(pkg, version = version)

    if (fn %in% ns$exports) {
      first_with <- next_index
    } else {
      last_without <- next_index
    }
  }

  history[first_with, ]$Version
}

implemented_in("relocate", "dplyr")
#> [1] "1.0.0"

However, this approach doesn't work for base R functions.
Answer: Actually, there's a package for that: apicheck. It's slower than printing the news, but probably more robust and tested (and it has much more functionalities as well):
library(apicheck) # hughjonesd/apicheck

when_fun_exists("base::list2DF", report = "brief")
#> [1] "4.0.0"

Created on 2022-07-26 by the reprex package (v2.0.1)


Rewrite with region in URL

Question: I'm trying to rewrite a url containing a region and language code. It's hard to explain, so I'll just demonstrate
I'd like https://www.example.com/en-us/get-started to actually request https://www.example.com/get-started?region=en-us
I also want https://www.example.com/get-started to work as well. I'm using another regex to rewrite requests. This is what I'm using at the moment to do that:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R]

I've tried other regex's to include the region code, but it doesn't like to play nice with the above regex.
Answer: After fiddling with the regex, I found that this works:
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -l
RewriteRule ^ - [L]
RewriteRule ^([a-z-]+)\/(.*)$ /$2?region=$1 [L,QSA]

Rewrite with region in URL


Need help centering this navigation menu css

Question: I need help centering this navigation menu. I am fairly new to css and need to finish a school project

<title>Website</title>
<link rel="icon" " href="favicon.ico" />

Home

News

Contact

About

Answer: Just add text-align:center to your
. This will center all display:inline and display:inline-block elements.
jsFiddle
ul.menu {
    text-align:center;
}

Answer: Assuming you want the text to be centered in the page, not just the inline music, just add
body {
  text-align: center;
}

wrap the ul in a div if you want, and center that instead.
Answer:

<title>Website</title>
<link rel="icon" " href="favicon.ico" />

Home

News

Contact

About

Answer: if you want your text centered horizontally, then yes 'text-align: center' should do the trick.
However, if you want all of your list items to display beside each other in a line, then you will need to specify:
li {
    display: inline-block;
}


Show that any almost complex structure is induced by at most one complex structure.

Question:
Show that any almost complex structure is induced by at most one complex structure.

Suppose $X$ is a complex manifold of dimension $n$ and $M$ is the underlying $2n$ dimensional real manifold.
If $J_1$ and $J_2$ are two almost complex structures induced by the same complex structure on $X$ I would want to show that $J_1 = J_2$.
I know that any almost complex structure induced by an complex structure is integrable so for both $J_1$ and $J_2$ we have that the Nijenhuis tensor $$N(X,Y)=[X,Y]+J([JX,Y] + [X,JY]) - [JX,JY]$$ vanishes. I'm wondering on whether this is enough  to conclude that $J_1=J_2$?
Comment: But that is not what you want to prove. That would prove that every complex structure induces a unique almost complex structure (do you think that is true?). But you want to show that if two complex manifolds induce the same almost complex structure, then the complex manifolds are isomorphic. This is a different statement.
Comment: Ah I had some misunderstanding here. So is the correct statement to consider two complex manifolds $X_1$ and $X_2$ with the _same_ underlying real manifold $M$ such that $X_1$ and $X_2$ induce almost complex structures $J_1$, $J_2$ with $J_1 = J_2$ and try to show that $X_1 \cong X_2$? @QuaereVerum
Comment: Yes, that's what would prove the statement in the title of this post.
Comment: Thanks for clarifying this. I couldn't find a definition for a complex structure, but I assume it is just an holomorphic atlas $\{\varphi_\alpha : U_\alpha \to \mathbb{C}^n \}$ so in light of the problem I could consider the two complex atlases $\{\psi_\beta : V_\beta \to \mathbb{C}^n \}$, $\{\varphi_\alpha : U_\alpha \to \mathbb{C}^n \}$ and it would be sufficient to show that these two give the same maximal atlas? @QuaereVerum
Comment: What you want to show is: given two complex manifolds with the same underlying smooth manifold, if the bundle map $J:TM\to TM$ that they induce is the same, then the complex manifolds are isomorphic. This bundle map is defined in local holomorphic coordinates $(z^j=x^j+iy^j)$ by $J(\frac{\partial}{\partial x^j})=\frac{\partial}{\partial y^j}$ and $J(\frac{\partial}{\partial y^j})=-\frac{\partial}{\partial x^j}$.
Comment: @QuaereVerum I tried to think about what you said, but I can't find any relation of $J$ to a biholomorphic map $F : X_1 \to X_2$ which I would need to show that the manifolds are iso.
Answer: To address the problem in the title, rather than the problem you set up in the subsequent text: let $\mathcal{X}_1$ and $\mathcal{X}_2$ denote two complex structures on an underlying manifold $X$. There are corresponding bundle maps $J_1,J_2:TX\to TX$. Suppose that $J_1=J_2$, or (more generally) that $f^*J_1=J_2$ for some diffeomorphism $f:X\to X$. Then we must show that $\mathcal{X}_1\cong\mathcal{X}_2$, as complex manifolds. This amounts to checking that $f$ (which in the simplest case is $f=\text{id}$) is a biholomorphism. Now prove the following:
Lemma. Let $f:\mathcal{X}\to\mathcal{Y}$ be a smooth map between complex manifolds with induced almost complex structures $J_X$ and $J_Y$. Then $f$ is holomorphic if and only if $df\circ J_X=J_Y\circ df$.
Using the lemma, you can now show that the assumption that $f^*J_1=J_2$ implies that $f$ must be a biholomorphism, and therefore $\mathcal{X}_1\cong\mathcal{X}_2$.
Comment: Isn't $f:\mathcal{X}\to\mathcal{Y}$ actually the identity here if the manifolds have the same underlying smooth manifold? Or at least we could pick it as a candidate for the biholomorphism. @quaere-verum
Comment: As noted, in this case (which is the simplest case), $f$ is indeed the identity. More generally, it can be a self-diffeomorphism, and this case is also import to consider if one wants to construct the moduli space of complex structures on $X$. However, it is important to be aware of the fact that the identity map on $X$ is **NOT** by default a biholomorphism. Whether or not it is, depends on the given complex structures.


Can every ideal have a minimal generating set?

Question:
Let $I$ be an ideal of commutative ring $A$ with unity. Does $I$ have a minimal generating set?

At times, I am able to compute what they are for specific example, but it seems like it is true in general with some existence proof (I guess it is true for non-commutative rings with some adjectives such as "left" or "right").
I have thought about Zorn's lemma but generating sets are very likely to be incomparable (nor the existence of lower bound of each chain was not clear) and the intersection of all generating sets may be too small to generate an ideal. Sounds not too difficult, but it seems not clear what to do.
Answer: Consider the ring: $$\mathbb Q\left[\{x^{1/n}\}_{n\in\mathbb Z^+}\right]$$
The maximal ideal consisting of the expressions with constant term zero, has no minimal set of generators - you can always remove any element of a set of generators and still have a set of generators.
Proving this is not entirely trivial. It is clear that the obvious set of generators does not have a minimal generating subset, so anything Zorn-like will fail.
Answer: Here is a slight modification of Thomas's example that is easy to prove.  Let $R$ be a quasilocal ring with a nonzero idempotent maximal ideal $M$, e.g., the ring in Thomas's solution localized at his maximal ideal.  Then $M$ has no minimal generating subset.  Suppose to the contrary that it did have such a subset $\{a_i\}$.  Then we have an expression $a_j = \sum_i x_ia_i$ with each $x_i \in M$.  Solving for $a_j$ (note that $1-x_j$ is a unit), we see that it can be written as an $R$-linear combination of the other $a_i$'s, a contradiction.
Comment: More generally, by the same argument, any nonzero ideal I of a ring R with I = J(R)I does not have a minimal generating set.
Comment: you should mention in your hypothesis that $M$ is not principal .... if $M$ is principal, then you have no contradiction ... btw, do you know of any other example of such a ring other than the example in Thomas's solution ?
Comment: Actually the hypotheses imply that $M$ is not finitely generated.  (By Nakayama's Lemma or the argument of the proof, a quasilocal ring cannot have any nonzero idempotent finitely generated ideals.)
Comment: I follow the convention of using "quasilocal" to mean the ring has a unique maximal ideal, without implying anything about whether the ring is Noetherian or not.  I personally use "local" to mean "quasilocal plus Noetherian".
Comment: The method of constructing examples by localizing monoid domains seems to be the easiest to describe and prove, but certainly that's not the only way to get a quasilocal ring with an idempotent maximal ideal.  (Note that my example above is technically a slight modification of Thomas's idea.)  Here is another pretty similar method.  Consider $\mathbb{Q}[[\mathbb{Q}^+]]$, a "generalized power series ring" in the sense of Ribenboim.  It is quasilocal with an idempotent maximal ideal.  Or pick any valuation domain with a non-principal maximal ideal.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/89310/discussion-between-jason-juett-and-user521337).


Cross-validation misuse (reporting performance for the best hyperparameter value)

Question: Recently I have come across a paper that proposes using a k-NN classifier on an specific dataset. The authors used all the data samples available to perform k-fold cross validation for different k values and report cross validation results of the best hyperparameter configuration.
To my knowledge, this result is biased, and they should have retained a separate test set to obtain an accuracy estimate on samples not used to perform hyperparameter optimization.
Am I right? Can you provide some references (preferably research papers) that describe this misuse of cross validation?
Comment: Note that instead of a separate test set one can use so-called *nested cross-validation*. If you search for this term on this site, you will find a lot of discussions. Look in particular for [the answers by @DikranMarsupial](http://stats.stackexchange.com/search?tab=votes&q=user%3a887%20nested) who is one of the authors of the second paper cited in the accepted answer.
Answer: Yes, there are issues with reporting only k-fold CV results. You could use e.g. the following three publications for your purpose (though there are more out there, of course) to point people towards the right direction:

Varma & Simon (2006). "Bias in error estimation when using cross-validation for model selection." BMC Bioinformatics, 7: 91
Cawley & Talbot (2010). "On Over-fitting in Model Selection and Subsequent Selection Bias in Performance Evaluation." Journal of Machine Learning Research, 11: 2079-2107
Bengio & Grandvalet (2004). "No Unbiased Estimator of the Variance of $K$-Fold Cross-Validation." Journal of Machine Learning Research, 5: 1089–1105

I personally like those because they try to state the issues more in plain English than in Math.
Comment: More precisely, the issue is not reporting cross validation results, but reporting performance estimates that have been part of the selection/optimization process.
Comment: Also note that the Bengio & Grandvalet paper is somewhat less relevant if the issue here is the performance of a specific model trained on a particular data set - they discuss performance for the same trainig algorithm applied to new data sets from the same population (which needs to include variance between different data sets of the same size sampled from the same source - which is not an issue if we're talking about the prediction performance of a model trained on a specific data set).
Comment: @cbeleites Correctly spotted: in my first draft of the answer I accidentally picked the third reference instead of the second one, but later didn't want to remove any information from the already accepted answer anymore - which is why I instead added the second in between (see versions of answer). Nevertheless, I think the question was mainly around the reported error, and those papers point out some of the things that one can do wrong with CV in this regard very well IMHO.


Somar horas de todos funcionarios durante o mes

Question: Estou desenvolvendo um sistema em PHP e MySQL onde uma pessoa faz algumas horas extras durante o mês.
pessoa = id - 5 - int /nome - 15 - varchar /

boletins = id -5 - int / idpessoa - 5 - int / horaextra - time / data - date /

Gostaria de gerar um relatório somando a hora extra de todos durante todo o mês, mas não estou conseguindo.
SELECT time_format( SEC_TO_TIME( SUM( TIME_TO_SEC( horaextra ) ) ),'%H:%i:%s') AS horaextra FROM boletins where idpessoa = (numero do id, mas queria listar todos com a hora somada do mes inteiro)

Comment: Utilize a cláusula GROUP BY idpessoa e a função de agregação SUM e como condição o mês/ano desejado.
Answer: Tente:
SELECT pessoa.nome, TIME_FORMAT(SEC_TO_TIME(SUM(TIME_TO_SEC(boletins.horaextra))), '%H:%i:%s') AS horaextra
FROM pessoa INNER JOIN boletins ON (pessoa.id = boletins.idpessoa)
WHERE MONTH(boletins.data) = mês_desejado AND YEAR(boletins.data) = ano_desejado
GROUP BY pessoa.nome;

ou algo parecido, de acordo com o SGBD utilizado.


Access Elements in XSD to C# Class With xs:Choice

Question: I have read several dozen articles on the xs:Choice XSD element but cant wrap my head around how we are supposed to use the resulting class. Here is the XSD element and the class conversion from Xsd2Code++:
<xs:element name="VariantRoads">
    <xs:complexType>
        <xs:choice minOccurs="0" maxOccurs="unbounded">
            <xs:element ref="Variant" minOccurs="0"/>
            <xs:element ref="DepVariant"/>
            <xs:element ref="ArrVariant"/>
        </xs:choice>
    </xs:complexType>
</xs:element>

[XmlArrayItemAttribute("ArrVariant", typeof(ArrVariantType), IsNullable = false)]
[XmlArrayItemAttribute("DepVariant", typeof(DepVariantType), IsNullable = false)]
[XmlArrayItemAttribute("Variant", typeof(VariantType), IsNullable = false)]
public object[] VariantRoads
{
    get
    {
        return _variantRoads;
    }
    set
    {
        _variantRoads = value;
    }
}

So that compiles and now I am ready to start populating my main class.
BaseRoadType brd = new BaseRoadType();
brd.VariantRoads = = new object[3]; // not sure how to initialize
brd.VariantRoads[0] = ??? // how do I assign my property

I am just really lost on how I should populate the VariantRoads class and then read it later and determine what choice was made.
Answer: The XmlArrayItemAttribute attributes at the top of the public object[] VariantRoads declaration gives you type hints that are acceptable element values of the array.
An xs:choice is meant to model just one of multiple possibilities - but there's also the maxOccurs="unbounded" attribute set on the choice definition, which turns the type declaration to an object array object[].
The choice definition reads in plain English as basically 'zero or many choices of ("ArrVariant", "DepVariant", "Variant") elements'
So this is acceptable:
BaseRoadType brd = new BaseRoadType();
brd.VariantRoads = new object[1] {
  new ArrVariant()
};

Andt this is too:
brd.VariantRoads = new object[3] {
  new Variant(), new ArrVariant(), new DepVariant(),
};

And also multiple instances of the same type:
brd.VariantRoads = new object[2] {
  new ArrVariant(), new ArrVariant(),
};

Because each element in the array represents your 'choice' of the possible 3, the maxOccurs="unbounded" also means you can have more than one choice (hence the array).
To take it further, if the choice definition didn't have the maxOccurs="unbounded", the generated code would probably look like this:
[XmlArrayItemAttribute("ArrVariant", typeof(ArrVariantType), IsNullable = false)]
[XmlArrayItemAttribute("DepVariant", typeof(DepVariantType), IsNullable = false)]
[XmlArrayItemAttribute("Variant", typeof(VariantType), IsNullable = false)]
public object VariantRoad { get; set; }

Meaning you could only have one choice.
Comment: Ahhhhhhhh I think I get it now. I wasn't even looking at other parts of the element. Thanks for the explanation.
Comment: Glad to help. Another thing I forgot to mention is that the choice also has `minOccurs="0"`, which means that this too is also valid:
`brd.VariantRoads = Array.Empty();`


Unexpected token - React

Question: Estou tentando executar um projeto, porém o mesmo está exibindo um erro no console relacionado à uma função que tenho, o erro é o seguinte:
"63:25  error  Parsing error: Unexpected token, expected (
 function toggleDrawer = (open) => () => {
^
state={"

Meu projeto é esse:
import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import { withStyles } from 'material-ui/styles';
import AppBar from 'material-ui/AppBar';
import Drawer from 'material-ui/Drawer';
import Button from 'material-ui/Button';
import IconButton from 'material-ui/IconButton';
import Toolbar from 'material-ui/Toolbar';
import MenuIcon from 'material-ui-icons/Menu';
import TextField from 'material-ui/TextField';
import Paper from 'material-ui/Paper';
import Grid from 'material-ui/Grid';
import '../assets/scss/main.scss';
import img from '../assets/images/react.png';

const styles = theme => ({
  root: {
    width: '100%',
  },
  flex: {
    flex: 1,
  },
  menuButton: {
    marginLeft: -12,
    marginRight: 20,
  },
  inputProps: {
    step: 300,
  },
  button: {
    margin: theme.spacing.unit,
  },
  input: {
    display: 'none',
  },
  paper: {
    padding: 50,
    textAlign: 'center',
    border: '5px solid black',
    width: '100%',
  },
  paper1: {
    backgroundColor: 'red',
    marginTop: '13%',
  },
  img: {
    width: '45%',
  },
  appbar: {
    marginLeft: '-20.20%',
    marginTop: '-20%',
    width: '139.99%',
  },
});

function ButtonAppBar(props) {
  const { classes } = props;
  const state = {
    inputs: {},
  };

  function toggleDrawer = (open) => () => {

      state={

        open:false,
      };
    this.setState({
      open,
    });
  };

  const updateInputValue = (evt) => {
    state.inputs[evt.target.name] = evt.target.value;
    console.log(state.inputs);
  };

  const handleSubmit = (event) => {
    // console.log('handleSubmit', username, password);
    if (!event.target.checkValidity()) {
      console.log({ displayErrors: true });
    }
    event.stopPropagation();
    event.preventDefault();
    return 0;
  };
  return (

      <Grid container spacing={8} alignItems="center" justify="center">
        <Paper className={classes.paper}>
          <AppBar position="static" className={classes.appbar}>
            <Toolbar>
              <IconButton onClick={this.toggleDrawer(true)} className={classes.menuButton} color="contrast" aria-label="Menu">
              <Drawer open={this.state.open} onClose={this.toggleDrawer('open', false)}>
              onClick={this.toggleDrawer('open', false)}
              </Drawer>
                <MenuIcon />
              </IconButton>
            </Toolbar>
          </AppBar>

          <form onSubmit={handleSubmit} noValidate>
            <TextField id="email" type="email" label="Usuário" className={classes.user} value={state.inputs.username} onChange={evt => updateInputValue(evt)} />

            <TextField id="password" type="password" label="Senha" className={classes.senha} value={state.inputs.password} onChange={evt => updateInputValue(evt)} />
            <AppBar position="static" className={classes.paper1}>
              <Link to="/Orders">
                <Button type="submit" color="contrast">Login</Button>
              </Link>
            </AppBar>
          </form>
        </Paper>
      </Grid>

  );
}

ButtonAppBar.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(ButtonAppBar);

Answer: Você está usando um componente funcional sem estado ("Stateless functional component"), definido assim:
function MeuComponente(props) {
  return (
    {/* Template aqui */}
  );
}

Esse componente não mantém estado. Usando coisas como this.setState não faz sentido. Outra coisa também é que seu método toggleDrawer está retornando uma função. Não sei se você realmente quis fazer isso.
Você deve usar um componente de classe se quiser manter estado, como esse:
class MeuComponente extends React.Component {
  render() {
    return (
      {/* Template aqui */}
    );
  }
}

Documentação: https://reactjs.org/docs/state-and-lifecycle.html#converting-a-function-to-a-class
Answer: Incrementando a resposta do @nbkhope, após você fazer as modificações necessárias para se utilizar state, seu problema irá persistir, devido ao erro de síntaxe. Arrow functions possui síntaxe mais curta.
O correto para sua função seria:
toggleDrawer = (open) => {
    this.setState({
        open: open
    });
};

Você também pode fazer assim:
toggleDrawer(open) {
    this.setState({
        open: open
    });
};

Vale lembrar que ao fazer como o código acima, você devera fazer um bind do método toggleDrawer para poder utilizar o this dentro dele.
...
constructor(props) {
    super(props);
    this.state = {
        open: false
    };
    this.toggleDrawer = this.toggleDrawer.bind(this);
}
...

Exemplo funcionando no stackblitz.

Leitura recomendada:

Arrow functions
Por quê é necessário usar bind quando se trabalha com ES6 e ReactJS?

Unexpected token - React


Can we customize user login block in Hybridauth module

Question: Can we customize user login block in Hybridauth module in our custom theme?
Like writing block-hybridauth-hybridauth.tpl.php.
I need to customize the way of output. Instead of the Sign In icon which gives the overlay of enabled social accounts list, I need some text to replace it and add div and content along with it? Is it possible?
Answer: There are two template files used
hybridauth_widget.tpl.php
This one is used to create the list of the icons. It gets a variable called $providers which has all the enabled providers.
hybridauth_provider_icon.tpl.php
This one is used to print the individual icons. Two variables are used here. $provider_name is the name of the provider like facebook twitter etc. and $icon_pack_classes which has the current selected icon pack classes.
These template files can be found in with in the templates folder of the module.
You can make copy of the same in your theme and make the required changes.


Prelude to Cauchy-Schwarz, Quadratic proof.

Question: I have a problem in trying to prove the following observation: "Show that if $ a,b,c \in \mathbb{R} $ are such that for all $ \lambda \in \mathbb{R} $, $a\lambda^2 + b\lambda +c \geq 0 $ then $ b^2 - 4ac \leq 0 $." I know that this is elementary since is the graph of a parabola possibly above the $\lambda$ axis. But when I try to do an inequality approach I cannot seem to see it.
My work: Since it works for any $ \lambda $ I choose $ \lambda = - \dfrac{b}{2a} $ and I get:
$$ \dfrac{a \cdot b^2}{4\cdot a^2} - \dfrac{b^2}{2a} + c \geq 0 $$
After some algebra I arrive at:
$$ \dfrac{-b^2 + 4ac}{4a} \geq 0 $$
Which clearly has my desired conclusion, but i cannot jump since $ 4a $ could be negative. Can anyone provide a proof that $ 4a > 0 $. Thanks!
Comment: If $a$ were negative, what sign would $a\lambda^2 +b\lambda +c$ have for $\lvert\lambda\rvert$ large, regardless of $b$ and $c$?
Comment: @DavidCardozo I think it should be $\lambda= -\frac{b}{2a}$ that you substitute in.
Comment: @DanielFischer Oh thank you Daniel, it is an excelent hint thanks.
Comment: If $a \geq 0$ take one $\lambda$. If $a < 0 $ take another one..
Answer: Thanks to @DanielFischer.
Observation: $4a$ is positive
Proof: It will suffice to show that a is positive. Assume the contrary, that a is negative, also assume that $a \lambda^2 + b \lambda + c \geq 0 $, now choose $ \lambda = -\dfrac{c}{b} $. so that, $a \cdot {\dfrac{c^2}{b^2}} -c + c \geq 0$.
this is equivalent to:
$a \cdot {\dfrac{c^2}{b^2}} \geq 0$. But this contradicts the fact that $ a < 0$. So our assumption is wrong a must be a possitive number.
Comment: Using the hint $|\lambda|\to \infty$ is a better approach, as your argument would fail when $b=0$.


Relative minor key change in chord progression

Question: I'm writing a song in F Major key.
I have a chord progression that goes Like
4/4
C7 - C#dim - Dm - Dm
( V7 - V#dim - Vi - Vi )
After this four measures, I wanted to change key to Dm for a moment.
So thinking the last measure's Dm (Vi) as a tonic (i) for the next four measure,
I  went
A7 - A#dim - Bm7-5 - Bm7-5
which is the same ( V7 - V#dim - Vi - Vi ) in Dm key.
But I start to think, is ( A7 - A#dim - Bm7-5 - Bm7-5 ) really ( V7 - V#dim - Vi - Vi ) in Dm key ?
or am I still in F Major key and the actual chord progression is
V7/VI - III#dim - iv#m7-5 - iv#m7-5
what are the details that establish a key change ?
Comment: @AlexBasson no what I'm asking is very simple. did I really went to Dm key when I went to the A7 part
Comment: I'm voting to close because, as written, this question is generating some confusion as to what the OP is really asking.
Comment: @HyunYooPark What you're asking is very simple only if you believe there's some objectively true answer possible. But there isn't. Did you intend to modulate to D minor? Or did you just write down chords that sounded good to you and then try to figure out what it meant later? We can't answer that for you. And either way, your listeners are going to hear the music on its own and make of it what they will for themselves, independent of your intent.
Comment: Is this school homework or something? Why do you care about what the key "really" is? Who's going to act upon your key classification?
Comment: @piiperi no I don't have any teachers. because I like to know everything going on in my music
Comment: @HyunYooPark If Dm feels to you like the tonic chord at that point, then you went to Dm. Try it to find out how you feel. It's a practical, not theoretical exercise. Note that _how_ you play the chords can affect the result.
Comment: I vtc as the question is based on confusing ideas.
Answer: It is subjective. Your feelings define it.
https://en.wikipedia.org/wiki/Key_(music)

... a tonic or tonic chord, which provides a subjective sense of
  arrival and rest ...

If you feel that the home base moved, then you feel that the key changed. Someone else might feel differently.
If your real question is, how to create those feelings, i.e. how to establish a key, I think there are questions and answers about that already. Use a proper cadence or something. If establishing Dm is what you're trying to do, then why do you move the bass to B instead of D, and via an A#dim instead of C#dim? If you want your audience to think about an elephant, why say "excavator". You might still be able to make it sound clearly like Dm if you write a strong melody line that disregards the obfuscated chords and overlays something that's strongly in Dm.
Comment: Isn't A#o the same as C#o, maybe with a different bass note, depending how it gets written? Although Go and Eo probably fit the key better anyway.
Comment: @Tim it's the bass note I meant. A - C# - D bass movement feels more effective for establishing a Dm tonic than A - A# - D. My opinion only though. But the OP wasn't really asking how to establish a key ... he is asking for others to tell him what the key is in a chord progression he wrote.
Answer: Every modulation is a key change. Usually a modulation will have some close relationship to the previous key, like C>Dm, or C>F, or C>G, involving at least a common note or chord,  whereas a key change could be a move a semitone or a tone up.
It's not always necessary to change key signature for a modulation - which may even re-modulate back to the original key - but for a complete key change it's worthwhile changing the key sig.
Quite often a piece will drift in and out of, say, C and Am. Certainly more of a mod. than a key change, but not really worth considering as either, unless one wants to be totally academic. It's just what music sometimes does.
Comment: @HyunYooPark I think what we're not getting is that you seem to be asking us to explain to you what your musical intent is. You've written down some chord progressions and then asked us "Is my intent to be in D minor or F major?" But of course this isn't a question we can answer—no one can say what your intent is but you.
Comment: @AlexBasson to be fair, I think you're actually giving a good answer to the question! IOW the answer is: it's a question of intention and perception, not definition.
Comment: O.k. it's established you're not talking about notation. What *are* you talking about?
Comment: I'm not talking about notations.
Comment: I already wrote it detail as possible in my question. can you tell me what is your not getting ?
Answer: Nothing definitively indicates a key change in the kind of situation you are talking about.
Of course it's true that there are many 'textbook' examples of key changes, for example where the change is prepared and fulfilled in a certain way. But in general, there isn't really any one particular thing - or even group of things - that you can point to that 'defines' a key change, and likewise there isn't really anything that defines the 'momentary' key of a piece in the first place.
The nearest thing you will get to a definition of the overall key of the piece will be a combination of key signature, and an instruction as to the key either in the title of the piece, or elsewhere in notation. If there's no such instruction, then at the very least you will have to make your own judgement as to whether the key is major or the relative minor, and while there are many cases where most people would agree, there are some ambiguous cases too.
And of course, you have the same difficulty when discussing key changes, especially (as in your case) between relative minor and major keys. What one person hears as a key change, another might simply hear as a movement to the vi chord.

But I start to think, is ( A7 - A#dim - Bm7-5 - Bm7-5 ) really ( V7 - V#dim - Vi - Vi ) in Dm key ?
  or am I still in F Major key and the actual chord progression is
  V7/VI - III#dim - iv#m7-5 - iv#m7-5 ..?

It's up to you, as the person analysing the piece, to decide which perspective is more useful.
Answer: As you change from F (C7 is the dominant) to dm this is a false cadence. To establish this new key Dm I propose a normal cadence in the new key Dm, to make the moduation perfect or unambiguous.
Comment: going to Dm is not my goal. my attention was doing Parallel structure with ( V7 - V#dim - Vi - Vi ) on dm key
Answer: F major and D minor are so closely related as to be almost the same key.  I'm inclined to describe what you're doing as simply sequential imitation within a single key.
Does it make any difference, other that in what labels you put on the chords?


Tangent Line to the curve that is Parallel to the line part $2$

Question: Find the equation of the tangent  line to the curve $y=x^2-1$ parallel to  the line $2x+y=6$.
Hello, can someone can help me with this? Thank you. ;)
Answer: HINT:
The slope of the line $2x+y=6$ is $-2$.  Two lines are parallel if they have the same slope.  What construction in calculus gives you the slope of a tangent line to a point on the graph?
Answer: Since the slope of line $2x+y=6$ is $-2$, we left to find the derivative of $y=x^2-1$, which is $y'=2x$, and put $-2$ instead of $y'$(why we do that?).
$$-2=2x$$
$$x=-1$$
Substituting $x=-1$ into  $y=x^2-1$ we get $y=0$, and we have a point $(-1,0)$ with a slope $m=-2$. Can you proceed from here?
Comment: Hey, thank you for responding. I am stuck in the point (-1,0), and i really dont know  what to do next.
Comment: Use the line equation formula: $y-y_1=m(x-x_1)$ and put $x_1=-1$, $y_1=0$ and $m=-2$. What you get?
Comment: Ill comment my answer in few minutes
Comment: Is the answer y= 2x + 2 ?
Comment: No, that is not the answer. Two lines are parallel if they have the same slope. But your equation is with slope $2$.
Comment: Huh ? What do you mean ?  I thought that the slope is -2.
Comment: Substitute again.
Comment: Sorry i cant understand coz this is new to me
Comment: The line equation is: $y-0=-2(x-(-1))$ or...
$y=-2(x+1)=-2x-2$


Disable click on Progress bar

Question: i am trying to disable the touch while running progress bar on screen.Below code(getwindow) is not working. can anyone please help.
Using:
@Override
        protected void onPreExecute() {
            dialog.setMessage("Doing something, please wait.");
            dialog.show();
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                    WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
        }

Comment: do you mean that you want to dispose the progress bar when the background task finishes, and not when the user clicks outside the progress bar dialog?
Comment: yes, while progress bar is running i was to stop user touch. the problem is, progress bar is gone if i am touching anywhere on the screen
Answer: seems like you want to set dialog not Cancelable
just set property of dialog
dialog.setCancelable(false);

Answer: use dialog.setCancelable(false);
please refer to the following answer:

How to avoid dismissing my progress dialog when the user touches the screen?

Disable click on Progress bar


Quotient Ring and finite fields

Question: How is a quotient ring $\mathbb Z/p^e\mathbb Z$ (where p is prime and $e>2$) different from a finite field $\mathbb F_{p^e}$? When they are both rings, have the same elements?
I thought a finite field p is generated by $\mathbb Z/p\mathbb Z$?
Comment: The group structure is different. All $\Bbb F_{p^n}$ are vector spaces over $\Bbb F_p$, so they are isomorphic to

$$\left(\Bbb F_p\right)^n\cong\left(\Bbb Z/p\Bbb Z\right)^n$$

as groups
Answer: The ring $\mathbb Z/p^e\mathbb Z$ with $e\ge2$ is not a field because it has divisors of zero. Specifically, the product of $p+p^e\mathbb Z$ and $p^{e-1}+p^e\mathbb Z$ is zero. The additive group of $\mathbb F_{p^e}$ is isomorphic to $(\mathbb Z/p\mathbb Z)^e$, whereas that of $\mathbb Z/p^e\mathbb Z$ is cyclic.
Comment: Ok that make sense, thank you very much

Quotient Ring and finite fields


Postfix rewrite sender: why doesn't this work

Question: I have server A with an IP address only and a dummy FQDN (on the basis all machines should have a FQDN): pants.net.invalid.  All mail is relayed through another server elsewhere, which works fine.
On server A, Postfix rewrites the sender address with smtp_generic_maps = hash:/etc/postfix/generic.  According to the Rewrite manual at http://www.postfix.org/ADDRESS_REWRITING_README.html#remote, this should rewrite all outgoing external mail's Sender address:
$ cat /etc/postfix/generic
@pants.net.invalid     firstname.lastname@example.com

but it does not.  postmap -q email@example.com returns nothing.
This works:
firstname.lastname@example.com     email@example.com

It seems as though it is doing regex matching even though I specify type hash:. Clearly I am misunderstanding the manual.
I don't want to use regex or pcre expressions because there are only a couple of users (root and two others) and I don't want the overhead.
I can specify the users exactly and it works.  But, I would like to know what I am misunderstanding for future reference.
Thanks.
Answer: It works. According to the manual http://www.postfix.org/generic.5.html
But your postmap command is faulty. It should read:
postmap -q firstname.lastname@example.com hash:/etc/postfix/generic


Finding closed form of $u_{n+1} =2u_n - n^2$

Question:
Find a closed form formula for $u_n$ where $u_{n+1} =2u_n - n^2$ and $u_0=a$

I'm not totally sure how closed form expressions are derived of a given sequence. I tried generating functions which goes like this: $\begin{aligned}
\sum_{n=0}^{\infty} u_n x_0^n & =u_0+\sum_{n=0}^{\infty} u_{n+1} x^{n+1} \\
& =a+\sum_{n=0}^{\infty}\left(2 u_n-n^2\right) x^{n+1} \\
& =a+2 \sum_{n=0}^{\infty} u_n x^{n+1}-\sum_{n=0}^{\infty} n^2 x^{n+1} \\
& =a+2 x \cdot \sum_{n=0}^{\infty} u_n x^n-\sum_{n=0}^{\infty} n^2 x^{n+1}
\end{aligned}$ Im stuck here. Please help.
Comment: If I did the algebra correctly, $u = [a, 2a, 4a-1, 8a-6, 16a-21, 32a-63, 64a-189, \dots]$.  Notice a pattern?
Comment: @Dan the pattern seems to be $u_n= 2^{n-1}a - \text{something}$. That something seems to be tripling in the last three terms, but doesn't follow that in the starting terms
Answer: This is an inhomogeneous linear equation, so the general solution is of the form (one particular solution) + (general solution of homogeneous equation).  The initial condition can then be used to choose which solution of the homogeneous equation to take.
For the particular solution, try a polynomial of degree $2$.  For the homogeneous equation, try an exponential.
Comment: I don't understand what do you mean by "(one particular solution) + (general solution of homogeneous equation)". 1. What is one particular solution (like do you mean a term of the sequence?). 2. What is general solution of homogeneous equation? Can you please elaborate on your answer? Thanks
Comment: @zaemon_23: Oversimplifying things a bit, the solution to $u_{n+1} = 2u_n$ is an exponential $u_n = 2^na$, and the solution to $u_{n+1} = -n^2$ is a polynomial, so try assuming that the solution is an exponential *plus* a polynomial.
Comment: @Dan so we need to find these two closed forms individually right? The first one is $2^n$, and the second one us already well defined to be $-n^2$, now do we combine these two as Robert Israel said?
Answer: $$u_{n+1} = 2u_n - n^2$$
Since $(n + 1)^2 = n^2 + 2n + 1$, the relevant non recursive terms are $n^2$, $n$, and $1$.
$$u_{n} = v_{n} + An^2 + Bn + C$$
$$v_{n+1} + A(n+1)^2 + B(n+1) + C = 2v_n + 2An^2 + 2Bn + 2C - n^2$$
$$v_{n+1}-2v_n + (1-A)n^2 + (2A-B)n + (A + B - C) = 0$$
So choose
$$1 - A = 0 \implies A = 1$$
$$2A - B = 0 \implies B=2$$
$$A+B-C = 0 \implies C=3$$
Now all you have to do is solve $v_{n + 1} = 2v_{n}$.
Answer: For $|x|<1$, let $f(x) = \displaystyle\sum_{n\ge0} x^n = \frac1{1-x}$, and let $U(x)$ denote the generating function for $u_n$. Using the GF method, you should end up with
$$\begin{align*}
\sum_{n\ge0} u_{n+1} x^n &= \sum_{n\ge0} \left(2 u_n - n^2\right) x^n \\
\sum_{n\ge1} u_n x^{n-1} &= 2 \sum_{n\ge0} u_n x^n - \sum_{n\ge0} n^2 x^n \\
\implies \frac{U(x) - a}x &= 2 U(x) - \left(x^2 f''(x) + x f'(x)\right)
\end{align*}$$
Solving for $U(x)$ and expanding into partial fractions right away yields
$$\begin{align*}
U(x) &= \frac{a - x f'(x) - x^2 f''(x)}{\frac1x-2} \\
&= -\frac a2 + \frac{a-6}{2(1-2x)} + \frac2{1-x} - \frac1{(1-x)^2} + \frac2{(1-x)^3} \\
&= -\frac a2 + \left(\frac a2-3\right) f(2x) + 2f(x) - f'(x) + f''(x)
\end{align*}$$
Can you wrap up from here?
Comment: as I posted, I got this except for the last line. I'm not quite sure how would I proceed though. I'm pretty sure we have to solve for $U(x)$ but how
Comment: Solving for $U(x)$ is trivial, it's a linear equation. The harder part is expressing $U(x)$ as a series in order to identify $u_n$.
Comment: FWIW Expanding the partial fractions as a power series, allows you to calculate $u_n$.


Login using REST request gives 404

Question: This is so simple login request but cannot figure out why I am getting such error message when trying to login using Postman.
I use url http://localhost:8080/user/login?_format=json and input in the header Content-Type:application/json and I have in my body {"name":"user", "pass":"pass"} but I am getting this error message

{     "message": "The \"user\" parameter was not converted for the path
  \"/user/{user}\" (route name: \"rest.entity.user.GET\")" }

Using curl works though:
curl --header "Content-type: application/json" --request POST --data '{"name":"admin", "pass":"pass"}' http://localhost:8080/user/login?_format=json

curl result:

{"current_user":{"uid":"1","roles":["authenticated","administrator"],"name":"admin"},"csrf_token":"XXXXX","logout_token":"XXXXX"}
Answer: I have faced the same issue and resolved it by selecting "POST" method from dropdown list.
Find the below image:-

OUTPUT:-
{
    "current_user": {
        "uid": "1",
        "roles": [
            "authenticated",
            "administrator"
        ],
        "name": "admin"
    },
    "csrf_token": "XXXXXXXXXXXX",
    "logout_token": "XXXXXXXXXXX"
}
Note: we can get this output for the first time, if we try for the second time we will get message like

{
      "message": "This route can only be accessed by anonymous users." }

because postman works as a browser.
To get it work for the second time we need to remove the cookie from postman.
Kindly let me know if I am wrong.
Thanks..
Answer: This works for me (leave it on multiple lines):
$ curl --insecure \
  --header "Content-type: application/json" \
  --request POST "https://bo.mywebsite.com:8001/user/login?_format=json" \
  --data '{"name":"admin", "pass":"SuperSecret123&"}'

Note: --insecure is used to skip SSL verification.

Login using REST request gives 404


Magnus expansion and two point Gauss quadrature rule

Question: In many papers about Magnus integrators, like this one at slide
7, one truncates the Magnus expansion and apply a quadrature rule to the integrals.
My question is about the expression one gets if uses just the first two terms  and apply two-points Gauss quadrature rule with nodes $c_{1,2}=\frac{1}{2} \mp \frac{\sqrt{3}}{6}$.
The term to approximate is $$\int_0^h A(t_n + \tau) d \tau - \frac{1}{2}\int_0^h [\int_0^{\tau}A(t_n+ \sigma) d\sigma,A(t_n+\tau)] d \tau$$
where $$[\cdot,\cdot]$$ is the classical commutator.

For the first integral it's easy to see that applying Gauss quadrature rule with those $c_1,c_2$ its approximation is $$ \frac{h}{2}(A(t_n + c_1 h) + A(t_n + c_2h))$$
My question is about the other one: I'm having serious problem in finding the term in the literature
What I have to approximate is $$\int_0^h [\int_0^{\tau}A(t_n+ \sigma) d\sigma,A(t_n+\tau)] d \tau$$
The first thing that I had in mind is to see the inner part of the integral as a function of $\tau$,i.e. $$f(\tau)=[\int_0^{\tau}A_n(\sigma) d \sigma,A_n(\tau)]$$
and hence I see my integral as $I = \int_0^h f(\tau) d \tau$
Now, applying Gauss 2-point quadrature I get
$$ I \approx \frac{h}{2}(f(c_1 h)+f(c_2 h))$$
The problem is that now I don't know how to see that it is equal to $\frac{\sqrt{3}}{12}h^2[A_n(c_2h),A_n(c_1h)]$
Answer: A journal reference with explanation and analysis is
Iserles, A.; Nørsett, S. P., On the solution of lienar differential equations in Lie groups, Philos. Trans. R. Soc. Lond., Ser. A, Math. Phys. Eng. Sci. 357, No. 1754, 983-1019 (1999). ZBL0958.65080.
See the discussion after Corollary 3.3 in particular. The idea is to approximate $A$ by an interpolating polynomial, in this case
$$A(x)\approx A(c_1h)\frac{x-c_2h}{c_1h-c_2h} + A(c_2h)\frac{x-c_1h}{c_2h-c_1h}$$
I'll set $t_n=0$ and $h=1.$ Then
\begin{align*}
&\int_0^h \int_0^\kappa [A(\xi),A(\kappa)] \;d\xi \;d\kappa\\
&\approx[A(c_1),A(c_2)]\int_0^1 \int_0^\kappa \frac{\xi-c_2}{c_1-c_2}\frac{\kappa-c_1}{c_2-c_1}-\frac{\kappa-c_2}{c_1-c_2}\frac{\xi-c_1}{c_2-c_1} \;d\xi \;d\kappa\\
&=[A(c_1),A(c_2)]\int_0^1 \int_0^\kappa \frac{\kappa-\xi}{c_2-c_1} \;d\xi \;d\kappa\\
&=[A(c_1),A(c_2)]\int_0^1 \frac{\tfrac12\kappa^2}{c_2-c_1} \;d\kappa\\
&=[A(c_1),A(c_2)]\frac{\sqrt{3}}{6}
\end{align*}
Going back to the original question, the term you're asking about is
$$
- \frac{1}{2}\int_0^h [\int_0^{\tau}A(t_n+ \sigma) d\sigma,A(t_n+\tau)] \;d \tau$$
Changing variable names (to match the Iserles and Nørsett reference), setting $t_n=0,$ and pulling out the integral, this term is
\begin{align*}
&- \frac{1}{2}\int_0^h \int_0^{\kappa}[A(\xi),A(\kappa)] \;d\xi \;d \kappa\\
&=-\frac12 [A(c_1),A(c_2)]\frac{\sqrt{3}}{6}\qquad\text{ by the previous calculation}\\
&=\frac12 [A(c_2),A(c_1)]\frac{\sqrt{3}}{6}\qquad\text{because $[a,b]=-[b,a]$}\\
&=[A(c_2),A(c_1)]\frac{\sqrt{3}}{12}
\end{align*}
Comment: Since this is a 400rep question, it would be nice to include even the details you mention in the last sentence.
Comment: As wrote by @b00nheT, could you be a little more explicit in the last sentence?
Comment: @VoB: sure, I have added more detail
Comment: Thanks, perfect


OpenMP parallel for with vector of vectors

Question: I have a fixed-size 2D matrix with size W x H, each element in the matrix is a std::vector. The data is stored in vector of vectors with linearized index. I'm trying to find a way to concurrently fill the output vector. Here is some code to indicate what I'm trying to do.
#include <cmath>
#include <chrono>
#include <iostream>
#include <mutex>
#include <vector>
#include <omp.h>

struct Vector2d
{
    double x;
    double y;
};

double generate(double range_min, double range_max)
{
    double val = (double)rand() / RAND_MAX;
    return range_min + val * (range_max - range_min);
}

int main(int argc, char** argv)
{
    (void)argc;
    (void)argv;

    // generate input data
    std::vector<Vector2d> points;
    size_t num = 10000000;
    size_t w = 100;
    size_t h = 100;

    for (size_t i = 0; i < num; ++i)
    {
        Vector2d point;
        point.x = generate(0, w);
        point.y = generate(0, h);
        points.push_back(point);
    }

    // output
    std::vector<std::vector<Vector2d> > output(num, std::vector<Vector2d>());
    std::mutex mutex;

    auto start = std::chrono::system_clock::now();

    #pragma omp parallel for
    for (size_t i = 0; i < num; ++i)
    {
        const Vector2d point = points[i];
        size_t x = std::floor(point.x);
        size_t y = std::floor(point.y);
        size_t id = y * w + x;
        mutex.lock();
        output[id].push_back(point);
        mutex.unlock();
    }

    auto end = std::chrono::system_clock::now();
    std::chrono::duration<double> elapsed_seconds = end - start;
    std::cout << "elapsed time: " << elapsed_seconds.count() << "s\n";

    return 0;
}

The problem is the code is much slower with openmp enabled. I found some example to fill std::vector using reduction, but I don't know how to adapt it to vector of vectors. Any help is appreciate, thanks!
Comment: Please post a complete, working program that we can cut and paste.
Comment: @JiveDadson Sure, modified.
Comment: I suspect it is using a lot of time locking and unlocking the mutex. A mutex is a heavyweight that requires going into system mode.  Try using a condition variable. A good implementation will probably system calls when possible. You could also try spinning on a test-and-set.
Comment: Can you modify it so it does not require .  i don't even know what Eigen is.  All we need is Vector2d.
Comment: Modified(remove Eigen/Eigen). Yes, it takes a lot of time on the mutex things. I'm not sure how to use a condition variable on that. Could you give me an example? Thanks!
Comment: I tried using a condition_variable, in the hopes that the implementation would use a spin-lock before resorting to a system call.  No joy. On VC++ it was actually slower.  You have another problem besides the mutex, namely false sharing. OpenMP tasks could solve that by giving each task its own vector, and combining them at the end. My compiler does not do OpenMP tasks.  Could you use std::thread instead?
Comment: The generate() function is probably so fast that any kind of thread synchronization is going to be too much overhead.
Answer: There are some things you could do to improve the performance:
I would preallocate the second vector holding the Vector2d class, because every time you push_back a new Vector2d and the capacity of the std::vector is exceeded, it is going to reallocate. So if you do not care having initialized Vector2ds in your std::vector I would simply use:
std::vector<std::vector<Vector2d> > output(num,
               std::vector<Vector2d>(num, Vector2d(/*whatever goes in here*/)));

Then in your for loop, you coul access the elements in the second vector via operator[], which allows you to get rid of the lock.
#pragma omp parallel for
for (size_t i = 0; i < num; ++i)
{
    const Vector2d point = points[i];
    size_t x = std::floor(point(0));
    size_t y = std::floor(point(1));
    size_t id = y * w + x;
    output[id][i] = num;
}

Though I'm not sure, the before-mentioned way works with what you want to do. Otherwise you could reserve the storage for each std::vector<Vector2d>, which would leave you with your initial loop:
std::vector<std::vector<Vector2d> > output(num, std::vector<Vector2d>());
for(int i = 0; i < num; ++i) {
    output[i].reserve(num);
}

#pragma omp parallel for
for (size_t i = 0; i < num; ++i)
{
    const Vector2d point = points[i];
    size_t x = std::floor(point(0));
    size_t y = std::floor(point(1));
    size_t id = y * w + x;
    mutex.lock();
    output[id].push_back(point);
    mutex.unlock();
}

Which means you get rid of the vector re-allocation, but you still have the mutex...
Comment: Thanks for the example! But there is one problem, in my case, the input point number is so huge. If I preallocate the memory, it will consume a large mount of memories. Consider that in each cell of the matrix, one point will appear no more than once, do you think it's possible to use std::vector > to solve it?
Comment: Ahh, you're right the input number is way too big... I don't think `std::unordered_set ` will help here, as insertion normally takes longer then `push_back` (as `std::unordered_set::insert` compares the keys). I have tried to use the Map/Reduce Pattern and I noticed, that 2 threads filling their own output vector take as long as one thread filling one output vector... Hmm, dunno... I'm out of ideas. Can't help you here. Sorry :(


Way to integrate a latex-based wiki into a drupal 6 site

Question: I have a website with users already designed in Drupal 6. We would like to add an area/module that would allow registered users of a certain type/category to be able to collectively edit/contribute to a set of wiki-based statistical documents, ideally written in LaTeX, but that other users (registered and anonymous) could download in the original LaTeX or exported to .pdf. (Imagine a wiki-based, open-source statistics textbook.) There are wiki modules and LaTeX modules for Drupal, but no LaTeX-wiki modules.
Is there some stand-alone wiki software that could be hosted on a sub-domain of our site but uses the Drupal user permissions to manage access? Is there a Drupal module or option I haven't found?
What we have:
Drupal 6 site that anyone can visit/see, but that requires registered user status to contribute/participate on site. We can add subdomains/create any databases, etc. needed on the servers to do what we need to do.
What we envision:
A wiki that allows a subset of registered users to collaboratively edit/write statistical texts easily (many of these users are already familiar with LaTeX) that will preserve mathematical equations and render them onscreen (.html) and as .pdf output.
Version tracking and attribution to particular users is necessary.
Any user can view .html of current wiki, or download the raw LaTeX file (for their own use), or choose certain wiki pages to be exported as .pdf.
Is there some stand-alone wiki software that would meet these criteria? And, if so, could we somehow use the same user database as our drupal install to set permissions? We anticipate hiring someone to do the programming necessary (our current Drupal developers do not do this level of development), but it would be helpful to know whether we're looking for someone to modify two existing tools to work together or to write a new drupal module that suits our needs.
Answer: A solution would be to have a Drupal based wiki on your website and then to allow the usage of LaTeX markup for the wiki content. DruTeX]1 may allow the later, while Wikitools should provide the former. They will both need to be properly configured.


How to display inbox messages and sent messages order by date - private message module

Question: In private message module inbox and sent messages should be display by time wise.
Right now,
It is displaying where the unread messages list first and then the read messages list second.
But based on my requirement
All the messages should be displayed in date order weather it is read or unread
How can I do this?
Comment: Drupal 6 or 7? Possible in both, but requires a different hook.
Comment: @@Berdir: In drupal 6.. But i don't find any hook to do the same..  Could you guide me on this issue? thanks...
Answer: Have a look at the following issue: http://drupal.org/node/850932


Do we know the rate of divergence of the sum of reciprocals of the $k$-almost primes?

Question: A $k$-almost prime is a positive integer having exactly $k$ prime factors, not necessarily distinct. Let $\mathbb{P}_k$ be the set of the $k$-almost primes and let $$ \rho_k(n):=\sum\limits_{\substack{q\in \mathbb{P_k}\\q\le n}}\frac1q.  $$ So with $k=1$ and $n\to\infty$ we have the prime harmonic series, which diverges like $\log\log n+ B_1$, $B_1$ being the Meissel-Mertens the constant..
$\rho_2(n)$ diverges at a rate of $\frac{\log^2\log n}{2}+\frac15$.
In general, is the asymptotical behaviour of $\rho_k(n)$ known?
Comment: The counting function of the $k$-almost primes is known, so a straightforward partial summation should give you an asymptotic for the leading term of the sum of reciprocals.  Are you asking for an expansion that is accurate up to $o(1)$?
Comment: @VincenzoOliva do you know a proof for $\rho_2(n) \sim \frac{(\log \log n)^2}{2}+\frac15$.
Answer: The first-order asymptotics are easy.  The counting function of $\mathbb P_k$ satisfies the Poisson-like asymptotic:
$$P_k(x) := \#\{n \le x : n \in \mathbb P_k\} \sim \frac{x}{\log x}\cdot \frac{ (\log \log x)^{k-1}}{(k-1)!}.$$
By partial summation, the reciprocal sum is
$$ \sum_{\substack{n \in \mathbb P_k \\ n \le x}} \frac{1}{n} = \int_{t=2}^x \frac{d P_k(t)}{t} = \frac{P_k(t)}{t} \bigg|_{t=2}^x + \int_{t=2}^x \frac{P_k(t)}{t^2} dt.$$
The first term on the right is $O(1)$ since $P_k(x)/x \to 0$, so all the divergence in the sum is coming from the integral term, which is asymptotic to:
$$ \frac{1}{(k-1)!}\int_{t=2}^x \frac{(\log \log x)^{k-1}}{t \log t} dt = \frac{1}{(k-1)!} \int_{u=\log \log 2}^{\log \log x} u^{k-1} du = \frac{1}{k!}(\log \log x)^k + O(1).$$
Edit: The above is asymptotic to the reciprocal sum, which is not to say that $O(1)$ is the correct error term.  In fact, the asymptotic for $P_k(x)$ has a relative error of $O(1/\log \log x)$ (the error term must depend in some way on the specific definition of $k$-almost prime, like whether duplicates are allowed), so the same is true of the estimate above.  I would expect an error term of size $O(\log \log x)^{k-1}$.
Comment: Thank you, Erick. Is something known about those constants? For example, $B_1>1/5$. Does this go on indefinitely? Do they get smaller and smaller?
Comment: If you'd be so kind, would you please explain a bit more about how you got the asymptotic? Intuitively, it reminds me of $\pi(x)\simeq\dfrac{\ln x}x,$ and of $\displaystyle\sum_{n=1}^x\frac1{p_n}\simeq\sum_{n=2}^x\frac1{n\ln n}\simeq\int_2^x\frac{dt}{t\ln t}\simeq\ln\ln x,$ but I'm afraid I can't really grasp the specifics.
Comment: @Lucian Which asymptotics are you referring to specifically?  I starting to suspect there's an elementary approach to this, by just expanding out products of $\sum 1/p$.
Comment: @Erick: Would you please answer the question in my comment?
Comment: @VincenzoOliva I don't know the answer to the question in your comment.  Actually, come to think of it, the format of my answer is a bit misleading.  Let me fix.
Comment: @ErickWong: I was referring to $\dfrac{x}{\log x}\cdot\dfrac{(\log\log x)^{k-1}}{(k-1)!}.$
Comment: Please see related question at http://math.stackexchange.com/questions/1675624/asymptotic-of-reciprocal-sums-of-k-almost-primes


Erro - Jquery não carrega função corretamente

Question: O erro apareceu após eu tentar adicionar o .click(function())

Como é possível ver na imagem acima, o resultado não é o esperado, que seria que o h1 ficasse da cor laranja, com um fadeIn, e uma função onclick.
JQuery:
$(document).ready(function(){

$('h1')
.css("color","#f66")
.hide()
.delay('1000')
.fadeIn("slow")
.text('Teste')
.click(function()){
    $('body').css("background","#C30")
    $('h1').css("color","#fff");

});
});

HTML:

Teste aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

1
1
1

Eu já verifiquei, e a CDN está correta. Obrigado desde já!
Comment: Não está indo pelo caminho certo não amigo!
Comment: O erro só aconteceu após eu adicionar a parte do .click(function)()), porque antes estava funcionando corretamente, com o fadeIn e o color funcionando
Comment: Bom eu sinceramente não entendi o que você quer fazer. Mas no código você está cheio de **`});`** sobrando!
Comment: É apenas um teste amigo, estou apenas testando o uso do Jquery, por isso que eu coloquei tanta coisa, vou editar e mostrar o código completo
Answer: Basta rearanjar seu script
inicialmente setar a cor do h1 é incoerente pois já entra hidden.

   $(document).ready(function(){

        $('h1').css("color","#f66");
        $('h1').hide();
        $('h1').delay(1000);
        $('h1').fadeIn("slow");
        $('h1').text('Teste');

        $('h1').click(function(){
            $('body').css("background","#C30");
            $('h1').css("color","#fff");
       });

    });

Teste aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

    1
    1
    1
Answer: O seu problema é apenas um erro de sintaxe. Há um parênteses indevido nesta linha:
.click(function()){
                 ↑

O correto seria:
.click(function(){

Com a correção tudo funciona como previsto:

$(document).ready(function(){
   $('h1')
   .css("color","#f66")
   .hide()
   .delay('1000')
   .fadeIn("slow")
   .text('Teste')
   .click(function(){
       $('body').css("background","#C30")
       $('h1').css("color","#fff");
   });
});

Teste aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

1
1
1
Comment: Muito obrigado amigo!


Remote hosts accessing AD's registry

Question: I have a situation here. I have an intrusion detection system and it constantly alerts me that a remote host is accessing our AD's registry remotely.
Our remote hosts are mainly Windows XP and our ADs are W2K8. The remote hosts access them over SMB port 445
Is it normal for Windows hosts to access AD's remote registry? My colleagues confirmed with me that both host and AD is clean from virus with endpoint protection enabled.
Thanks.
Comment: Do you have a backup server that's backing up the System State of the DC? If so, that's probably the culprit.
Comment: @joeqwerty the remote hosts are not backup servers. Those are workstations. Thanks.
Answer: Can you find the offending host?  No I see no reason for remote client machines to access a domain controllers registry.  To do so, the remote connection should have to be authenticated with domain admin rights.
Comment: Hi Bret, what about servers? Would it be normal if servers have the same kind of behaviour towards AD server? Thanks.
Comment: @smitty deploying software, monitoring or running remote configuration of some kind might. Otherwise no not normally.
Comment: Yea no built in part of Windows or an AD network would have anything accessing the registry remotely of a DC.  It's either 3rd party or a program that means to do harm, or your IDS is wrong.
Answer: Based off of this cisco document, it is not uncommon for clients to access remote registry under normal use scenario.  It does not, however, list the individual cases.
Remote registry may be caused by some of the following, (these are off the top of my head - not an exhaustive list)

Viewing the list of Scheduled Tasks that appear on an SMB share
Using the registry editor remotely
Using Performance Monitor to access performance counters of the remote computer
Using Event Log to access log entries of a remote computer
Some COM+/DCOM applications
Software asset management programs
Viewing the list of installed printers that are not shared on a remote computer (unsure of this one)

Remote hosts accessing AD's registry


FIFA World Cup winners not qualifying automatically anymore for next edition

Question: It used to be the case that the winner of the World Cup qualified automatically for the final stage of  the following edition, but that's not the case anymore. France was the last team that this rule applied to, qualifying for 2002 by virtue of winning in 1998; afterwards, Brazil had to go through the regular qualification process for 2006 despite winning in 2002, and so did Italy for 2010, Spain for 2014, and now Germany for 2018.
What was the rationale for this rule change?
Answer: The main reason is to have more spots open for qualification. In 2002, before the start of the qualification, three countries were already qualified. These countries being France (1998 champions), Japan and South-Korea (hosts). So, only 29 spots were available for approximately 200 countries.
Closely related, in the 2002 qualification there were 14,5 spots for European teams, of which one was already assigned to 1998 world cup winner France. This caused other European teams to have a smaller chance of qualifying for the world cup. So, after the rule change, a nation is not affected in its qualifying chances anymore when a fellow confederation member won the previous world cup.
A minor reason could be to have the current world champion play more official matches.