SQL Server stored procedure in .NET Core 6 Web API to produce JSON data used in Angular app

Question: I have a SQL Server stored procedure that has an ID parameter and returns a string in JSON format that is needed in the Angular app.
Here is a sample of the JSON needed:
[
    {
        "type": "date",
        "name": "asofdate",
        "ui":
        {
            "label": "As Of Date",
            "placeholder": "Enter a date"
        },
        "validators": { "required": "true" }
    },
    {
        "type": "select",
        "name": "scope",
        "ui": { "label": "Scope", "placeholder": "Select a scope" },
        "validators": { "required": "true" },
        "source": [
                     { "value": 1, "text": "ABC" },
                     { "value": 2, "text": "CDE" },
                     { "value": 3, "text": "FGI" }
                  ]
    }
]

Here is a what the result of running the stored procedure looks like:

When I run the Web API passing the ID parameter to the stored procedure, I would like to capture the response as a JSON object to be used in the Angular app.
But the Web API is returning this:
[
  {
    "jsonResponse": "[
                      {
                       \"type\":\"date\",
                       \"name\":\"asofdate\",
                       \"ui\":{\"label\":\"As Of Date\",\"placeholder\":\"Enter a date\"},
                       \"validators\":{\"required\":\"true\"}
                      }
                      ,
                      {
                       \"type\":\"select\",
                       \"name\":\"scope\",
                       \"ui\":{\"label\":\"Scope\",\"placeholder\":\"Select a scope\"},
                       \"validators\":{\"required\":\"true\"},
                       \"source\":[{\"value\":1,\"text\":\"ABC\"},{\"value\":2,\"text\":\"DEF\"},{\"value\":3,\"text\":\"GHI\"}]}
  }
]

Is there a way to get the JSON response from the Web API without all the "\" and without:
{
    "jsonResponse": "

so that it matches the sample above?
Here is the code from the Web API:
[HttpGet("{ReportID}")]
public async Task<ActionResult<IEnumerable<usp_ReportParameterResult>>> GetReportParameters(int ReportID)
{
    if (_context.usp_ReportParameterAsync == null)
    {
        return NotFound();
    }

    var op = new OutputParameter<int>();
    var JSONresponse = await _context.usp_ReportParameterAsync(ReportID, op);

    if (JSONresponse == null)
    {
        return NotFound();
    }

    return JSONresponse;
}

The stored procedure uses JSON_QUERY and JSON PATH to create the needed nested arrays.
So, in the angular code I have the following hard-coded:
  TESTDATA:any[] = [
{
  type:'text',
  name:'firstName',
  validators:{
    required:true
  },
  ui:{label:'First Name',placeholder:'Enter Your First Name'}
}
,
{
  "type":"date",
  "name":"asofdate",
  "ui":{"label":"****As Of Date","placeholder":"Enter a date","class":["date-picker-wrapper"]},
  "validators":{"required":"true"}
}

]
What I need is instead of this data being hrad-coded it is being dynamically generated from a Web API.
The hard-coded data looks like the following from browser debug:
[![enter image description here][2]][2]
From the web api data looks like the following:

It is not an array like the TESTDATA. Is the a way to get response from web api into an array format as required?
Comment: Since you've already got JSON content in the string you've returned from the stored procedure, have you tried to declare your method returns a [ContentResult](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.contentresult?view=aspnetcore-6.0) and then return [Content](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.controllerbase.content?view=aspnetcore-6.0) with the `application/json` MIME type?
Comment: Hi @HALO, it is a correct json type data and do you meet any problem when use it in Angular app?
Comment: I have not tried to access yet in the Angular app. I will give that a try and see if I encounter any issues.
Comment: I added more information above as the format of the data returned from web api is not in the required format.
Comment: Can you just run the proc directly to ascertain where the escape chars are being introduced?
Comment: See above. The stored procedure results from SSMS does not show escape characters but the results from web api does. I believe its an issue with the [] around the results pushing the data into 1 array element rather that 2 as we can see in the hard-coded TESTDATA.
Comment: actually I modified the stored procedure and it is now returning the data correctly in Angular the only thing now is how to remove the escape characters in the array
Comment: I was able to get the API to return the data like TESTDATA. The only problem is that the UI and validators still have the extra "\". I'm thinking that its a issue on the Web API piece that is calling the stored procedure to create the JSON data. The model for the data sets all values: type, name, validators an ui to string. Validators and UI are not strings. Is there another type I can use on the model?
Answer: Actually, easiest solution was to remove the backlashes in the Angular app by simply doing the following:
        for (let item of this.formattedJSON) {
        item.ui = JSON.parse(item.ui);
        item.validators = JSON.parse(item.validators);
    }


Prove that $b^2-4ac$ is NOT a perfect square.

Question: Given that the $3$-digit number $abc= 100a+10b+c$ (not to be confused with $a*b*c$) is a prime, $p$, prove that $b^2-4*a*c$ cannot be a perfect square.
So far, I tried to prove it by contradiction. Let $f(x)=ax^2+bx+c$, so that $f(10)=p$, and both roots of $f(x)$ must be negative integers (since $a,b,c$ are digits). Then, I substituted the values in for $p$, and got $p=a(10-x_1)(10-x_2)$, where $x_1, x_2$ are the roots of $f(x)$. $p$ must divide one of the factors, say $(10-x_1)$, but I cannot continue from this point.
Comment: In general the factors are rational numbers rather than integers, so while at least one must have a prime factorization in which $p$ is raised to a positive power, it's not obvious either factor must be an integer multiple of $p$.
Answer: If $b^2 - 4ac$ is a perfect square, considering the quadratic formula or its derivation, we see that the quadratic equation you mentioned, $ax^2 + bx + c$, has two negative rational roots. Hence we can write
$$f(x) = ax^2 + bx + c = (kx + l)(mx +n )$$
for positive integers $k,l,m,n$. We have $f(10) = p = (10k+l)(10m+n)$, so $p$ must have two 2-digit factors. This contradicts the fact that $p$ is prime.


How to calculate the MaxClient value in apache?

Question: I want to set an optimum value for MaxClient in apache for my production server.
What are the parameters that I should consider while calculating this value ?
Answer: Complementing @Sameer answer, I read a lot of this theme and what I do is this:

Get the Apache process average size:
server# ps -ylC apache2 --sort:rss

S   UID   PID  PPID  C PRI  NI   RSS    SZ WCHAN  TTY          TIME CMD
S    33  6233 25895  0  80   0  7432 72802 poll_s ?        00:00:00 apache2
S    33  6250 25895  0  80   0  7432 72802 poll_s ?        00:00:00 apache2
S    33  6278 25895  0  80   0  7432 72802 poll_s ?        00:00:00 apache2
S    33  6280 25895  0  80   0  7432 72802 poll_s ?        00:00:00 apache2
S    33  6577 25895  0  80   0  7432 72802 poll_s ?        00:00:00 apache2
S    33  6299 25895  0  80   0  7772 72891 poll_s ?        00:00:00 apache2
S    33  6295 25895  0  80   0  7776 72891 poll_s ?        00:00:00 apache2

As you can see in the SZ column my Apache process size is about 73 MB
Make the following formula
MaxClients: ((Total_Memory)(1024)(MB) - Other_processes_memory) / 73

For Example: I have 16 GB RAM, I might leave free 2 GB for any other processes
MaxClients: ((16*1024) - 2048) / 73
MaxClient: 196

This is what I use & my server is going great.
You have to consider that my Apache processes are a little heavy, so you could have processes about 50 MB or less.
Regards,
Your SZ is slightly the same for all Apache processes.
In my case I have values between 23 and 212 Mb

What value should I use in your formula ?
By the way in Apache 2.4 MaxClients has been renamed to MaxRequestWorkers.
Is your formula still valid for this new parameter ?
Regards
Comment: Not necessarily a global solution as there are many many other factors and programming to consider.
Answer: The answer from tachomi is not overly comprehensive, but seems like a reasonable way to begin estimating.
In addition to that, this will help you to figure out some of the resources Apache is currently consuming:
ps aux | grep 'httpd' | awk '{count = NR;} END {print count " Apache processes";}'
ps aux | grep 'httpd' | awk '{print $6/1024;}' | awk '{sum += $1;} END {print sum " MB total mem usage";}'
ps aux | grep 'httpd' | awk '{print $6/1024;}' | awk '{avg += ($1 - avg) / NR;} END {print avg " MB avg mem usage";}'

Comment: To improve accuracy, you should insert a `grep -v grep` after the `ps` command. Otherwise awk will also count the grep process.
Answer: Refer to the Apache Performance Tuning guide.
Quote
"You can, and should, control the MaxClients setting so that your server does not spawn
so many children it starts swapping. This procedure for doing this is simple: determine
the size of your average Apache process, by looking at your process list via a tool such
as top, and divide this into your total available memory, leaving some room for other
processes."


Using Whisper API to Generate .SRT Transcripts?

Question: I'm exploring the capabilities of the Whisper API and was wondering if it can be used to generate an .SRT file with transcriptions. From what I understand, this transcription to .SRT can be achieved when running the model locally using the Whisper package. Unfortunately, I don't possess the computational resources to run the model locally, so I'm leaning towards using the API directly.
Has anyone had experience with this or can provide guidance on how to approach it through the API?
import os
import openai
openai.api_key = API_KEY
audio_file = open("audio.mp3", "rb")
transcript = openai.Audio.transcribe("whisper-1", audio_file)
print(transcript.text)

Answer: A cursory look at OpenAI's docs shows that srt is a supported value for the response_format parameter on the /v1/audio/transcriptions endpoint.
With the official Python bindings you're using in your example, you should be able to pass this as a named parameter to your openai.Audio.transcribe() invocation:
transcript = openai.Audio.transcribe("whisper-1", audio_file, response_format="srt")


Google Gadget API remote-content issue

Question: In my Google Gadget JavaScript, I have an URL to call from Google Apps Script.
<code>function getFileId(postData) {
  var params = {};
  var url = "https://script.google.com/a/macros/mycompany.com/s/AAABBBCCCDDEEE-FFF-GGG/exec";
  params[gadgets.io.RequestParameters.POST_DATA] = postData;
  params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
  params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
  gadgets.io.makeRequest(url , responseFileId, params);
};
</code>
So, when the function responseFileId() has returned obj.text, it actually goes to the mycompany.com login screen. That means it needs authentication from that Gadget I did. Didn't that Google Gadget hold my current domain's Google credential for running the Google Apps Script at "https://script.google.com/a/macros/mycompany.com/s/AAABBBCCCDDEEE-FFF-GGG/exec"?
I tried to run manually with Google Chrome browser, (https://script.google.com/a/macros/mycompany.com/s/AAABBBCCCDDEEE-FFF-GGG/exec) and it returns value without showing up the login screen...
Can someone tells what step has been missing for this? Has this something to do with Google OAuth?
Answer: Instead of doing this. I found a better idea => Using  tags for remote website.

Google Gadget API remote-content issue


Problem cropping an image to a perfect square with GD library

Question: I use a class that automatically crops an image as a square based on some options. The problem is that when the image is of a certain width and height, the image is cropped but a 1px column of black pixels is added to the right of the image. I think that the problem is in  the mathematics used to generate the new image size... Maybe when the division of the height and the width gives a decimal number then the square is not perfect and the black pixels are added...
Any solution?
This is how I call the object:
<code>$resizeObj = new resize($image_file); // *** 1) Initialise / load image
            $resizeObj -> resizeImage(182, 182, 'crop'); // *** 2) Resize image
            $resizeObj -> saveImage($destination_path, 92); // *** 3) Save image
</code>
The part of the class I'm talking about:
<code>private function getOptimalCrop($newWidth, $newHeight)
    {

        $heightRatio = $this->height / $newHeight;
        $widthRatio  = $this->width /  $newWidth;

        if ($heightRatio < $widthRatio) {
            $optimalRatio = $heightRatio;
        } else {
            $optimalRatio = $widthRatio;
        }

        $optimalHeight = $this->height / $optimalRatio;
        $optimalWidth  = $this->width  / $optimalRatio;

        return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
    }

    private function crop($optimalWidth, $optimalHeight, $newWidth, $newHeight)
    {
        // *** Find center - this will be used for the crop
        $cropStartX = ( $optimalWidth / 2) - ( $newWidth /2 );
        $cropStartY = 0; // start crop from top

        $crop = $this->imageResized;
        //imagedestroy($this->imageResized);

        // *** Now crop from center to exact requested size
        $this->imageResized = imagecreatetruecolor($newWidth , $newHeight);
        imagecopyresampled($this->imageResized, $crop , 0, 0, $cropStartX, $cropStartY, $newWidth, $newHeight , $newWidth, $newHeight);
    }
</code>
Update:
Maybe changing this:
<code>$heightRatio = $this->height / $newHeight;
$widthRatio  = $this->width /  $newWidth;
</code>
with this:
<code>$heightRatio = round($this->height / $newHeight);
$widthRatio  = round($this->width /  $newWidth);
</code>
Comment: If it helps, I know for sure I copied one of the square-thumbnail generating examples in the comments at http://php.net/manual/en/function.imagecopyresampled.php to do this job, and it's working fine for me. Unfortunately I'm at work, and the code is from a personal project I don't have access to at the moment, so I can't tell you which it is -- but there's only a couple there.
Answer: This line:
<code>$cropStartX = ( $optimalWidth / 2) - ( $newWidth /2 );
</code>
looks suspicious.
If this is integer division then for images that are an odd number of pixels wide you'll get truncation. Try:
<code>$cropStartX = ( $optimalWidth / 2.0) - ( $newWidth / 2.0 );
</code>
Make sure that all your arithmetic is using real numbers, preferably double precision ones, but with numbers in the range you are dealing with it should be OK to work in single precision floats.
Comment: How to make sure that all the arithmetic is using real numbers??
Comment: @Jonathan - If this were C# or C++ I'd say declare them as `double`, but as PHP isn't strongly typed I'm not sure there's a "correct" way.
Comment: PHP does support typecasting http://php.net/manual/en/language.types.type-juggling.php#language.types.typecasting


Jquery mobile navigator.geolocation.getCurrentPosition returns the error code: error.PERMISSION_DENIED. how to solve this?

Question: This is my code and it showing the error "User denied the request for Geolocation".
please help me to get the current location from google map or any way.
<!DOCTYPE html>

Click the button to get your position:

<button onclick="getLocation()">Try It</button>

Answer: Check the settings on your browser.
Have you allowed the site to access the Geolocation?   This setting can be denied, one time only or always allow.
Comment: Again I getting an error "Location information is unavailable" after allowed the site to access the Geo location.
Comment: Which browser are you using? Check that you are using a html 5 browser.  See the list at the bottom of this link http://www.browsergeolocation.com/
Comment: i am using firefox 20 .. i checked with the url that you had sent.. But it is on loading infinetly


Why do my widgets only show up in one case?

Question: I'm making a game based off of the periodic table with tkinter. I made the particle frame just fine, so I decided to copy the code and reuse it for the element frame, changing only the variable names. But for some reason, even though the particle frame works just fine, nothing shows up for the element frame. Here is my full code:
# Boilerplate

import random
import periodictable as pt
from tkinter import *
root = Tk()
root.title('Periodic Table Game')
root.geometry('350x250')
LightBlue = "#b3c7d6"
Menu = Frame(root)
elementFrame = Frame(root)
particleFrame = Frame(root)
settingsFrame = Frame(root)
root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)
for AllFrames in (Menu, elementFrame, particleFrame, settingsFrame):
    AllFrames.grid(row=0, column=0, sticky='nsew')
    AllFrames.configure(bg=LightBlue)
def show_frame(frame):
    frame.tkraise()
show_frame(Menu)

# Menu Frame

Menu.grid_columnconfigure(0, weight=1)
root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)

MenuTitle = Label(Menu, text="Periodic Table Game", font=("Arial", 15), bg=LightBlue)
MenuTitle.grid(row=0, column=0, pady=25)
MenuTitle.grid_rowconfigure(1, weight=1)
MenuTitle.grid_columnconfigure(1, weight=1)

MenuButton1 = Button(Menu, width=25, text="Guess The Particles", command=lambda: show_frame(particleFrame))
MenuButton1.grid(row=1, column=0)

MenuButton2 = Button(Menu, width=25, text="Guess The Element Name", command=lambda: show_frame(elementFrame))
MenuButton2.grid(row=2, column=0, pady=5)

SettingsButton = Button(Menu, width=25, text="Settings", command=lambda: show_frame(settingsFrame))
SettingsButton.grid(row=3, column=0)

# Particle Frame

particleFrame.grid_columnconfigure(0, weight=1)

BackButtonF2 = Button(particleFrame, text='Back', command=lambda: show_frame(Menu))
BackButtonF2.grid(row=0, column=0, sticky=W)

ParticleLabel = Label(particleFrame, text='testing', bg=LightBlue)
ParticleLabel.grid(row=1, column=0, pady=15)

ParticleEntry = Entry(particleFrame)
ParticleEntry.grid(row=2, column=0, pady=10)

ParticleEnter = Button(particleFrame, text='Enter', width=10)
ParticleEnter.grid(row=3, column=0, pady=10)

# Element Frame

elementFrame.grid_columnconfigure(0, weight=1)

BackButtonF3 = Button(particleFrame, text='Back', command=lambda: show_frame(Menu))
BackButtonF3.grid(row=0, column=0, sticky=W)

ElementLabel = Label(particleFrame, text='testing', bg=LightBlue)
ElementLabel.grid(row=1, column=0, pady=15)

ElementEntry = Entry(particleFrame)
ElementEntry.grid(row=2, column=0, pady=10)

ElementEnter = Button(particleFrame, text='Enter', width=10)
ElementEnter.grid(row=3, column=0, pady=10)

root.mainloop()

Why does identical code work only with one frame?
Comment: Sorry. I comment out `import periodictable as pt`. So I can see it. You used `particleFrame` for all widgets, but not  `elementFrame` and `settingframe`. That why you cannot see all two frames.
Comment: So why does it work for particleFrame but not elementFrame?
Answer: Precisely, because you copied the code you don't spot where the issue is.
When you are defining the element frame widgets you are placing them all into  particleFrame.
Example:
BackButtonF3 = Button(particleFrame, text='Back', command=lambda: show_frame(Menu))

should be
BackButtonF3 = Button(elementFrame, text='Back', command=lambda: show_frame(Menu))

Comment: Yes, the original code for particleFrame is ok, yes. But it is precisely because you copied it, that you forgot to change the particleFrame variables in all fields for elementFrame, as 3 of us have already commented.
Answer: Your problem will be solved.
Change this particleFrame, to elementFrame
snippet code:
BackButtonF3 = Button(elementFrame, text='Back', command=lambda: show_frame(Menu))
BackButtonF3.grid(row=0, column=0, sticky=W)

ElementLabel = Label(elementFrame, text='testing', bg=LightBlue)
ElementLabel.grid(row=1, column=0, pady=15)

ElementEntry = Entry(elementFrame)
ElementEntry.grid(row=2, column=0, pady=10)

ElementEnter = Button(elementFrame, text='Enter', width=10)
ElementEnter.grid(row=3, column=0, pady=10)

Screenshot before:

Screenshot  after same as elementFrame and particleFrame:


Can the harmonic series explain the origin of the major scale?

Question: This Wikipedia article is the source for two overtone series charts...

The numbers above the harmonic indicate the number of cents' difference from equal temperament (rounded to the nearest cent).

Regarding harmonic 11, is it a 'out of tune' Gb or an F?
Am I reading the charts correctly that there is no A natural in the series?

If I understood this article about cents, -49 on harmonic 11 is about 1/4 step - enough to be a horribly out of tune P4 - and -12 on harmonic 15 may drift past the threshold of perceptible depending on the person and the exactly sound context (it may be close enough.) Roughly the same for harmonic 5 as 15.
So the resulting major scale (based on these very weak harmonics) will have FA horribly out of tune, and MI and TI questionable.
Why would anyone use the harmonic series to explain the origin of the major scale with such bad tuning?
Based on the strength of the overtones the major triad is supported by the series. But the next strongest thing is a diminished triad! Past that everything is weak and out of tune!
Comment: @topomorto, the accepted answer here https://music.stackexchange.com/questions/8173/the-major-scale-why-and-how is what prompted my question
Comment: Ok, comments to the contrary. I guess I;m more concerned about the +19 votes and accepted answer. That's a pretty strong affirmation by this forum for something that is on theoretically shaky ground.
Comment: @  topo morto: When I met the first time SE  3 months ago and I  told my friends about it they were just laughing and mentioning exactly this point :) but this site here is even better than "parentology", "german language"  and some others I have seen.
Comment: Hi Michael - I'm a bit confused by the question "Why would anyone use the harmonic series to explain the origin of the major scale with such bad tuning?". Who is it that is claiming a direct link between the notes in the harmonic series and the notes in the major scale?
Comment: (Incidentally I *do* think that the harmonic series goes a long way towards explaining the major scale, but more because of the dissonance curve observed in figure 3 here: http://sethares.engr.wisc.edu/consemi.html)
Comment: I sort of think that the concept of the letter names breaks down when analysing the harmonic series. The only thing that matters is the interval's intonation. Besides, it's infinite, so eventually one would be playing notes so close together that it would be like "C, C but a little sharper, C a little sharper than that, C sharp, etc...".
Comment: @user45266 not at sufficient amplitudes to matter, not within the range of human hearing.
Answer:
Can the harmonic series explain the origin of the major scale?

Emphatically yes, but that doesn't mean the major scale is literally contained in the harmonic series. We seem to be dealing basically with a black-and-white fallacy here: there aren't just two options "the entire major scale is contained in a single harmonic series" and "the harmonic series can't explain the major scale". Rather, the scale is constructed from multiple building blocks that use the harmonic series.
As you said, the major triad is so well supported by the harmonic series that this can hardly be controversial. That's basically enough to explain the entire scale too if you just make use of the obvious candidates for a chord sequence: the Ⅰ chord gives the Ⅰ, ⅲ and Ⅴ scale degrees as 4:5:6 ratio, then the chord which has the original Ⅰ as its fifth is the Ⅳ subdominant, which adds the Ⅳ and ⅵ degrees, and finally the major chord on the Ⅴ degree gives you also the ⅱ and ⅶ.
The scale thus derived, using only the first five overtones in the harmonic series (plus extra octaves), is the Ptolemaic diatonic major scale. It could be argued that this is not the historically most relevant one, with the only 3-limit Pythagorean being an alternative. The fact that Pythagorean melody and Ptolemaic harmony can be pretty well approximated by a single tuning system – that's a meantone temperament, of which 12-edo is but one amongst many – is perhaps the centralmost feature of Western harmony.
Why use those particular three chords, Ⅰ, Ⅳ and Ⅴ to derive everything? Well, they are the obvious candidates insofar as you need to move the fundamental only by the simplest ratio – the 3:2 fifth. It is certainly possible to move around major chord by other steps, in particular by the mediant. That gives the ♭Ⅲ or ♭Ⅵ chords, which indeed are quite common in bluesy rock music and sound very tonal. Those songs sure enough tend to use not so much the full Ionian diatonic scale as the more flexible "blues scales" for their melodic content. It so happens that Common-practice music has not gone that road, which probably is mostly because those kinds of chord changes are much more natural for a parallel movement, sliding chords around the guitar neck style which CP so avoids. But I'd say that both approaches are clearly based on the harmonic series.
Similar story for

But the next strongest thing is a diminished triad

– kinda, however 7:6 is significantly narrower than a 6:5 minor third or even a 12-edo minor third. So it's no surprise if a diminished chord sounds dissonant although 5:6:7 are low integer ratios: because it would be way out of tune from that interpretation. A true 4:5:6:7 chord however sounds pretty amazing. Why does the seventh harmonic not feature in standard Western scales? Well, Western music has been to a huge degree shaped by the composers of the Baroque who loved symmetry and modulation. The playfield set up this way from only 5-limit primitives allowed for an enourmous richness. That was carved out by composers in the 18th and 19th centuries. Now, if you toss 7-limit intervals into that kind of music, everything would become a heck lot more complicated. 7- or even 11- and 13-limit intervals do feature in other musical traditions, but the Western composers just happen to take the more symmetrical road of 5-limit meantone music.
I do think extending Western counterpoint with 7- and 11 limit intervals is a great way in which music could evolve in the future. Just, it's really quite difficult to keep the overview over the fine-grained scales and still keep it melodically graspable; about the only composer who has really been successful in that direction is Ben Johnston. Better computer frameworks, if not AI, might soon help as an assistant.
Comment: The numbers in the fractions, the 12-edo sizes and the interval names are essentially unrelated numbers. They have different historical/mathematical derivations, and it just so happens that they come out to about the same absolute frequencies. That's perhaps the most confusing thing.
Comment: What are "5-limit primitives?" I only know primitives from computer data types.
Comment: @leftaroundabout, thank you, that is very kind of you to say. Personally (and not just with your answer, I have the same problem with the Just Intonation article on Wikipedia), I get stuck with the fractions and names (I do not understand how notes get their names within the JI system, like "minor third", and where the other names come for scales that have >12 notes). All the numbers seem magical, because I fail to understand the context and how the fractions are derived to begin with. Even after reading Kyle Gann's article on the topic, I don't understand the algorithm for a JI octave.
Comment: Not sure what you mean by "algorithm for the octave". An octave is just two notes, the higher of which has exactly twice the frequency of the lower. Similar with the other intervals, except it's not just a number 2 but some fraction – ³⁄₂ for a fifth, ⁵⁄₄ for a major third, ⁶⁄₅ for a minor third, ⁹⁄₈ for a major second. And it so happens that all those ratios can be approximated by terms of the form 2^(_n_ / 12), with _n_ = 2 for a major second, _n_ = 3 for a minor third, _n_ = 4 for a major third and _n_ = 7 for a fifth. That is the 12-edo approximation.
Comment: Re "unrelated numbers" and "different historical derivations": what are you talking about? Twelve-tone equal temperament descends directly from just intonation.  They're not in the least unrelated.
Comment: @phoog of course the reason why 12 was chosen is that it results in close JI approximations, but the point is that the number-mapping between `interval name` and `number ot 12-edo steps` is essentially opaque, given by where the approximations happen to lie rather than any direct, designed integer-association. — I think multiple comments were auto-deleted from the discussion here, it doesn't really make sense as it stands.
Comment: I wouldn't characterize the 12-tone system as the result of choice. It sounds like a bunch of theoreticians brainstormed about approximating JI until they came up with 12 tones. What actually happened was that just intonation arose alongside the 7-tone diatonic scale, wherein five of the seven intervals were roughly twice as big as the other two, and the bigger intervals got filled in. The number 12 arose centuries before anyone was dividing the octave equally. So my point is that history does indeed explain the (yes, opaque) relationships between these these otherwise "unrelated" numbers.
Comment: Also, it is routine to tune 7-limit major seconds and minor sevenths in 19th century repertoire (barbershop, for example, but also Brahms).  Composers may not have specified them explicitly, and they can't be reasonably used for tuning keyboards, but that doesn't mean that people weren't using them.
Answer: There are several numerological methods to derive a major scale. Historically, several sets of six notes were used (called "hexachords") from which by various roundabout means, the various modes were derived. (Not every theorist used the same modes nor the same derivations.) The overtone series doesn't quite generate a nice scale (nor mode); neither do any others.
One method is to take combinations of overtones based on the first overtone (octave) and second (fifth). One gets "Pythagorean Tuning" using ratios containing only twos and threes. Tones an octave apart are considered "equivalent" for these constructions and the rations all become between 1.0 and 2.0. Thus the octave has a ratio of 2:1 (I prefer fractions 2/1) and the fifth (not called that yet) with a ration of 3/2. The inverse of the octave is 4/3 (the fourth). One can get twelve tones by noticing that 12 fifths is about the same as four octaves:  (3/2)^12 (reduced) is 531441/252144 or 2.027.... which is close to an octave. Nothing ever comes out exact because no power of two is a power of three (except the 0th power which is 1). (Actually they are never too close except  8 and 9). One can take the twelve powers of 3/2 (0 through 11), reduce them to between 1 and 2, then sort. One gets an approximation to the 12-note chromatic scale. The first 7 powers are similar to the 7-notes of the major scale (or any of its modes).
One problem is that the "major third" (interval from C to E in modern terminology) has a ratio of 81/64 which is a bit out of tune (whatever that means) for lots of people. The next step is to expand the multipliers to using 2s, 3s, and 5s. This yield "just tuning" which sounds pretty good for a few chords. (Check in the Wiki: just tuning, temperament, Pythagorean tuning, mean-tone tuning, hexachord theory, etc. Iterate the bibliography operator.)
The fact that (except for the zeroth power) no prime powers are equal means that all system fail. One must make some type of compromise; either some keys are not in tune or all keys are out of tune. But this is all a bit of a digression (people do get unreasonably passionate about tunings though).
The Greeks defined several tetrachords (four-note collections). Medieval theorists used various tetrachord combinations to derive scales. The Greeks used three descentind tetrachords (later theorists used ascending tetrachords). The "diatonic" tetrachord was (in modern notation) A-G-F-E (two tones and a semitone), the "chromatic" tetrachord A-Gb-F-E (a minor third and two semitones), and the "enharmonic" tetrachord A-Gbb-Fq-E (a major third and two quarter-tones). The major scale (or the Greek version) was made of two (descending again) tetrachords joined by a whole tone: E-D-C-B+A-G-F-E (the pattern of modern major and minor scales by permutation, and modes for that matter). That's how it was done harmonically. The Wiki on "tetrachords" gives a nice description.
My conclusion is that the major (and other) scales were not really derived from overtones. Overtones were later used to "explain" (actually, "almost explain") these scales.
Comment: And actually -1, because **a)** there's clear historical evidence that the ancient Greeks did know about just intonation and the Western major scale was developed much later **b)** even if a scale wasn't _knowingly_ designed around integer ratios – most of them match way to well too such ratios to put it off as mere coincidence. At least octaves and fifths really feature in so many cultures across the world, you can't seriously claim that the ratio-integerness isn't a real _working principle_ here.
Comment: If I follow your 2nd paragraph, harmonic 3, the P5 (strong is the series, important musically) is used in Pythagorean Tuning to get 12 chromatic tones (which contain a diatonic series too.) But that series doesn't match up with _any_ part of the overtone series. This more or less restates my question. Or, by your final comment confirms my attitude on the subject... unless someone gives me a much more convincing argument.
Comment: "The fact that (except for the zeroth power) no prime powers are equal means that all system fail." Something like that is often said, but IMO pretty baseless. All it means is that _finite note systems in JI can't allow infinite modulation_ – but that's hardly surprising, is it? Regardless, for any _finite_ number of keys (possibly more than 12!), you _can_ have a system that covers all of them in perfect JI. Whether that's _practical_ is another question, but it's certainly not a fundamental mathematical dilemma.
Comment: A good explanation of why tuning can't accomodate both perfect fifths and octaves perfectly: https://youtu.be/8syA7S_5E3A?t=225
Comment: @leftaroundabout "for any finite number of keys, you can have a system that covers all of them in perfect JI" the problem is that you can't cover even one key in perfect JI. For example, in C major you need two As: P5 above D and M3 above F. But because you need two As, you need two Ds, and then two Gs, and then two C's. But now that you have two C's, you need _three_ As, and we've just entered an infinite spiral. In a real piece of music you won't spiral very far before the end of the piece, but the finite set of frequencies needed depends on the piece you're playing, not just on the key.
Comment: One attempt to maintain just intonation (or any other) locally. It does require both forward and backward analysis. https://www.academia.edu/40539710/A_Practical_Guide_to_Intonation_and_Tuning_for_unaccompanied_ensembles_and_vocal_groups
Comment: @phoog arguably (highly so), the P5 from D to A is not part of the key of C-major. It is part of the secondary dominant (i.e. actually a temporary modulation) of the neighbouring G-major.
Comment: @leftaroundabout there's also the ii chord.  In fact I have noticed a preference for ii6-V-I over IV-V-I in some (mostly earlier) baroque repertoire, so I wonder whether they weren't more likely to use a raised F (as compared to C) rather than a lowered A (compared to D).  But really nobody ever used JI to tune keyboards.  Because of this wolf in the white notes (in sheep's clothing?) they would have settled on meantone temperament very quickly after deciding that they should use 5-limit thirds.
Comment: @ttw that paper illustrates my point quite well.  I haven't read it yet, just scanned it, but the Byrd example rather suggests a meantone temperament (indeed, possibly equal temperament or something close to it on viols, which were fretted).
Answer: The major scale was generated by stacking 5ths, the strongest/most audible non-octave overtone.  If you're a caveman and you're trying to tune two pieces of sabretooth tiger gut strings you can hold your finger 1/3 of the way down the lowest string, and tune the 2nd string to that note until the "beats" are gone. Now you have the 2nd overtone minus an octave as your 2nd string. Rinse and repeat with the other stings. If you repeat this to the 5th string you get a pretty good pentatonic scale. Cavemen don't have frets, electronic tuners, etc so they can only tune by ears. This is how people tuned things for a long time- eliminating the "beats" caused by an out of tune unison. Eventually metal was invented and we could get more tuning forks, frets etc, and then the metronome was invented and we could measure beats per second accurately. Keyboards got popular. Composers got experimental wanted to write music that modulated into keys that were many 5ths away (as you mentioned earlier, the relationship is a little off from equal temperament, so the more 5ths away something is the more out of tune the modulation will be... it's more complicated than that, but let's go with that.) If you "fudge" or "temper" the numbers a little (totally screwing all the 3rds and 6ths but making them kinda ok) then you can make all the intervals equal to one another (and all a little screwy, but "acceptable.") We didn't "get the major scale" from the overtone series, but rather it was a long process, like boiling a frog, and now nobody knows what 3rds sound like except for really awesome choruses. The major scale is derived from pragmatism and social acceptance, not science.


Get user ID for database insert

Question: I have a form inserting into a database in Drupal 8. I would like to insert the user id. I have the following code:
<code>$userCurrent = \Drupal::currentUser();
$uname = (int)User::load($userCurrent->id());
</code>
Without the (int) Drupal throws an error saying it cannot be converted into a string. With the (int) Drupal always returns 1. What am I doing wrong?
UPDATE: As stated I would like the user ID not the user name. Sorry if it doesn't make sense, I am very new to Drupal and there is not a lot of documentation for 8 yet.
Comment: `User::load()` returns a `User` object; if you cast it to `int`, you don't get what you want.
Comment: The fact you store the value in `$uname` makes me think you are trying to obtain the username, and your code is wrong. May you say what exactly you are trying to achieve. Saying what `User::load()` returns is probably just the tip of the iceberg.
Comment: Also, if you are really looking for the username, you can get directly \Drupal::currentUser()->getAccoutName()/getDisplayName(). As others said, there are many things about your question that don't make any sense.
Answer: Do you want to get the username, as the variable name suggests?
<code>$uname = User::load($userCurrent->id())->name->value;
</code>
Your question does not make sense, why load the user with the id to get the id, you already have?
Comment: Sorry, no I want the user id
Comment: The user id is `$uid = $userCurrent->id()`

Get user ID for database insert


Separar texto com Javascript

Question: Eu tenho uma string e preciso separar o nome da rua, bairro, cidade e estado.
string:
Rua tal Muniz, 124 - ramones, Sapucaia - SP

Como eu posso fazer usando JavaScript?
(Pode ser uma solução com ou sem a utilização da biblioteca jQuery)
Comment: É importante lembrar que nessa ideia se qualquer uma das informações já tiver uma virgula ou hifen cria-lhe um problema.
Comment: @Josimara Apenas uma breve explicação da minha edição. No caso você comentou que a informação vinha em texto então acredito que você não possuia de fato um array e sim uma string. Outro ponto é que você colocou "javascript ou jquery" esse "ou" pode permitir uma má interpretação ao leitor, que é a ideia que jquery não é javascript, sendo que, ele nada mais é do que um conjunto de funções em javascript. Espero ter ajudado :)
Comment: O endereço vem sempre nesse formato aí ou pode ter variações?
Comment: vem sempre nesse formato
Comment: Poderia colocar exatamente como está o seu array, junto com o código que tentou fazer? Em qual informação ficou com dificuldade?
Comment: @AndersonCarlosWoss a informação vem assim em texto corrido eu precisaria das informações separadas
Comment: `.split(",")` e subsequente `split(" - ")` talvez resolva o seu problema. Só você sabe dizer
Comment: Eu não fiz o codigo ainda, eu preciso de um norte pra seguir não faço ideia de como começar preciso de dicas só
Comment: E o array que citou, onde fica?
Comment: Você pode começar tentando dividir a string nas vírgulas, depois dividir no hífen.
Comment: Alguma resposta ajudou a resolver o problema e pode sanar dúvidas similares de outros usuários? Caso positivo não esqueça de marcar a resposta como aceita. Pra fazer isso é só clicar no ✓ do lado esquerdo da mesma (abaixo do indicador de up e down votes).
Answer: Uma forma é utilizando a posição dos separadores como abaixo:

