An Effective Splash Cymbal

Question: Note: I'm not looking for recommendations of particular brand names!
I have several 'splash' cymbals - typically 8" and 10", but they all have quite a long sustain. Rather like mini versions of their bigger siblings of 18", 20", etc.
What I'm looking for is a way to make any of the smaller ones produce a real 'splash' - of 1 second duration at most.
What ideas have worked for any drummers out there? Some sort of choking (but not by hand!) would maybe be productive. Some sort of damping may do the trick, but there still needs to be the initial 'splash'.
Comment: Sounds like the setup to a joke: "Q: How to you make an effective splash cymbal"; "A: Throw it in a lake."
Comment: You really nd to define your acceptable decay parameters. A thin crash in a metal band will appear shorter than a splash in a drum/piano duo, because of your SNL.
Comment: Several seconds of decay is in my opinion normal for a splash, and if you play one at low volume it sounds just like a crash. If something sounds shorter it's either because it's buried in the mix under something louder or because it's actually a ribbon crasher, splash stack or something else.
Comment: @Tetsujin - thing is, it's certainly not in a metal band, but I don't know what that would sound like. I already said <1 second. All my splashes last *several* seconds, which to my mind doesn't really make them any more than small crashes. Is my SNL curable..?
Comment: clamp a fairly wide felt pad on it?
Comment: In French, cymbale is actually feminine! So I got it wrong anyway! I'm sorry for potentially causing great grief to over half the population! Just forgot for a moment how P.C. we are expected to be now!
Answer: One common way to produce a very short splash is stacking small cymbals. Different combinations of splashes and mini chinas as well as putting one of the cymbals upside down produce different variants of the short splashy sound. Searching for "cymbal stack" should find a lot of videos to give an idea what it sounds like. If you have several splashes, this is probably the place to start.
Other temporary solutions are hanging a chain or any random piece of sheet metal across the cymbal. Putting loose rivets to the cymbal is also an option, but I wouldn't try it on anything that I wasn't prepared to throw away.
Comment: @ojs rivets on big, heavy cymbals can increase _perceived_ sustain. It works because these cymbals have very long-lasting low-frequency partials, which are however almost inaudible except in very sparse ensembles and/or with close miking. Rivets turn those LF vibrations into much more audible sizzle, which doesn't last as long as the free vibration would but does give a much longer duration where the sound is actually heard.
Comment: Had time so far to try the stacked idea. It worked best with a 10" Zyldjian under a Meinl 8". Trying various combinations with Zyldjian, Paiste and Meinl 8s and 10s resulted in only this one successful (for me) sound, of around <1 second. Thanks for the idea, yet to attempt John's variable damper.
Comment: I thought that rivets were attached to give *more* sustain, not less!
Comment: I don't understand how they could add sustain, the ones I have seen have had more "sizzle" and less sustain.
Comment: @leftaroundabout you're technically correct (the best kind of correct) but this discussion was about small, thin splash cymbals.
Answer: A one second cymbal without manually choking it seems like a tall order but this is an idea I had after reading your question. I have no idea if it will work and I don't have a cymbal to test it on but it should be pretty easy to come up with a rudimentary way to test it and see if it will work.
Set up the cymbal so that on the back side opposite the striking side the cymbal rests lightly on a piece of foam or something similar. It might work better if the cymbal is just above the foam without touching it.
When you hit the cymbal the side you strike will go down and the opposite side will go up giving you a splash. The back side of the cymbal will then immediately drop and hit the dampener. Here is a rudimentary drawing, let me know if it works or is a bust. You can also experiment with different materials, hardnesses and sizes.
Comment: It certainly appears to be a working example! A simple, foolproof auto-damper. With adjustment it could be a winner! On the way to the bathroom right now!
Comment: I found an extension for a cymbal which fits a cymbal stand. But careful arrangement, I positioned the felts on the edge of a 10" 'splash'. Which actually gave me the crash  I wanted, and by altering the pressure between the two felts, would change the decay of the crash. It works!! So now, I have two new cymbal sounds - short splash and odd splash. Many thanks to all.
Comment: @Tim I added a bit to the last paragraph, maybe a small pillow or other material might work better.
Comment: @Tim You can also experiment with the amount of pressure the damper puts on the cymbal from being a few inches below it to lifting the back end a few inches.
Comment: Nice solution to solve the contradiction (see my comments comment about my answer).
Comment: @Tim I'm curious, did it work?
Comment: @JohnBelzaguy - as I said, not had time to set up your idea yet. The 2 cymbal idea works to an extent, but the sound, while short enough for  my expectations, has lost the initial splash/crash that i want to retain. Have found the necessary ironwork to set up your idea, which I think will give that, so will report back in a few days.
Comment: @Tim I did not see that mentioned, sorry. Before you spend time  making hardware I suggest setting up a cymbal stand close to the edge of a table or counter and just place some foam or a pillow under the edge of the cymbal.
Answer: To have dampening , which varies in time, you need to move from constant dampening to a variable on.
All mechanical attachments don't offer this property, be it tape, rivets, stacks etc., unless it's a kind of machine you attach.
Hand is an option, you exclude in your situation.
So foot can be an alternative: mount the splash as a kind of Hihat (open splash, closed done).
If you think in terms of a machine, go beyond mechanics, the classical perception. Think in terms of actuators, which brings you to electronics. In deed, the required electronics can be simple, while the electromechanical actuator needs some consideration.
A practical solution might be like this:

Perceive the splash as a speakers membran
Attach the required joke, magnet and coil to make it a speaker
Use it as a pickup to start a signal
Make the signal vary such that it increases "stiffness" (dampening) quickly
A simple RC circuit may do that part of the "trick".

Finally, a simple and "classical" solution might be a splash assistant: a person, lending you a hand when it's needed. Funny. Why not. There are trained triangle players around, which do just that on their instrument  …
Comment: The hi-hat idea may work, with some damping instead of the lower cymbal, but that adds another pedal to an already crowded floor.
Comment: Why would the dampening need to vary over time?
Comment: If it doesn't, the splash sounds dull from the start. If you want it sounding bright AND have it silent quickly after, you don't get both: it's a so called trade-off situation, which is a different (bad) way to state a contradiction. // You can also watch the hand action: you don't attach the hand to the cymbal all the time. Rather, you separate in time, which is an other way to state variable dampening. // BTW, the drawing above introduces sep.in.time: free when hit, damped once returned to its rest position.
Comment: This sounds a lot like a made up problem to me. In real life cymbal stacks have a bright attack that is amplified by the two cymbals bouncing against each other. There is this video site called Youtube where you can find examples.
Comment: To me, that's daily business. Much like reading notes may be to you :)
Comment: Right. John posted a nice proposal. It should work with any kind of fabric, not just foam. // However, if you reconfigure your HH with a splash, it might also work/sound like an ordinary HH.

An Effective Splash Cymbal


How to hide horizontal tabs on page load?

Question: I have installed the field group module for horizontal tabs, so I can put several nodes in a tab via rendered node.
The question is simple:
How can I hide these tabs on page load?
I want to show the links but only when the user clicks on it, the tab shows up.
Thank you for your collaboration.
Gael
Comment: I'm not familiar with this module, however, this sounds like something that can be solved by inserting javascript into your themes template and then adding an onclick function for the items/tabs you mentioned above. aka, they are always hidden, but when something is clicked on, they are shown.
Comment: Would you be so kind and give me a link to your module? Are you using [field group](https://www.drupal.org/project/field_group)?
Comment: @Huelfe yes my friend, i am using field group. the javascript that controls the tabs is in field_group/horizontal-tabs/horizontal-tabs.js
unfortunately I do not have enough skill in tweaking jquery code, so thanks Janpan, I share your idea but I cannot put in practice, you know...
Comment: @Janpan will you be more tecnique?
Comment: Read [documentation](https://www.drupal.org/node/1017838) how to use this module. This module provides hiding fields, if they are not in current tab. Either you have an javascript issue or you configured something wrong. Check your browser console if you get some errors.
Comment: @Huelfe if you have the solution write a comment, if you have tell me read the documentation only to gain some badge as good commentator, please keep it for you.
Comment: there is no option to hide nodes in the field group.
Answer: Following @Janpan suggestion, I have hidden the tab content and then added a click function, so I have shown the rendered node inside the div.
here the code:
<code> $("fieldset").hide();
                $(".tab a").click(function(){
                    $("fieldset").slideDown({
                        direction: "up"
                        }, 300);
                });
</code>


Overcoming the "we're not good enough" syndrome in amateur choirs

Question: I've seen this in pretty much every amateur choir I've ever been in; the director will avoid putting certain pieces in front of the full choir (or any of them), the major reason being some sugarcoated version of "you're not good enough to sing this piece".
I do understand some of the meta-reasons; we're all music lovers, and if we can't do a piece justice we don't want to sing it poorly just to say we sang it. Other choirs are "amateur working choirs" like church choirs which have to get pieces prepared on a tight timeline, and there just isn't enough time to polish a masterpiece every week. And, in those situations, sometimes it may really be true; half of the average church choir can't read music; they see the shape of the line, read the lyrics, and learn the exact pitches and rhythms by ear.
But, "if there is no struggle, there is no progress." - Frederick Douglass. You don't get better as a musician if you're not challenged musically. You have to push, otherwise you'll be stuck singing the same stuff over and over again until you get bored and quit. At the very least, if you can sing a Whitacre or Lauridsen piece, or something from the classical era like a Bach or Palestrina, even if you wouldn't put it in front of an audience (yet), when you go back to the level of music you had been doing normally, you find it very easy to pick up. Skill is gained, not discovered. So I say, put that challenging piece in front of the choir, and spend some time working on it even if you don't get it polished up just right for a performance. It'll pay off in other ways, and who knows? That group of non-music-readers may just surprise you.
Am I wrong? Is this the wrong way to think for the average case?
Comment: This is more a psychology question.
Comment: I've been in choirs that have sung pieces that were too hard. Taking a hard piece only makes sense if the choir director is able to convey the goal and able to decide whether to abandon it later if necessary despite sunk costs.
Answer: I think that every piece of music deserves the best possible method of being prepared in a such a way that both the musicians and audience have a pleasing experience. Preparation includes time, rehearsal, and every member stepping up to meet the challenge including the conductor's interpretation so that the entire group is a part of the solution.
If your present group is missing any of these essentials it might be time to sort out a group where you are all looking in the same direction with common goals and expectations. If you are a five star chef, you don't want to be stuck being a cook at a fast food chain for the rest of your career, eventually you have to make the move.
On the other hand what is keeping everyone in your present group to move together to reach the next level? A choir is so much about the synergy of musicianship that it is hard to imagine any choir functioning without team work. Every voice, every note, every beat is a group project. Perhaps, your group could use some team building analogs to break down obstacles? Exercises?
This might a bit corny, but do you remember the movie "The Mighty Ducks"? Do you remember the exercise where the coach (Emilio Estevez) ties up the entire hockey team and they have to learn to move as a unit in order to make their way down the rink?
You have presented a very good analysis, so I think you have a chance at investigating where your present group is falling short and work with the director on exercises that will engage team building. Start with the weakest link(s).
Perhaps you are all five star chefs that just need the right exercises to see clearly that what might appear as a fast food chain is actually the world's best mom and pop restaurant?
Answer: Chapeau to the directors you encountered. I can only speak for orchestras, but there I've seen more than once the over-ambitious director, frequently choosing pieces, which were (at least one level) too difficult. It's always a tight line to find, but the danger of musicians stumbling through a piece completely absorbing all concentration, so that none remains for looking or listening to others is not desirable either. Occasionally playing a piece slightly too difficult helps for constant improvement (and prevents boredom of the best), but in the same concert should also be something to relax (so the weaker colleagues are happy with it). There is a nice sentence of Robert Schumann: "Try to play easy pieces nice and really good; its better than achieving a mediocre performance on difficult ones."


Gradient in Internet Explorer 9 overflows the rounded border

Question: I'm having a problem with rounded borders and a gradient in IE9. The gradient overflows the rounded border.
.cn_item:hover, .selected{
    width:300px;
    border:1px solid #333333;
    cursor:pointer;
    position:relative;
    overflow:hidden;
    height:49px;
    color:#333333;
    padding:5px;
    margin:6px 5px 0px 0px;
    text-shadow:1px 1px 1px #000;
    background-image: -ms-linear-gradient(top, #DDDDDD 25%, #FF0000 5%);
    filter:  progid:DXImageTransform.Microsoft.gradient(startColorStr='#ffffff', EndColorStr='#666666');
    -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorStr='#ffffff', EndColorStr='#666666')";
    zoom: 1;

    -moz-border-radius:5px;
    -webkit-border-radius:5px;
    border-radius:5px;
}

I already use the overflow:hidden; but nothing works. Any suggestions?
Answer: This is a known bug. If you search stackoverflow there are some questions just like this one.
IE9 border-radius and background gradient bleeding
The only way around it without adding more markup is to use svg.
Colorzilla gradient editor should make it easy.
Answer: Just use a wrapper div (rounded & overflow hidden) to clip the radius for IE9. Simple, works cross-browser. No need for SVG, PIE, JS, or conditional comments.

text or whatever

.ie9roundedgradient {
display:inline-block; overflow:hidden; -webkit-border-radius: 8px; -moz-border-radius: 8px; border-radius: 8px;
}
.roundedgradient {
-webkit-border-radius: 8px; -moz-border-radius: 8px; border-radius: 8px;
/* use colorzilla to generate your cross-browser gradients */
}


UISearchBar AutoLayout ios7 bug?

Question: I'm using AutoLayout and have a UISearchBar, UITableView ad a UIView. Initially the layout is correct and positioned according to my AutoLayout rules.

When the UISearchBar has focus it expands abruptly in height covering my top UIView.

No matter how I layout my autolayout constraints this happens.
If I don't set
self.searchBar.translatesAutoresizingMaskIntoConstraints = NO;

and set a frame instead then it behaves as normal.
self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 100.0f, 45.0f)];

