Disable SMTP AUTH on Port 25

Question: Due to PCI-DSS, we are required to disable plaintext authentication. We've achieved this by encapsulating communications between our mail server and clients with TLS on port 465.
The problem lies in that port 25 must remain open and unencrypted for us to receive email from the internet, but should not allow authentication.
I've tried disabling the AUTH command, but that breaks authentication on port 465, too.
Is there a mail server or proxy that will allow separate configuration for port 25 and 465, such that authentication is only available over a secure channel?
Also noteworthy: we are using MailEnable with stunnel in FIPS mode.
Update:
MailEnable supplied a patched SMTP executable that allowed me to configure via Windows' registry whether authorization is offered on each listening port. This solved my problem—hopefully, they will publish the patch as a hotfix.
Comment: Can't you just block connections from the internal network to port 25?
Comment: That's not good enough for Qualys, unfortunately: any mention of AUTH LOGIN is a fail and an EHLO spits it right out on 25 or 465.
Comment: Is postfix capable of disabling auth on one of two or more listening ports?
Answer: Yes, postfix is perfectly capable of this.
Take a look at the Postfix HOWTO:
http://postfix.state-of-mind.de/patrick.koetter/smtpauth/
and particularly:
http://postfix.state-of-mind.de/patrick.koetter/smtpauth/smtp_auth_mailclients.html
(those two pages are linked from the fairly extensive official Postfix docs page http://www.postfix.org/docs.html)
For my server, the configuration in master.cf looks like:
# ==========================================================================
# service type  private unpriv  chroot  wakeup  maxproc command + args
#               (yes)   (yes)   (yes)   (never) (100)
# ==========================================================================
smtp      inet  n       -       n       -       -       smtpd
submission inet n       -       n       -       -       smtpd
  -o smtpd_tls_security_level=encrypt
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
  -o milter_macro_daemon_name=ORIGINATING
smtps     inet  n       -       n       -       -       smtpd
  -o smtpd_tls_wrappermode=yes
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
  -o milter_macro_daemon_name=ORIGINATING

And main.cf has a line like:
smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination

In this case, authentication is only turned on for the submission (587) and SMTPS (465) ports.
Comment: Now, to find a HOWTO on convincing Windows-entrenched executives to leverage a Unix-based system. ;D Thank you for the resources, @cjc. I've some reading to do.
Comment: I don't mean to wake a zombie up but those links are not working anymore.
Comment: Walking Dead Alert  --- this is why posting links is discouraged
Answer: It seems that the Postfix's option smtpd_tls_auth_only = yes is exactly what you search. It allows to use SMTP AUTH only when TLS is activated, which is only relevant on port 25 for your configuration.
http://www.postfix.org/SASL_README.html#id396969
http://www.postfix.org/postconf.5.html#smtpd_tls_auth_only
Answer: You can also do the following to only advertize tls on certain ports with exim4.
tls_advertise_hosts = 192.168.40.5:${if eq {$interface_port}{587} {*}{}}

So only clients connecting from 192.168.40.5 and clients connecting through port 587 would be offered tls.  As long as your auth setting are setup to require tls before advertise, only clients using port 587 with TLS would be able to use auth.
Comment: Excellent! So far, my MailEnable and stunnel configuration is holding strong following the fix. It's nice to have options, should my employer become less Microsoft-entrenched—thank you.
Answer: Exim lets you set:
server_advertise_condition = ${if def:tls_cipher}

on an authentication driver, so it's only advertised/available within TLS.
Exim is very frequently used as a frontend gateway between MS mail servers and the open Internet; LDAP integration letting you query AD for address verification, authentication, etc; decent integration into various malware detectors, etc.
Comment: MailEnable is working on a fix, but I'm not very optimistic—thank you for the information on Exim and configuration as a frontend.

Disable SMTP AUTH on Port 25


Solr multi-select facets occurs bad request error

Question: I faced with a weird problem using apache solr faceting search. While selecting two facet constraints, solr respond with 400 error:

"400" Status: null: null HTTP ERROR 400
Problem accessing /solr/project/select. Reason:
null

Basically I have one index configured and number of fields indexed inside. I'm using facet for "content type" field. There is no problem at all when only one facet constraint is selected.

http://localhost:8983/solr/project/select?fl=item_id,score&fq={!tag=facet:type}ss_type:"system"&start=0&rows=10&sort=ds_created
  desc&facet=true&facet.sort=count&facet.limit=10&facet.mincount=1&facet.missing=false&facet.field={!ex=facet:type}ss_type&f.ss_type.facet.limit=50&wt=json&json.nl=map&q.alt=(ss_search_api_language:"sv")
  (index_id:"project_nodes_index") (hash:gf1tmd)

Problem starts where two constraints are selected:

http://localhost:8983/solr/project/select?fl=item_id,score&start=0&rows=10&sort=ds_created
  desc&facet=true&facet.sort=count&facet.limit=10&facet.mincount=1&facet.missing=false&facet.field={!ex=facet:type}ss_type&f.ss_type.facet.limit=50&wt=json&json.nl=map&q.alt=(ss_search_api_language:"sv")
  ((({!tag=facet:type}ss_type:"system") OR
  ({!tag=facet:type}ss_type:"product")))
  (index_id:"project_nodes_index") (hash:gf1tmd)

Standart modules are used:
* search_api_solr
* search_api
* facetapi
Solr version 3.6.2
Comment: having exactly the same issue here :)
Answer: I think you can update to the latest dev version.
For more info you could check this issue:
https://www.drupal.org/node/2290601


Explain this CSS custom properties behavior

Question: I'm struggling to understand the following with CSS variables, I believe the code speaks for itself otherwise please let me know.

:root {
    --color: red;
    --hover-color: var(--color);
}

div {
    --color: green;

    background: var(--color);
}

div:hover {
    background: var(--hover-color);
}

Why am I red on hover? Shouldn't I be green? When inspecting this element on hover, chrome shows the green color!?

What's absolutely baffling to me is that when inspecting the element in Chrome Devtools it shows the hover color as green??
Comment: Do other browsers handle it differently? It's either a bug (within Chrome), or the variables are set by reference rather than by value.
Comment: Same behavior in Mac Firefox.
Comment: an important rule: never do evaluation at root level
Answer: --hover-color resolves to the --color value of the scope in which it exists, meaning it will compute the value detected at that time. This is to avoid dependency cycles. You can read about these cycles in the specification document.

Custom properties are left almost entirely unevaluated, except that they allow and evaluate the var() function in their value. This can create cyclic dependencies where a custom property uses a var() referring to itself, or two or more custom properties each attempt to refer to each other.

To prevent this, you would want to expand a bit, and do the following:

:root {
    --color: red;
    --hover-color: var(--color);
}

div {
    --color: green;
    --hover-color: var(--color); /* Added this here */

    background: var(--color);
}

div:hover {
    background: var(--hover-color);
}

I am green on hover, as expected.

But this raises an interesting issue with Chrome's DevTools, which indeed shows a green color preview next to the hover state's background value. You might want to file an issue and have this looked into.
Comment: Oh I see. It's a little annoying we need to reset both `--color` and `--hover-color`, and really weird that Chrome shows it as green, but I can live with it. Thanks for the explanation.
Comment: I don't understand why you are refering to cycles here?
Comment: Now devtool can display the correct value. Looks like chrome has fixed this.
Answer: What you are doing is , you are making a variable then passing color to it , purely my thinking don't know this is the reason or not
Let's say its a javascript variable , then
var color = red;
var hoverColor = multiplier * color;

Then , you passed
color  = green;

Then in hover , what happening is
hover = hoverColor;

(i.e. hoverColor = someMultiplier * color & color is green)
Comment: CSS variables/properties are completely different to most other language's variables though. I understand why this would happen with JS.


Case When to check if is null