const separar = endereco => {
  let posicao = endereco.indexOf(',');
  const rua = endereco.substring(0, posicao).trim();
  let aux = endereco.substring(posicao + 1).trim();
  posicao = aux.indexOf('-');
  const numero = aux.substring(0, posicao).trim();
  aux = aux.substring(posicao + 1).trim();
  posicao = aux.indexOf(',');
  const bairro = aux.substring(0, posicao);
  aux = aux.substring(posicao + 1).trim();
  posicao = aux.indexOf('-');
  const cidade = aux.substring(0, posicao).trim();
  aux = aux.substring(posicao + 1).trim();
  posicao = aux.indexOf('-');
  const estado = aux;

  return {
    rua,
    numero,
    bairro,
    cidade,
    estado,
  }
}

console.log(separar('Rua tal Muniz, 124 - ramones, Sapucaia - SP'));

Outra forma é utilizando a seguinte expressão regular:
/^(.+),(.+)-(.+),(.+)-(.+)$/gm

Da seguinte forma:

const ENDERECO = /^(.+),(.+)-(.+),(.+)-(.+)$/gm;

const separar = endereco => {
  const match = ENDERECO.exec(endereco);

  return {
    rua: match[1],
    numero: match[2],
    bairro: match[3],
    cidade: match[4],
    estado: match[5],
  }
}