But i'm reliant upon AutoLayout in this app for iOS7. Is this a genuine bug? Or most probably i've missed something!
Comment: You can add height constraints to your UISearchBar view.
Comment: Yes I have tried that as an additional constraint, makes zero difference.
Comment: Did you add top, leading, trailing and height constraints to your UISearchBar view?
Comment: Hello @JMWhittaker, did you solve this issue?
Answer: Had the same problem. Try this in viewDidLoad
if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
    self.edgesForExtendedLayout = UIRectEdgeNone;
}

Comment: This didn't help with my layout but I get your thinking on this.

UISearchBar AutoLayout ios7 bug?


Asp web api and returning multiple images to angularjs

Question: How do I use asp web api to return multiple images and then set angularjs to show them?
I have been searching for a bit but I did not get anything working. I am really stuck here so any help will be greatly appreciated!
My current code:
    List images;
            using (var uow = new UnitOfWork())
            {
                images = uow.ImageMetadatas.Query(m => m.AlbumId == albumId).Select(m => m.Filename).ToList();
            }
        var content = new MultipartContent();
        foreach (var img in images)
        {
            var image = new Bitmap(img);
            var thumbnail = image.GetThumbnailImage(200, 200, ThumbnailCallback, IntPtr.Zero);
            var stream = new MemoryStream();
            thumbnail.Save(stream, ImageFormat.Jpeg);

            var imgContent = new StreamContent(stream);
            imgContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg");
            content.Add(imgContent);
        }
        return new HttpResponseMessage(HttpStatusCode.Accepted) { Content = content };

Answer: Take a look here and see if it helps:
Book Store application using AngularJS and Asp.Net Web Api
Thanks
EDIT:
Explanation:
The following code is to handle image files that are already saved on the server.
First you have to make the call to the web api from angularJS. The easiest way to do this is to use $http from angular controller, but I would recommend creating a data service for this scenario and inject that service into all the controllers that need to access that data.
Use this code directly into your controller:
$scope.myData = [];
$http({
        method: 'GET',
        url: 'api/controller/'
    }).
    success(function (data, status, headers, config) {
        $scope.myData = data;
    }).
    error(function (data, status) {
        console.log("Request Failed");
    });

or create a service and inject it into the controller:
var myApp = angular.module('myApp', []);
myApp.factory("DataService", function ($http, $q) {
  var myData = [];
  var read = function () {
    var deferred = $q.defer();
    deferred.resolve($http({
      method: 'GET',
      url: 'api/controller/'
    }));
    return deferred.promise;
  };
  return {
    MyData: myData,
    ReadData: read
  };
});
myApp.controller('MainCtrl', function ($scope, DataService) {
  $scope.myData= [];
  DataService.ReadData().
   then(function (config, data, headers, status) { $scope.myData = arguments[0].data; });
});

Then on the server side, create a 'GET' method to return an enumerable object with the images data:
public List<myData> GetData()
{
  List<myData> returnData = GetImagesData();
  return returnData;
}

here 'myData' class is the data model.
Hope it helps.
Comment: Even if the link contains a complete answer, please , add an explanation. Your answer should stand for itself without reference.


Getting PHP to work with apache to run .php files through browser

Question: I have VPS running Debian 5.0 (I think) and I would like to get it to run PHP files. I was told it needed to be configured with Apache. I tried entering the command apt-get install apache2 php5 libapache2-mod-php5. But there was no change. Console output: http://pastebin.com/sVMWq6mA
This is everything in my /etc/apache2/mods-enabled:
http://img35.imageshack.us/img35/6474/modsb.jpg
My webserver can be accessed here:
http://18.104.22.168/test/
In my test.php file I have the code :
<?php
 phpinfo();
?>

but instead of displaying the page, it tries to download it. How can I fix this?
Answer: Try this:
apt-get install libapache2-mod-php5
apache2ctl graceful

EDIT: some explaining
Installing just the php5 package does not give Apache any modules. Installing the libapache2-mod-php5 package installs the php5 module to Apache and should enable it by default.
Comment: vps:~# apache2ctl graceful
httpd not running, trying to start
(98)Address already in use: make_sock: could not bind to address 0.0.0.0:80
no listening sockets available, shutting down
Unable to open logs
Answer: Have you tried "a2enmod php" or "a2enmod php5" on your console to enable the php module?
Your command line is correct and it seems that everything is installed correct.
Edit: I have looked its
a2enmod php5
apache2ctl restart

Edit2: Ok i have looked on the server for the problem. There were different problems with the apt-get installer. Then were httpd running on port 80 so apache2 could'nt start on the port and the test.php file was not in a correct file encoding this was the main problem. After checking all of them and create a new file with vi it was running.
Comment: I have installed before a few minutes a the same problem. But i have made a new apt-get install php5 and then restart the apache with apache2ctl restart. Then it was working. And under mods-avalable must be an mod php5.conf and php5.load
Comment: And have you tried "php5" ? Edit: With witch user do you try this? And you can look to the mods-available folder. There are all available modules and you can look for the name.
Comment: Ok another way go to /etc/apache2/mods-available is there a module called php? oder php5? @Kevin Duke
Comment: `ERROR: Module php does not exist!`
Comment: a2enmod php5 also says module does not exist. I'm using the root user for this.
Comment: nothing seems to be working... could we try teamviewer?
Comment: lol I'm usually up late so it shouldn't be a problem ;) However, I get an "Unknown user error" when adding firstname.lastname@example.com on MSN. You can try adding me firstname.lastname@example.com. Thanks a lot, I really appreciate this!
Comment: @stony lol I restarted apache2 with `/etc/init.d/apache2 reload` and php doesn't work again. Would you mind taking a look again? Thanks :)
Comment: @Stony Ah, I guess you aren't online, when you get back, if you don't want to connect, could you please tell me what to do to fix it again? Thank you!
Comment: I am on write me @Kevin Duke
Comment: @Stony it keeps saying you're offline and when I send you a message it says "Cannot send" :/ I'm always online so if you can, please write to me
Comment: I looks that MSN has some trouble. I write you @Kevin Duke
Comment: @stony I'm online right now. When I try to view your information in MSN, it says "Error retrieving profile. The user most likely does not exist." Ah stupid MSN or maybe stupid US government haha
Answer: Check your httpd.conf file and ensure you have a line like this:
AddType application/x-httpd-php .php
Also ensure that you have loaded your php module:
LoadModule php5_module        *path to your php module*/libphp5.so
This is the way I have configured it on my web servers.
Comment: When you install php5 over the apt-get function he load automaticly the php module. When you write this in your canfig you should look to your errorlog if the module is loaded 2 times.
Comment: command LoadModule not found :/ and what directory can I find the httpd.conf
Comment: LoadModule is not a command. You have to write this into your httpd. config in debian this should be under /etc/apache2/
Comment: @Stony Do I put both of these in httpd.conf? Right now the file is blank.
Comment: It still doesn't work by adding these
Comment: I'm not sure what was confusing about my response and warranted downvoting. The response was correct for a vanilla install of apache. If you add the lines that i suggested to the httpd.conf file you could have loaded the php module and told the server what to do with .php files.


Upload file in angular2: Body (FormData) empty

Question: I'm trying to upload a picture with Angular2 to my REST Service (Loopback).
The Loopback service works (tested with Postman) and accepts files with the x-www-form-urlencoded header.
Here's a simplified service method that sends the POST request:
public uploadFile(url : string, file: File): Observable<any> {
  let headers: Headers = new Headers();
  headers.append('Content-Type', 'application/x-www-form-urlencoded');

  let formData = new FormData();
  formData.append('file', file);

  let options: RequestOptionsArgs = { headers: headers };

  return this.http.post(url, formData, options)
  .map((res: any) => (res.text() != "" ? res.json() : {}));
}