Question: I have a filter for the clients for a report, if the person put the filter Client it uses,else it ignores and bring all clients.
This is my Where clause.
Where [S].ano_mes = @ano_mes OR @ano_mes IS NULL
            AND S.cnpj = @cnpj or @cnpj is null
            AND S.cod_produto = @cod_produto or @cod_produto is null
            AND CASE WHEN (len(@cnpj) > 0) THEN
                 (S.CGC_Cliente +''-''+S.Seq_Cliente) in(SELECT cnpjseq FROM #Tb_CliSelecionados)
                    END

The problem is in the CASE WHEN part,the rest works.
If the variable @cnpj has value THEN it should use the filter.
The filters is  CGC_CLIENTE and SEQ_CLIENTE together.
The table #Tb_CliSelecionados has the parameters Concatenated equals,exemple,both the table with alias S and #Tb_CliSelecionados has '060746948041730-00'
i'm getting erro in two parts in the "IN" its says incorrect syntax near "IN"
And in the END saying incorrect syntax near "END".Expection ")"
Someone knows what i'm doing wrong in the case when part?
Comment: There's a syntax error in your case statement, you should try it another way. What are you trying to filter out there? Maybe you could specify some sample data and what the result should be?
Answer: CASE return one expresion isn't a flow control.
 AND CASE WHEN len(@cnpj) IS NULL
               THEN 1
          WHEN (len(@cnpj) > 0)
               THEN  CASE WHEN exists
                           (SELECT 1
                            FROM #Tb_CliSelecionados
                            WHERE cnpjseq = S.CGC_Cliente +''-''+ S.Seq_Cliente )
                          THEN 1 -- if exist the match return the row
                          ELSE 0 -- other wise ignore the row
                     END
         ELSE 1 -- if len(@cnpj) == 0 then return all rows
     END = 1  -- HERE YOU return the row if CASE return 1

Answer: The CASE WHEN clause is incorrect. It should look like:
         AND CASE
             WHEN @cnpj IS NULL
                 THEN 1
             WHEN (len(@cnpj) = 0)
                 THEN 1
             WHEN (S.CGC_Cliente +''-''+S.Seq_Cliente) in (SELECT cnpjseq FROM #Tb_CliSelecionados
                 THEN 1
             ELSE 0
         END = 1

Comment: Yours is much cleaner than mine. But I think `exists`  is better than`IN` for this case because can use any index for do the match.
Comment: The last Then i got an error,incorrect syntax near 'THEN', the first two when dont do nothing, the last when with the condition needs to filter,in the last when i need to change the THEN 1 part?
Comment: Was a missing ), but then i filter it brings nothing
Comment: Try this one but with the `exists` instead of `IN`
Answer: You can change that part to
AND ( len(@cnpj) > 0
       AND S.CGC_Cliente + '-' + S.Seq_Cliente in (SELECT cnpjseq FROM #Tb_CliSelecionados))

Case When to check if is null


Should remove "Thanks" in the question or not?

Question: When editing a question, I try to keep "Thanks" in the content. Others try to remove it? What should we do in this case?
Comment: http://meta.stackexchange.com/q/2950/224252
Comment: http://meta.magento.stackexchange.com/questions/503/should-salutations-be-removed-from-questions/505#505
Answer: In my opinion a sentence like "thank you" does not add anything to the question, as also introductions (like "I'm a newbie" additions) do not add valuable information.
I tend to remove "Thank you" from anywhere, but I do edit a lot, and I have Edit Questions And Answers privileges (>2000 rep), so then you don't need approvals from reviewers.
I think it would be good to remove superfluous additions as "thank you" if you are already changing/improving other things in a question. I think it is better not to suggest these superfluous edits if you do not have reached the Edit Questions And Answers privilege as I think the reviewers that have to review such edits can use their time in a better way.
Answer: You have mentioned two different scenario

Keep Thanks as a editor
Reviewer of edit

In first scenario you keep "Thank you" It's ok For me as well site (I think)
In the second scenario if editor has made some more good edit then accept those edits.
And if editor removes only thank you from question or post, then reject those edit mark as no improvement
This is what I do. Otherwise all people have their own believe and own thinking about this.
Answer: I leave "Thanks" lines in questions, but I've no problem if it is removed along with other edit (fixed tags or other stuff), but it makes no sense to edit questions just to remove this.
Actually "Teja Bhagavan Kollepara" makes a lot of such and it brings up old questions w/o any further improvements :(
Can a moderator please ask him to stop this?

From Should salutations be removed from questions?

When editing questions, I always remove "fluff" like that, as it is policy on StackOverflow as well, but I wouldn't go so far to edit questions just to remove "Thank you".

Edit:
... and you probabbly should not add thank you lines. :)


making a metric space for special open ball

Question: is it possible to find a metric space for my arbitrary open ball?
for example I wanna find a metric
ℝ×ℝ→ℝ and my open balls be in the form of triangel or square(or any other shape)....
Answer: Probably. How about Taxicab geometry?
Comment: @fatima. The above mentioned $l^1-norm$ and $sup-norm$ are the first metrics came to mind which happens to make squares (or diamonds) in two dimensional Euclidean Space. I don't know any metrics which have open balls as triangles (or any other regular polygons for that matter), though i'm surprised if i see a proof that it is not possible.
Comment: tnx.your answer was helpfull


$form_state=>setErrorByName/setError on fieldset/container/etc

Question: I have written a custom validation handler for webform that compares two fields.  If the fields are in a container/fieldset/etc., I would like to set the error on the container instead of on the fields (since either of the two fields could be the erroneous field).  For example, the fieldset is trip-dates, the fields are start-date and end-date and I want an error if start-date is after end-date.
I can use setErrorByName/setError to set errors on individual fields, but it doesn't work if I try to set an error on the fieldset.  When called against a fieldset, setErrorByName/setError call sets the error message at the top of the form, but does nothing to highlight/set an error class on the fieldset.
Webform Source:
<code>event_details:
  '#type': fieldset
  '#title': 'Event Details'
  '#attributes':
     name: event-details
  date_container:
    '#type': fieldset
    '#title': 'Travel Dates'
    '#required': true
    '#attributes':
       name: date-container
     departure_date:
       '#type': date
       '#title': 'Departure Date'
       '#required': true
       '#default_value': '+1 day'
       '#format': short
       '#date_date_min': today
       '#datepicker': true
       '#datepicker_button': true
       '#date_date_format': m/d/Y
     return_date:
       '#type': date
       '#title': 'Return Date'
       '#required': true
       '#default_value': '+1 day'
       '#format': short
       '#date_date_min': today
       '#datepicker': true
       '#datepicker_button': true
       '#date_date_format': m/d/Y
</code>
Class Code:
<code>  $errorFields=[
     'date_container',  //sets message, fails to highlight
     'date-container',  //sets message, fails to highlight
     'event_details][date_container',   //sets message, fails to highlight
     'event-details][date-container',   //sets message, fails to highlight
     'return-date',     //sets message, fails to highlight, as expected
     'departure-date',  //sets message, fails to highlight, as expected
     'return_date',     //sets message, highlights single field as expected
     'departure_date',  //sets message, highlights single field as expected
  ];
  foreach($errorsField as $errorField){
    if (!($left_val <= $right_val)) {
      $formState->setErrorByName(
       $errorField,
      $this->t('some weird message'));
    }
  }
</code>
I have also tried changing the names of the containers to underscores instead of dashes...no luck.  If it would just add an error class to the fieldset, I could style it easily enough, but it doesn't seem to change anything about the fieldset.
I have also tried container, details and section instead of fieldset.
Comment: Did you also try with [setError](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21FormState.php/function/FormState%3A%3AsetError/8.2.x) ?
Comment: Yes, I tried both setError and setErrorByName...btw, in diving into the code, setError just calls setErrorByName
Comment: I see you have a fieldset inside another fielset. Keep it simple, create some test webform and try to get it to work first using just one fielset. Also, use the default "Bartik" theme just in case.
Answer: A workaround may be to add a class to the form which you could then use to style the fieldset:
<code>$form['#attributes']['class'][] = 'my-fieldset-error';
</code>
Answer: I finally got it working by explicitly giving both name and id attributes to the fieldset.


Using Qt Creator (with Qwt), really basic stuff

Question: I'm trying to make a Qt program using Qt Creator and Qwt for plotting. I've never used Qt Creator before. I've created a MainWindow and added a Qwtplot widget there (object name: qwtPlot). The widget shows up in the program when I compile and run it. But theres no mention of the qwtPlot object anywhere in the (autogenerated) code so I assume it is being added at compile time from the .ui xml file (or something).
My question is that... how do I modify/change the qwtPlot object? Or where should I place the code?
I'm having a hard time articulating my question but the question basically is "How do I do anything with the qwtPlot widget which is created (graphically) with Qtcreator?". I've checked some tutorials but in the tutorials they add the widgets manually in the code, but I'd like to use Qt Creator (because my UI will be fairly complicated). This whole Qt Creator is pretty confusing...
Answer: A typical solution is to use multiple inheritance or contain the UI component as a private member. Qt explains the process on their web site:
Using a Designer UI File in Your Application
For a main window, most of this is auto-generated for you (on my version, at least ... 2.0.1)
You should have (or create) a mainwindow.h file that contains a member of type Ui::MainWindow.
class MainWindow : public QMainWindow
{
  Q_OBJECT

public:
  explicit MainWindow(QWidget *parent = 0);
  ~MainWindow();

private:
  Ui::MainWindow *ui;
};

Your mainwindow.cpp should initialize it properly, and then you can get to the auto-generated members through the private ui member.
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow) {
    ui->setupUi(this);
    ui->myControl->setProperty(...);
}

MainWindow::~MainWindow() {
    delete ui;
}

If you use the multiple-inheritance method, you can access the members directly.
Comment: So basically I create a class that inherites the qwtPlot object and so I can use the qwtPlot object embedded in my mainwindow?
Comment: Qt should have created a `ui_mainwindow.h` (or something like that) in your project. **That** is what you inherit from. You then have access to the members of Ui::MainWindow in your class, and can manipulate them as needed.


Size of basketball used by 7th/8th grade boys per state

Question: I can't find a resource to answer this question.  Looking for the size of the basketball used by boys in the 7th/8th grade by state.
28.5
Ohio

29.5
Kentucky
West Virginia
Indiana
Michigan
Comment: I have refereed in a few states and I have never heard of a junior high grade using a 28.5" ball.   There is a good chance you will have a 6'0"ish height player on a good 7th grade team.   That would be ridiculous using a kids ball.   Also the question is bad.   This is because NFHS and high school rules in general are not subject to non-high school basketball.   The specific league you play in notes that it will choose to play by a standard and could even say it plays by NFHS but wants a certain size ball used.   The league can do whatever it wants - there is no body for 7th grade bball.
Comment: Question is not bad as most middle school teams follow the HS rules with a few exceptions.  As they do in states that surround me.
Answer: Any programs that follow the US Amateur Basketball National Rules:

The National High School Federation Rules and Regulations (NHSF) will apply to all US Amateur Basketball games with the following exceptions.
...

Middle and High School (Grades 7 thru 12) will consist of two sixteen minute halves and will use a regulation size basketball (intermediate size ball for Women).

Grades 3 thru 6 will consist of two fourteen minute halves and will use the 28.5 intermediate size ball.
Answer: Ebay listing says the 28.5" Spalding-1000 is the official size for women and boys 12 and under.
Although I'm having trouble finding records for many states, so far I've found:
Alabama & Alaska use NFHS rules, but don't specify ball size for Junior High. Probably 29.5".
29.5
Arizona
Comment: This is not accurate at all.  I've been doing my research.  So far, every state I've gotten info from is 29.5 except Ohio.  Updating post momentarily.
Comment: There is nothing that governs 7th/8th grade basketball in the US.   Each league can do whatever it wants (I am sure 99% use 29.5" at these ages as this size ball is usually introduced in 4th-5th grade)
Answer: Very much a partial answer; in Kansas we use the 28.5 for middle school boys.  I should know; as a middle school coach I've got something like twenty of the little things.
Comment: Over 3 years later, literally the first place that I've heard to use the 28.5 outside of Ohio.


Where is phonegap pulling the splash screen from? Replaced all images in xcode

Question: I went to the general tab of my project target in xcode, and changed all of the Launch Images to the ones that I want to see displayed. The preview shows they are the correct ones. I deleted the default images from the platforms/ios/app/resources/splash folder and replaced them with the correctly labeled and correctly sized custom images. AND STILL, phonegap is still using it's default image for the splash screen.
Where is it even pulling that image from? Am I missing a step? I'm using phonegap 3.4.
Answer: Hello i think you have change the images in wrong directory. you need to replace images in the below splash folder. i have attached screenshot where you need to change the files.
Hope this helps.


Change content depending where scrollbar is currently at?

Question: Is there a way to change for instance a the color of a link depending how far you have scrolled down? I'm guessing this would be accomplished with jQuery?
Comment: Yes, it's possible, and doesn't require jQuery. What have you tried?
Answer: You can use the scrollTop property to see how far the page is scrolled down.
jQuery: http://api.jquery.com/scrollTop/
Javascript: https://developer.mozilla.org/en-US/docs/DOM/element.scrollTop
and $("html").scroll(function(){...}); for the scroll event.
$('a').css('color', 'blue') to change color.


Connection between proof and algebraic factor theorem

Question: It is (no proof needed)
Let $f \in End(V)$ and $ f^2 = f$ Then $V = Ker(f) \oplus Im(f)$.
What does this mean for the following sentence??
"Factor Theorem. Let $F : V \to W $ be linear and $A = (u_1, ..., u_r, v_1, ..., v_k)$ be a Basis of V with ker(F) = span$(v_1, ..., v_k).$
By definition of $U = span(u_1, ..., u_r)$ we get:
1) $ V = U \oplus Ker(F)$
2) The Restriction $F|U: U \to Im(F)$ is an isomorphism
3) If $P: V = U \oplus Ker(F) \to U, v = u + v' \to u$ is the projection, so $F = (F|U) \circ P$.
Thank you very much for any kind of help, since I'm a bit confused :)
Well what I did see is that I proofed $V = Ker(f) \oplus Im(f)$. So according to 1) it is $Im(f) = U$....
Comment: When you have $V=U\oplus W_1$ and $V=U\oplus W_2$, you can only conclude $W_1 \simeq W_2$, not $W_1=W_2$. Now this theorem says that by forgetting the subspace $\ker(F)$ where $F$ is $0$, one obtains an injective linear map. And by forgetting the vectors of $W$ that aren't touched by $F$, one obtains the isomorphism of 2). 3) says that from the decomposition $U\oplus\ker(F)$ and $F_{\mid U}$ one recovers $F$ by putting $F(x) = 0$ for $x\in\ker(F)$, and extending linearly.
Comment: Hello. Thank you, but I still have some questions. 1) Why do I obtain an injective linear map by forgetting the subspace ker(F)? 2) Forgetting the vectors of W means forgetting the vectors of V sind my f is an endomorphism (f: V -> V) ??
Answer: I'll expand here my comment, and try to answer to your second question.
Let us consider the general case where $F : V\rightarrow W$ is a homomorphism, and not an endomorphism of $V$.