console.log(separar('Rua tal Muniz, 124 - ramones, Sapucaia - SP'));

^ assegura que a posição está no início da linha
Captura o grupo (.+):

.+ combina qualquer caractere (exceto terminadores de linha);
O quantificador + combina entre 1 ou vezes ilimitadas, quantas vezes forem possíveis;

, combina o caractere literal ,;
Captura o grupo (.+):

.+ combina qualquer caractere (exceto terminadores de linha);
O quantificador + combina entre 1 ou vezes ilimitadas, quantas vezes forem possíveis;

- combina o caractere literal -;
Captura o grupo (.+):

.+ combina qualquer caractere (exceto terminadores de linha);
O quantificador + combina entre 1 ou vezes ilimitadas, quantas vezes forem possíveis;

, combina o caractere literal ,;
Captura o grupo (.+):

.+ combina qualquer caractere (exceto terminadores de linha);
O quantificador + combina entre 1 ou vezes ilimitadas, quantas vezes forem possíveis;

- combina o caractere literal -;
Captura o grupo (.+);
$  assegura que a posição está no final da linha.
Answer: Se a string seguir sempre esse padrão, você pode tentar algo assim:

var endereco = 'Rua tal Muniz, 124 - ramones, Sapucaia - SP';
var separado = endereco.split(',');