Note that I've set the header to application/x-www-form-urlencoded and send the formData containing the file in the body.
In Angular, up until the point where I http.post the request, the formData is populated with the file, the file content is present, everyting's fine:
Data before Request
But in the request, the body is an empty object {}:
Request
I assume, Angular is trying to do JSON.stringify(formData), at least, when I try this, I also get "{}" as output.
I've seen plenty of posts doing exactly the same (http.post(url, formData)). So what am I missing?
Comment: @AngularFrance Thanks for the Plunker! I compared it with my code and watched the output and it was so similar, also all the data was set, real strange! I tried removing the options from the request, because I figured that's the only aspect that differs between our solutions. And now it works. The request is then with multipart/form-data but interestengly my Loopback service does not care. However, it's still a bit frustrating. Would like to know why it doesn't work with urlencoded
Comment: Did you try to give blob data to form?
Comment: Strange. I recently created a [Plunker](https://plnkr.co/edit/R8yJpRWsE35pMpB1QeG3?p=preview) to answer a similar question and as you can see, just POSTing `formData` works. AFAIK, Angular DOES NOT automatically `JSON.stringify(formData)`. It will POST what you pass as is.
Comment: What is printed in the console?
Comment: I have done this the same way also. Are you 100% sure you 'file' is set to something?
Comment: What happens if you add a .subscribe to the post?
Comment: @BenCameron Thx for your suggestions. 'file' was indeed set. The Observable is subscribed to in the caller method. That's not it. Could see the request go out, only with {} in the body.
Comment: @Christoph did you solve this problem? I'm stuck on this as well.
Answer: Just remove headers.append('Content-Type', 'multipart/form-data'); can solve problem.
See here
2017-08-24
Comment: This solved it for me, using Web Api 2 and Angular 4
Comment: Why is that? What's wrong with headers.append('Content-Type', 'multipart/form-data')?
Comment: Can you see my problem please: https://stackoverflow.com/questions/49942899/upload-file-in-angular-5
Comment: Please see this package https://github.com/bleenco/ngx-uploader, the best file uploader I have fount. @OnnaB
Answer: From this How to inspect FormData? SO answer and this MDN documentation outputing FormData in the console just results in a {}.
FormData can directly be used in a for ... of structure, instead of entries(): for (var p of myFormData) is equivalent to for (var p of myFormData.entries()).
Answer: There is another solution is to use base64 and convert it in back-end side:
`
var reader = new FileReader();
    reader.readAsDataURL(file);
    let res;
    reader.onload = function () {
    let headers = new Headers();
    headers.append("Content-type","application/x-www-form-urlencoded");
    headers.append('Accept', 'application/json');
    let options = new RequestOptions({ headers: headers });
    return this.http.post(config.serverUrl+"/index.php",
      {
         "file":reader.result}, options)
         .toPromise()
         .then(this.extractData)
         .catch(this.handleError);
      }
    };
    reader.onerror = function (error) {
        console.log('Error: ', error);
    };`

Answer: In my case i used formData.set() instead of formData.append()
please see example below :
 UploadFile(fileToUpload: File): Observable<boolean> {
     const endpoint = 'api/image/upload';
     var formData = new FormData();
     formData.set('file', fileToUpload);
     return this._http
     .post(endpoint, formData)
     .map(() => { return true; })
     .catch((e) => this.handleError(e));
 }


PyMC3/Arviz: CDF value from trace

Question: I have a sample from PyMC3 and I'm trying to get a cumulative probability from it, e.g. P(X < 0). I currently use this:
trace = pymc3.sample(return_inferencedata=True)
prob_x_lt_zero = (trace.posterior.X < 0).sum() / trace.posterior.X.size

Is there a better way to do this, either with some helper function from Arviz or XArray?
I haven't found any .cdf() method or anything similar.
It's weird that such basic functions are missing, but more advanced ones are there, such as trace.posterior.X.quantile().
Answer: You could approximate the CDF with a kernel density estimate, but I am not convinced that this is better than your current approach:
import arviz
grid, pdf = arviz.kde(trace.posterior.X.values, cumulative=True)
idx = np.sum(grid < 0) - 1
prob_x_lt_zero = pdf[idx]

Answer: I would recommend your original approach evaluating the condition and averaging (that is basically using the empirical cdf) instead of using the KDE.
There is no equivalent that I know of, probably also because there is no equivalent in numpy either (which has both quantile and percentile). There is one in scipy: scipy.stats.percentileofscore but I wouldn't recommend it either unless you are working with discrete data and need the kind argument to evaluate ties (i.e. would you care or notice any difference between using < or <=?). This scipy function also takes only a scalar as value to evaluate the ecdf against.
My recommendation therefore is to stick with your method, but modify a bit the implementation, so it also works when evaluating multiple values at the same time and when not reducing all the dimensions:
import arviz; import xarray
x = xarray.DataArray([-.1, 0, .1])  # skip that if working with scalars
post = arviz.load_arviz_data("rugby").posterior
prob_x_lt_zero = (post.atts < x).mean(("chain", "draw"))

which returns the probabilities for each of the 3 values we are evaluating
at all 6 teams.
<xarray.DataArray (team: 6, dim_0: 3)>
array([[0.    , 0.    , 0.0485],
       [0.347 , 0.975 , 1.    ],
       [0.    , 0.004 , 0.4245],
       [0.64  , 0.994 , 1.    ],
       [1.    , 1.    , 1.    ],
       [0.    , 0.    , 0.    ]])
Coordinates:
  * team     (team) object 'Wales' 'France' 'Ireland' ... 'Italy' 'England'
Dimensions without coordinates: dim_0

PyMC3/Arviz: CDF value from trace


Atualização de data no Laravel

Question: Eu gostaria de alterar o valor do campo de data no momento de uma edição de dados. Consigo trazer todos os valores, menos os de data.
Estou usando o Form:: do Laravel:
{!! Form::label('dtemissao','Data de Emissão') !!}
{!! Form::input('date','dtemissao',$FinContaspagar[0]["DtEmissao"]->format("d/m/Y"), ['class' => 'form-control']) !!}

Estou usando o $FinContaspagar[0]["DtEmissao"]->format("d/m/Y") para alterar o valor padrão de dd/mm/aaaa, porém não tive exito na mudança de valor.
Alguém tem alguma solução?
Answer: Utilize o formato: Y-m-d, exemplo:
<input type="date" value="{{$data->format('Y-m-d')}}">

no seu código:
{!! Form::label('dtemissao','Data de Emissão') !!}
{!! Form::input('date','dtemissao',$FinContaspagar[0]["DtEmissao"]->format('Y-m-d')) !!}

Comment: Deu certo @Virgilio Novic obrigado!

Atualização de data no Laravel


Como encontrar palavra reservada em uma frase?

Question: Estou criando uma rotina para buscar palavras reservadas em um texto (nome de pessoas). Já fiz testes com Contains() e IndexOf(). Funciona bem na maioria das vezes. No entanto em algumas palavras o retorno não satisfaz. Exemplo: no nome CORALINA retorna a palavra reservada ORAL.
Abaixo o código realizado:
    public JsonResult GetPalavrasReservada1(string frase)
    {
        var palavras = db.TBL_PALAVRA_RESERVADA.Where(pal => pal.PLR_ATIVO == 0).Select(i => new {i.PLR_DESC}).ToList();

        var palavrareservada = "";

        for (int i = 0; i < palavras.Count; i++)
        {
            if (frase.ToUpper().Contains(palavras[i].PLR_DESC.ToString()))
            {
                return Json(palavras[i].PLR_DESC.ToString());
            }
        }

        return Json(palavrareservada);
    }

Estou utilizando lógica ou métodos errados?
Comment: E não tá certo? De fato o nome "Coralina" contém a palavra "oral".
Comment: @LINQ não está de acordo com a definição de palavra aqui adotada. Você está pensando em substring, aqui uma palavra é um token devidamente delimitado. Como "coralina" forma um token só, ele não contém "oral"
Comment: Não seria o caso de verificar tem espaço em branco antes e depois da palavra?
Answer: Se achar uma palavra reservada o algoritmo para e não acha outras, é isto que deseja?
Se deseja só pegar palavras inteiras tem que quebrar todas as palavras e fazer a verificação. Só que isto não é tão simples a não ser que controle o conteúdo do texto anteriormente e possa garantir que não tenha certos padrões. Se puder fazer isto quebrar a frase é só dar um Split() pelo espaço e/ou outros caracteres que quebram uma palavra. Mas é improvável que não tenha situações de exceção a esta regra, aí teria que tratar tudo na mão. Obviamente que isto exigiria um laço extra para testar todas as palavras reservadas em todas palavras da frase.
Seria mais performática fazer um parser especializado, mas complica mais ainda.
Pode ser que um RegEx ajude, mas não gosto da ideia, é fácil fazer errado. Tem exemplos no SO (outro e com LINQ).
Um erro claro é usar o ToUpper(), isto não é correto. Veja a forma mais correta.
A variável palavrareservada não tem função alguma neste código, pode ser eliminada.
Ficar pegando as palavras direto do banco de dados pode não ser a melhor estratégia.
Comment: Com relação a este problema fiz testes com a utilização do split e também regex que separam o texto em palavras e, neste caso, acaba resolvendo.
1. Com relação ao ToUpper() que você disse que está incorreto. Exatamente no que?
2. Se possuir uma palavra reservada com duas palavras (NAO CONSTA, por exemplo) o tratamento teria que ser diferente do que a utilizada com split ou regex.
Comment: É ineficiente e há casos (não em português, é verdade) que não dá o resultado esperado.
Answer: Eu usaria Regex com o pattern \d para verificar a existência de palavras  inteiras na frase.
Regex.IsMatch("CAROLINE", @"\bORAL\b",RegexOptions.IgnoreCase); // false
Regex.IsMatch("Discurso oral", @"\bORAL\b",RegexOptions.IgnoreCase); // true
Regex.IsMatch("Nada consta contra", @"\bNada Consta\b",RegexOptions.IgnoreCase); // true

No seu código, ficaria assim:
if ( Regex.IsMatch(frase, "\\b" + palavras[i].PLR_DESC.ToString() + "\\b",RegexOptions.IgnoreCase ))

Comment: Olá @Fernando, esta forma, utilizando o Regex.IsMatch acabou resolvendo o problema. Muito agradecido.


When exactly is HttpResponse being sent to the client in .net core API middleware pipeline?

Question: I am so confused about when IIS sends back the response, I really want to know how this works under the hood since I am doing response logging and I don't want to corrupt the body.
This is my logging middleware Invoke which is called before the MVC middleware (controllers). Is the response sent IMMEDIATELY after controller returns its Ok method or does it wait for the rest of the middleware? Is there any chance of corrupting the response if I do logging this way?
public async Task Invoke(HttpContext context)
{
    var requestResponseLog = new RequestResponseLog
    {
        RequestTime = DateTimeOffset.UtcNow,
        Request = await FormatRequest(context)
    };

    Stream originalBody = context.Response.Body;

    using (MemoryStream newResponseBody = _recyclableMemoryStreamManager.GetStream())
    {
        context.Response.Body = newResponseBody;

        await _next(context);

        newResponseBody.Seek(0, SeekOrigin.Begin);
        await newResponseBody.CopyToAsync(originalBody);

        newResponseBody.Seek(0, SeekOrigin.Begin);

        requestResponseLog.ResponseTime = DateTimeOffset.UtcNow;
        requestResponseLog.Response = await FormatResponse(context, newResponseBody);

        _requestResponseHandler(requestResponseLog);
    }
}

Answer: Think of each registered middleware as a step along the path of creating a request. Your invoke method is "your" step on that path. The await _next(context); instructs the framework to move onto the next middleware in the pipeline at that point - but - come back after the rest of the middlewares have executed, so that your code can be picked back up again.
So.. With that in mind, lets assume we have 3 middlewares set up. The pipeline works like this:
[REQUEST COMES IN]
Middleware-1 => Middleware-2 => Middleware-3
[THE RESPONSE IS PRODUCED]
Middleware-3 => Middleware-2 => Middleware-1
[RESPONSE GOES OUT TO CALLER]
Lets say you added await _next(context) into Middleware2's Invoke method. When the code reaches that point, it skips onto the next middleware in the pipeline, but it knows to stop there when it comes back through with the response. So you can intercept it again.
If you are logging a request, your custom code would go before that await _next(context) call. If you are logging a response, it would come after that call.
Note: Additionally, middleware ordering is determined by the order they are registered in your Startup class.
Comment: Hi Robert, thank you for your reply, I understand, however: some people have told me that response goes out to the caller **immediately after** the response has been written to.
Comment: They could be both correct, and wrong. It depends on what you plan to do with the request. **If** you want to change the response sent back to the client, thats a slightly different issue. Since, trying to edit the response once its created will cause problems.


How to programmatically apply a fee/promotion?

Question: I am trying to use the new commerce_fee module to programmatically apply a fee during admin payment flow. I did a simple form_alter to the commerce_payment_add form to have a list of my Fee entities show up as checkboxes. This allows staff to add the specific fee if they choose.
I also set:
<code>$form['payment']['amount']['#default_value']['number'] = $form['payment']['amount']['#default_value']['number'] + $form_state->getValues()['fee_amount'];
</code>
so that the fee is added in to the next step as the amount which will be charged to the customer's CC.
But the Fee is not properly added to my Order. I have seen Commerce documentation and a post here re: this but they do not work. At the moment I have a #submit added to the payment_add_form which follows some of the code I have seen; but no luck:
<code>function _sia_add_fee_to_order (&$form, $form_state) {
  // its crazy that i need to figure out the Order from the URL; why isn't it in the form??
  $url = $_SERVER['REQUEST_URI'];
  $bits = explode('/', $url);
  $order_id = $bits[4];

  $order = Order::load($order_id);
  $fee = current(Drupal\commerce_fee\Entity\Fee::loadMultiple());

  $price = $fee->getPlugin()->getConfiguration()['amount'];
  $splitter = \Drupal::getContainer()->get('commerce_order.price_splitter');
  $amounts = $splitter->split($order, new Price($price['number'], $price['currency_code']));

  foreach ($order->getItems() as $order_item) {
    $order_item->addAdjustment(new Adjustment([
      'type' => 'fee',
      'label' => $fee->getName(),
      'amount' => $amounts[$order_item->id()],
      'source_id' => $fee->id(),
    ]));
  }

  $fee->apply($order);
  $order->recalculateTotalPrice();
  $order->save();
}
</code>
The post I saw here left out all the commerce documentation steps of adding adjustments to each line item and simply had the $fee->apply() function. Neither of theses work.
ADDED:
More info about commerce_fee: https://www.drupal.org/project/commerce/issues/2903716, https://github.com/lisastreeter/commerce_fee
This is basically the commerce "promotion" module but redone to be more specific to fees. The question i have posted could be asked re: promotions as well; as should apply equally to either.
Comment: Could not find the commerce fee module that you speak of. Can you provide link?
Comment: Added info/links to original post. Basically it is the same as "promotion" module; but for fees. The same same question could be asked of how to add a promotion and it would likely apply the same to my question.
Comment: try using the service instead, `$fee = \Drupal::service('commerce_fee.fee_order_processor');`
Comment: Not sure how that would be used. I see that service has a method called process; which requires an OrderInterface rather than an order Entity, so i added this: $processor = \Drupal::service('commerce_fee.fee_order_processor');
  $orderInterface = OrderInterface::load($order->id());
  $result = $processor->process($orderInterface); and i get this error: Cannot call abstract method Drupal\Core\Entity\EntityInterface::load()
Answer: After a lot of trial and error I thought of moving the code out of the form submit function and into an event subscription; in particular, i moved it to the commerce_order.order.paid event.
So I ended up with this in an existing event subscriber call back I already had:
<code>  public function placeOrder($event) {
    $order = $event->getOrder();

    $fee = current(\Drupal\commerce_fee\Entity\Fee::loadMultiple());
    $price = $fee->getPlugin()->getConfiguration()['amount'];
    $splitter = \Drupal::getContainer()->get('commerce_order.price_splitter');
    $amounts = $splitter->split($order, new Price($price['number'], $price['currency_code']));
    foreach ($order->getItems() as $order_item) {
      $adjustments = $order_item->getAdjustments();
      $adjustments[] = new Adjustment([
        'type' => 'fee',
        'label' => $fee->getName(),
        'amount' => $amounts[$order_item->id()],
        'source_id' => $fee->id(),
      ]);
      $order_item->setAdjustments($adjustments);
      $order_item->save();
    }
  }
</code>
This code includes code to split the fee up among all the items; which may or may not be what you want (although doesn't seem like it could ever be a bad idea).


How to combine two series of solutions into one?

Question: I have an equation, like
$$\sin\left((\beta-1)\sqrt{\xi^2-\gamma^2}\right)\sin\xi=0,$$
with $\beta>1$ and $\gamma>0$. I've found two series of solutions, corresponding to roots of each of the $\sin$ factors:
$$\xi'_{n'}=\pi n',$$
$$\xi''_{n''}=\sqrt{\left(\frac{\pi n''}{\beta-1}\right)^2+\gamma^2},$$
where $n',n''\in\mathbb{Z}$. Now I'd like to get a single explicit expression for $\xi_n$, where $n$ would numerate the equation solutions, so that $\xi_n>\xi_{n-1}$.
I can of course make some sort of an algorithm which would take finite number of steps to figure out the correct $\xi_n$ given some particular $n$. But I'd like to have an explicit expression, which would allow to just compute $\xi_n$ without any iterations or whatever. I.e. I want to have an explicit form for inverse of root-counting function.
How can I combine my solutions to achieve this? I'm mainly interested in enumerating such positive $\xi$ that $\xi^2\ge\gamma^2$, if this simplifies the problem.
Answer: Given two sequences of solutions $(a_n)$ and $(b_n)$, we can collapse them into a single sequence by defining
$$c_n:=\begin{cases}
a_{\frac{n+1}2}&\text{if }n\text{ is odd,}\\
b_{\frac{n}2}&\text{if }n\text{ is even.}
\end{cases}$$
You can easily show that
$$c_n=b_{\lfloor\frac{n}2\rfloor}+\frac12[(-1)^n-1](b_{\lfloor\frac{n}2\rfloor}-a_{\lfloor\frac{n+1}2\rfloor}).$$
In your case the use of the floor function is unnecessary, as your sequences have natural extensions to $\{\frac{n}2\,|\,n\in\mathbb{N}\}$. I can't think of many situations where the above form is preferable to simply expressing it as two sequences, though.
EDIT: I missed the condition $\xi_n>\xi_{n-1}$. In many cases that will be impossible, for instance if either $(a_n)$ or $(b_n)$ is bounded but contains infinitely many distinct points. It certainly doesn't look possible for this case, although it would depend on the specific values of $\beta$ and $\gamma$.
Comment: This doesn't seem to satisfy $c_n>c_{n-1}$.
Comment: Ah, I missed that condition. I'll edit.
Comment: Why do you think this is impossible for this case? Both sequences are unbounded and in fact they both grow almost linearly for large $n$. See also update about $\beta$ and $\gamma$ values.
Answer: Let's study how root counting function for this equation behaves. For this, define:
$$
\begin{align}
n_1(\xi)&=\xi/\pi,\\
n_2(\xi)&=(\beta-1)\sqrt{\xi^2-\gamma^2}/\pi
\end{align}$$
and consider only the case of $\xi>\gamma$ (the other case is much simpler because only $\sin\xi$ will have zeros then).
The root counting function can then be defined as
$$n_r(\xi)=\lfloor n_1(\xi)\rfloor+\lfloor n_2(\xi)\rfloor.$$
If we neglect the floor operations, we'll end up with the function, which estimates the root count
$$n'_r(\xi)=n_r(\xi)+\Delta(\xi)=n_1(\xi)+n_2(\xi),$$
where $\Delta\in[0,2)$. Thus, $n'_r$ gives us an upper bound on $n_r$ with error of at most $2$ — due to fractional parts of $n_1$ and $n_2$.
Here's how the root counting function $n_r$, its upper bound $n'_r$ and lower bound $n'_r-2$ look for $\beta=2.9516$, $\gamma=24.25$:

Now we can use our estimating function $n'_r$ to find approximate inverse of root counting function, solving this equation:
$$\pi n=\xi_a+(\beta-1)\sqrt{\xi_a^2-\gamma^2},$$
for positive $\xi_a$ and getting
$$\xi_a=\frac{-\pi n+(\beta-1)\sqrt{(\beta-2)\beta\gamma^2+\pi^2n^2}}{\beta(\beta-2)}.$$
Since $n'_r(\xi)$ is an upper bound for root counting function, $\xi_a(n)$ is a lower bound for the inverse of root counting function.
Now that we have the lower bound for $\xi$, we have to determine which of the two series of solutions it is closest to. The candidate values for $n_1$ and $n_2$ are
$$n_{1c}=\lceil\xi_a/\pi\rceil,$$
$$n_{2c}=\left\lceil\frac{\beta-1}{\pi}\sqrt{\xi_a^2-\gamma^2}\right\rceil=\lceil n-\xi_a/\pi\rceil.$$
There're only two possible candidates for $n$, because the error $\Delta$ is strictly smaller than $2$. Thus candidates values for $\xi$ are
$$\xi_{1c}=\pi n_{1c},$$
$$\xi_{2c}=\sqrt{\left(\frac{\pi n_{2c}}{\beta-1}\right)^2+\gamma^2}.$$
Now, since $\xi_a$ is smaller than both of $\xi_{1c}$ and $\xi_{2c}$, we can write $\xi$ as
$$\xi=\min(\xi_{1c},\xi_{2c}),$$
which is the explicit formula for $\xi(n)$.


What is this old time signature (2 with a vertical line through it)?

Question: On the fourth line of page 5 of the score of Fasch's Ouverture-Suite in F major, one reads a time signature that is the number 2 with a vertical line through it:

What does it mean? I know some 'standard' old time signatures, but I have never seen this one.
Comment: Well, it looks like the first bar lasts for 5 beats and the rest - 4. The symbol looks like an odd combination of a 2 and a 4. It's familiar, but I don't remember how to interpret it.
Comment: @Pyromonk since it appears at the beginning and end of a part that should be repeated: could this be a predecessor of today's volta brackets?
Comment: @Pyromonk the first bar is four quarters long: 8th rest, 16th rest, 16th note, dotted 8th note, 16th note, dotted quarter note, 8th note.
Comment: @phoog, I meant the first bar after the mystical symbol, not the first bar of the piece.
Comment: @Pyromonk oh! That bar is actually a five-measure rest, so it's 20 quarters long (or ten half notes).
Comment: @phoog, yep, that's what I meant by 5 beats! It's quite mystical...
Comment: @Pyromonk but if you're counting quarter notes (which I presume you are because you say the rest of the piece has four beats per measure) then that "bar" is a 20-beat rest.  It's 5 *bars,* not 5 beats.
Comment: @phoog, I am officially confused. I have no idea what we're talking about (where in the piece each one of us is) and what mistake you think I am making.
Comment: @Pyromonk I'm talking about the notation `5.` just to the right of the red arrow in the picture included in the question, in the bottom-right corner.  That bar indicates 20 beats of rest, using two different methods.  The first is the number 5, meaning "this is a 5-measure rest," and the second is the two rests in the staff.  The first of those, between the second and fourth lines, is a [longa](https://en.wikipedia.org/wiki/Longa_(music)) rest (worth four semibreves/whole notes) and the second is a semibreve/whole note rest, for a total of 20 beats.  Were you talking about a different spot?
Comment: @phoog, I was talking about the same spot, but I now see that we must have been using a different definition of "beat". How exactly do you define "beat"? I basically meant quarter notes. Thank you for using both the British and the American terms to clearly indicate your message.
Comment: @Pyromonk since it's not clear whether either section of the piece is in 2/2 or 4/4, I adopted your assumption that it's in 4, counting the quarter note (crotchet) as the beat.  If the section is in 2/2 then the rest is 10 beats long, counting half notes (minims).
Comment: @Pyromonk to put it another way, let's assume that a metronome is set to 120 quarter notes (or, equivalently, 60 half notes) each minute, so a single measure is 2 seconds.  Your comment seems to say that the bar in question is 2.5 seconds, but actually it is 10 seconds.
Answer: This should really be a comment, because I have no answer to the question.  But as I need to show  a picture...
Here's the bit following the strange time signature.  It continues in the same bar lengths.

(Also interesting to note the very literal G clefs.  A letter G on the second line.)
Comment: Is that cut 2/2 time or double cut time or some such thing? Is there such a thing?
Comment: Maybe it would be worth editing the question to insert the image there...
Comment: @David, take a look at the updates to my answer.  Still a bit of a mystery
Comment: @DavidBowling I suspect that the c-slash time is actually 4/4; it would be very unusual for a French overture to be in 2/2.
Answer: This is a good question.  I cannot explain the time signature, but I am certain that it is a time signature.  As evidence against the hypothesis that it is somehow a part of the repeat sign, note the last movement of the piece, which has repeats, but lacks the sign in question.
Note also the fact that the c-slash time signature is reintroduced at the end of the second section, which is why the unexplained time signature must be included after the final repeat sign as well as after the first repeat sign.  The reintroduction of c-slash can be seen on the second page of the first violin part, at the end of the tenth staff.  There is also a fermata on the first note of this measure, but it is difficult to see in this part because it is squeezed between the f' on that staff and the c''' on the staff below.
This is a natural manifestation of the French overture form, which typically begins with a slow stately section with dotted rhythms, followed by a faster fugato section.  Anyone familiar with Handel's overtures knows that there is normally a brief return to the stately tempo at the end of the movement; here the road map is slightly different, such that the fugato section is followed by a return to the stately material and is then repeated without returning to the stately material.
Back to the symbol in question, I would note that its form is rather different from that of the numeral 2 written at the top of the Violin 2, Oboe 2, and Horn 2 parts, as well as the 2/4 time signature of the Andante Air.  Of course, that doesn't exclude the possibility of the symbol in question nonetheless being derived from the numeral 2.
From the context, then, we can infer that the symbol implies a faster tempo.  I suspect that the c-slash section is probably actually in 4/4, not 2/2, given the norms of the French overture form  (The standardization of c-slash to mean 2/2 came later; for example, in Bach's Mass in B minor, the second Kyrie is in c-slash meter but has four half notes per measure.)
The meaning of the c-slash time signature for measures with four quarter notes could perhaps be established with more certainty with more knowledge about when these parts were prepared and by whom, and with some comparative study of Fasch's other overtures.  If the stately section is indeed in a four-beat meter, it's reasonable to infer that the 2-slash means two beats per bar instead of four.
Comment: It is helpful if those who downvote explain what they think is wrong with the answer.
Comment: In the [Musescore](https://www.musescore.org) [time signatures](https://musescore.org/en/handbook/2/time-signatures) palette, the 2 with a line through it means Cut Time (Bach) which meant 2/2 in Bach's time. While transcribing Fasch's Overture-Suite in F major in Musescore from the edition in the body of the question, for every ¢ time signature in the manuscript, use 4/4 or C and for every 2-with-a-line-through-it time signature, use 2/2 or ¢ in Musescore. The 3 with a line through it in the time signatures palette means Cut Triple Time (9/8).
Answer: update number 2
I took a look at the following pages in the IMSLP link, and observed thattheree is a "repeat" sign at the end of the Overture followed by a "VS" indicator (and nothing else).

So now one wonders exactly what the " :||: "  marking indicates as well!  I'm leaning towards the  ":||: {slash2} " is an old way of indicating a repeat section, and nothing else.
Some digging...  here

The general principles of ancient time signatures are that three
strokes or a circle or the figure 3 denote perfections, or ternary
divisions, and two strokes, or a semicircle, or the figure 2 denote
imperfection or binary division. A line drawn through a circle or
semicircle, or the inversion of these figures, shows diminution of the
value of the notes to the extent of one half, so that longs are to be
sung as if they were breves, breves as if they were semibreves, etc.

Without seeing the following measures, can't tell if that slash thru the "2" is stylistic or some oddball hack.
previous info, where I looked at the top of the image --
It looks to me like the standard "Cut Time" notation, indicating 2/2.
quoting the online Dolmetsch (which everyone should bookmark),

alla breve: also called 'cut time' or 'alla cappella time'; marked
with a large C with a vertical line through it, used for quick duple
time in which the minim or half note is given one beat instead of two.
(occasionally written with two parallel vertical lines through a large
C)
Comment: Oh, --- I see you mean that bit at the end of the image.  How about you post an image of the measures **following** that  slash-2 so we can see what is written?
Comment: @JimM -- you have to look all the way at the end of the last line of the posted image to see that OP isn't talking about the cut time that the piece starts in, but about a clear "2" with a cut line through it.
Comment: But the piece was already in cut time. I am wondering if this is indicating 2/4 time. The marking looks like a stylized 2/4.
Comment: Oh dear this does make me feel old.  I recall learning this at school. As @Carl Witthoft says this is Alla Breve or 2/2.  A big "C" was shorthand for common time  (4/4) whereas a big "C" with a line through it was shorthand for Alla Breve or 2/2 time.
Comment: Whoops.  My bad.  Still feel old though.
Comment: The sign is certainly a time signature.  It is used at the final repeat because c-slash time is reintroduced in the middle of the second section.  Also note that the repeats in the final movement lack this sign.  See [my answer](https://music.stackexchange.com/a/74757/2257) for more detail.
Comment: @DavidBowling The first link in the question points to a PDF containing the entire set of parts for all three movements.  The c-slash is already weird, as I noted in my answer, since the opening of a French overture would normally be in 4/4, though it might be possible to do this as a very slow 2/2.  Playing the fast section in 1/1 is seriously unlikely to work, however.  Unfortunately, Fasch has a huge body of work available on imslp, so going through all the manuscripts to seek other instances of this symbol would be very time consuming.
Comment: @DavidBowling there's another movement in 2/4 time and the sign looks nothing like this one (and very much like a 2 over a 4).  There are also 4 quarters per measure here rather than 2.
Comment: @phoog -- when I was pondering 2/4, the post did not show subsequent measures. Unless this music departs from conventional notation, it begins in cut time (2/2). The symbol in question (the 2 with a cut through it) could indicate cut 2/2 time (i.e., 1/1, or perhaps double cut time). I have never seen this before, but it would be consistent with conventional usage of the cut-line and the subsequent 4 quarter notes per bar supports this interpretation. That is what my later comment was attempting to suggest.


Entrada única no formulário asp.net

Question: Tenho um código que faz o cadastro de certo tipos de equipamento, os campos de formulário que tenho são: Nome, Servidor, Tipo e Porta do equipamento.
Gostaria que não fosse possível o usuário cadastrar dois equipamentos com a mesma porta e não sei como fazer.
Meu código asp.net é:
<%@ Page Title="" Language="C#" MasterPageFile="~/interna.master" AutoEventWireup="true" CodeFile="equipamentocadastro.aspx.cs" Inherits="usuariocadastro" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolderCorpo" Runat="Server">

                                                                Cadastro de equipamentos

Entrada única no formulário asp.net


Type 1 and Type 2 Errors with Costs

Question: I know the ex-ante cost of type 1 and type 2 errors in my study. How do I select my alpha, given that I know that alpha governs both type 1 and type 2 errors?
Suppose my null is that $\beta=0$ and my alternate is that $\beta=10$. I know that if the null is true and I accept the alternate i.e. type 1 error, through some policy choice, I will incur a cost of 100 dollars. If alternate is true but I make an error of selecting null and basing policy on null, I will incur a cost of 50 dollars. SD is same at 2 for both the cases i.e. when null is true or alternate is true.
$\alpha$ governs both type 1 and type 2. How should I optimally set it?
Comment: What do you mean "select" alpha? You already stated that you know your type 1 error. And besides, alpha is chosen at the beginning and is fixed.
Comment: @user2974951 I mean that I can select what width of CI interval to look at. I know the cost of the type one error. What alpha or cutoff should I use. Using smaller alpha  reduces type I error but increases type 2 error, whose cost I also know. I am unable to write down a maximization problem for the optimal alpha.
Comment: That's not how it works, you select your alpha at the beginning, this is fixed, for ex. 5 %. Then you estimate what your type 2 error / power will be based on this. You don't try to "optimize" type 1 and type 2. This could be considered p-hacking.
Comment: @user2974951 I understand that it is bad practice. I am wondering if it can be done for self-study reasons.
Comment: Well, in that case, yes it is possible. Can you post an example in your question?
Comment: @user2974951 Added a small example. Is this what you are looking for or something more?
Comment: We also need a measure of SD for both cases, null and alternative, or if you assume equal variances just one.
Comment: @user2974951 added SD
Answer: I don't think this is really about Type 1 and 2 errors. This looks more like an optimization problem. Nevertheless, considering what we discussed in the comments, solving this is a simple problem.
What we need to do is, for every value of alpha (CDF of the null distribution in the upper tail) multiply it by 100, that is how much you will pay on average for type 1 errors. To this you add how much you will pay for type 2 at this point, which is the CDF / probability / p-value of the second distribution in the lower tail.

You can repeat this for many such points and find the minimum, that is minimize loss.
Comment: Do I need a prior on with what probability is null hypothesis correct and with what probability is alternate hypothesis correct? Because, $\alpha$ is type 1 error only under null and similarly the blue region represents type 2 probability only true under alternate. So do   I need the prior to write the optimization problem?
Comment: @user52932 What do you mean by prior? You need the distribution of the two hypotheses, so mean and SD in case of a normal distribution, that is all. The hypotheses are clearly defined beforehand.
Comment: I mean, that what is the correct loss function here? Isnt the correct loss function: (Probability that null is true) * (Probability of error under null true) * (cost of type 1 error) + (Probability that alternate is true) * (Probability of error under alternate true) * (cost of type 2 error). I know the cost. I think $\alpha$ controls (Probability of error under null true)  and (Probability of error under alternate true). But don't I still need the outer probability i.e. which of the two distribution above happens?
Comment: @user52932 There is no probability on the null or alternative being true, these two are fixed, you fix them at the start and you suppose they are true, no probability. If you had the probabilities of null alternative being true, why even do all this? You would choose the most likely ones and do your optimization on them?
Answer: It seems to me that you are finding this difficult because you are focussed on only two aspects where there are (at least) four that are important: sample size; effect size; false positive errors; and false negative errors. You might find the section 2.5 of this chapter helpful when thinking about experimental power and design: https://link.springer.com/chapter/10.1007/164_2019_286
A larger sample size will always yield a smaller error rate than a smaller sample size, but sample size rarely comes for free. That means that you need to account for the cost of data acquisition (time, money, effort, etc.) when trying to optimise the design of an experiment. Consider the fact that if the data are free then you can simultaneously minimise false positive error rates and maximise power by simply obtaining a massive dataset!
Effect size is equally important, but in some ways more nebulous. It is not really sufficient to say that a false negative error costs $x, as false negative errors sometimes involve missing an important (i.e. large) effect and sometimes a trivially small effect. If you are interested mostly in finding large true effects then you can probably use a design with lower power by either designing a smaller sample or using a lower pre-set alpha value. It is common to input either the 'expected' effect size or the effect size that one would like to have designed power to avoid missing (or both) when doing a power analysis, but inspection of the full power vs effect size curve is more useful than the usual analysis where a single number for power or sample size is obtained. See the graphs in Figure 4 here: https://link.springer.com/chapter/10.1007/164_2019_286
If you just think about the error rates with all-or-none costings then you will generate an experimental design that is sub-optimal in the real-world considerations that should be primary.

Type 1 and Type 2 Errors with Costs


Pesquisa em tempo real com jQuery

Question: Eu tenho o seguinte código para fazer um pesquisa em tempo real com jQuery, buscando valores dentro de uma tabela:
$(document).ready(function () {

    $(".nada").hide();

    var $rows = $('.linhas');
    $('#search').keyup(function () {

        var val = '^(?=.*\\b' + $.trim($(this).val()).split(/\s+/).join('\\b)(?=.*\\b') + ').*$',
            reg = RegExp(val, 'i'),
            text;

        $rows.show().filter(function () {
            text = $(this).text().replace(/\s+/g, ' ');
            return !reg.test(text);
        }).hide().filter(function () {

            $(".nada").show();

        });

    });

});

Porém ocorre um problema: mesmo que retorno apenas um valor igual ao que é digitado, ele cai no hide() e mostra o $('.nada').show().
Como posso arrumar isso?
Comment: não sei se te ajuda ou se vc pode usar uma lib jquery para isso mas eu uso essa aqui: https://mottie.github.io/tablesorter/docs/example-option-theme-bootstrap-v4.html
Answer: Você pode utilizar esta função passando o valor buscado e onde buscar:

 function busca(value,targetSelector){
        $(targetSelector).show();
        $(targetSelector+':not(:contains("'+ value +'"))').hide();
    }

    $('#search').keyup(function () {
       busca($(this).val(), '.linhas');
    })

  Nome
  Sobrenome

  paulo
  guina

  jailson
  mendes

  silas
  malafaia

  marcos
  feliciano

<input id="search" placeholder="buscar">

A função vai mostrar tudo e depois esconder o que não contem o texto.

https://api.jquery.com/contains-selector/

Pesquisa em tempo real com jQuery


If $N$ is a submanifold of $M$ and $\dim M=\dim N$ then $M=N$?

Question: I need to prove that:
Let $M$ be a smooth n-dimensional manifold and $N$ a immersed submanifold of $M$. If $\dim M=\dim N$ then $M=N$
By the First Isomorphism Theorem it is clear that $i_{*x}:T_xN\to T_xM$ is a bijection for all $x\in M$. From here, how can I prove that $M$ must be equal to $N$?
Comment: This is not true as stated. Are you assuming $M$ is connected?
Answer: Any non-empty open subset $U$ of $M$ is naturally an embedded (hence immersed) submanifold of $M$. And $\dim U=\dim M$.


Finding $\lim_{n\to\infty}(\frac{1}{\sqrt{n^2+1}} + \frac{1}{\sqrt{n^2+2}} + ... + \frac{1}{\sqrt{n^2+n}})$

Question: I'm trying to find $\lim_{n\to\infty}(\frac{1}{\sqrt{n^2+1}} + \frac{1}{\sqrt{n^2+2}} + ... + \frac{1}{\sqrt{n^2+n}})$.

I tried to use the squeeze theorem, failed.
I tried to use a sequence defined recursively: $a_{n+1} = {a_n} + \frac{1}{\sqrt{(n+1)^2 +n+1}}$. It is a monotone growing sequence, for every $n$, $a_n > 0$. I also defined $f(x) = \frac{1}{\sqrt{(x+1)^2 +x+1}}$. So $a_{n+1} = a_n + f(a_n)$. But I'm stuck.

How can I calculate it?
Comment: Can you elaborate on your squeezing? It should work.
Answer: It looks squeezable.
\begin{align}
\frac{n}{\sqrt{n^2+n}} \le \sum_{k=1}^n\frac{1}{\sqrt{n^2+k}} \le \frac{n}{\sqrt{n^2+1}}
\\
\\
\frac{1}{\sqrt{1+\frac{1}{n}}} \le \sum_{k=1}^n\frac{1}{\sqrt{n^2+k}} \le \frac{1}{\sqrt{1+\frac{1}{n^2}}}
\end{align}
Answer: If $k\in[1,n]$ then the difference between $\frac{1}{\sqrt{n^2+k}}$ and $\frac{1}{n}$ is rather small:
$$ 0\leq \frac{1}{n}-\frac{1}{\sqrt{n^2+k}} = \frac{k}{n\sqrt{n^2+k}(n+\sqrt{n^2+k})}\leq \frac{1}{2n^2} $$
hence $\sum_{k=1}^{n}\frac{1}{\sqrt{n^2+k}}$ tends to $1$ as $n\to +\infty$, since $\sum_{k=1}^{n}\frac{1}{n}=1$ and $0\leq\sum_{k=1}^{n}\frac{1}{2n^2}=\frac{1}{2n}$.
Answer: Hint:
$$n\frac{1}{\sqrt{n^2+n}}\leq\sum\frac{1}{\sqrt{n^2+n}}\leq n\frac{1}{\sqrt{n^2}}$$


What practical application is there for the Asymptotic Mean Integrated Squared Error in kernel density estimation?

Question: Introduction
For some time now I have been struggling to understand how theoretical results can be applied in practice. Fortunately in most cases the link between theory and practice is not hard to find, for instance:

You can directly use a theoretical result for your calculations.
You cannot actually find a solution, but you at least have an upper or lower bound that can indicate how good your real solution is.
By observing the theoretical formulas you can make something 'similar' and hopefully with similar performance
The general case is only theoretical, but in special cases it can be applied directly.

Well, this is not everything, but I won't try to make a complete list of how statistical theory can be useful. Until now I have always succeeded in at least grasping the idea of how theory can be applied in practice.
However, it now appears that I have stumbled opon something of which I cannot see how it could possibly be applied.
I was studying some smoothing methods, amongst which (nonparametric) kernel smoothing, as described on Wikipedia , and found that there is a theoretical solution for the AMISE, as well as the bandwidth,hAMISE that optimizes it. However, both in the notes that I was reading, as well as the Wikipedia page I have been unable to find any practical application of this.
The Question
Is there any practical application for the AMISE and its optimal bandwidth?
Discovering that there actually is an application for would be very motivating so I  hope it can be achieved!
Comment: Regarding the interpretation of `AMISE`, you have to understand first the "expected $L_2$ risk function". There are many distances that you could use instead of this, but MISE is the most common in the context of KDE. This is a helpful criterion given that it leads to an interpretable and formal choice of the bandwidth. There are several applications of this, for instance see [this answer](http://stats.stackexchange.com/questions/30141/determine-if-a-heavy-tailed-distributed-process-has-improved-significantly/30148#30148) in the context of reliability.
Comment: My last two cents: I think one of the uses of the MISE and AMISE is for comparing the performance of different kernels in terms of efficiency. See [Comparison of Data-Driven Bandwidth Selectors](http://www.jstor.org/stable/2289526).
Comment: @Procrastinator Thank you for your thoughts, I understand that MISE is a measure to define which estimation is "better". However, this does not yet make it clear to me what the implications are of a theoretically optimal, yet always unknown AMISE.
Answer: The AMISE allows one to obtain an expression for the optimal bandwidth for the unknown density $f$. Unfortunately, the expression is in terms of derivatives of $f$. However, it is possible to derive a similar expression giving the optimal bandwidth for a kernel estimate of those derivatives. This is expressed in terms of even higher derivatives of $f$. And so on.
This seems like it might be an unending sequence of pointless theory. But the neat thing is, that for some sufficiently high order derivatives you can just assume that $f$ is normal. Then you can work your way back through the levels to find the bandwidth for $f$. It turns out that this works really well and almost nothing is lost provided $f$ is sufficiently smooth and enough levels of iteration are used (usually only 2 or 3 levels are needed).
The practical result is a bandwidth selection method which is general and quite robust. The most popular version of this is the Sheather-Jones plug-in method which is implemented in several software packages. In R, you can get a density estimate using the Sheather-Jones method:
density(x, bw="SJ")

That usually gives better results than the default bandwidth.
Comment: (+1) Nice explanation, particularly the conditions for obtaining a good performance of the Sheather-Jones method.


Dynamically render FontAwesome icon in NativeScript view

Question: If I try to render a hard-coded FontAwesome icon in a NativeScript view, like so:

...then it displays correctly. However, if I try to render a dynamically generated FontAwesome icon instead, by either using text="{{ item.faIcon }}" or [text]="item.faIcon", like so:
private buildMenuItems() {
        this.menuItems = [];
        this.menuItems.push({ title: 'Alerts', faIcon: '', url: '/alerts/list' });
        this.menuItems.push({ title: 'Properties', faIcon: '', url: '/properties/list' });
        this.menuItems.push({ title: 'Tenants', faIcon: '', url: '/tenants/list' });
        this.menuItems.push({ title: 'Accounting', faIcon: '', url: '/accounting/transactions/list' });
        this.menuItems.push({ title: 'Task Management', faIcon: '', url: '/todos/list' });
        this.menuItems.push({ title: 'Documents', faIcon: '', url: '/documents/list' });
        this.menuItems.push({ title: 'Reports', faIcon: '', url: '/reports/list' });
        this.menuItems.push({ title: 'Notes', faIcon: '', url: '/notes/list' });
    }

<WrapLayout orientation="horizontal" itemWidth="120" class="menu">
        <StackLayout orientation="vertical" *ngFor="let item of menuItems" (tap)="selectMenuItem(item)">

        </StackLayout>
    </WrapLayout>

...then it displays the faIcon characters as text instead of the actual icon. How can I display the actual icons?
Answer: The answer was to encode the font-awesome icons in the Component.ts:
this.menuItems.push({ title: 'Alerts', faIcon: String.fromCharCode(parseInt('f0f3', 16)), url: '/alerts/list' });

Answer: you need to decode the icon Unicode using String.fromCharCode()
view.text = String.fromCharCode(0xf0f3)


DropDownListFor ASP MVC4

Question: I am getting this error "CS1928:

'System.Web.Mvc.HtmlHelper' does
  not contain a definition for 'DropDownListFor' and the best extension
  method overload
  'System.Web.Mvc.Html.SelectExtensions.DropDownListFor(System.Web.Mvc.HtmlHelper,
  System.Linq.Expressions.Expression>,
  System.Collections.Generic.IEnumerable)'
  has some invalid arguments"

My controller looks like this
    public class IndexController : Controller
{
       public ActionResult Index()
       {
               EpfeSelectScreen model = new EpfeSelectScreen();

               var b = (from a in dbEntitiesErste.CONFIG_APPLICATIONS
                               orderby a.APPLICATION_ID
                               select new EPFE.CustomDataObjects.CustomObjects
                               {
                                   Text = a.APPLICATION_NAME,
                                   Value = a.APPLICATION_ID
                               });

               model.Application = b.OrderBy(x => x.Text).ToList();

               return View(model);

       }
}

My model is this
    public class EpfeSelectScreen
{
    public string Search { get; set; }
    public string selectedApplication { get; set; }
    public List<SelectListItem> Country { get; set; }
    public List<CustomObjects> Application { get; set; }
    public List<SelectListItem> MetaData { get; set; }
    public List<SelectListItem> References { get; set; }
    public List<SelectListItem> ReferencedBy { get; set; }
    public List<SelectListItem> TreeView { get; set; }

    public EpfeSelectScreen()
    {
        Country = new List<SelectListItem>();
        Application = new List<CustomObjects>();
        References = new List<SelectListItem>();
        ReferencedBy = new List<SelectListItem>();
        TreeView = new List<SelectListItem>();
    }
}

My CustomObjects is this
    public class CustomObjects
{
    public string Text { get; set; }
    public short Value { get; set; }
}

I have one record in my model.Application, but when that data is passed to my View i get that error.
And my View looks like this
@model EPFE.Controllers.EpfeSelectScreen
@Html.DropDownListFor(m => m.selectedApplication, Model.Application)

How to solve this problem? What am i doing wrong? I get the same error when i try to use ListBoxFor.
Answer: DropDownListFor takes a SelectList as a second argument while you are passing a List.
You could have something like the following:
@Html.DropDownListFor(m => m.selectedApplication,
                     new SelectList(Model.Application,"Value","Text"))

Comment: It worked. Thank you. I didn't know that part with SelectList and List. You helped me alot.
Answer: For Adding items to drop down you can use ViewData for passing values to the dropdown.
in the controller:
you can have scenario like
       IList<SelectListItem> SelectedOptions = new List<SelectListItem>();
        IList<Options> DropDownOptions = new List<Options>();
        //Add items to this shipping
        foreach (var item in DropDownOptions)
        {
            SelectListItem sliItem = new SelectListItem();
            string optionText = item._name;
            sliItem.Value = item._value.ToString();
            sliItem.Text = optionText;
            SelectedOptions.Add(sliItem);
        }
        ViewData["Option"] = SelectedOptions;

and in the view you can simply use
 @Html.DropDownList("Option", ViewData["Option"] as SelectList)

while submitting the form if you are using the class, do remember to put a string property with the name option in the class so that you can use it in the controller also the selected value when the form is submitted.

DropDownListFor ASP MVC4


how to find pigeon holes in a question related to pigeon hole principle

Question: prove that every set of 10 two digit numbers has two disjoint subsets with the same sum of elements.
In this question i don't know how to choose the pigeon holes, or what will be the pigeon holes
Comment: Hint:  first verify the claim without the condition that the sets be disjoint (that's straight pigeonhole).  Then argue that you can produce disjoint examples out of non-disjoint ones.
Answer: Some of the better "pigeon hole" problems are quite subtle and it is not trivial to figure out how the principle will be used.
In this case, think of all the different sums you can create. (How many subsets, of all possible cardinalities, does a set with 10 elements have?) Those are the pigeons.
On the other hand, the sums are at most 1,000 (ten numbers, all two digits at most). These are the holes.
The pigeon hole principle, after you do the count in the second paragraph, will tell you that two of those sums, for two different subsets, must be equal. This doesn't give you DISJOINT subsets, but you can simply cancel out the common terms.


Como atualizar coluna para cada SELECT em determinada tabela?

Question: Tentei criar uma trigger para uma tabela usando para que ela fosse ativada após cada select, mas pesquisando um pouco descobri que não é possivel criar triggers para seleções, apenas para atualização (update), inserção (insert) e deleção (delete).
Minha aplicação é uma api e a mesma esta apresentando problemas em teste de Benchmark; toda vez que faço um select eu tenho uma outra função que executa um update e incrementa uma coluna desse registro selecionado. O problema é que muitos updates ao mesmo tempo estão causando este erro:

sorry, too many clients already

Foi ai que pensei em criar uma trigger direto no banco de dados para não ter que executar um update via código a cada select.
Este foi o código que criei em plpgsql para tentar incrementar a coluna:
create table urls(
    id integer not null,
    url varchar(255) not null,
    encoded varchar(255) not null UNIQUE,
    clicks integer DEFAULT 0,
    created_at timestamp not null DEFAULT current_timestamp,
    constraint pk_urls_id primary key (id)
);

CREATE OR REPLACE FUNCTION increment_clicks_counter()
    returns trigger as
        $BODY$
            BEGIN
                UPDATE urls SET clicks = clicks + 1 WHERE encoded = OLD.encoded;
            END;
        $BODY$
language 'plpgsql';

CREATE trigger increment_clicks AFTER SELECT ON urls
    for each ROW EXECUTE procedure increment_clicks_counter();

Como posso criar uma rotina para incrementar uma coluna a cada seleção de uma determinada tabela?
Este é o Benchmark que estou executando em GO:
func BenchmarkAPI(b *testing.B) {
    // Valores que estão presentes na coluna 'encoded' da tabela urls
    random := []string{
        "A", "B", "C", "D", "H", "F", "E", "G",
        "8", "5", "9", "6", "7", "2",
    }

    for n := 0; n < b.N; n++ {
        url := fmt.Sprintf("http://localhost:5000/%s", random[rand.Intn(len(random))])

        _, err := http.Get(url)
        if err != nil {
            b.Log(err.Error())
        }
    }
}

Answer: Infelizmente (ou felizmente), em PostgreSQL não existem TRIGGERS do tipo AFTER SELECT.
Porém, você pode resolver o seu problema "encapsulando" sua tabela em uma stored procedure escrita em PL/pgSQL.
Essa stored procedure seria capaz de recuperar os dados da tabela e depois gravar essa atividade em uma outra tabela específica, a tabela não poderia ser acessada diretamente e seus dados só seriam recuperados por meio dessa função de encapsulamento.
Considere a seguinte estrutura/dados:
CREATE TABLE tb_pessoa
(
    id BIGINT PRIMARY KEY,
    nome TEXT NOT NULL,
    nascimento DATE NOT NULL,
    sexo VARCHAR(1) NOT NULL
);

CREATE TABLE tb_log
(
    id BIGSERIAL PRIMARY KEY,
    tabela TEXT NOT NULL,
    operacao TEXT NOT NULL,
    diahora TIMESTAMP NOT NULL
);

INSERT INTO tb_pessoa ( id, nome, nascimento, sexo ) VALUES ( 1, 'JOAO',  '1980.02.10', 'M' );
INSERT INTO tb_pessoa ( id, nome, nascimento, sexo ) VALUES ( 2, 'MARIA', '1966.05.10', 'F' );
INSERT INTO tb_pessoa ( id, nome, nascimento, sexo ) VALUES ( 3, 'JOSE',  '1973.07.10', 'M' );
INSERT INTO tb_pessoa ( id, nome, nascimento, sexo ) VALUES ( 4, 'ANA',   '1984.03.10', 'F' );
INSERT INTO tb_pessoa ( id, nome, nascimento, sexo ) VALUES ( 5, 'JESUS', '1970.12.10', 'M' );

Essa função de encapsulamento ficaria mais ou menos assim:
CREATE OR REPLACE FUNCTION fc_wrapper_pessoa()
RETURNS SETOF tb_pessoa AS
$$
DECLARE
    rec tb_pessoa%rowtype;
BEGIN
    FOR  rec IN SELECT * FROM tb_pessoa
    LOOP
        return next rec;
    END LOOP;

    INSERT INTO tb_log ( tabela, operacao, diahora ) VALUES ( 'tb_pessoa', 'SELECT', now() );

    RETURN;
END
$$
LANGUAGE 'plpgsql';

As consultas a tabela tb_pessoa seriam todas feitas por meio dessa função, por exemplo:
SELECT * FROM fc_wrapper_pessoa();
SELECT * FROM fc_wrapper_pessoa() WHERE id = 5;
SELECT * FROM fc_wrapper_pessoa() WHERE nome = 'JESUS';
SELECT * FROM fc_wrapper_pessoa() WHERE nascimento BETWEEN '1960-01-01' AND '1969-12-31';

E por fim, para cada consulta feita na tabela tb_pessoa seria gravado um registro na tabela tb_log:
SELECT * FROM tb_log WHERE tabela = 'tb_pessoa' AND operacao = 'SELECT';

Saída:
| id |    tabela | operacao |                     diahora |
|----|-----------|----------|-----------------------------|
| 11 | tb_pessoa |   SELECT | 2018-06-14T16:06:18.073404Z |
| 12 | tb_pessoa |   SELECT | 2018-06-14T16:06:18.073404Z |
| 13 | tb_pessoa |   SELECT | 2018-06-14T16:06:18.073404Z |
| 14 | tb_pessoa |   SELECT | 2018-06-14T16:06:18.073404Z |

Se o que importa para você é a quantidade de consultas que a tabela sofreu:
SELECT count(1) FROM tb_log WHERE tabela = 'tb_pessoa' AND operacao = 'SELECT';

Saída:
| count |
|-------|
|     4 |

SQLFiddle
Comment: faz todo sentido! obrigado.


Does anyone explore non-linear transformations on IVs prior to regularization?

Question: I am intending to use penalized ordinal regression (the shrinkage method used is elastic net) as I have ~ 50 variables (using the ordinalNetpackage in R). My past experience with transforming IVs have been rather manual, inspecting residuals, fitting 'binned' effects and seeing if the relationship is linear etc. This obviously doesn't scale to situations with a large number of variables!
If I wanted to explore IV transformations in an automated way, does it make sense to generate all sensible transformations for IV's and supply this saturated model (incl. all transformations) to elastic net? I am having trouble finding examples of people using regularization to select specific transformations of an IV -- maybe this is because it is not recommended.
[EDIT]: Or maybe this is because regularization is moving more into the 'machine-learning' space, where transformations of the IVs are uncommon? It's been mentioned before here:
why-arent-power-or-log-transformations-taught-much-in-machine-learning
I appreciate any advice. Thanks!
Answer: I don't know why they don't teach certain things, but it doesn't mean that those things are not used. Machine learning research is at the moment taking two main avenues:
a) Narrow AI
b) General AI (aka AGI)
The hot potato for narrow AI these days is Deep Learning. The advantage of Deep Learning is that it is able to learn "relatively" complex functions, and training is done with numerical optimization techniques which are also relatively fast. However you are limited to the functions that are simple in the Chomsky hierarchy and also limited to low time and space complexities.
https://en.wikipedia.org/wiki/Chomsky_hierarchy
https://en.wikipedia.org/wiki/Theory_of_computation
Is this a big deal? For many problems not really, and there is the theoretical argument of growing the network size and make the claim that we are anyhow resource bounded.
But AGI guys will disagree with you: "How can one understand the complexities of our universe by discarding complex functions (that take forever to compute)?" with a shame on you attitude.
Now when you get into the realm of AGI you start building very complex models that require not only numerical optimization but also combinatorial optimization. It means you start trying different transformations with various different levels of complexity. And this is something horrendously slow, and that's why you need giant distributed computer farms. This is the automated equivalent of old-school statistics where you try transformations of variables.
Probably the reason you are not seeing it is AGI is somewhat a smaller and more esoteric community.
Comment: Very interesting answer, did not think to start looking for answers from the AGI community. Thanks!


RXJava2 "neverending" Observable

Question: I'm new to RX and got stuck with the next:
I'm using SQLBrite and when query method is called it gives me back a "neverending" Observable which listens to the db changes. When some items are emitted - I need to make some async calls in a loop and give back that items which I received. The sample code:
<code>public Observable<List<Entity>> execute() {
   return someManager.getAccount()
            .take(1)  // I do not need RX to trigger updates when account changed, so use take(1)
            .flatMap(accountOptional -> {
                if (accountOptional.isPresent()) {
                    SomeAccount account = accountOptional.get();
                    return someManager.getEntityDataSource()
                            .query(new EntitySpecification(account.getId()));
                }
                return Observable.just(new ArrayList<Entity>()); // No account - no entities
            })
            .flatMapIterable(entities -> entities)  // Here I have a list of entities i I need to make async calls to fill entities with some iiner data (some other entities)
            .flatMap(this::loadInnerData)
            .toList()
            .toObservable();
}

private Observable<Entity> loadInnerData(Entity entity) {
    return do some work with entity;
   }
</code>
The trouble comes when I use toList() - it waits till Observable ends it's job - but it will not be done, as this observable is listening to the db. How can I achieve ability to listen to not stop listening to the "neverending" Observable and loop async calls with RX (as it is done with loadInnerData())?
Answer: Maybe try with
<code>    return Observable.create(new Action1<Emitter<String>>() {
        @Override
        public void call(final Emitter<String> stringEmitter) {
          // here u can use onNext / onError
                            stringEmitter.onNext(s);

                            stringEmitter.onError(e);
                        }
                    });

            stringEmitter.setCancellation(new Cancellable() {
                @Override
                public void cancel() throws Exception {
                    subscription.unsubscribe();
                }
            });
        }
    }, Emitter.BackpressureMode.BUFFER);
</code>

RXJava2 "neverending" Observable


Constructors are not inherited but behaving strangely

Question: I have found this issue and I do not understand why constructors are being inherited in the first case.
As far as I know, constructors are not inherited. Am I missing something very important ?
class Bird {
{ System.out.print("b1 ");}
public Bird() {System.out.print("b2 ");}

class Raptor extends Bird
{
    static {System.out.print("r1 ");}

    public Raptor() {System.out.print("r2 ");}

    {
        { System.out.print("r3 ");}
        static {System.out.print("r4 ");}
    }

class Hawk extends Raptor
{
    public static void main(String[] args)
    {
        System.out.print("pre ");
        new Hawk();
        System.out.println("hawk ");
    }
}

The answer for the above is:
r1 r4 pre b1 b2 r3 r2 hawk
Comment: Clean up your formatting and be more specific about what you're trying to demonstrate.
Comment: That looks logical. What is the question? What do you not understand?
Comment: I asked how did the output come
Answer: If you don't explicitly call the parent class constructor (via super(...)) or another constructor from the same class (via this(...)), the 0-argument parent class constructor is implicitly called.
Specifically, your code public Raptor() {System.out.print("r2 ");} implicitly calls the Bird constructor as the first thing, as if you had typed public Raptor() {super(); System.out.print("r2 ");}
Works similarly for your Hawk subclass.
Comment: Thanks Elliot - updated


Find limit $\lim_{h \to \infty} \frac{1}{2n+1}+\frac{1}{2n+3}+....+\frac{1}{2n+(2n-1)}$ using Riemann sum.

Question: I want to find limit value using Riemann sum
$$\lim_{n\to\infty}\sum_{i = 1}^{2n} f(a+\frac{(b-a)k}{n})\cdot\frac{(b-a)}{n}= \int_a^b f(x)dx$$
Question:

$$\lim_{n \to \infty} \frac{1}{2n+1}+\frac{1}{2n+3}+....+\frac{1}{2n+(2n-1)}$$

Attempt:

$$\lim_{n \to \infty}\sum_{k=1}^n \frac{1}{n}\frac{1}{2+(2k-1)\frac{1}{n}}$$
  i try to isolate 1/n but i cant find way to make this become $f(\frac{k}{n})$ since k is stuck in $2k-1$, can someone give me a hint? thanks
Answer: Hint:)
Let $x_k=\dfrac{2k-1}{n}$ then $\Delta x=\dfrac{2}{n}$.
Edit:(
With $\Delta x=x_{k+1}-x_k=\dfrac{2k+1}{n}-\dfrac{2k-1}{n}=\dfrac{2}{n}$ we have by your notation
\begin{align}
\lim_{n \to \infty}\sum_{k=1}^n \frac{1}{n}\frac{1}{2+(2k-1)\frac{1}{n}}
&=
\frac{1}{2}\lim_{n \to \infty}\sum_{k=1}^n \frac{2}{n}\frac{1}{2+\frac{2k-1}{n}}\\
&=
\frac{1}{2}\lim_{n \to \infty}\sum_{k=1}^n \frac{1}{2+x_k}\,\Delta x\\
&=
\frac{1}{2}\int_0^2\dfrac{1}{2+x}\,dx\\
&=
\color{blue}{\ln\sqrt{2}}
\end{align}
Comment: sorry still dont get it..do you get $2/n$ out of the fraction?
Comment: @fiksx Full solution added.
Comment: thankyou so much!!, so here i can choose any $x_k$ but it will change the $\Delta x$ right? and also i try to substitute $0$ and $n$ to $k$ in $x_k=(2k-1)/n$ so it will produce $x_n=(2n-1)/n$ = $x_n=2-1/n$, how did you get 0 to 2 for the integral ?
Comment: $x_1=\dfrac1n\to0$ as $n\to\infty$
Comment: oh got it!!!!! thankyou somuch!!!! so in problem like this, the main point is to get $1/n$ out of the fraction and the rest will follow(?)
Comment: Can you find upper limit?
Comment: In your attempt you got $\dfrac{1}{n}$ out of fraction with factorization, this made $\Delta x$ in Riemann sum! right
Comment: yes, so as long as i can factorize the $1/n$ as $\Delta x$ out of the fraction, i just have to choose my $x_k$, and according to my $x_k$ it will determine the $\Delta x$ that will be use in the equation right?
Comment: Exactly, except that $\dfrac1n$ made $\Delta x$ with factor $\dfrac12$ which we pull out of our sum!
Comment: ok thankyou so much!!! really appreciate for the help!!! thanks for answering my questions too ^^
Comment: You'r welcome :))
Answer: The above limit can be written as $$\lim_{n \to \infty} 1/n \sum_{k=1}^n  \frac{1}{1+2k/n}$$  because when in the limit $n \to \infty$ $1/n=0$.Now standard formula can be applied.
Comment: how to isolate $1/n$ ?
Comment: I didn't get you @fiksk
Comment: can you give me more hint? and how to make $\frac{1}{1+2k/n}$?


Can someone explain the derivation to me?

Question: This is from some class notes of a friend. In the line marked as (??), I can't understand the inclusion of -2. When x belongs to [-2,2], the transformation isn't 1-1, I get all that. But when the transformation is 1-1, and x belongs to (2,3], why are we putting -2 in the lower limit of the CDF of Y? Shouldn't it be 2? Or why put a number at all...its all very confusing.
Answer: In the line above, we have $P[-2\leq X\leq \sqrt y]$. Translating this into the CDF of $x$, this is exactly equal to $F_x(\sqrt y) - F_x(-2)$.
To adress the more basic concern: For any $y$-value between $0$ and $4$, the value of $Y$ lies between $0$ and $y$, meaning $X$ lies between $-\sqrt y$ and $\sqrt y$.
When $y\geq 4$, the same bound of being between $-\sqrt y$ and $\sqrt y$ still applies to $X$, but this time we are also bound by the fact that $X\in [-2, 3]$. So $X$ can't go as low as $-\sqrt y$, it can only go as low as $-2$. Any value of $X$ between $-2$ and $\sqrt y$ (and no other values of $X$) is going to give $Y = X^2$ a value between $0$ and $y$, which is what we're after.
Comment: I understood that portion, I just can't understand why -2 and not +2? Because when y is varying from 4 to 9, x takes values 2 to 3. The pdf for x ranging from -2 to 2 is already covered separately. So I don't understand why -2...
Comment: I've edited the question accordingly
Comment: @AP_ I edited my answer a bit.
Comment: FINALLY. I've been trying to understand this for a few hours, don't know why it took me so long. Thank you so much.
Answer: $(*)$ is actually redundant.
It is enough to state that for $y\geq0$ we have $$F_Y(y)=F_X(\sqrt y)-F_X(-\sqrt y)$$ This however in the understanding that $y\geq4$ we have $F_X(-\sqrt y)=0$ and for $y\geq9$ we have $F_X(\sqrt y)=1$.
That comes into play later by taking the derivative in order to find the PDF.


Python: invalid literal for int() with base 10

Question: I'm getting an invalid literal for int() with base 10 where it seems as if the input stream is concatenating values generated in a loop.
def collectData():
    lst = makeCases()
    cases = int(input())
    for i in range(cases):
        size = int(input())
        case = []
        for j in range(size):
            value = int(input())
            case +=[value]
        insert(lst,case)
    return lst

That is the function generating the issue. The value and size variables are the problem as they seem to concatenate subsequent values before the conversion.
The makeCases() function generates a tuple on the form ("Case",[]).
EDIT: The code works fine locally but won't work in the hackerrank IDE
Comment: Python3 or Python2?
Comment: You're using `int(input())` in several places.  Obviously, `input()` is returning something other than a number string in one of those calls.  Find out what string you're passing to `int()` and fix it.  You could write your own `input_int` function that catches bad values and prints them out.  In any case, I don't think the problem has anything to do with concatenation.
Comment: You probably have an empty line, or the user just presses .  You should test the reply from `input()` before converting to an `int`, or use exception handling.
Comment: I was using python 3. The input strings are '3 ' for whatever reason.
Answer: As Tom Karzes has said, input() is returning something other than a number. Looking at the error message that is produced by Python, I assume you are using Python 3 but I will cover Python 2 too.
Python 2
input() checks if the given input from stdin is something it can evaluate to. It is equivalent to eval(raw_input()). (Pydoc)
>>> a = input()
123
>>> a
123
>>> abc = 3
>>> a = input()
abc
>>> a
3

It produces a different error when you input() something it cannot eval:
>>> a = input()
abc
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'abc' is not defined

Since it performs eval on the given input, it will assume that abc may be a variable name. It searches for it but throws an error because it couldn't find it.
Python 3
input() is the new raw_input() in Python 2. input() returns a string even if the given input is a number. (Pydoc)
>>> a = input()
123
>>> a
'123'

This is the most likely reason you would convert it to an int() after you get an input().
I can replicate your error message as so (in Python 3):
>>> a = int(input())
abc
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'abc'
>>> a = int(input())
123 123
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '123 123'

In conclusion, the most likely reason why it is returning such an error is because you are giving it something it cannot convert to an int.


Changing footer of a Magento theme

Question: I have a Magento installation. In the footer area I want to replace 'FROM TWITTER' block with a static block and text in it. Theme developer has helped me a little which he said I should go to /app/design/frontend/default/trego/template/page/html/footer.phtml and find the below code, then replace with my custom code.

<?php echo $this->__('From Twitter') ?>

            <?php echo $this->getChildHtml('twitterfeed'); ?>

Please tell me what code I should replace the above one with, so I can have a simple static block with text.
Answer: Create a static block with the content you want and replace the getChildHtml bit with
<?php echo ($this->getLayout()->createBlock('cms/block')->setBlockId('BLOCK_IDENTIFIER')->toHtml()); ?>

replace BLOCK_IDENTIFIER with the assigned identifier from your cms admin page
Comment: Anytime.  I like using this method because it allows for content update without editing files

Changing footer of a Magento theme