If $V = U\oplus \ker(F)$, then $f_U : U\rightarrow W$ defined by $F_U(x) = F(x)$ is an injective homomorphism. Indeed, its kernel is $\{x\in U : F_U(x) = 0\} = \{x\in U : F(x) = 0\} = \{x\in U : x\in \ker(F)\} = U\cap \ker(F)$ and this intersection is trivial (i.e, it is $\{0\}$) by definition of the direct sum. Hence $F_U$ is injective.
Considering $F_U$ as a mapping between $U$ and $\mathrm{im}(F)$. This means that we forget about vectors that are in $W$ but that are not reached by $F$. This mapping is still injective, and now it is surjective: if $y\in \mathrm{im}(F)$ then by definition there is $x\in V$ such that $F(x) = y$. Consider the decomposition of $x$ as $x = u + n$, where $u\in U$ and $n\in\ker(F)$ (this exists by definition of direct sum, and is unique). Then $F(u) = F(x) - F(n) = F(x) - 0 = F(x)$ so that $F(u) = y$ and $u\in U$, i.e $y$ has a preimage by $F_U$ and $F_U$ is surjective. Hence $F_U : U\rightarrow \mathrm{im}(F)$ is an isomorphism.

Hence it always holds that if $V=U\oplus \ker(F)$, then $U\simeq \mathrm{im}(F)$, and you can derive from this fact the rank theorem: $\dim(V) = \dim(\ker(F)) + \mathrm{rk}(F)$.
In your special case where $F$ is an endomorphism, you have furthermore that $\mathrm{im}(F)\subseteq V$ and $F^2 = F$, and only with these hypotheses it is possible to prove that $V = \mathrm{im}(F) \oplus \ker(F)$.
Hoping this will help you see clearer.
Comment: This really was a very good comment and great explaining. I thank you very much, you made me happy after having a long working-day ;-)


Unity - Erro: Object reference not set to an instance of an object - Instantiate

Question: Fiz o tutorial do Survival Shooter que pode ser encontrado na asset store do Unity em https://www.assetstore.unity3d.com/en/#!/content/21028
O jogo está funcionando, mas  tá dando esse seguinte erro no código. Como resolvo isso?
NullReferenceException: Object reference not set to an instance of an object EnemyManager.Spawn () (at Assets/Scripts/Managers/EnemyManager.cs:26)
(Instantiate (enemy, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);)

esse erro aparece justamente quando o jogo começa e os bonecos começam a atacar o player.
O código é o seguinte, que é o mesmo do tutorial do seu canal e do site da unity:
using UnityEngine;

public class EnemyManager : MonoBehaviour
{
    public PlayerHealth playerHealth;       // Reference to the player's heatlh.
    public GameObject enemy;                // The enemy prefab to be spawned.
    public float spawnTime = 3f;            // How long between each spawn.
    public Transform[] spawnPoints;         // An array of the spawn points this enemy can spawn from.

    void Start ()
    {
        // Call the Spawn function after a delay of the spawnTime and then continue to call after the same amount of time.
        InvokeRepeating ("Spawn", spawnTime, spawnTime);
    }

    void Spawn ()
    {
        // If the player has no health left...
        if(playerHealth.currentHealth <= 0f)
        {
            // ... exit the function.
            return;
        }

        // Find a random index between zero and one less than the number of spawn points.
        int spawnPointIndex = Random.Range (0, spawnPoints.Length);

        // Create an instance of the enemy prefab at the randomly selected spawn point's position and rotation.
        Instantiate (enemy, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);
    }
}

Comment: Olá @Claudemir, poderia por favor adicionar uma captura de tela do Inspector do objeto EnemyManager - clica nele na hierarchy. Parece que ele não está encontrando os inimigos ou não encontrou o spawnpoint.
Answer: Entendimento do Problema
O erro Object reference not set to an instance of an object acontece quando você trabalha com alguma variável que não foi instanciada.
No Unity o método Instantiate pode ser usador de duas formas

Instantiate(original: Object);
Instantiate(original: Object, position: Vector3, rotation: Quaternion);

http://docs.unity3d.com/ScriptReference/Object.Instantiate.html

No teu código você passa enemy e o spawnPoints
Instantiate (enemy, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);

E são criados e instanciados em:
public GameObject enemy;                // The enemy prefab to be spawned.
public Transform[] spawnPoints;

Você passa ele como parâmetro pelo Inspector do teu objeto de jogo EnemyManager.
Deveria estar alguma coisa assim:

Se estiver faltando algum pode acontecer este problema
Soluções Possíveis
Recomendo que veja duas coisas:

se o Prefab de todos os personagens existem(zombunny, zombear e hellephant),eles pode ter desaparecido durante a migração para o Unity 5 que aconteceu nas ultimas semanas.

Se todos os spawnPoints existem na hierarchy do teu unity conforme imagem abaixo.

Se tuas imagens baterem com a minha é capaz que funcione. Senão é importante que compartilhe mais informações.
Adicione uma captura de tela dos teus elementos para ajudar na investigação se essa resposta não te ajudar.
Comment: @LeonardoV.DeGasperin obrigado pela dica, o cara dá uma força legal para a galera que quer desenvolver.
Comment: Oi Nills, eu tive o mesmo problema com instancia mas é com conversação 'MessagingClientReceiver().start' se quiser me ajudar me fala que eu fasso a pergunta certinho e mando o link
Comment: @LeonardoV.DeGasperin como você está usando o Instantiate com o MessagingClient?

Não precisa convidar um usuário para abrir tua dúvida, crie e descreva bem o teu problema que outras pessoas poderão te ajudar. Abraço.
Comment: oi Nils eu sei que não precisa mas poderíamos compartilhar respostas das perguntas foi nisso que pensei. Porém estou aqui para ajudar vou te passar um link que me ajudou muito la tem um post meu vou passar depois, pois tenho que reencontrar, esse site é de um desenvolvedor de games da game desenvelopent team muito bom e me ajudou muito http://darkgenesis.zenithmoon.com   espero que o ajude também.
Comment: http://darkgenesis.zenithmoon.com/DarkGenesisForums/topic/ch5-messagingclientreceiver/   aqui eu obtive as respostas aqui meu post responde a sua pergunta perfeitamente. meu post ta la para baixo eu perguntei para o Simon em 4 de Julho


Returns a value as an output parameter

Question: I have a question in C where I need to insert coefficients of a quadratic equation into a function and return the number of solutions and result.

Write a program that accepts a series of 3 real numbers, which are the
  coefficients of a quadratic equation, and the program will print out
  some solutions to the equation and the solutions themselves.
  Guidelines:

Functions must be worked with one of the functions that
  returns the number of solutions as a returned value, and returns the
  solutions themselves through output parameters.
3 numbers must be
  received each time. The input will be from a file (will end in EOF)

In the meantime I built the function without reading from a file just to see that it works for me, I built the function that returns the number of solutions but I got entangled in how to return the result as output parameter
here is my code for now:

int main ()
{

    double a, b, c, root1,root2,rootnum;

    printf("Enter coefficients a, b and c: ");

    scanf("%lf %lf %lf",&a, &b, &c);

    rootnum=(rootnumber(a,b,c);

    printf("the number of roots for this equation is %d ",rootnum);
}

int rootnumber (double a,double b, double c)
{

    formula=b*b - 4*a*c;

    if (formula<0)

        return 0;

    if (formula==0)

        return 1;
    else
        return 2;
}

Comment: `else return 2` => `else return 2;` and `printf("the number of roots for this equationis ")`=> `printf("the number of roots for this equationis ");` also `rootnum=(rootnumber(a,b,c);` => `rootnum=rootnumber(a,b,c);`
Answer: In C, providing an "output parameter" usually amounts to providing an argument that is a pointer.   The function dereferences that pointer and writes the result.   For example;
 int some_func(double x, double *y)
 {
     *y = 2*x;
     return 1;
 }

The caller must generally provide an address (e.g. of a variable) that will receive the result.   For example;
 int main()
 {
     double result;
     if (some_func(2.0, &result) == 1)
        printf("%lf\n", result);
     else
        printf("Uh oh!\n");
     return 0;
 }

I've deliberately provided an example that illustrates what an "output parameter" is, but has not relationship to the code you actually need to write.   For your problem, you will need to provide two (i.e. a total of five arguments, three that you are providing already, and another two pointers that are used to return values to the caller).
Since this is a homework exercise, I won't explain WHAT values your function needs to return via output parameters.  After all, that is part of the exercise, and the purpose is for you to learn by working that out.
Answer: Apart from a wayward parenthesis in the call and some other syntax errors, what you have so far looks fine. To print out the number of roots, you need to put a format specifier and an argument in your printf statement:
printf("the number of roots for this equation is %d\n", rootNum);

The %d is the format specifier for an int.
Answer: Here is your working code:
#include <stdio.h>

int rootnumber (double a,double b, double c)
{
    double formula = (b*b) - (4*(a)*(c));
    if (formula > 0) {
        return 2;
    }
    else if (formula < 0) {
        return 0;
    }
    else {
        return 1;
    }
}

int main (void)
{
    double a, b, c;
    printf("Enter coefficients a, b and c: ");
    scanf("%lf %lf %lf",&a, &b, &c);
    printf("The number of roots for this equation is %d ", rootnumber(a,b,c));
    return 0;
}

Answer: It just need some sanity checking, its working now:
#include<stdio.h>
int rootnumber(double a, double b, double c);
int main ()
{

    double a, b, c, root1,root2;
    int rootnum;

    printf("Enter coefficients a, b and c: ");

    scanf("%lf %lf %lf",&a, &b, &c);

    rootnum=rootnumber(a,b,c);

    printf("the number of roots for this equation is %d", rootnum);

    return 0;
}

int rootnumber(double a, double b, double c)
{

    int formula= (b*b) - (4*a*c);

    if (formula<0)

        return 0;

    if (formula==0)

        return 1;
    else
        return 2;
}

Comment: thanks , i fixed the missing ";" but this isn't my problem

Returns a value as an output parameter


How to find the Nash equilibria of a game with continuous strategy spaces

Question: Let $u, w \geq 0$. Let the payoff function $f_1: [0, u] \times [0, w] \to \mathbb{R}$ for player $1$ be defined as $$f_1(a, b) = \frac{u - a}{1+e^{a-b}} $$
for $a \in [0, u]$ and $b\in [0, w]$.
Similarly, let the payoff function $f_2$ for player 2 (when player 1 plays $a$ and player 2 plays $b$) be defined as
$$f_2(a,b) = \frac{w - b}{1+e^{b-a}}$$
My question is how we can compute the Nash equilibria of the general-sum game that $f_1$ and $f_2$ define. In particular, I don't know how to deal with the fact that the strategy spaces $[0, u]$ and $[0, w]$ are continuous. (I do believe that a Nash equilibrium has to exist, since the payoff functions are continuous and quasi-concave.)
Moreover, is there a way to find all Nash equilibria of the game?
Comment: Have you tried writing each player's best response correspondence given a generic action by the other player?
Comment: I tried doing that by simply taking the derivative of $f_1$ (and $f_2$). However, those derivates are very very messy. Is there another way to do it?
Comment: I could also first look at an easier problem, where $f_1$ and $f_2$ take an easy to differentiate form? E.g. $f_1 = (u-a)\frac{1+a-b}{2}$ and $f_2 = (w-b)\frac{1+b-a}{2}$? But even if I can write down the "best response", i.e. the maximum of these functions, how do I continue?
Comment: You want a "fixed point": a value of $(a, b)$ such that both functions are simultaneously maximized.
Comment: Note that to solve this, you don't need to "solve" the best response functions completely--I'll try to write a brief answer now.
Answer: Given any choice of $b$ which I'll denote $\overline{b}$, Player 1 must respond optimally. This means they choose $a$ to maximize $\frac{u-a}{1+e^{a-\overline{b}}}$. Differentiating, we attain:
$$\frac{-(1+e^{a-\overline{b}}) - (u-a)e^{a-\overline{b}}}{(1+e^{a-\overline{b}})^2} = \frac{-1 + (a - u - 1)e^{a-\overline{b}}}{(1+e^{a-\overline{b}})^2} $$
Note that regardless of $\overline{b}$, this is negative for any $a \in [0, u]$. Thus $0$ is always the best response of Player 1; it's a dominant strategy. Similarly for Player 2. Thus $(0,0)$ is the only Nash equilibrium.


What is the real life use of hyperbola?

Question: The point of this question is to compile a list of applications of hyperbola because a lot of people are unknown to it and asks it frequently.
Comment: ...not to be confused with "hyperbole", which is a bajillion times more awesome than any hyperbola.
Comment: Should I upvote the question because it will certainly bring some interesting answers, or should I downvote it since any basic research regarding the word "hyperbola" on the web already gives a lot of answers?
Comment: http://www.pleacher.com/mp/mlessons/calculus/apphyper.html
Comment: @Djaian: That neutralizes and becomes $0$ vote indeed. ;)
Comment: http://mathcentral.uregina.ca/qq/database/QQ.09.02/william1.html
Comment: @zzzzBov, that is the single-most funniest thing I've ever heard. Ever.
Comment: Brought here by a featured question link in the sidebar. Thought question was interesting but didn't realize that I'd left dba.se. Thought it seemed odd that the question was being voted up and answered. Figured DBAs must just be a free-wheeling, easy going bunch. Getting coffee now.
Comment: [hyperbolas in real life](http://www.ehow.com/info_8546768_importance-hyperbolas-life.html)
Comment: @Djaian that is indeed an extremely interesting and important question...not
Comment: This question has a rating of 10? Seriously?
Comment: @zzzzBov, +1, quite humorous. Interstingly, in my language, it's the [same](http://pt.wikipedia.org/wiki/Hip%C3%A9rbole_(figura_de_estilo)) [word](http://pt.wikipedia.org/wiki/Hip%C3%A9rbole).
Comment: The answers are good, but this question is just like "Give me an essay full of this   and that  r . ."-1.
Comment: The inverse hyperbolic cosine can be used to calculate points an a suspended wire, and is therefore useful for calculating load on power lines.
Answer: Applications of hyperbola
Dulles Airport, designed by Eero Saarinen, has a roof in the
shape of a hyperbolic paraboloid. The hyperbolic paraboloid is a three-dimensional
surface that is a hyperbola in one cross-section, and a parabola in another cross section.
This is a Gear Transmission. Greatest application of a pair of hyperbola gears:

And hyperbolic structures are used in  Cooling Towers of Nuclear Reactors.. Doesn't it make hyperbola, a great deal on earth? :)
Comment: @MatthewLeingang Hmm, of course - as you say, I was looking at a picture of this fact when I wrote my comment. I always associate the cooling tower picture with Miles Reid's book Undergraduate Algebraic Geometry (where it appears when talking about the infinitely many lines on a quadric surface), and thus with the 27 lines, which is one of Reid's favourite examples and also appears prominently in the book, although of course the two have little to do with each other. Anyway, my previous comment stands if you replace "cubic" by "quadric" and "27" by "infinitely many".
Comment: @MatthewLeingang Ha, don't worry! I make silly mistakes often enough that I don't really have time to be too embarrassed about them! Better to correct it.
Comment: @MattPressland: hyperboloids are quadric surfaces and contain infinitely many lines, as shown in the picture.
Comment: @AlexBecker: ..:)
Comment: @Inceptio can you tell me why cooling towers are made in hyperbolic shape.
Comment: @Neer Wikipedia references this [Y! Answer](http://answers.yahoo.com/question/index;_ylt=Alrw.x3s0yYU7yIw6LoN0uUjzKIX;_ylv=3?qid=20070308072329AA7Q4H3).
Comment: @Neer: I'm a 12th grader. And maybe that's a **difficult** engineering question as Khush's link suggests.
Comment: It's not just for nuclear reactors; it's for every thermal power plant (that is, coal or gas fired ones too) that's not located next to a large body of water to act as a heat dump, or are situated to dump its waste heat into district heating. (Conversely, nuclear plants located by the coast usually don't have cooling towers).
Comment: One other advantage of hyperbolic cooling towers that I was told about (but may not be an actual reason for the shape) is that because they are cubic surfaces they contain 27 lines, which in practical terms means you can build a framework to "hang the concrete on" using straight metal rods or girders, even though the surface is curved.
Comment: Indeed.  I didn't want to embarrass you personally, only to correct the record.
Comment: im sorry i dont understand how this is an example of hyperbola, can someone pleas eexplain
Comment: @Inceptio Nice answer! (+1)
Comment: @Inceptio So am I.
Comment: @Inceptio Yeah me too.I will give joint in 2014.
Answer: Did you ever take a look at the light projected onto a wall by a nearby lamp with a standard lampshade?  That's right: the light on the wall due to the lamp has a hyperbola for a bounday.  The reason for this is clear once you think about it for a second: the light out of the lampshade forms a vertical cone, and the intersection of a vertical cone and a vertical wall makes a hyperbola.
Also, consider a pair of sources of ripples in water that produce concentric waves.  The intersections of those concentric waves - surfaces of constant phase, are hyperbolae.  Why?  Because a hyperbola is the locus of points having a constant distance difference from two points (i.e., a phase difference is is constant on the hyperbola).
Comment: +1: Nice examples, and clear explanations to help the "light to go on".
Comment: @LarsH: thanks.  When my son was in kindergarten, he actually asked me what the shape of the light was on the wall.  I told him and had him repeat it to his utterly baffled teacher.
Answer: Of course it does. Among other things, this is the function that describes the trajectory of comets and other bodies with open orbits. Another astronomy related use is Cassegrain telescopes, where hyperbolic mirrors are used (

Image by Szőcs Tamás.
Comment: And similarly, radio antennas (which are a bit more practical).
Comment: Extreme-telephoto mirror lenses for cameras are also built on this principle. It's the only practical way I know of to get a 1000mm+ focal length on a lens that isn't actually a meter long.
Answer: Hyperbolas are used extensively in economics and finance (specifically portfolio theory), where they can represent the various combinations of securities, funds, etc. that yield similar risk-return ratios. This is why you often see efficient portfolio frontiers represented as partial hyperbolas. For similar reasons, production frontiers, which represent various combinations of capital and labor that produce a given output, as hyperbolas.
I don't know if that's entirely a "real-world" example because it's not a tangible object, but the mathematics of hyperbolas are still very important.
For example, the upper edge of this hyperbola (the part of the curve above the inflection point) in this plot:

represents the optimal combination of two risky assets, assuming the portfolio doesn't contain any risk free assets like Treasury bills. In this case, an optimal allocation is one that provides the highest ratio of expected return to risk, i.e. standard deviation. This is also known as the Sharpe Ratio.
Comment: Why the downvote? I'd like to improve my answer if necessary.
Answer: In addition to the awesome answers, here is something mundane: a hyperbola occurs whenever you have a formula of the form $$xy = c$$ Two hyperbolas, if you consider negative values. Equations of this form crop up all over the place, in natural sciences, economics, you name it.
Then, in space, when a small mass passes by a large one (say, comet around a planet), and it is moving faster then escape velocity with respect to the large one, its path is hyperbolic.
Comment: "Two hyperbolas, if you consider negative values." Not to be overly pedantic, but I think that's still one hyperbola (but with both its branches).
Comment: Fair enough, indeed.
Answer: Most receptors are made in the shape. e.g. RADARs, television reception dishes, etc. because they need to reflect off the signal and focus it on a single "point".
When two stones are thrown in a pool of water, the concentric circles of ripples intersect in hyperbolas. This property of the hyperbola is used in radar tracking stations: an object is located by sending out sound waves from two point sources: the concentric circles of these sound waves intersect in hyperbolas.
Comment: I was thinking TV dishes etc. used a parabolic shape (Parabola is even used as a brand name) when they're designed to focus on a single point. But I could be wrong ... I don't know why a telescope could have a hyperbolic mirror as well as a parabolic one.
Comment: You are correct of course. Practically, there is no difference between parabola and hyperbola - hyperbola is just a parabola with a mirror image ;-)
Comment: I thought there was a more significant qualitative difference between the two. For example, in the illustration on this page of a telescope containing a hyperbolic mirror and a parabolic one, the hyperbolic mirror doesn't have a mirror image. I realize that the "conic section" definition hinges on whether a plane intersects both halves or just one half of a double cone. Yet there seems to be more to it than whether the curve has one branch or two.
Comment: I don't believe there's a qualitative difference between the two.
Answer: In computer science, it's the shape of the response-time curve for request-reply pairs.  It starts off parallel to the x-axis at low loads, curves upwards and ends up approaching parallel to the line y = (Dmax * x) - Z, where Dmax is the service demand of the slowest part of the system and Z is the user think time between requests.
Answer: Hyperbolas are used extensively in Time Difference of Arrival (TDoA) analysis, which has many applications. For example, it is used for geolocation to determine the location of a vehicle relative to several radar emitters (e.g. passive geolocation of UAVs), localizing cellular phones without requiring a GPS fix (e.g. U-TDOA), or making "tapscreens" that can sense the precise location of a tap on a large display without expensive touchscreens (e.g. MIT's Tapper).
In TDoA, multiple sensors each detect the arrival time of a particular signal. The time differences between any two sensor measurements define a hyperbola of possible origin locations (since those are the points with a constant difference in distance to each sensor). Intersecting the hyperbolas gives you the position of the signal's source very quickly and precisely.

What is the real life use of hyperbola?


Which chords should be avoided in a four-chord progression (mathematically)?

Question: I notice that 4 chord songs almost never use the iii chord or the viidim chord. Do these chords not fit mathematically (into the circle of 5hts)?
3-chord history
https://en.wikipedia.org/wiki/Three-chord_song
Circle of 5ths and the 4-chord song mathematically speaking
https://www.classicfm.com/discover-music/music-theory/four-chords-every-pop-song/
Comment: What do people do with this math mysticism stuff? Make music? How?
Comment: By "VII," do you mean (in C major) a B diminished triad or a B-flat major triad?
Comment: i-iii-IV-V is very often used .... I'm afraid many Pop singers simply don't know more chords the othe most used  4 chords  ;)
Comment: By the way, have you ever checked out Hook Theory? https://hookpad.hooktheory.com/
Comment: @piiperiReinstateMonica when you make music, you make math as well, no matter if you know it or not. The other approach is pretty much legitimate, as long as people want to listen to the result.
Answer: Strictly speaking, you can use any chord in a 4-chord progression, but you're looking for a spiral of chords that have a strong function that leads from one to the next. All of the chords work mathematically thanks to equal temperament.
The iii chord doesn't have a clear function because it shares so many notes with the I and V; however, they're more often used in an altered form as a chromatic mediant or a V/vi.
My guess is that the vii° chord is used less often in pop because the diminished interval needs to resolve quickly and makes the tonic sound too resolved. vii°6 to I6 is more common.
Comment: It's used less often in (guitar driven) pop because it's harder to play (on guitar) than most other common chords :) The two most common bar forms also require (sort of) four fingers but are easily relatable to the open position E and A so they are easier to introduce to students. Most casual players I have encountered have never even heard of diminished or half-diminished chords and have trouble wrapping their fingers around them, much less their brains around what the appropriate functional usages are. Too bad, since the half-diminished is the single most useful chord in theory. Just my .02
Answer: What are you basing your 4 chord theory on?  Can you provide a list of songs?
I would say that the iii is one of the most common chords used but that may depend on the genre of music.  Also, the vii is a substitute for the V7 and is probably just as common as the V7 for this reason.
The circle progression is constructed by walking through the diatonic chords by 4ths (while staying in key).  This is NOT the same thing as the circle of 4ths or 5ths which moves you out of key.  The circle progression is...
I --> IV --> vii --> iii --> vi --> ii --> V --> I
You can play this with all 7th chords in the key and you will immediately notice the overlap.
Poly chords and substitutions can be used to relate these chords.  For example, the I maj7 can be created by "adding" together the I triad and the iii triad, I + iii = I maj7.  For this reason they can be substituted for each other.  The same is true for the V7, V + vii = V7, and for all other pairs of triads separated by a 3rd.
Rather than say the vii never shows up think of how it is related to the V7 and see that it's always there.  In fact, there is a cadence in classical music (perhaps earlier than classical) called the leading tone cadence, vii --> I, which has the classic 7->8 and 4->3 motion in it.
Other substitutions include replacing a Maj chord with its relative minor, the vi can replace the I and vice verse.
With this in mind it is easy to see that the entire circle progression can be distilled to the I, IV, V.  I'd say if you are using 4 chords instead of 3 you missed a substitution.  That's not to say that the other chords are useless.  They create more interesting harmonies and movement.  But in fact, you can harmonize a diatonic melody with just 3 chords.
But to answer your title question directly.  None.  Why should any chord be avoided?  If you want to harmonize a diatonic melody then any group the 3 chords that covers the scale should work and by using substitutions they may all be equivalent to the I, IV, V in some sense.
Comment: @JosephDoggie No. C7 is either a note, the next highest C on a piano; or it is a C major chord with an added 7th so it contains the notes C-E-G-Bb. While VII is [Roman numeral chord notation](https://en.wikipedia.org/wiki/Roman_numeral_analysis) - VII means that the root note of the chord is the 7th note in the scale you are playing in. VII (uppercase) is a major chord, vii (lowercase) is a minor chord.
Comment: If you played a progression in the key of 'C' then the V chord would be a 'G'. You would be looking for 'G7'.
Comment: @j-g-faustus: To further confuse things, it's common to use a diminished vii chord as a substitute for a V7; in F major, such a chord would be E-G-Bb, the E and Bb of which are often the most functionally important notes in a C7 chord (since the tritone between them creates tension, which can be resolved by moving the E to F and the Bb to A).
Comment: 'You can harmonise a diatonic melody with just 3 chords'. True, go to most bars in Spain or Canaries, and you can hear just that...
Comment: I don't think that's what he's asking about w/r to the C7.
Comment: That us interesting.   I am not familiar with the accordion.  If the buttons activate chords then it is possibly a 7th chord, C E G Bb.
Comment: I used to have accordion lessons and there was a note called C7.  Is this the VII chord you speak of, or is that something different?
Comment: Probably not.  That would be a V7 chord if the key was F maj.  These symbols don't refer to specific notes.   It seems to me that you could be referring to C in the 7th octave.  We use the notation (letter)(number) to indicate a note and the octave.  I think C4 is middle C on the piano.
Comment: From my recollection, it was a chord.  It is on the 'button' side of the accordion, and there was C (plain), C major, and C7.  It seemed holding certain buttons would automatically cause other buttons to be depressed as well.
Comment: Again on the accordion, for completeness, there were:  C (plain), C major (CM), C minor (Cm), and C7 [and potentially others, which of course would be dependent on specific accordion]. As I indicated above:  This was  the 'button' side of the accordion (I believe my left hand, but it's been a long time!), and holding certain buttons would automatically cause other buttons to be depressed as well. This fascinated me as a child, and I guess, to a certain extent still does.  NOTE: I  couldn't edit the above comment, which IMHO I should be able to do.  Oh well.... hence this separate comment.
Answer: iii isn't that uncommon.  viidim lacks individual identity because it sounds so much like V7.
There's more to harmony than the circle of 5ths.  Other frequent visitors to pop/rock music are bVII, iv, bIII, III....
Answer:
Circle of 5ths and the 4-chord song mathematically speaking https://www.classicfm.com/discover-music/music-theory/four-chords-every-pop-song/

The way you worded your question sort of implies that only the last four chords of the circle of fifths progression would be used for a four chord progression. So, let's first list out that progression...

7    6    5   (4    3    2    1)
IV   viio iii  vi   ii   V    I

...viio and iii are more than four steps back so supposedly they would be excluded. Keep in mind it a circle, there isn't a start or end, so maybe you're thinking of the section ii V I IV.
There really isn't any math involved with this and I don't think the linke article does a good job of explain the music theory about this stuff.
Let's first list out the Axis of Awesome chords and the first four of Pachelbel's Canon...
I V vi IV
I V vi iii
First, neither of those is a segment of the circle of fifth progression.
The second thing is the notion that iii is not used because of some connection to the circle of fifths progression don't really make sense when the article goes on to use Pachelbel's Canon as an example, because it actually uses the iii chord.
The problem comes from trying to explain too much through the literal circle of fifths progression. Instead of that, a better fundamental concept to work with is roots by descending/ascending perfect fifth. When roots by descending/ascending perfect fifth are combined with the idea of harmonic sequences, it goes a long way to explain a lot of harmony, harmony that has been used for the last 500 years! Add in relative major/minor chords (which the article does mention) and you have the bulk of most chord progressions.
Using brackets to enclose the roots by fifths we can see those fundamental units and how they are repeated using harmonic sequencing...
|: [I V] vi [IV :|: I] ...
Considering the Axis of Awesome usually is repeated, we have I V and IV I as two ascending fifth progressions. This is literally a harmonic sequence, because the I is elided, the sequence would be [IV I][I V], but the I isn't repeated so it's three ascending fifths IV I V. The vi can be called a deceptive progression (like the deceptive cadence), or it's the relative minor of IV.
[I V][vi iii]
The Pachebel progression is very obviously built of ascending fifths using harmonic sequences. The is a common minor analog to that [i V][♭iii ♭VII].
Other super common progression using this process are:
[I IV][V I] two descending fifths, sequenced by ascending fifth
[I V][♭VII IV] two ascending fifths, sequenced by descending whole step
[I V][VI I] two ascending fifths, sequenced by descending fifth
Notice that the last one is the common blues turnaround and it is just the progression/sequence inversion of I IV V I. Some people get themselves all worked up over the retrogression of V IV in the blues, but when you view progressions in terms of progressions by fifth and harmonic sequence, things all fall into place nicely.
You don't need to worry about chords to avoid. Try thinking positively about the fundamental relationships that underlie common progressions. Add to the stuff above borrowed chords and the tritone substitution/augemented sixth chords and you have a very nearly complete picture of tonal harmony. At that point you should have solid harmony and any supposed "avoid" chord, becomes either a potential source of surprise/uniqueness to exploit, or can be made to work through means like repetition, harmonic sequence, or modulation.
Answer: There are two relevant facts here that often get merged together, but can be separated...

In Major tonality, the chords I, IV, V and vi make a strong group. (You can look at reasons why this is from a number of different perspectives).
Harmonically simple music often features progressions featuring a small number of chords, which may indeed be 3 or 4.

When you combine these facts, you can see why it is quite common to find songs that have only I, IV, V and vi, or only I, IV, and V; and it's unsurprising that there are a number of common particular progressions that are based around those chords.
However: there's no reason to only use certain chords in a 4-chord progression. In fact, repeating a chord progression round and round can give it a coherence and sense of 'resolved expectations' without that needing to solely come from the harmonic relationships between the chords. And there's certainly no need to only use  I, IV, V and vi, or only I, IV, and V: for a start, consider minor harmony, which wouldn't use a major I.

Which chords should be avoided in a four-chord progression (mathematically)?

None need be avoided. Unless by "four-chord" progression you actually mean four particular chords - in which case, of course, avoid chords other than those!

I notice that 4 chord songs almost never use the iii chord or the VII chord.

As per Laurence's answer, iii isn't that uncommon, and vii° is very close to being an inversion/voicing of the very common V7 - though you could also consider that it's rather dissonant.
Answer: The simplest answer would be that the iii chord and the vii chord are indeed the farthest away from the I chord in the circle of fifths of a major scale.  I suspect this is part of the reason they are uncommon, but there are probably other factors as well.
Comment: I think **ⅱ** is less common than **ⅵ** in pop music, though. (Not in some other genres, of course.) So arguing with distance in the circle of fifths alone is quite dubious.
Comment: @leftaroundabout Distance in the circle of fifths still places iii and vii, which I'm willing to bet are the least common chords used in pop music, the furthest from I.  But as I said, there are probably other factors as well.


Proof that the left or right adjoint composed after a diagonal morphism in a 2-category is the identity

Question: Suppose I have some strict 2-category $\mathcal{C}$ that's cotensored over $\mathcal{C}at$. Then for $A\in \mathcal{C}$ and $X\in \mathcal{C}at$, there's the diagonal morphism $\Delta:A\to A^X$. Suppose $\Delta$ has a left adjoint $\Delta_!$. I want to show that $\Delta_!\Delta\cong\mathrm{id}_A$. More specifically, I expect that that 2-isomorphism is exhibited by the counit of the adjunction. Is this always true (as it obviously is when $\mathcal{C}=\mathcal{C}at$), and if so, how is it proven?
Answer: Just work representably: by the universal property of the cotensor and the fact that 2-functors preserve adjunctions, the sequence you get upon homming some $R$ into this is $A^R\to \mathrm{Cat}(X,A^R)\to A^R$ where the maps are the diagonal and the colimit.
Comment: Thanks! I knew it was something silly, but it was good to have it spelled out for me.


Total Derivative $f(x, y, z ) = x^2 + y^2 -z^2$

Question:
Evaluate total derivative of  $f(x, y, z ) = x^2 + y^2 -z^2$ at  $a=(1,-2,1)$ what is it's value in the direction of $h = (-1,1,1)$.

I'm not sure, I completely understand how to do this.
Is it just:
$Df(a)(h) =\frac{\partial f}{\partial x}(a_1)\cdot h_1 + \frac{\partial f}{\partial y}(a_2)\cdot h_2 + \frac{\partial f}{\partial z}(a_3)\cdot h_3
= -1(2) + 1(-4) + 1(-2) = -8$
$\frac{\partial f}{\partial x} = 2x, \frac{\partial f}{\partial y}  =2y,\frac{\partial f}{\partial z} = -2z$
Comment: by the way, the partial derivatives should all be evaluated at $a$, so it should be $\dfrac{\partial f}{\partial x}(a)$ rather than $\dfrac{\partial f}{\partial x}(a_1)$ etc. In this case, you were lucky because $\dfrac{\partial f}{\partial x}(x,y,z) = 2x$,  which only depends on the first entry, hence there were no calculation errors
Answer: Almost. Say we had to look at it in the direction of $h=(-10,10,10)$. This is the same direction as before -- the answer should be the same. But, if you carry through your method, you'd get an answer tenfold of what it should be. The problem is that you have to normalize $h$ first, by dividing by $||h||$, to get an answer that is $\sqrt{3}$ times smaller than your one.


SIM800L GSM Module working with http and shows error with https, why?

Question: I'm trying to send some sensor data to MySQL database using Arduino and sim800l GSM module. And it's working perfectly when I use HTTP for the URL and remove the SSL certificate from my website. But when I have enabled the SSL certificate on my website it shows HTTP response code 606 in the serial monitor.
Here is my working code without SSL certificate(this code works perfectly)
#include <SoftwareSerial.h>
SoftwareSerial gprsSerial(3, 2);

void setup()
{
  gprsSerial.begin(19200);
  Serial.begin(19200);

  Serial.println("Config SIM900...");
  delay(2000);
  Serial.println("Done!...");
  gprsSerial.flush();
  Serial.flush();

  // attach or detach from GPRS service
  gprsSerial.println("AT+CGATT?");
  delay(100);
  toSerial();

  // bearer settings
  gprsSerial.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");
  delay(2000);
  toSerial();

  // bearer settings
  gprsSerial.println("AT+SAPBR=3,1,\"APN\",\"myapn\"");
  delay(2000);
  toSerial();

  // bearer settings
   gprsSerial.println("AT+SAPBR=0,1");
   delay(2000);
  gprsSerial.println("AT+SAPBR=1,1");
  delay(2000);
  toSerial();
}

void loop()
{
   // initialize http service
   gprsSerial.println("AT+HTTPINIT");
   delay(2000);
   toSerial();

   // set http param value
   gprsSerial.println("AT+HTTPPARA=\"URL\",\"http://www.website123456.com/data/index.php?data1=2.88&data2=2.93\"");
   delay(20000);
   toSerial();

   // set http action type 0 = GET, 1 = POST, 2 = HEAD
   gprsSerial.println("AT+HTTPACTION=0");
   delay(6000);
   toSerial();

   // read server response
   gprsSerial.println("AT+HTTPREAD");
   delay(10000);
   toSerial();

   gprsSerial.println("");
   gprsSerial.println("AT+HTTPTERM");
   toSerial();
   delay(300);

   gprsSerial.println("");
   delay(10000);
}

void toSerial()
{
  while(gprsSerial.available()!=0)
  {
    Serial.write(gprsSerial.read());
  }
}

Here is the output when I replace the URL with https and enable my website ssl. (as you can see it shows http response code 606 "Not Acceptable
The user's agent was contacted successfully but some aspects of the session description such as the requested media, bandwidth, or addressing style were not acceptable"
23:16:48.974 -> Config SIM800L...
23:16:50.946 -> Done!...
23:16:51.079 -> AT+CGATT?

23:16:51.079 -> +CGATT: 1
23:16:51.079 ->
23:16:51.079 -> OK
23:16:53.107 -> AT+SAPBR=3,1,"CONTYPE","GPRS"

23:16:53.107 -> OK
23:16:55.100 -> AT+SAPBR=3,1,"APN","dialogbb"

23:16:55.133 -> OK
23:16:59.122 -> AT+SAPBR=0,1

23:16:59.155 -> OK
23:16:59.155 -> AT+SAPBR=1,1

23:17:01.151 -> OK
23:17:03.185 -> AT+HTTPPARA="URL","https://www.mywebsitttte.com/index.php?dAT+HTTPSSL=1

23:17:08.207 -> OK
23:17:14.221 -> AT+HTTPACTION=0

23:17:14.255 -> OK
23:17:14.255 ->
23:17:14.255 -> +HTTPACTION: 0,606,0
23:17:24.266 -> AT+HTTPREAD

23:17:24.266 -> OK
23:17:36.595 ->
AT+HTTPTERM

23:17:36.595 -> OK

So what are the modifications I should do to this code, to be able to upload data to the website with SSL certificate? I have seen people say I need to enter to SSL mode using this code AT+HTTPSSL=1  where should I put this code. Thanks
Comment: @AshfaqHAhmed yes I have figured out it finally, It happens because this sim800 only supports TLS 1.0. But it's a deprecated version and many websites and host services have disabled it. You can check your server TLS version from here https://www.cdn77.com/tls-test
Comment: On a small 8bit Arduino, you should simply forget about SSL.
Comment: But it shows an error when I have SSL on the website. I don't need ssl for this data sending process, but i need ssl for the website
Comment: `603 Decline :"The destination does not wish to participate in the call, or cannot do so"`
Hmm, so your question is: how to make the web server accept http requests (Port 80)
Comment: It's accepting the request when i send with https but not with https
Comment: @datafiddler The module should be handling encryption, not Arduino.
Comment: Why not use [a library](https://github.com/ostaquet/Arduino-SIM800L-driver) that handles all that AT command juggling in a proper way?
Comment: I don't want to complicate this. I just need to do this with https instead of http
Comment: When I use https instead of http in the arduino url, I'm getting http response code 606
Comment: The point of libraries is to abstract complex thing and make things less complicated.
Comment: facing the same issue on SIM800 . Did anyone find. any solution to this
Answer: I have figured out it finally, It happens because this sim800 only supports TLS 1.0. But it's a deprecated version and many websites and host services have disabled it. You can check your server SSL version from here cdn77.com/tls-test
Answer: Check your SIM800 firmware first, I had old firmware on my 808 module that had no SSL and I only bought it a few weeks ago. you can check using this AT command:
AT+HTTPSSL=?

If you get error then check and update the firmware.
Otherwise if working this is the order I use:
 client.println("AT+HTTPINIT");
 getresponse();
 delay(1000);
 client.println("AT+HTTPSSL=1");    // set SSL for HTTPS
 getresponse();
 delay(1000);
 client.println("AT+HTTPPARA=\"CID\",1");
 getresponse();
 delay(1000);

I can reliably HTTPS connect to my Firebase database.


Preciso relacionar duas tabelas de forma a me trazer um resultado dentro das condições que eu quero

Question: Estou usando o SQLSERVER
Condição(O que o resultado deve me retornar)
· Criação da agenda. Necessário a criação do fluxo para criação de agenda e bloqueio para reserva das vagas;
Ao cruzar os dados de duas tabelas eu preciso atribuir uma vaga para aquele paciente que entrou em contato primeiro. E essa vaga não pode mais ser atribuida a nenhum outro paciente.

Para fazer isso pensei na criação de uma procedure, mas não consigo acertar na sintaxe, me ajudem por favor, ou se tiver alguma outra forma de fazer isso também
CREATE PROCEDURE OcuparVaga
AS
BEGIN
-- Criando tabela de retorno da proc
    SELECT CodPaciente, NomePaciente, NULL NomeEspecialidade, NULL NomeMedico,Telefone,
    Celular, NULL DataVaga, NULL HoraVaga, 0 StatusVaga, NULL Obs
    INTO #Retorno
    FROM  Paciente WHERE StatusSolic = 0

-- Declarando variavel para ser utilizada no while
      DECLARE @i INT
        SET @i = 0

-- Tabela temporaria para controle do while
    SELECT * INTO #Solicitacoes FROM Paciente WHERE StatusSolic =0

-- Verificando se existe Pacientes com status igual a 0(disponivel)
    IF (SELECT COUNT(*) FROM #Solicitacoes) ==0
    BEGIN
        RETURN 'Não há Pacientes a serem atribuido a vaga'
    END
-- Iniciando o while
    WHILE @i < (SELECT COUNT(*) FROM #Solicitacoes)
    BEGIN
        DECLARE @CodPaciente INT --Variavel que representará a linha da tabela Paciente que estamos executando

----Preenchendo a váriavel com a menor data/hora (conforme definido a prioridade)
        SELECT @CodPaciente = CodPaciente FROM #Solicitacoes
        ORDER BY DataContato, HoraContato

--- Pegar a primeira linha com a menor data/hora dentre as vagas disponíveis para atribuir ao Paciente de acordo com a especialidade, regra de data e statusVaga

        SELECT TOP 1 a.* INTO #Disponivel FROM Horarios AS a
        INNER JOIN Paciente AS s ON a.CodEspecialidade = s.CodEspecialidade
        WHERE a.DataHorarios >= DATEADD(day, 3, s.DataContato)
        AND a.StatusVaga=0 AND s.CodPaciente = @CodPaciente

        DECLARE @CodHorarios INT = 0 --Será utilizada para o preenchimento da vaga
        SELECT @CodHorarios = CodHorarios FROM #Disponivel -- Setar na variável o id da vaga disponível que está na tabela temporária

--Se existir uma vaga disponível, o status da vaga e do Paciente serão alterados
        IF @CodHorarios >0
        BEGIN
            UPDATE Horarios SET StatusVaga = 1, CodPaciente = @CodPaciente
            WHERE CodHorarios = @CodHorarios

            UPDATE Paciente SET StatusSolic = 1
            WHERE CodPaciente = @CodPaciente

            UPDATE #Retorno SET NomeEspecialidade = a.NomeEspecialidade,
                        NomeMedico = a.NomeMedico,
                        DataVaga = a.DataHorarios, HoraVaga = a.HoraHorarios,
                        StatusVaga = 1, Obs = 'Vaga preenchida com sucesso!'
            FROM #Retorno r
            INNER JOIN Horarios AS a ON r.CodPaciente = a.CodPaciente
            WHERE a.CodHorarios = @CodHorarios
        END
        ELSE
        BEGIN
            UPDATE #Retorno SET Obs = 'Não foi encontrado um horário para a especialidade desejada.'
            WHERE CodPaciente = @CodPaciente
        END
        -- Deleta a linha atual para o while seguir para a próxima
        DELETE FROM #Solicitacoes WHERE CodPaciente = @CodPaciente
        SET @i= @i+1 --Incrementa +1 no indice do while
    END
SELECT * FROM #Retorno
END
GO

Comment: Ele informa que sintaxe incorreta e q create procedure deve ser a unica instrução no lote.
Comment: Poderia acrescentar na descrição acima do tópico: (1) quais são todas as regras que devem ser seguidas para a construção do código; (2) o código que cria as tabelas; (3) código que gera a massa de dados para testes.
Answer:
Ao cruzar os dados de duas tabelas eu preciso atribuir uma vaga para aquele paciente que entrou em contato primeiro. E essa vaga não pode mais ser atribuida a nenhum outro paciente.

O ideal é construir códigos que tratem as linhas em blocos (data set) e não uma linha de cada vez (row by row). Para tabelas pequenas não faz diferença, mas para grandes volumes o aumento no tempo de processamento é enorme.
Eis esboço de sugestão, que trata da alocação das solicitações de consultas com as vagas disponíveis seguindo a regra "atribuir uma vaga para aquele paciente que entrou em contato primeiro":
-- código #1 v4
declare @PacOk table (CodPaciente int, CodHorarios int);

BEGIN TRANSACTION;

with
grupoPaciente as (
SELECT *, Seq= row_number() over (partition by CodEspecialidade
                                  order by DataContato, HoraContato)
  from Paciente
  where StatusSolic = 0
),
grupoVaga as (
SELECT *, Seq= row_number() over (partition by CodEspecialidade
                                  order by DataHorarios, HoraHorarios)
  from Horarios
  where StatusVaga = 0
)
UPDATE gV
  set CodPaciente= gP.CodPaciente,
      StatusVaga= 1
  output inserted.CodPaciente, inserted.CodHorarios into @PacOk
  from grupoVaga as gV
       inner join grupoPaciente as gP on gP.CodEspecialidade = gV.CodEspecialidade
                                         and gP.Seq = gV.Seq;

UPDATE Paciente
  set StatusSolic= 1
  where CodPaciente in (SELECT CodPaciente from @PacOk);

COMMIT TRANSACTION;

-- relata vagas que foram alocadas nesta execução
SELECT H.CodPaciente, P.NomePaciente, P.Telefone, P.Celular,
       H.CodEspecialidade, H.NomeEspecialidade, H.NomeMedico,
       DataVaga= H.DataHorarios, HoraVaga= H.HoraHorarios,
       'Consulta marcada' as Obs
  from Horarios as H
       inner join Paciente as P on P.CodPaciente = H.CodPaciente
  where H.CodHorarios in (SELECT CodHorarios from @PacOk);

-- relata solicitações de atendimento não marcadas
SELECT CodPaciente, NomePaciente, Telefone, Celular, CodEspecialidade,
       'Não há horário disponível para a especialidade desejada' as Obs
  from Paciente
  where StatusSolic = 0;

Imagem com resultado do teste:

Estrutura e dados utilizados para teste:
-- código #2
CREATE TABLE Horarios (
  CodHorarios int,
  CodEspecialidade varchar(20),
  NomeEspecialidade varchar(30),
  CodMedico int,
  NomeMedico varchar(30),
  DataHorarios date,
  HoraHorarios time(0),
  CodPaciente int default 0,
  StatusVaga tinyint default 0
);

CREATE TABLE Paciente (
  CodPaciente int,
  NomePaciente varchar(30),
  CodEspecialidade varchar(20),
  Telefone varchar(20),
  Celular varchar(20),
  DataContato date,
  HoraContato time(0),
  StatusSolic tinyint default 0
);

set dateformat dmy;

TRUNCATE TABLE Horarios;
INSERT into Horarios values
  (1, '004 3/02', 'ALERGIA - ASM', 1, 'Abílio de Barros', '9/5/2018', '7:00', 0, 0),
  (2, '004 3/04', 'CLINICO', 3, 'Roberto', '10/5/2018', '7:10', 0, 0),
  (3, '004 3/02', 'ALERGIA - ASM', 1, 'Abílio de Barros', '11/5/2018', '7:20', 0, 0),
  (4, '004 3/03', 'CARDIOLOGIA', 2, 'Fernanda', '9/5/2018', '7:00', 0, 0);

TRUNCATE TABLE Paciente;
INSERT into Paciente values
  (1, 'José', '004 3/02', '(11)5789-8547', '(11)92485-6128', '6/5/2018', '7:00', 0),
  (2, 'Maria', '004 3/04', '(11)5789-7857', '(11)9455-6187', '9/5/2018', '7:05', 0),
  (3, 'Hugo', '004 3/03', '(11)5619-8548', '(11)97085-2630', '9/5/2018', '7:30', 0),
  (4, 'Natália', '004 3/02', '(11)5529-3849', '(11)9278-6241', '6/5/2018', '7:15', 0);

Comment: Obrigado por esse retorno, ao tentar executar ele me retorna erro nas variáveis @PackOk dos dois UPDATE'S e no -SELECT para relatar as vagas que foram alocadas nesta execução.

A mensagem diz que: É necessário declarar a variável de tabela "@PackOk"
Comment: Estou pesquisando um pouco, mas não consigo entender, porque ela foi declarada antes de começar a transação. Tentei executar toda a query. Tentei executar somente a linha DECLARE e depois a transação, mas continua me retornando essa mensagem
Comment: @RogérioCristiano A variável de tabela está declarada como @ PacOk mas no código constava @ PackOk. Já corrigi.
Comment: Coloquei uma resposta com as imagens do resultado para ilustrar melhor a query
Comment: Hoje pela manhã houve momento em que efetuei modificação no código #1 v3 mas rapidamente a desfiz. Não sei se você copiou o código #1 v3 neste momento. Na dúvida, renumerei o código; poderia testar a v4? // Simulei aqui os dados, executei o código #1 v4 e o resultado foi correto. Acrescentei na resposta acima a massa de dados utilizada para testes. // Além da regra _atribuir uma vaga para aquele paciente que entrou em contato primeiro_, quais outras existem? Na descrição somente consta esta, mas no seu código percebi que há um teste de 3 dias...
Comment: Tentei com o v4 e ele ainda me trouxe o José como o paciente atribuído a todas as vagas.

Além de atribuir uma vaga para aquele paciente que entrou em contato primeiro. A data da consulta tem que ser pelo menos 3 dias após a data do contato do paciente, Como o José entrou em contato 06/05, a data da consulta dele tem que ser a partir do dia 09/05.

Dessa forma somente o José e a natalia é para estarem atribuidos as suas respectivas vagas.
Comment: O código #1 foi construído usando a regra "_atribuir uma vaga para aquele paciente que entrou em contato primeiro_". Com essa regra o código #1 retornou o resultado correto, conforme consta na imagem anexada na resposta acima. // Se o resultado dos seus testes foi outro, provavelmente modificou o código #1 que postei. // A regra "_A data da consulta tem que ser pelo menos 3 dias após a data do contato do paciente_" não consta na descrição do problema. Ela implica em outra abordagem para a solução do problema.
Comment: José, muito obrigado mesmo, verifiquei e realmente eu tinha feito a estrutura errada, fiz de acordo com o que você passou e deu certo. Muito obrigado
Answer: @JoséDiz
Estou quase lá, esse resultado me trouxe:

O Paciente José atribuido a todas as outras especialidades
E quando eu mudo a consulta que me traz as vagas alocadas. colocando
SELECT H.CodPaciente, P.NomePaciente, P.Telefone, P.Celular,
       H.CodEspecialidade, H.NomeEspecialidade, H.NomeMedico,
       DataVaga= H.DataHorarios, HoraVaga= H.HoraHorarios,
       'Consulta marcada' as Obs
  from Horarios as H
       inner join Paciente as P on P.CodPaciente = H.CodPaciente
  where H.CodEspecialidade = P.CodEspecialidade AND CodHorarios in (SELECT CodHorarios from @PacOk);
Ele me traz, somente a especialidade que o jose solicitou, mas atribuindo a ele os dois horarios disponiveis, onde deveria ser somente a primeira vaga:


"Connection: Keep-Alive" in server response

Question: I'm trying to establish a HTTP persistent connection from a Silverlight application to a PHP page (ie without creating a new TCP connection for each HTTP request) hosted by an Apache server.
To this end, I need the webserver to send its HTTP responses with the "Connection" header set to "Keep-alive". Client-side, there doesn't seem to be any issue as the network API provided by Silverlight is basically a wrapper of the browser network capabilies, from what I've read : so if the browser supports HTTP 1.1 and Connection: Keep-Alive by default for its requests, it's fine. Content-Length is also well defined, so that the server knows when
it has to send the response. However, the server response to the PHP request sets systematically "Connection:" to "close", thus ending the connection and preventing a persistent connection.
I've tried some things to work around this problem : different Methods (GET and POST), explicitly giving a "Connection: keep-alive" to the response with the following PHP code at the beginning of my script :
header("Connection: Keep-alive");

The latter adds the expected header to the response, which is good, but an additionnal "Connection: close" is still appended later in the response headers.
Is it a feature of PHP or Apache which enforces "close" (for some security or performance  purpose, I'm guessing) or am I just missing something here ?
Thanks in advance.
P.S. : By sniffing packets, I've noticed that not many websites use "Keep-alive" and the TCP connection is reestablished. Isn't Keepalive the default and preferred behavior under HTTP 1.1 ?
Comment: That's probably apache, not PHP -- to the best of my knowledge, PHP has no control over that.  You could verify by attempting to request a static file via the same connection.  Apache directive:   http://httpd.apache.org/docs/2.2/mod/core.html#keepalive
Answer: The Keep-Alive functionality is not meant for persistent connections.
Keep-Alive is meant to reduce the number of connections for a website. Instead of creating a new connection for each image/css/javascript in a webpage many requests will be made re-using the same connection.
There are some settings that prevent this in Apache too, like maximum number of requests on a connection or timeouts between requests. This will also eat your resources very fast because every connection needs its own thread.
You should switch to another solution, that is made for that kind of work.
For services that keep your connection open you can take a look at http://orbited.org and http://twistedmatrix.com/trac/
Comment: +1 for not abusing HTTP for persistent connections. It's easy enough to let a PHP daemon listen to a port / socket if needed.
Comment: yes, thats also a possibility. in my opionion orbited can do that much easier and is more stable while still providing a basic http server :)
Comment: I'm programming a real-time instant messaging app (sort of like Google Wave for the real time aspect) in a restricted context (PHP only and minimal webserver features). I am not even allowed to use datebases. In this kind of pressuring requesting (each keystroke basically yield a request), it would be useful to keep-alive the connection with the server. Thanks for your advice.
Comment: +1 for a much better answer than ZZ Coder. Keep-Alives have very little to do with the task described in the comment above by zenithm - there are several approaches, COMET springs to mind although ajax polling is a better option for a scalable system.
Comment: This answer is surely more elaborate, but I think my problem was just the Apache configuration. Still, thanks for pointing out to me the Comet solution. I'll look into it.
Comment: I also have to precise that I have no problem at all with the webserver pushing data to the SL app through a long-lived connection. It's the other way round which causes me trouble.
Answer: Since PHP doesn't manage the HTTP connection, it has no way to change this setting. You need to set that in servers. For example, you can enable keep-alive like this in Apache if you are using mod_php,
KeepAlive On

Comment: Thanks, this parameter indeed seems to be set to Off on my server.
Comment: This enables keep alive for all requests


Topology of product of affine varieties

Question: In this wiki article: https://en.wikipedia.org/wiki/Affine_variety#Products_of_affine_varieties, it states that polynomials that are in $k[x_1, \ldots, x_n, y_1, \ldots, y_m]$ but not in $k[x_1, \ldots, x_n]$ or $k[y_1, \ldots, y_m]$ define algebraic varieties that are in the Zariski topology of $\mathbb{A}^n \times \mathbb{A}^m$ but not in the product topology. However, $\mathbb{V}(x_1y_1)$ satisfies this condition, yet is in the product topology: $\mathbb{V}(x_1) \times \mathbb{A}^m \cup \mathbb{A}^m \times \mathbb{V}(y_1).$ Any guidance would be appreciated.
Furthermore, is it true that for any nonfinite affine varities $X, Y$ that the Zariski topology $X \times Y$ is not the product topology?
Answer: That claim is incorrect: rather, it should be that any polynomial in $k[x_1,\cdots,x_n,y_1,\cdots,y_m]$ which can't be written as a product of polynomials in $k[x_1,\cdots,x_n]$ and $k[y_1,\cdots,y_m]$ defines a subvariety not closed in the product topology.
Your guess needs a little refinement in order to work: if you're working over a field $k$ and your product is really $\times_k$, this is true. Embed $X$ and $Y$ in to $\Bbb A^n_k$ and $\Bbb A^m_k$ respectively, which induces an embedding $X\times_k Y \to \Bbb A^n_k\times_k \Bbb A^n_k$. Pick some subvariety $Z$ of $\Bbb A^{n+m}_k$ which is not closed in the product topology and intersects $X\times_k Y$ with dimension at least 1. Then $Z\cap X\times_k Y$ cannot be a closed subvariety of the product topology on $X\times_Y K$.
(Note that this is false if we work over the integers and $X=Y=\operatorname{Spec}\Bbb Z$. The product here is over $\operatorname{Spec} \Bbb Z$ so $X\times Y = X =Y$, which is definitely affine, has the product topology, and is not finite. It's always good to specify your base!)
Comment: Ah many thanks. How do we find such a $Z$ given that $X = \mathbb{V}(f_1, \ldots, f_r)$ and $Y = \mathbb{V}(g_1, \ldots, g_s).$ I am trying to construct a polynomial that depends on the $f_i, g_j$ that cannot be written as a product of polynomials in $k[x_1, \ldots, x_n]$ and $k[y_1, \ldots, y_m]$ but can't seem to guarantee that its intersection has dimension at least 1.
Comment: The easiest way to do this is to consider the hyperplane $H$ cut out by $x_1+y_1=c$ for some $c\in k$. We can pick a $c$ which makes this hyperplane intersect the embedded copy of $X\times Y$, and then by the affine dimension theorem $(X\times Y)\cap H$ is of dimension $\dim X+ \dim Y -1 > 0$ and thus a non-finite subvariety which is not closed in the product topology.
Comment: Ah great! Makes a lot of sense. Thank you very much!

Topology of product of affine varieties


Limits problem of $0/0$ form

Question: I am given problem as $$\lim\limits_{x \to 1} (\frac{-ax + \sin(x-1)+a}{x+\sin(x-1)-1})^\frac{1-x}{1-\sqrt{x})}$$ so what would be largest non negative $a$ such that value of limit is $\frac{1}{4}$.
Now since both power and base are of indeterminate form so I solved them individually as
$$ \frac{1-x}{(1-\sqrt{x})}= \frac{(1-\sqrt{x})(1+\sqrt{x}}{(1-\sqrt{x} )} = 1+\sqrt{x}$$ now putting limit it becomes $2$ now since base is of  $0/0$ form I used L'Hopitals Rule hence it became $$\lim\limits_{x \to 1} (\frac{-a + \cos(x-1)}{1+\cos(x-1)})$$ putting limits it becomes $$(\frac{-a + 1}{1+1})^2$$ which should be $1/4$ as given in the problem
$$(\frac{-a + 1}{2})^2=\frac{1}{4}$$
 but greatest non negative value that satisfies given result seems to be $2$ but correct answer is $0$ , where did I go wrong?
Answer: When $a=2$ then near $x=1$ you have $\dfrac{-a+1}{2} \approx -0.5$ and $1+\sqrt{x} \approx 2$ but you cannot conclude that  $\left(\dfrac{-a+1}{2}\right)^{1+\sqrt{x}} \approx 0.25$ in the real numbers.
For example, what do you think $(-0.500005)^{1.99995}$ would be?
So you want $\dfrac{-a+1}{2}$ to be non-negative, which requires $a$ to be less than $1$.

Limits problem of $0/0$ form


Shopify product page - update slick slider to selected variant

Question: I added a slick slider to Shopify's Boundless theme's product page and it properly displays the products images. The part where I'm having trouble is making the slider update to match the selected variant.
Here is the relevant JS:

productVariantCallback: function(variant) {
      var $pageLink = $(selectors.pageLink, this.$container);

      if (variant) {
        if (variant.featured_image) {
           var newImg = variant.featured_image;
          var el = $(selectors.variantImage)[0];

          var $slider=$('#product-slides');
          if( $slider.length ) {
            var newImgBase = newImg.src.substring(0, newImg.src.lastIndexOf('.')).split(':').pop();

            if( $slider.hasClass('slick-initialized') ) {
              var newIndex =   $('#product-slides.slick-initialized img[src^="' + newImgBase + '"]')

              .closest('.slick-slide')
              .last()
              .data('slick-index');
              console.log( 'Goto slide ' + newIndex );
              $slider.slickGoTo( newIndex, true  );
            } else {
              var newIndex =   $('#product-slides img').index( $('#product-slides img[src^="' + newImgBase + '"]'));
              Shopify.sliderInitAt = newIndex ;
            }
          }

// more code, but I don't believe it is relevant to the issue

and the relevant chunks of liquid:

  {% assign current_variant = product.selected_or_first_available_variant %}

  {% assign featured_image = current_variant.featured_image | default: product.featured_image %}

  <meta itemprop="url" content="{{ shop.url }}{{ product.url }}">
  <meta itemprop="image" content="{{ featured_image | img_url: 'grande' }}">
  <meta itemprop="name" content="{{ product.title }}{% if product.variants.size > 1 and product.selected_variant %} - {{ current_variant.title }}{% endif %}">

    {% assign first_image = featured_image %}

    {% if product.images.size > 1 and section.settings.skip_first_product_image and first_image == product.featured_image %}
      {% assign first_image = product.images[1] %}
    {% endif %}

    {% if product.images.size > 0 %}

            {% for image in product.images %}

          {% endfor %}

            {% for image in product.images %}

            {% endfor %}

    {% endif %}

            {% form 'product', product, id:form_id, class:form_class, data-cart-form: '' %}

          <select name="id" id="ProductSelect-{{ section.id }}">
              {% for variant in product.variants %}
                <option {% if variant == product.selected_or_first_available_variant %} selected="selected" {% endif %} {% unless variant.available %} disabled="disabled" {% endunless %} value="{{ variant.id }}" data-sku="{{ variant.sku }}">{{ variant.title }} - {% if variant.available %}{{ variant.price | money_with_currency }}{% else %}{{ 'products.product.sold_out' | t }}{% endif %}</option>
              {% endfor %}
            </select>

          {% endform %}

coding is not at all my field, so I have no idea what I'm saying when I say: I think it might be that my images need to be indexed on the liquid side then referenced on the JS side
Answer:

Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Comment: Welcome to Stack Overflow! Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the [help center](https://stackoverflow.com/help/how-to-answer).


I have logged out and the login block is missing,how do I login back?

Question: I had created a block that has replaced the default block on the frontpage i.e. the login block and I have logged out of the site so how do I log in back?
I have tried:

sitename/user/login
sitename/?q=user
sitename/?q=admin
sitename/subdirectory/?q=user

All it shows is "Page not found" or "Access Denied"
Is there any other way I could log in back to my site?
And I'm using Drupal 8
Comment: Any thing custom that was introduced? For. ex. Custom module/Block? Changes to settings file?
Answer: You can get the one time login url with drush command: drush uli;


Abrir nova aba usando selenium e python

Question: Já tentei de tudo. É o seguinte. Abro uma página usando selenium e a linguagem python, depois tento abrir uma nova guia, para depois ir para essa nova guia, depois fechar esta guia. Só isso. Mas na prática, a página inicial é carregada, as linhas de abrir nova guia (e consequentemente fechá-la) são ignoradas, sem lançar nenhuma exceção, e depois ele prossegue o código normalmente e fecha o navegador, como se eu não tivesse mandado abrir uma nova guia e fechá-la. E se tem erros nesse código de abrir nova guia e fechar, ele deveria lançar exceção, não?
Código:
from selenium import webdriver

from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()

driver.get("http://www.google.com/")

# Abre uma nova aba
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')

# Carrega a nova aba
driver.get('http://stackoverflow.com/')

# Fecha a aba
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 'w')

driver.close()

Answer: Você pode tentar isso:
# Abre uma nova aba e vai para o site do SO
driver.execute_script("window.open('http://stackoverflow.com/', '_blank')")

# Muda de aba
driver.switch_to_window(driver.window_handles[1])

# Fecha a aba
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 'w')

Comment: Ok. Mas essa solução tem dois problemas 1) Ao menos no meu computador, o programa está fechando a guia atual e deixando a nova guia lá. Pelo que entendi, a guia que o André quer fechar é a nova. 2) Uma questão menor: o método switch_to_window está deprecated, foi substituído por switch_to.window
Comment: Exatamente. Quero ir para a nova guia, e depois fechá-la
Comment: Então, para fazer isso basta trocar driver.window_handles[0] por driver.window_handles[1]. Tenta aí
Comment: Editei o código pra funcionar como você quer. A questão era só alterar o para driver.window_handles[1], já que a primeira aba seria a aba 0.
Comment: Qual erro? Testei aqui e funcionou bem. Tenta dar um import time e dar um tempo entre carregar a nova aba e fechar, com time.sleep(3), por exemplo.
Comment: Está dando erro quando executo o código, está faltando alguma biblioteca? usei as seguintes bibliotecas, talvez mais do que precisasse e o código ficou assim:

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys

# Abre uma nova aba e vai para o site do SO driver.execute_script("window.open('stackoverflow.com', '_blank')")

# Muda de aba
driver.switch_to_window(driver.window_handles[1])

# Fecha a aba
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 'w')
Comment: Ele acusa erro nesta linha:

----> 6 driver.execute_script("window.open('http://stackoverflow.com/', '_blank')")
Comment: Galera funcionou, me desculpe Guilherme, copiei o seu código, coloquei importei as bibliotecas, mas tinha esquecido de iniciar o navegador. Foi mal, seu código funcionou sim, muito obrigado man!!!
Comment: Sem problemas, André! Que bom que funcionou. Se possível, clica no botão de 'check' ao lado da resposta para marcar como correta. Abraço!
Comment: Está lá clicado brother! Valeuzão
Answer: o essa linha de mandar comando no crhome (driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')) num deu certo. mas consegui resolver o problema selecionando a aba com esse (driver.execute_script("window.open('http://stackoverflow.com/', '_blank')") e pra fechar basta selecionar a aba com (driver.switch_to_window(driver.window_handles[1])) depois fecha com o driver.close().
tentei mandar um comando de uma linha fechando uma tela específica mas deu certo não. mas resolveu o problema só de selecionar. se num selecionar ele fecha a primeira aba.
Comment: Please provide additional details in your answer. As it's currently written, it's hard to understand your solution.

Abrir nova aba usando selenium e python


Como pegar valor de um formulário com AngularJS?

Question: estou começando com AngularJS e surgiu uma dúvida que me parece ser simples.
Estou fazendo um carrinho de compras (só pra aprendizado mesmo) com o pouco que aprendi (ng-controller, ng-repeat, ng-model, etc).
Tenho uma lista que vem do Controller e quero adicionar automaticamente no carinho. Porém, gostaria de saber como pego o valor da quantidade e passo para a função no Controller... utilizei ng-model='quantidade' e tentei recuperar via {{ quantidade }}, o que obviamente não funcionou.
Podem me ajudar?
Meu código: https://jsfiddle.net/r7r99sr9/
Obrigado! =)
Answer: Crie uma variavel no controller referente a esse ng-model e pegue o valor do $scope.quantidade, depois é só passar a variavel para a função.
       //Pega o valor do input
        var quantidade = $scope.quantidade;

Answer: Segue um exemplo 100% funcional de como você poderá recuparar os dados informados via javascript.
<!DOCTYPE html>

Try to change the names.

First Name: <input type="text" ng-model="firstName">

Last Name: <input type="text" ng-model="lastName">

Full Name: {{firstName + " " + lastName}}

<input type="button" value="Ok" onclick="ok()">


Degrau feito com css

Question: Estou precisando fazer este detalhe no css:

O detalhe cinza, com este degrau.
A Pergunta é tem como fazer com css?
Ou apenas com imagem ?
Comment: dá pra fazer com um triangulo
Comment: Como ficaria ? Pode mostrar um exemplo de uma div que tenha aquele detalhe em algum dos lados ? se possivel nos 4
Answer: Existem vários métodos de se fazer isso, acredito que esse seja o mais simples, utilizando um triangulo no final de cada linha para simular um degrau. Segue o código de exemplo com dois:

.chao1{
  width:50%;
  height:20px;
  background:#cecece;
  float:left;
}
.degrau1{
  float:left;
  width: 0;
  height: 0;
  border-style: solid;
  border-width: 20px 0 0 40px;
  border-color: transparent transparent transparent #cecece;
}
.chao2{
  width:90%;
  height:20px;
  background:#cecece;
  float:left;
}
.degrau2{
  float:left;
  width: 0;
  height: 0;
  border-style: solid;
  border-width: 20px 0 0 40px;
  border-color: transparent transparent transparent #cecece;
}

Answer:

div{
  font-size: 0;
  display: inline-block;
}

.ground{
  padding: 0;
  margin: 0;
  width: 40%;
  height: 20px;
  background-color: #000;
  position: relative;
  vertical-align: bottom;
}

.footer{
  width: 60%;
  height: 40px;
  background-color: #000;
  position: relative;
  vertical-align: bottom;
  padding: 0;
  margin: 0;
}

.footer::before{
    content: "";
    position: absolute;
    right: -14px;
    background-color: #F00;
    width: 26px;
    height: 20px;
    top: 8px;
    transform: rotateZ(50deg);
  }

 A

 B

Deixei o 'degrau' em vermelho. Assim você vê o truque que eu fiz. Mude a cor e está pronto.

Degrau feito com css