var rua     = separado[0].trim();
var bairro  = separado[1].split('-')[1].trim();
var cidade  = separado[2].split('-')[0].trim();
var estado  = separado[2].split('-')[1].trim();

console.log('Rua: ' + rua);
console.log('Bairro: ' + bairro);
console.log('Cidade: '+ cidade);
console.log('Estado: '+ estado);
Answer: Tente usar o código abaixo. Testando aqui, funciona. Antes de fazer a quebra do texto por "," faça uma reposição do "-" por uma vírgula.
function myFunction() {
    var str = "Rua tal Muniz, 124 - ramones, Sapucaia - SP";
    str = str.replace("-", ",");
    var res = str.split(",");
    //variável res agora é um array que você pode percorrer com um loop ou posições fixas
}

Separar texto com Javascript


Get only parent categories wordpress

Question: i'm trying to create a category list, but i only want to list the parent categories and not the child categories. How can i do this? so far i've created a list, which list all parent and child categories.
function categoryList() {

  $args = array(
  'orderby' => 'name',
  'order' => 'ASC'
  );
$categories = get_categories($args);

  $output .= '
';
  foreach($categories as $category) {
          if ($category){
          $output .= '
term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'';
          }
  }

  $output .= '
';
  $output .= '
';

  return $output;

}

Answer: By parent categories, I assume you mean top-level categories. This is actually documented on the Codex page for get_categories: You should call get_categories with parent => 0
$args = array(
  'orderby' => 'name',
  'order' => 'ASC',
  'parent' => 0
);
$categories = get_categories($args);

Comment: the strange thing is i have 3 parent categories with no childs and one parent category with 3 childs. however when i add above it onnly shows the parent category with chidls
Comment: That is strange! I don't really know what could be the issue then. Perhaps you should unaccept my answer so that someone else can chime in.
Answer: List only top-level (parent) categorizes in wordpress. The option  'hide_empty' => 0 makes sure to list even empty top-level categories.
        $args = array(
                'orderby' => 'name',
                'order' => 'ASC',
                'parent'   => 0,
                'hide_empty' => 0,
                //'exclude'   => '7',
                // optional you can exclude parent categories from listing
         );

        $categories = get_categories( $args );

Answer: use this:
$categories = get_categories( [ 'parent'=> id_parent ,'hide_empty' => 0,] );

Comment: When adding an answer to a five year old question with three existing answers it is very important to point out what new aspect of the question your answer addresses. Code only answers can almost always be improved by adding some explanation of how and why they work.
Comment: While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. I would recommend you to check SO's [official How to Answer article](https://stackoverflow.com/help/how-to-answer) along with the comprehensive [blog post](https://codeblog.jonskeet.uk/2009/02/17/answering-technical-questions-helpfully/) from [Jon Skeet](https://stackoverflow.com/users/22656/jon-skeet).
Answer: A native Wordpress solution to return the CURRENT parent category,
excluding unwanted categories:
function primary_categories($arr_excluded_cats) {

if($arr_excluded_cats == null) {
    $arr_excluded_cats = array();
}

$post_cats = get_the_category();

$args = array(
  'orderby' => 'name',
  'order' => 'ASC',
  'parent' => 0
);

    $primary_categories = get_categories($args);

    foreach ($primary_categories as $primary_category) {

        foreach ($post_cats as $post_cat) {
            if(($primary_category->slug == $post_cat->slug) && (!in_array($primary_category->slug, $arr_excluded_cats))) {
                return $primary_category->slug;
            }
        }
    }
}

//if you have more than two parent categories associated with the post, you can delete the ones you don't want here
$dont_return_these = array(
        'receitas','enciclopedico'
    );

//use the function like this:
echo primary_categories($dont_return_these);

Comments:

if you only have one parent category by post, pass null instead of array
if you want another output instead of slug change this to return $primary_category-> slug;
Answer: The code below will give us the parent cat name and the URL.
function ns_primary_cat() {
  $cat_now = get_the_category();
  $cat_now = $cat_now[0];
  if ( 0 == $cat_now->category_parent ) {
     $catname = 'term_id ) . '">' . $cat_now->name . '';
  } else {
    $parent_id = $cat_now->category_parent;
    $parent_cat = get_category( $parent_id );
    $catname = '' . $parent_cat->name . '';
  }
  return $catname;
}

Get only parent categories wordpress


No Ruby on Rails a regra de negócio fica no model?

Question: No Java a regra de negócio fica no controller, mas ouvi uma palestrante dizendo que no Ruby on Rails a regra de negócio fica no model.
Alguém me confirma isso?
Comment: eu ia formular uma resposta, em base acredito que Model nada tenha relação com ORMs, isto ocorreu com o tempo-vs-necessidade. Na verdade o Model são as "regras de negócio", eles acessam dados e atualizam, a unica coisa que ele não deve fazer obter dados diretamente ou enviar dados para a saída (exibir na tela), isto claro visando a organização.
Answer: Resolvi responder porque não há consenso sobre isso. O que indica que há problemas no padrão MVC. Quando algo é bom de verdade, todo mundo concorda.

Tratar regras de negócio no model é uma má prática?
Aqui as respostas indicam que é no model, salvo algum motivo muito forte. Todos usuários que responderam tem boa reputação aqui no site.

Como implementar um controller "magro"
A resposta com vários votos indica que o controller não é o local adequado.

Regras de Negócio no Banco de Dados - quais as vantagens e desvantagens?
Aqui se discute se a regra de negócio deve estar no banco de dados ou não. Ora, se tem muita gente que acha que deve estar no banco de dados, então se estiver na aplicação, o mais próximo do banco de dados é o model e não o controller.

O que é Regras de aplicativo e quais são as diferenças em relação às Regras de negócio?
Nessa mostra a diferença entre regra de negócio e de aplicativo. Talvez a confusão seja porque algumas pessoas consideram como regra de negócio o que na verdade é regra de aplicativo. Essa última fica no controller. Mas estamos falando de regra de negócio.

Em um projeto MVC, onde devo deixar os enums?
Mais uma mostrando que tem que saber para que está fazendo cada coisa.

Qual camada da aplicação é voltada para processamento de regras de negócio mais amplas e complexas?
Aqui, em uma resposta, a aceita e mais votada, fala para criar uma camada extra. Isso não é bem MVC, certo? De qualquer forma não é para usar no controller.
Tem outra que vai pelo mesmo caminho, apesar de ser um pouco confusa para afirmar isso.

Qual pattern usa-se para validar regra de negócio?
Temos uma resposta que diz claramente que deve ficar no model e outra que vai para outras camadas que não fazem parte do MVC, mas foi a pessoa que disse na primeira pergunta que era para colocar no model, então nem a mesma pessoa concorda com si mesma (ela pode estar dizendo que depende do cenário).

Onde deve ficar a regra de negócio no padrão MVC?
Agora complicou porque a mesma pessoa que respondeu ali na anterior agora está dizendo que é para colocar no controller.
Tem outra resposta bem votada lá que fala que depende. Pelo que entendi vai pelo caminho de que as pessoas confundem regra de negócio com regra de aplicação, mas fala em modelos, então parece tender para o mesmo que vimos antes.
E tem uma terceira bem votada que mostra que depende do caso. Ela confunde regra de negócio com regra de aplicação. Mas foi respondida pela mesma pessoa que respondeu como diferenciar uma da outra. Se é regra de negócio você pode confiar que a view faça isso? Você pode nem ter controle do que é a view na aplicação.

É errado deixar regra de negócio nos controllers?
Nessa há um depende de novo. Meu entendimento que lá está escrito que deve colocar no controller a não ser que fique grande demais (aãã?!?!).
A outra resposta vai pelo mesmo caminho indicando que se o sistema for pequeno pode por no controller. Acho muito estranho a decisão depender do tamanho do sistema. O que eu até acho é que se o sistema for pequeno não deve usar MVC. Há quem não use MVC até mesmo em sistemas grandes, e se dá muito bem com isso. Mas mudar o padrão de acordo com o tamanho do sistema é esquisito.

No Java a regra de negócio fica no controller

<code>É mesmo? Tem referência sobre isso? O Java todo? Me parece uma afirmação que não se sustenta na forma apresentada. Mas acredito que em algum lugar deve dizer que é assim. Será que a fonte é confiável? Tem outras confiáveis que confirmem isso? Outras que contraditam? São confiáveis mesmo?
</code>
Conclusão
Você pode estar pensando que no RoR é diferente. Sim, poderia ser, mas o MVC muda de acordo com a linguagem? Não pode. É isso que estou falando, cada um foi por um caminho.
Pra mim o controlador é só uma camada simples pra fazer o modelo se comunicar com a visão, qualquer operação extra que seja usada estaria errado.
Eu vejo que muitas pessoas acabam tendo dificuldade de pegar do modelo porque o modelo nem sempre está do jeito que precisa, então o controlador tem que contornar isso. E o problema é que o modelo a ser usado deveria ser adequado para essa operação toda e na verdade o modelo que usam é algo básico.
Por outro lado começa ficar complicado. Começa virar DDD em cima de MVC. Então as pessoas preferem violar o padrão para simplificar o código, o que eu acho bom, até que dê problema. Eu acho que o MVC nasceu para um contexto simples e hoje as pessoas precisam ou de algo mais complexo ou algo tão simples que até o MVC não faz sentido. Mas essa parte ainda é opinativa.
É bom deixar claro que eu tenho uma tendência a não gostar do MVC, por isso, a despeito do que muita gente diz, talvez colocar regras de negócio no controller não seja tão absurdo. Se ele fosse tão magro assim talvez seja o caso de nem tê-lo, e não adotar MVC. Eu demorei para pensar sobre isso, mas me parece que o MVC exista justamente quando o controller é complexo. Sem ele tem só um modelo e uma visão, que uma lógica muito simples já resolve. Claro, depende um pouco da complexidade do roteamento também. Colocar a lógica de acesso direto na visão faz cada ação estar vinculada com uma página de forma direta, o que é só o que a maioria dos sistemas precisam.
Não estou dizendo que regras de negócio devem estar na camada de controle, mas o MVC só deve existir se essa camada realmente tem muita lógica.
Se não tiver tudo isso muito claro, não saber bem o que está fazendo no caso específico, provavelmente tomará um decisão ruim.
Então a resposta simples é que você deve fazer o que mais lhe parece correto. Mas tudo indica que quase todo mundo concorda que a regra de negócio vai no model e que em menor grau há alguma concordância que a regra de aplicativo deve ir no controller ou view, de acordo com a necessidade e complexidade. O que define se é regra de negócio ou de aplicativo é algo um pouco aberto.
Coloquei no GitHub para referência futura.
Comment: Muito boa resposta, 11 anos de Rails e realmente o consenso é regras de negócio no model, com algumas observações para uso de Decorator/Services(ou outro poro como camada extra) para extração de regras de negócio não relacionadas ao BD
Comment: Comecei no PHP estruturado, na faculdade estudei java e agora escolhi trabalhar com Ruby on Rails, por isso estive um pouco confuso. Sou novo no ruby on rails e tenho que melhorar bastante, mas espero ser tão bom quanto você parece ser Luiz Carvalho, obrigado pela força que você tem me dado =D

Obrigado pela resposta Bigown


Historico de edições de um modelo Ruby on rails

Question: Gostaria de saber como posso criar um histórico com todas as edições realizadas em um modelo, em ruby on rails.
Answer: Existem várias gems de versionamento de registros. A mais conhecida é a PaperTrail. Essa gem cria uma tabela que grava o histórico de todas as alterações dos modelos monitorados, inclusive pode associar ao usuário que fez a alteração.
Adicionar o PaperTrail em seu projeto é bem simples. Basta incluir gem 'paper_trail' no Gemfile, criar a tabela de versionamento, e adicionar has_paper_trail nas classes que deseja versionar.


What does an infrastructure that hosts an FTP server with HTTP access look like?

Question: I am wondering about how companies provide access to the same files over FTP and HTTP/HTTPS. What are the different servers involved in setting up such an infrastructure?
I am interested, particularly, about if the metadata of the files on an FTP server changes when the files are mirrored to the HTTP server. For example, let's say that I have two files, both with the same content. Given the potentially various ways one can set up and FTP-to-HTTP infrastructure, what are the differences (if any) in the metadata of the same two files between the FTP server and HTTP server?
Comment: most of them use cpanel, same files same server
Comment: So no chance of a metadata difference between an FTP and HTTP access of the same file?
Comment: I'd get a copy of cpanel and play with it,  but no not usually (in my experience anyway)
Comment: I have software that gets a file's Last-Modified attribute from the HTTP header of a URL pointing to a file. I'm just wondering how the Last-Modified attribute of a file on an FTP server mirror into the HTTP header.
Answer: Typically the FTP server and Webserver are not running on different computer systems but both services are running on 1 single host.
Both the FTP service and web service point at the same directory and expose the same files, there is no mirroring of files involved. Filesystem locking prevents the FTP server from changing a file that is being modified by the web server (and vice versa).
And any changes made in a file/directory over FTP will immediately show in the webserver.
Comment: Locking is part of the filesystem  and operating system and not something you need to manually set up. (except in distributed and cluster filesystems) It is one of the requirements for a multi user OS.
Comment: Thanks. Is file-system locking a requirement to implement this infrastructure?
Comment: While this is true in general, there are some webservice providers (e.g. some German providers) that indeed use two different servers for ftp and http that sync in fixed intervals.


Can lines connecting nearest neighbors ever cross?

Question: I don't have any background in graph theory so I am sorry if this is a basic question.  I want to know if lines connecting nearest neighbors can cross in a few different cases.

I have convinced myself that if there are no ties for nearest
neighbor it is impossible for lines to cross.  Is this correct?
I think it might still be impossible even if ties are allowed, in which case either or both lines can be drawn but I haven't come up with solid reasoning to back that up.
This case is a bit more complicated.  Say that points can be connected to their second nearest neighbor if a line originating from them has yet to be drawn and they are already connected to their nearest neighbor.  In this condition, two pairs of points very far from one another would be connected into one long line.  Each pair would get a line connecting it to its nearest neighbor and then one or two lines would connect between the pairs.  Connecting to the third nearest neighbor is not allowed.  It seems to me that in this case as well no lines would cross.

I have no idea where to begin looking for formal math to back up these statements.  Is there a general theory of lines crossing in a network of nearest neighbor connections?  Any help would be appreciated.
Answer: If $A$ has nearest neighbor $B$, then any point $x$ on the line segment joining $A$ and $B$ is nearest to either $A$ or $B$, but not to any other point (not even tied):
Assume that there exists a point $C$, such that $d(x,C) \leq d(x,A),d(x,B)$ for some $x$ on $AB$. Then, by the triangle inequality (the inequality is strict because we know $C$ can't lie on $AB$)
\begin{align*}
d(A,C) &< d(A,x) + d(x,C) \\
&< d(A,x) + d(x,B) \\
&< d(A,B)
\end{align*}
contradicting the fact that $B$ is the nearest neighbor of $A$.
Now assume there are 4 points $A,B,C,D$, such that there's an edge between $A,B$ and between $C,D$. Then if the lines $AB$ and $CD$ would cross, the point of intersection $x$ would be strictly nearer to at least one of $A$, $B$ than to any other point, and also strictly nearer to at least one of $C,D$ than to any other point, which is absurd.
Also, for some general theory: Voronoi diagrams and Delaunay triangulations can be very helpful when thinking about such problems. The above is actually equivalent to the fact that in a Voronoi diagram, the line connecting two nearest neighbors only crosses the Voronoi cells of these two points (which must be adjacent).
EDIT: I overlooked something: If $A$ is the point nearest to $B$, then that doesn't necessarily imply that $B$ is also the nearest point to $A$. I assume you want to consider the graph formed by connecting every point to its nearest neighbor (so it can happen that multiple lines are adjacent to a certain point). The argument was easy to fix though.
Comment: thank you.  Does your argument generalize to connecting points to their nearest and second nearest neighbor?  I know lines start crossing if points connect to their third nearest neighbor but it still seems to me there should be a way to show that no crossings can happen for second nearest.
Comment: There is an error here: "the line connecting two nearest neighbors only crosses the Voronoi cells of these two points".  That's not true.  If $B=(10,0)$, $C=(9,-1)$, and $A=(0,0)$, then the line segment from $A$ to $B$ passes through the Voronoi cell of $C$ (assuming no other points than $A$, $B$, $C$ are considered).  Draw the picture and you'll see it.  In particular, the point $(8,0)$ is in the Voronoi cell of $C$.
Comment: but $9^2 + (-1)^2 = 82 < 10^2 = 100$, so the nearest neighbor to $A$ is in fact $C$.
Comment: The fact that two sites have neighboring Voronoi cells doesn't mean at least one of them is the nearest neighbor of the other.  Take $A,B,C$ as in my comment above.  The nearest neighbor of $A$ is $C$; the nearest neighbor of $B$ is $C$; the nearest neighbor of $C$ is $B$.  So neither $A$ nor $B$ is the other's nearest neighbor.  But (as always happens in a Voronoi diagram in the plane with only three non-collinear sites) $A$ and $B$ have neighboring Voronoi cells.
Comment: @Lieven : OK, I now see what you're saying.  At first I thought you were saying the line between two neighboring points in a Voronoi diagram only passes through their two Voronoi cells.
Answer: Assume $A,B,C,D$ are distinct points, $B$ is the closest to $A$ of $B,C,D$, and $D$ is the closest to $C$ of $A,B,D$ (with possible ties).  Suppose the lines $AB$ and $CD$ cross at $E$.  If $E$ is $A$ or $B$, it is closer to $C$ than $D$ is, contradicting the assumption that $D$ is the closest to $C$.  Similarly if $E$ is $C$ or $D$, it is closer to $A$ than $B$ is.   The remaining case is where $E$ is distinct from $A,B,C,D$.  Then $d(A,D) < d(A,E) + d(E,D)$ and $d(B,C) < d(B,E) + d(E,C)$ so
$d(A,D) + d(B,C) < d(A,E)+d(E,B) + d(C,E)+d(E,D) = d(A,B)+d(C,D)$.  But by assumption
$d(A,B) \le d(A,D)$ and $d(C,D) \le d(B,C)$ so $d(A,B) + d(C,D) \le d(A,D)+d(B,C)$, contradiction.
Comment: Can you generalize this to the second nearest neighbor?  Nobody has answered the third case yet.


How to find associated energy functional for a given PDE

Question: let $U\subseteq\mathbb{R}^n$ be open and bounded and here we have
$-\sum_{i,j=1}^{n}D_i(a_{ij}D_ju)=g(x)$, for $x\in U\subseteq\mathbb{R}^n$
If we assume that $u$ is smooth, $a_{ij}$ and $g$ are continuous and also assume that $a_{ij}(x)=a_{ji}(x)$ for all $x\in U$ and $1\leq i,j\leq n$
How can I find the associated energy functional?
My attempt is that multiply both side by $u$ and then using partial integration
$\int_{U}u\nabla\sum_{j=1}^na_{ij}(x)D_ju\mbox{ }dx=\int_{\partial U}\sum_{j=1}^na_{ij}(x)D_ju\cdot u\cdot\hat n\mbox{ }dx-\int_U\sum_{j=1}^na_{ij}(x)D_ju\cdot\nabla u\mbox{ }dx=\int_{U}g(x)u\mbox{ }dx$
But I really don't know how to continue.
Comment: Try to find a weak formulation first using green formula. Then test it with the solution u.
Comment: What is $\nabla$?
Comment: @ArcticChar I think $\nabla$ as the sum of first derivative
Answer: consider $L(p,z,x)=\frac{1}{2}\cdot\sum_{i,j=1}^{n}a_{ij}(x)p_ip_j-zg(x)$
then we have $L_{p_i}=\sum_{j=1}^{n}a_{ij}(x)p_j$ for $i=1,\ldots,n$ and $L_z=-g(x)$.
Hence the associated E-L equation is that
$I[w]=\int_{U}\frac{1}{2}\cdot\sum_{i,j=1}^{n}a_{ij}w_{x_i}w_{x_j}-wgdx$
therefore the PDE is that $-\sum_{i,j=1}^{n}(a_{ij}(x)u_{x_j})_{x_i}=g$ in $U$
which is also $-\sum_{i,j=1}^{n}D_i(a_{ij}(x)D_ju)=g(x)$


Windows DHCP server - distribute multiple default gateways?

Question: I'm helping a client through the process of configuring a Windows 2012 DHCP server while migrating from Linux ISC DHCP.
In the Windows New Scope Wizard dialog, there is an option to:

...specify the routers, or default gateways (plural), to be distributed by the
  scope.

My customer asked when it would make sense to distribute multiple default gateways to DHCP clients...
I didn't have a good answer. So I'm curious when/if this functionality is appropriate, and does it hinge heavily on certain clients systems (e.g. Windows PCs)? I'd like to hear about practical scenarios.
Comment: In a properly designed network, you don't.
Comment: `Any given connection defines a gateway as non-operational (dead) when a packet sent to the gateway must be retransmitted more than half of the number of times specified in the value of the TcpMaxDataRetransmissions entry. The connection switches to the next gateway in the list in the DefaultGateway or DhcpDefaultGateway entries. The system defines a gateway as dead when more than 25 percent of its connections have switched to the next default gateway in the list.` Source: http://technet.microsoft.com/en-us/library/cc960464.aspx
Comment: This seems to be a prominent dialog box that I've *clicked-through* many times. Are there any real use cases for it?
Comment: Only if you have multiple default gateways on the same subnet, which isn't the right way to handle gateway redundancy
Comment: Personally I don't see anything particularly wrong with this kind of setup. If you only care about outbound internet access and you've got two independent internet connections from two different providers then you can deploy multiple default gateways via DHCP and let Dead Gateway Detection take care of it in the event of a failure of one of the internet connections. That seems like a pretty good "poor man's" implementation of providing redundant internet connections.
Comment: @joeqwerty But the gateway would likely be up, correct? An upstream ISP connection could be down while a gateway remains pingable. Also, this is Microsoft only, no?
Comment: I think Dead Gateway Detection works based on the destination ip address, not the DG ip address.
Answer: If you got multiple subnet linked from a switch in exemple and your main router as your gateway CAN'T do ICMP Redirect, you better give the default gW, or route 0.0.0.0 to the router with the internet  behind and to do static rule in the computer to make the computer talk to other router to go somewhere else (like another site)
Only time I seen it can be usefull to have two GW it's on layer 3 switch&router scenario. What I seen in the past was that;
<code>[PC]---1 GW (switch vlan ip)---[SWITCH LYR 3]----- GW#1--[RTR-1]---[WAN1]
                                              -----GW#2--[RTR-2]---[WAN2]
</code>
So, is it usefull, no IMO, as nowaday router are cheap and allow multiple WAN, not like in the past.
Answer: This is an old post but for anyone else with this question:
If you're using HSRP or VRRP for L3 high availability, you can load balance across the two L3 switches by creating two HSRP/VRRP groups and using one switch as the active forwarder for one group and standby for the other (vice versa on the other switch). Some client gateways would be pointed to the first groups virtual IP and some client gateways would be pointed to the second groups virtual IP.
See the image below:
Answer: I am a CCIE, the answer to your question depends on the topology and your business parameters.  In fact, where most people leverage HSRP or VRRP you can probably get away with just distributing multiple default gateways via DHCP.  Failure can be a little more seamless via HSRP or VRRP and if any stateful devices in the path also happen to record or track the mac then you'll run into problems (some firewalls do in internal tables as well as load balancers).  Keep in mind all devices on the network would need to support multiple routers for holistic redundancy.  You may run into problems on things like print servers and IoT type devices.  Outside those instances, you'd be fine.  Whenever possible, keep it simple
Answer: This only makes sense if you have a company structure that is split into many subnets but every network has its own gateway with different IPs:

Consider your organisation has three different networks. In your
  office you have three systems, each from individual network. you may
  have only one laptop. You need to work on these three networks.
  Instead of connecting one network at one time, you can access all
  three networks at once.

http://www.whatvwant.com/lan-multiple-default-network-gateway/
Comment: This doesn't work and in Win8.1 and newer it will not let two default routes on the same interface have the same metric.
Answer: If you're using a First Hop Redundancy Protocol, especially Multigroup HSRP, on your local network then you want to split half your users to default out Router1 and the other half out of Router2.
So to explain you have 2 routers at a site with redundancy in mind. You want to load balance traffic out both of the routers. Each router acts as a gateway to the user. To balance the traffic you create a DHCP scope that sets half of your users to use Router1 as their default gateway and the other half to use Router2 as their default gateway.
Answer: To answer the question of why this might be needed, consider the scenario with network access from a foreign country. Normal activity would all be from NAT'd addresses from your firewall/router all of which would come from the foreign IP cluster of your provider. The firewall provides private IP addresses (say 192.168.1.xxx) to devices on the network gateway'd to the "foreign access" address set.
For specific devices by MAC address dhcp can provide another set of private IP addresses (say 10.0.0.xxx) that are gateway'd to a VPN that terminates in the United States and provides NAT'd to US IP addresses.
There are lots of reasons to do this, use your imagination.


Problema entre PagSeguro e número de parcelas

Question: Fiz a implementação de uma loja virtual customizada na linguagem PHP e como checkout estou utilizando PagSeguro.
Na implementação foi utilizado o checkout transparente e estava funcionando corretamente, porém o cliente solicitou que seja adicionada a opção de parcelamento do pedido. Ao tentar realizar a requisição de parcelas utilizando a API Javascript, a resposta é sempre a mesma:

{"errors":{"SESSÃO inválida:
d4d905b585ec4d4d8056e380df70e4a5.":"10005"},"error":true}

Para fazer essa requisição estou utilizando o seguinte método Javascript:
PagSeguroDirectPayment.getInstallments

Gostaria de uma ajuda para solucionar, pois como disse anteriormente o checkout estava funcionando corretamente e a única alteração realizada foi a adição do parcelamento.

Métodos utilizados
Retorno do getSessionId

{"result":true,"data":"b099c6f4beff41e0a08a4912f7ce9554"}

Busca bandeira do cartão
PagSeguroDirectPayment.getBrand({
    cardBin: $scope.pagamento.cartao,
    success: function(response) {
        if (response && response.brand && response.brand.name) {
            $scope.bandeira = response.brand.name;
            $scope.getParcelasCartao();
        }
    },
    error: function(response) {
        console.log(response);
    }
});

Busca dos meios de pagamento
PagSeguroDirectPayment.getInstallments({
    amount: valor,
    maxInstallmentNoInterest: 2,
    brand: $scope.bandeira,
    success: function(response) {
        console.log(response);
        if (response.error == false) {
            $scope.parcelamento = response.installments[$scope.bandeira];
        }
    },
    error: function(response) {
        console.log(response);
        $scope.parcelamento = new Array();
    },
    complete: function(response) {

    }
});

Parametros que são enviados na requisição para buscar o parcelamento

sessionId: b099c6f4beff41e0a08a4912f7ce9554
amount: 49.90
creditCardBrand: visa
maxInstallmentNoInterest: 2

Retorno da busca:

{"errors":{"SESSÃO inválida: b099c6f4beff41e0a08a4912f7ce9554.":"10005"},"error":true}
Comment: Se puder, poste parte do seu código para nos ajudar a lhe ajudar :)
Comment: Olá @GuilhermeNagatomo, obrigado pela sugestão. Já adicionei as informações e os parâmetros enviados em cada requisição lembrando que estou utilizando a API Javascript do PagSeguro
Answer: Fiz recentemente uma integração com o PagSeguro transparente, e me deparei com essa e outras dificuldades.
Supondo q vc esteja usando a biblioteca oficial deles no PHP (https://github.com/pagseguro/php), segue abaixo os problemas encontrados e como foram resolvidos, começando pelo que eu acredito ser a causa do seu problema (claro que para ter certeza há a necessidade de ver o código PHP):
maxInstallmentNoInterest

Um erro comum é enviar um campo ao PS pelo JS e não fazer o mesmo pelo PHP. O problema é que no caso específico deste campo, a biblioteca não possui um atributo próprio para enviá-lo, sendo necessário fazer o uso de addParameter, dessa forma: $psRequest->addParameter('noInterestInstallmentQuantity', 2);

Nome do Banco

Para pagamentos via Débito Online (EFT), há a necessidade de se informar o nome do banco, algo que não fica claro no manual. Para isso, utilize o método setOnlineDebit, dessa forma: $psRequest->setOnlineDebit(array("bankName" => 'nome do banco');

EFT vs ONLINE_DEBIT

O método do JS getPaymentMethods retorna um JSON cuja nomenclatura para pagamentos online é ONLINE_DEBIT. Porém, na biblioteca do PHP essa nomenclatura muda para EFT. A classe do PHP onde isso se encontra é a PagSeguroDirectPaymentMethods, e uma das formas de corrigir esse conflito é por adicionar a seguinte linha na declaração do atributo $methodsList: "ONLINE_DEBIT" => "eft",

Espero que estas sugestões possam lhe ajudar a finalizar o seu projeto.
Comment: Obrigado pela resposta @Szag-Ot, o problema nesse caso era o Javascript. Como estava utilizando a API em sandbox o javascript deveria vir do sandbox também.
Acho meio falho esse método pois pode ocorrer um monte de erros por esquecimento.
Problema que na documentação não diz nada disso rsrs.
Mas obrigado pela ajuda
Comment: Ainda nem saí do PagSeguroDirectPayment.getBrand, já cai direto no error com Object {error : true}, estou passando '411111' (6 primeiros dígitos do cartão de crédito da SandBox). Pode me ajudar?
Comment: @JhonatanPereira não entendi sua dúvida.... poderia postar o erro que está dando ou parte do código? Talvez seria melhor criar uma nova questão para isso
Comment: É que é um problema tão curto... Como você já conhece o código, deixei bem resumido: https://jsfiddle.net/jpdesignerrio/drhdomng/2/
Comment: Caso não dê pra saber o porquê do erro, e porque ele não retorna o motivo do erro, abro uma nova questão
Comment: @JhonatanPereira o trecho do codigo postado está correto... porem vc sabe que o getBrand deve ser continuação de outro método, né? O getPaymentMethods. Segue link com trecho do código que uso em nosso sistema, espero que ajude: http://codepen.io/szagot/pen/RRdXVY?editors=0010
Comment: Obrigado @Szag-Ot
Comment: Cara, estou recebendo o erro 59001 : "unknown web session id" e não acho solução pra ele! Já abri novo tópico aqui no Stack há 3 dias, mas até agora ninguém respondeu... Sabe me dizer o motivo do erro?
Comment: http://pt.stackoverflow.com/questions/148507/pagseguro-getpaymentmethods-erro/148773#148773
Comment: verificando, @JhonatanPereira
Comment: O problema era o navegador, funcionou. Só não sei o que mais preciso fazer depois da função que pega o Token do Cartão


Code sign error with Xcode 3.2

Question: I had a fully working build environment before upgrading to iPhone OS 3.1 and Xcode 3.2. Now when I try to do a build, I get the following:

Code Sign error: Provisioning profile 'FooApp test' specifies the Application Identifier 'no.fooapp.iphoneapp' which doesn't match the current setting 'TGECMYZ3VK.no.fooapp.iphoneapp'

The problem is that Xcode somehow manages to think that the "FooApp Test" provisioning profile specifies the Application Identifier "no.fooapp.iphoneapp", but this is not the case.
In the Organizer (and in the iPhone developer portal website) the app identifier is correctly seen as 'TGECMYZ3VK.no.fooapp.iphoneapp'.
Also, when setting the provisioning profile in the build options at the project level, Xcode correctly identifies the app identifier, but when I go to the target, I'm unable to select any valid provisioning profile.
What could be causing this problem?
Update: I've tried to create a new provisioning profile, but still no luck. I also tried simply changing the app identified in Info.plist to just "no.fooapp.iphoneapp". The build succeeds, but now I get an error from the Organizer:

The executable was signed with invalid entitlements. The entitlements specified in your application's Code Signing Entitlements file do not match those specified in your provisioning profile. (0xE8008016).

This seems reasonable, as the provisioning profile still has the "TGECMYZ3VK.no.fooapp.iphoneapp" application identifier.
I also double checked that all certiicates are valid in the Keychain.
So my question is how I can get Xcode to see the correct application identifier?
UPDATE: As noted below, what seems to fix the problem is deleting all provisioning profiles, certificates, etc., making new certificates / profiles and installing them again. If anyone has any other solutions, they would be welcome. :)
Answer: I had to manually remove the provisioning profiles from my phone, then rebuild the apps after doing a "clean all targets" from the build menu.
That's under Settings -> General -> Profiles
This happened to me when I got a new Mac.  You'll fix it, don't worry
Answer: Well, as seems to be the case with a lot of these code signing issues, deleting all provisioning profiles, certificates, etc. and revoking and generating everything all over again turned out to do the trick. I even created a new bundle identifier, app identifier, etc., and now AdHoc distribution is working again.
Comment: this certificate stuff stinks. Apple never managed to do this work correctly.
Comment: in case this is not working for you you might try to delete the xcuserdata folder in your xcproj .

http://stackoverflow.com/a/9968884/300694
Answer: I had this same error yesterday. I tried all of the various resetting procedures in the other answers with no luck. Eventually I also

rebooted my mac
rebooted my iPhone
deleted all of my iphone provisioning profiles from the phone using XCode
deleted all profiles from my mac (~/Library/MobileDevice/Provisioning Profiles for me)
what else? deleted build folder, restarted XCode, installed update to 3.1.2 sdk, sacrificed a chicken.

Lo and behold, it now works, the error is gone. This is serious voodoo territory.
Comment: I was in a similar situation. Went to Organizer -> Provisioning Profiles (on the left) -> clicked on "Refresh"! And it looks like it worked. BTW, "sacrificed a chicken" lol
Comment: what do you know, it happened again. thanks apple for wasting an hour of my life...
Answer: Also, make sure that you added a reference to the Entitlement filename "dist.plist" in your project configuration CODE_SIGN_ENTITLEMENTS.
Answer: Check both Code Signing Entitlements in info for both the Build Target and the Main Application - if Code Signing Entitlements says  on either then remove it
Answer: In XCode, in the "Groups & Files" pane, expand "Targets" and double-click on your app's target.
This will bring up the Info pane for your target. In the "Build" section, check the "code signing" section for any old profiles. This has happened to me many times particularly after an upgrade to a new version of the sdk and iphone os
Comment: The problem is, when I try to select my (previously working) Application profile, I am unable to select it. Xcode seems to "believe" that the Application Identifier in the profile is "no.fooapp.iphoneapp", instead of correctly identifying it as "TGECMYZ3VK.no.fooapp.iphoneapp". When viewing the provisioning profile in the Organizer, the Application Identified is correcly shown as "TGECMYZ3VK.no.fooapp.iphoneapp".
Answer: Quick Hack if you are on Xcode 4.3.
In Xcode under Project Settings > MyTarget > Summary tab all the way in the bottom there is a checkbox that says "Enable entitlements". When I unchecked it, it made the error go away.
Answer: After being stumped by this for quite a while I revisited the settings and discovered that I had reversed the 'Code Signing Identity' and the 'Any iPhone OS Device' entries. - The clue I had as to this happening was shown by.

Deleting every profile off the phone
Build and Go

At this point xcode attempts to provision the phone (device)

Examine the phone to see which provisioning profile has been added.

As I prefix all my profiles 'AdHoc' or 'Development' or 'AppStore' I saw immediately that the install process was putting a development profile on the device and not an AdHoc profile.
Answer: Inside Resources/Entitlements.plist there is a Boolean "get-task-allow" if that is not checked, check it ON. This fixed the issue for me.
Answer: The device may not be in the list. Try modify your provisioning profile.
Answer: Just to add a note here: I encountered the same error (0xE8008016) after replacing my Macbook's logic board (although I imagine you'd have the same problem on a completely new mac), and after hours of going around in circles I realised that the iPhone Developer Program Portal had separate certificates for Development and Distribution.
A change in hardware means you need to reissue both certificates - I'd reissued Developer but not Distribution. Because my name hadn't changed when my hardware did (and certificates are identified by the owner's name), this made it a tricky problem to spot ;) Hope this saves someone else my frustration.
Answer: For reference, I ran into the same issue and deleting all of my profiles, existing certs and everything from my local drive and from the developer portal, and deleting my existing devices and re-adding them (developer portal)  seemed to do the trick.
Answer: Another cause is if the device you want to install onto is not an approved device in the Distribution Certificate.
Answer: The problem is in the "project.pbxproj" file located inside the [your project].xcodeproject file. If you feel brave right click on the .xcodeproject and view contents then open "project.pbxproj" with a plan text editor. Inside search for the offensive path and correct it. In my case I just removed the entire path and just left "Entitlements.plist" and it cleard my issues up. I STRONGLY reccomend backing up your .xcodeproject before attempting this.
Answer: Double click the target  then select the "Properties" tab. There change the com.yourcompany.${...}.
Answer: Sometimes Xcode does not automatically copy your provisioning profile to the right location.
In my case, that was true.
Check that your provisioning profile is in ~/Library/MobileDevice/Provisioning Profiles directory and if not just drag and drop, clean and build

Code sign error with Xcode 3.2


Is there a similar library to PixTools for MAC?

Question: Is there a similar library to PixTools for capturing images, images from a scanner and then treat them with image recognition for OSX operating systems?
PixTools / Scan developers programmatic Gives Control of the Entire scanning process and every scanner feature
I am programming a system in MAC that use a scanner,i am programming in swift.
I require is a library that allows me to manipulate the images and perform OCR as pixtools for .Net
Answer: Yes; what you're looking for are the ImageKit and ImageCaptureCore frameworks.
Note that ImageKit is a bit more general than PixTools; it handles transferring images from cameras as well as running scanners. However, it does not support some of the more complex image enhancement and recognition features supported by PixTools.
Comment: but i need a library to OCR


Why are linear phase EQs not the standard?

Question: Considering all the phase issues that may arise when working with non-linear phase EQs, I asked myself why are the linear ones not the standard? Why do non-linear EQs even exist? It may sound a bit extreme, but there are a lot of cases when using a non-linear EQ might mess things up really bad.
I read that linear-phase eq introduces some latency, but couldn't track down how much, and if it becomes noticeable. This would explain the live scenario, or live monitor when studio recording, but not the mixing/mastering when tracks have already been recorded.
I think I've gained enough knowledge to understand when and why to use one, but because I see no downsides to using a linear one, and I couldn't find an answer to what I'm asking, I turned to this community.
Thanks in advance!
Answer:  I'm gonna throw this in as a first-guess answer, rather than as a comment
I honestly don't know, but I'd be tempted to say they don't make nearly so much difference on a single instrument as a full mix, so people may hold then in reserve for latency/CPU performance until they do become important - on the master bus.
My entire mastering chain is all Linear plugs, EQ, multiband comp/lim etc. Before then… I've never really noticed it to make a difference I can actually hear.
You may as well ask why would anybody use a model of a 1960s Abbey Road EQ… when they're quite clearly "less accurate" than a modern one.
Answer: The main problem with linear phase EQs is that if they are perfect, the latency they introduce is infinite.  For some applications, that is too much.  So basically you have to design them around errors you are still willing to accept.  A typical method of implementation is to filter the signal with a normal IIR in windows, once forward in time, and once backward in time.  The ringing at the end of input in theory lasts forever, but cutting it off with tapered and overlapping windows introduces a limited amount of error.
In contrast, a good IIR EQ has very little delay except for the transition and stop bands and is simple to implement.  It works fine in live situations and when monitoring where the large latency of linear-phase EQ is just not workable.
Comment: thank you for introducing the latency thing. You can't select and cut/boost frequencies in real time if you think about it. So LP DSp's work by "predicting the future" which means really adding a delay and then "cheating" nature by feeding out the processed sound from whenever in the past. If yo think about it further this can introduces a raft of problems of its own. You don't get something for nothing.
Answer: In addition to latency, the audible downside of linear-phase EQ is pre-ringing. I cannot explain it better than this page: https://cravedsp.com/blog/linear-phase-eq-explained
Quote:

Pre-ringing is a backwards echo. It sounds like a strange sucking sound. It is most noticeably heard on transients.

If you're familiar with convolution reverbs, and how an impulse response is translated to sound, you might understand what linear-phase EQs (or any audio processing systems) do in terms of pre/post-ringing when you see their impulse responses.
Comment: right! you are better off in fact with some artefacts (phase shifts) which are a natural-sounding consequence of the thing you were trying to do in the first place, than a horrible artefact which is a result of "cheating physics" (so to speak).
Comment: Thanks for commenting on this non-trivial issue whch was unknown to me!
Answer:
On single instruments recorded with 1 mic there are no benefits to linear phase EQs. Phase is a relative impact parameter: it produces audible effects only when compared against something else with the same content. Record a guitar with 2 mic, flip the phase on one of them and hear for yourself.

We agree on that. Although not put in words in the question because if LEQs became the standard, single mic takes "wouldn't be harmed either".

Even on multimic'd instruments, the issue is not as likely to occur than one could think. Most of the time, different mics are there to play different roles so that they're set up to pick up different sounds.

That's true on the drum scenario you brought up. Consider now a string section recording, or an orchestral recording, or a chamber music recording, where mics are playing a bigger role that capturing very specific instruments and frequencies. Try using minimum phase eq differently on each mic, you'll notice very, very quickly!
Having said that, Sonar's Everything Equalizers free eBook [1] helped me get some facts straight:

Minimum phase EQs sound great in most instances, but during mastering or  when applying delicate EQ adjustments to acoustic instruments it's often best  to use linear phase EQ plug-ins. Linear-phase EQs do not alter the phase of a  signal, creating a more natural tonal effect and may also work well for parallel  EQ duties. However, linear-phase EQs suffer from greater latency and high CPU  usage, which means they can't be used during tracking or in large, CPU  intensive mixing sessions.

It is clear to me now that latency does become an issue, and so des CPU processing, if LEQ is used indiscriminately.

Linear phase EQs also introduce their own type of distortion called
pre-ringing, which some very picky people find offensive. In practice,
pre-ringing is rarely audible or much of a concern.

To better understand pre-ringing, I found this very useful video:

EQ: Linear Phase vs Minimum Phase by fabfilter

Quoting [1] again:

These equalizers avoid phase shift by analyzing the frequency content and  applying gain with FIR filters, a process that takes a lot of time (latency). The processed audio is subsequently shifted earlier to try to keep everything in time. This time shift produces an audible echo, called a pre-ring, that immediately precedes sounds with strong transients, like drums. This pre-ring can smear or weaken the attack of drums and picked or plucked  instruments. Getting back to the no free lunch idiom, linear phase equalizers  trade phase shift for pre-ringing artifacts. We have now established that both  minimum phase and linear phase equalizers have good and bad attributes.

On the use cases for LEQ:

For most applications of EQ, like sweetening instruments or mastering mixes, the actual phase shift is minimal because we use broad bandwidths and gentle boosts and cuts. For extremely narrow cuts or boosts, like when removing a resonant frequency from a snare drum, phase shift will drastically affect the frequencies surrounding the EQ'd frequency. In this case, linear phase EQ would be a wise choice and would remove the offending resonance without affecting the overall sound of the drum. Likewise, a steep high-pass filter that removes rumble from a vocal mic or guitar cabinet could wreak havoc on phase at frequencies well above the cutoff frequency. Phase shift artifacts may cause instruments to sound strange, so linear phase EQ would be a great choice. We can say that narrow cuts and boosts and steep bandpass filters are two situations where you might consider linear phase over minimum phase EQs.
Parallel processing instruments or subgroups in a mix would be another situation for linear phase EQ. Let's say we have a vocal track and wish to duplicate the track and add some high-frequency shimmer by applying a high pass filter and compression to the duplicate (parallel) track. Minimum phase EQs, especially high pass filters, can induce phase shift that adversely affects the combination of the two tracks, causing unintended tonal changes. You can't simply "flip the phase" and fix this problem. So, for parallel EQ duties, the linear phase EQ, with its lack of phase shift, may be our new best friend. You should audition both linear and minimum phase for parallel  processing since in some cases you might find that phase artifacts sound interesting.
How about blending a top and bottom snare mic? For similar reasons to the above example, a linear phase high pass filter on the bottom snare mic (or hi-hat mic) may help retain the natural body of the snare while removing some low-frequency mud. The same goes for EQ'ing multi-miked guitar cabinets. For stereo miking, however, minimum phase EQ may be just fine since we are typically applying the same eq curve to both mics and both mics contain very similar source audio. Again, try both linear phase and minimum phase to hear what each does in your mix.

As of the latency:

Another consideration when deciding whether to use linear-phase EQ is latency and CPU power. Many linear phase equalizers load your CPU slightly more than traditional equalizers and all linear phase equalizers can impart extreme amounts of latency. Linear-phase EQ latency  can range from around 3,000 samples to over 20,000 samples. At a 44.1kHz  sample rate, that translates to between 100 milliseconds and more than half a second. While most DAWs provide plugin delay compensation, you may near the compensation limit once you exceed 10,000 samples. Pro Tools, for example, provides about 16,000 samples of delay compensation at a 44.1kHz sample rate.
Many modern plugin equalizers, like those from Izotope and Fabfilter, provide linear-phase, minimum-phase, and even mixed-phase modes. Mixed modes provide some benefits from each type of EQ. You should audition these modes on various sources to find the best uses of each type. Further, many equalizers provide resolution or quality settings to further optimize your preferences of sonic character vs latency.

Finally: should I use LEQ?

To answer the question of "Should I use linear phase EQ?" the answer is, as usual, it depends. Minimum phase equalizers, with their familiar personalities, would be my first choice most of the time. In certain situations, like narrow bells and steep filters, linear phase probably has the advantage. For parallel processing and multi-miked sources linear phase also probably comes out on top.

Bonus:
Some popular Linear Phase options:

Blue Cat Liny EQ
DMG EQUALITY
Fabfilter Pro-Q3
Izotope Ozone 9 or Neutron 3
Logic Linear Phase EQ (Stock Logic Plugin)
Melda MEqualizer LP
Nugen SEQ-S
T-RackS Linear Phase EQ
Waves Linear Phase EQ

[1] https://try.sonarworks.com/everything-equalizers/
Answer: On single instruments recorded with 1 mic there are no benefits to linear phase EQs. Phase is a relative impact parameter: it produces audible effects only when compared against something else with the same content. Record a guitar with 2 mic, flip the phase on one of them and hear for yourself.
Even on multimic'd instruments, the issue is not as likely to occur than one could think. Most of the time, different mics are there to play different roles so that they're set up to pick up different sounds. Ex: a kick drum will be picked up by both the kd mic and the overheads but it will sound so different in each (not mentioning the delay introduced by the distance to the mic) that phase is irrelevant and certainly does not grant the use of a PLEq.
On a stereo master, unless each side is eq'd differently, the same is true: no use.
In general, the use cases of LP are very limited. Possibly when EQing individual mics in a Decca tree or in a surround mic setup?
Let's also remember that the phase shift associated with most eqs is a physical constraint of capacitors in eq circuits. They were never "designed" that way. And still, they account for the sound of 99.999% of all recorded music in history.